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 484 lines 18.1 KB
Raw
1 """The ``composio.experimental`` namespace.
2
3 Houses experimental SDK surfaces whose shape may change in future
4 releases. Two flavours live here today:
5
6 - Decorators for in-process custom tools and toolkits
7 (``composio.experimental.tool`` / ``composio.experimental.Toolkit``).
8 Implementation details for these still live in :mod:`custom_tool`;
9 this module just exposes them on the namespace.
10 - Experimental SDK methods that take a Composio client
11 (``composio.experimental.update_acl``).
12
13 Anything new on the ``composio.experimental`` namespace should land here,
14 not on the underlying model modules.
15 """
16
17 from __future__ import annotations
18
19 import typing as t
20 import warnings
21
22 import typing_extensions as te
23 from pydantic import BaseModel
24
25 from composio.client import HttpClient
26 from composio.utils.pydantic import none_to_omit
27 from composio.client.types import (
28 connected_account_patch_response,
29 custom_create_toolkit_params,
30 custom_create_toolkit_response,
31 custom_delete_toolkit_response,
32 custom_sync_response,
33 custom_update_toolkits_params,
34 custom_update_toolkits_response,
35 custom_upsert_params,
36 custom_upsert_response,
37 usage_retrieve_params,
38 usage_retrieve_response,
39 usage_retrieve_summary_params,
40 usage_retrieve_summary_response,
41 )
42
43 from .custom_tool import (
44 CustomTool,
45 ExperimentalToolkit,
46 _get_caller_locals,
47 _infer_tool_from_function,
48 )
49
50 # Server-side 400 message the API uses to reject ACL writes against a
51 # PRIVATE connection. Substring-matched in `update_acl` here and in the
52 # sibling `link()` / `authorize()` call sites — kept as a single constant
53 # so a server-side message tweak only requires one edit.
54 ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT = "acl_config_for_shared is only valid on SHARED"
55
56
57 class UsageSummaryResponse(
58 usage_retrieve_summary_response.UsageRetrieveSummaryResponse
59 ):
60 """Project usage summary with the exact USD Instant charge for the window."""
61
62 instant_charge: str
63
64
65 class ExperimentalUsage:
66 """Project usage metering, accessed via ``composio.experimental.usage``.
67
68 Experimental — the response shape may change in future releases. Scoped
69 to the project the API key belongs to.
70 """
71
72 def __init__(self, client: t.Optional[HttpClient] = None) -> None:
73 self._client = client
74
75 def _require_client(self) -> HttpClient:
76 from composio import exceptions
77
78 if self._client is None:
79 raise exceptions.ValidationError(
80 "experimental.usage requires a Composio client. Access it via "
81 "composio.experimental.usage.summary(...)."
82 )
83 return self._client
84
85 def summary(
86 self,
87 **params: te.Unpack[usage_retrieve_summary_params.UsageRetrieveSummaryParams],
88 ) -> UsageSummaryResponse:
89 """
90 Fetch a usage summary for the project. Experimental — shape may change.
91
92 :param from_: Start of the window (Unix epoch milliseconds).
93 :param to: End of the window (Unix epoch milliseconds).
94 :param entity_types: Restrict the summary to these entity types.
95 :param filters: Additional server-side filters.
96 :return: Usage totals under ``.entities`` and the exact USD amount in
97 ``.instant_charge`` (``"0"`` when nothing was charged).
98
99 Example:
100 summary = composio.experimental.usage.summary(
101 entity_types=["tool_calls"],
102 )
103 """
104 response = self._require_client().project.usage.retrieve_summary(**params)
105 # The pinned generated client retains new response fields as Pydantic extras.
106 return UsageSummaryResponse.model_validate(response.model_dump())
107
108 def breakdown(
109 self,
110 entity_type: str,
111 **params: te.Unpack[usage_retrieve_params.UsageRetrieveParams],
112 ) -> usage_retrieve_response.UsageRetrieveResponse:
113 """
114 Fetch a grouped usage breakdown for one entity type. Experimental —
115 shape may change.
116
117 :param entity_type: The metered entity type, e.g. ``tool_calls`` or ``sessions``.
118 :param from_: Start of the window (Unix epoch milliseconds).
119 :param to: End of the window (Unix epoch milliseconds).
120 :param group_by: Field to group the breakdown by (API default: ``tool_slug``
121 for ``tool_calls``, ``user_id`` for ``sessions``).
122 :param order_by: Sort key (``key``, ``total_quantity`` or ``event_count``).
123 :param order_direction: ``asc`` or ``desc``.
124 :param limit: Maximum number of groups to return.
125 :param filters: Additional server-side filters.
126 :return: The usage totals and per-group breakdown.
127
128 Example:
129 breakdown = composio.experimental.usage.breakdown(
130 "tool_calls",
131 group_by="tool_slug",
132 )
133 """
134 return self._require_client().project.usage.retrieve(entity_type, **params)
135
136
137 _UPSERT_DEPRECATION = (
138 "custom_toolkits.upsert() is deprecated. Use create() for a "
139 "new toolkit and update(slug, ...) to change its name, logo or API key field."
140 )
141
142 # Warn once per process so services that upsert on every deploy aren't spammed.
143 _upsert_warning_emitted = False
144
145
146 class CustomToolkits:
147 """Project-owned custom toolkits, accessed via ``composio.custom_toolkits``.
148
149 These toolkits are registered in your Composio project from your own app
150 or MCP server, with their own auth configs and connected accounts. They
151 are unrelated to the in-process toolkits built with
152 ``composio.experimental.Toolkit``.
153 """
154
155 def __init__(self, client: t.Optional[HttpClient] = None) -> None:
156 self._client = client
157
158 def _require_client(self) -> HttpClient:
159 from composio import exceptions
160
161 if self._client is None:
162 raise exceptions.ValidationError(
163 "custom_toolkits requires a Composio client. Access it via "
164 "composio.custom_toolkits.create(...)."
165 )
166 return self._client
167
168 def create(
169 self,
170 **params: te.Unpack[custom_create_toolkit_params.CustomCreateToolkitParams],
171 ) -> custom_create_toolkit_response.CustomCreateToolkitResponse:
172 """
173 Create a custom MCP toolkit and return its generated slug.
174
175 Set ``user_id`` to ``"all"`` to share the toolkit with every user in
176 the project, or to a user ID to make it private to that user.
177 ``mcp_url``, ``auth_schemes`` and ``user_id`` cannot change later:
178 delete and re-create the toolkit instead.
179
180 :param name: Display name of the toolkit.
181 :param mcp_url: The MCP server URL. Must use https.
182 :param auth_schemes: How users authenticate to the MCP server.
183 :param user_id: ``"all"``, or the user ID the toolkit is private to.
184 :param logo_file: Optional base64 PNG or JPEG logo.
185 :param callback_url: Where to send the user after they connect. Used
186 only for ``connect_link``.
187 :return: The toolkit ``slug`` and, for a private toolkit, a
188 ``connect_link`` to send that user to (else ``None``).
189
190 Example:
191 toolkit = composio.custom_toolkits.create(
192 name="Internal API",
193 mcp_url="https://mcp.internal.example.com/mcp",
194 auth_schemes=[
195 {
196 "mode": "API_KEY",
197 "headers": {"Authorization": "Bearer {{generic_api_key}}"},
198 }
199 ],
200 user_id="user_123",
201 )
202 """
203 return self._require_client().custom.create_toolkit(**params)
204
205 def update(
206 self,
207 slug: str,
208 **params: te.Unpack[custom_update_toolkits_params.CustomUpdateToolkitsParams],
209 ) -> custom_update_toolkits_response.CustomUpdateToolkitsResponse:
210 """
211 Update a custom toolkit's name, logo or API key field copy. Omitted
212 fields keep their current value.
213
214 On a project with 2FA enabled, updating a private toolkit requires the
215 ``user_id`` it is private to.
216
217 :param slug: The custom toolkit slug returned by :meth:`create`.
218 :param name: New display name.
219 :param logo_file: New base64 PNG or JPEG logo.
220 :param api_key_field: Label and help text for the API key input on
221 the connect page. API_KEY toolkits only.
222 :param user_id: The user the toolkit is private to.
223 :return: ``success``.
224
225 Example:
226 composio.custom_toolkits.update(
227 "CUSTOM_INTERNAL_API_K7F2Q",
228 name="Internal API (prod)",
229 user_id="user_123",
230 )
231 """
232 return self._require_client().custom.update_toolkits(slug, **params)
233
234 @te.deprecated(_UPSERT_DEPRECATION, category=None)
235 def upsert(
236 self,
237 **params: te.Unpack[custom_upsert_params.CustomUpsertParams],
238 ) -> custom_upsert_response.CustomUpsertResponse:
239 """
240 Create a custom toolkit, or update its display metadata (name, API key
241 field copy) when the project already owns one with this slug.
242
243 .. deprecated::
244 Use :meth:`create` for a new toolkit and :meth:`update` to change
245 its name, logo or API key field. ``create`` generates the slug,
246 so store the slug it returns.
247
248 ``mcp_url`` and ``auth_schemes`` cannot change on an existing
249 toolkit: re-sending them unchanged is a no-op, and changing them fails
250 with a 409. Delete and re-register the toolkit instead, which revokes
251 its connections.
252
253 :param slug: Letters, digits, underscores or spaces (max 30). The API
254 prefixes it with ``CUSTOM_`` and turns spaces into underscores.
255 :param toolkit_config: ``name``, ``mcp_url`` (the MCP URL for MCP
256 apps), ``auth_schemes`` and an optional base64 ``logo_file``.
257 :return: The toolkit's ``slug``.
258
259 Example:
260 composio.custom_toolkits.upsert(
261 slug="INTERNAL_API",
262 toolkit_config={
263 "name": "Internal API",
264 "mcp_url": "https://mcp.internal.example.com/mcp",
265 "auth_schemes": [
266 {
267 "mode": "API_KEY",
268 "headers": {"Authorization": "Bearer {{generic_api_key}}"},
269 }
270 ],
271 },
272 )
273 """
274 global _upsert_warning_emitted
275 if not _upsert_warning_emitted:
276 from composio import exceptions
277
278 _upsert_warning_emitted = True
279 warnings.warn(
280 _UPSERT_DEPRECATION,
281 exceptions.ComposioDeprecationWarning,
282 stacklevel=2,
283 )
284 return self._require_client().custom.upsert(**params)
285
286 def sync(
287 self, slug: str, *, connected_account_id: t.Optional[str] = None
288 ) -> custom_sync_response.CustomSyncResponse:
289 """
290 Re-fetch a custom toolkit's tool definitions from its remote MCP
291 server. Call it when automatic sync fails or the remote tools change.
292
293 :param slug: The custom toolkit slug (``CUSTOM_...``).
294 :param connected_account_id: Connected account to use when fetching
295 the remote tool definitions.
296 :return: The toolkit ``version`` and ``synced_count``.
297
298 Example:
299 result = composio.custom_toolkits.sync("CUSTOM_MY_TOOLKIT")
300 print(result.synced_count)
301 """
302 return self._require_client().custom.sync(
303 slug=slug, connected_account_id=none_to_omit(connected_account_id)
304 )
305
306 def delete(
307 self, slug: str
308 ) -> custom_delete_toolkit_response.CustomDeleteToolkitResponse:
309 """
310 Delete a custom toolkit owned by the project, with its tools, auth
311 configs and connected accounts. The credentials behind those
312 connected accounts are revoked in background jobs
313 (``revoke_job_ids``). Composio-managed toolkits cannot be deleted
314 (API 403).
315
316 :param slug: The custom toolkit slug (``CUSTOM_...``).
317 :return: What was deleted.
318
319 Example:
320 composio.custom_toolkits.delete("CUSTOM_MY_TOOLKIT")
321 """
322 return self._require_client().custom.delete_toolkit(slug)
323
324
325 ExperimentalCustomToolkits = CustomToolkits
326 """Deprecated alias of :class:`CustomToolkits`."""
327
328
329 class ExperimentalAPI:
330 """Experimental APIs accessed via ``composio.experimental``.
331
332 Provides decorators for creating custom tools and toolkits that run
333 in-process alongside remote Composio tools, plus experimental SDK
334 methods whose shape may change in future releases.
335 """
336
337 Toolkit = ExperimentalToolkit
338
339 usage: ExperimentalUsage
340 """Project usage metering. Experimental — shape may change."""
341
342 custom_toolkits: CustomToolkits
343 """Deprecated: use ``composio.custom_toolkits``, the same object."""
344
345 def __init__(self, client: t.Optional[HttpClient] = None) -> None:
346 self._client = client
347 self.usage = ExperimentalUsage(client=client)
348 self.custom_toolkits = CustomToolkits(client=client)
349
350 def update_acl(
351 self,
352 nanoid: str,
353 *,
354 allow_all_users: t.Optional[bool] = None,
355 allowed_user_ids: t.Optional[t.List[str]] = None,
356 not_allowed_user_ids: t.Optional[t.List[str]] = None,
357 ) -> connected_account_patch_response.ConnectedAccountPatchResponse:
358 """
359 Update the per-user ACL on a SHARED connected account. Experimental —
360 shape may change in future releases.
361
362 Only valid on SHARED connections; raises
363 ``ComposioAclOnlyForSharedError`` on a PRIVATE connection. Omit a
364 parameter to leave it unchanged; pass an empty list to clear an
365 allow/deny list. At least one parameter must be provided.
366
367 :param nanoid: The connected account ID (``ca_xxx``).
368 :param allow_all_users: When True, any ``user_id`` may use this
369 SHARED connection (subject to the deny list).
370 :param allowed_user_ids: Explicit list of allowed ``user_id`` strings.
371 Pass ``[]`` to clear.
372 :param not_allowed_user_ids: Explicit deny list (wins over allow on
373 conflict). Pass ``[]`` to clear — note that clearing the deny
374 list silently re-grants access to previously-blocked users.
375 :return: Response with ``id``, ``status``, and ``success``.
376
377 .. deprecated::
378 Use :meth:`composio.connected_accounts.update_acl` instead — ACL
379 updates graduated onto the ``connected_accounts`` model. This
380 experimental alias is kept only for backwards compatibility and
381 delegates to it. Prefer the ``connected_accounts`` model; do not
382 generate new code against this alias.
383
384 Example:
385 composio.connected_accounts.update_acl(
386 'ca_abc',
387 allow_all_users=True,
388 not_allowed_user_ids=['user_bob'],
389 )
390 """
391 from composio import exceptions
392
393 from .connected_accounts import ConnectedAccounts
394
395 if self._client is None:
396 raise exceptions.ValidationError(
397 "update_acl requires a Composio client. Access it via "
398 "composio.connected_accounts.update_acl(...)."
399 )
400
401 return ConnectedAccounts(client=self._client).update_acl(
402 nanoid,
403 allow_all_users=allow_all_users,
404 allowed_user_ids=allowed_user_ids,
405 not_allowed_user_ids=not_allowed_user_ids,
406 )
407
408 @t.overload
409 def tool(self, fn: t.Callable[..., t.Any], /) -> CustomTool: ...
410
411 @t.overload
412 def tool(
413 self,
414 *,
415 slug: t.Optional[str] = None,
416 name: t.Optional[str] = None,
417 description: t.Optional[str] = None,
418 extends_toolkit: t.Optional[str] = None,
419 output_params: t.Optional[t.Type[BaseModel]] = None,
420 preload: t.Optional[bool] = None,
421 ) -> t.Callable[[t.Callable[..., t.Any]], CustomTool]: ...
422
423 def tool(
424 self,
425 fn: t.Optional[t.Callable[..., t.Any]] = None,
426 *,
427 slug: t.Optional[str] = None,
428 name: t.Optional[str] = None,
429 description: t.Optional[str] = None,
430 extends_toolkit: t.Optional[str] = None,
431 output_params: t.Optional[t.Type[BaseModel]] = None,
432 preload: t.Optional[bool] = None,
433 ) -> t.Union[CustomTool, t.Callable[[t.Callable[..., t.Any]], CustomTool]]:
434 """Decorator to create a custom tool from a function.
435
436 Infers slug, name, description, and input_params from the function.
437 Override any with explicit keyword arguments.
438
439 Examples::
440
441 # Bare decorator — no parens
442 @composio.experimental.tool
443 def grep(input: GrepInput, ctx):
444 \"\"\"Search for a pattern.\"\"\"
445 return {"matches": []}
446
447 # With parens — no args
448 @composio.experimental.tool()
449 def grep(input: GrepInput, ctx):
450 \"\"\"Search for a pattern.\"\"\"
451 return {"matches": []}
452
453 # With extends_toolkit — inherits auth
454 @composio.experimental.tool(extends_toolkit="gmail")
455 def create_draft(input: DraftInput, ctx):
456 \"\"\"Create a Gmail draft.\"\"\"
457 return ctx.proxy_execute(toolkit="gmail", ...)
458 """
459
460 def decorator(f: t.Callable[..., t.Any]) -> CustomTool:
461 annotation_locals = _get_caller_locals()
462 return _infer_tool_from_function(
463 f,
464 slug=slug,
465 name=name,
466 description=description,
467 extends_toolkit=extends_toolkit,
468 output_params=output_params,
469 preload=preload,
470 annotation_locals=annotation_locals,
471 )
472
473 if fn is not None:
474 return _infer_tool_from_function(
475 fn,
476 slug=slug,
477 name=name,
478 description=description,
479 extends_toolkit=extends_toolkit,
480 output_params=output_params,
481 preload=preload,
482 annotation_locals=_get_caller_locals(),
483 )
484 return decorator