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 905 lines 35.4 KB
Raw
1 from __future__ import annotations
2
3 import functools
4 import logging
5 import math
6 import time
7 import typing as t
8 import warnings
9 from email.utils import parsedate_to_datetime
10
11 import typing_extensions as te
12 from composio_client import BadRequestError, ConflictError, RateLimitError, omit
13
14 from composio import exceptions
15 from composio.client import HttpClient
16 from composio.client.types import (
17 connected_account_complete_auth_response,
18 connected_account_create_params,
19 connected_account_patch_params,
20 connected_account_patch_response,
21 connected_account_refresh_params,
22 connected_account_refresh_response,
23 connected_account_retrieve_response,
24 connected_account_revoke_response,
25 connected_account_update_status_response,
26 link_create_params,
27 )
28
29 from .base import Resource
30 from .experimental import ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT
31
32 logger = logging.getLogger(__name__)
33
34 # Mirrors TS `ConnectionRequest.ts:terminalErrorStates`. INACTIVE is excluded
35 # on purpose — it can recover to ACTIVE.
36 _TERMINAL_CONNECTION_STATES: t.FrozenSet[str] = frozenset(
37 {"FAILED", "EXPIRED", "REVOKED"}
38 )
39
40 # Delay between `wait_for_connection` polls. Mirrors TS `ConnectionRequest.ts`.
41 _INITIAL_POLL_DELAY_SECONDS = 1.0
42 _MAX_POLL_DELAY_SECONDS = 5.0
43 _POLL_DELAY_GROWTH = 1.5
44
45 # One-time-per-process guard so long-running services don't spam the deprecation
46 # warning on every initiate() call.
47 _legacy_initiate_warning_emitted = False
48
49 _REFRESH_DEPRECATION = (
50 "connected_accounts.refresh() is deprecated: the API marks "
51 "POST /connected_accounts/{id}/refresh as deprecated. Re-initiate "
52 "auth with connected_accounts.link() or toolkits.authorize() instead."
53 )
54
55 _REFRESH_VALIDATE_CREDENTIALS_IGNORED = (
56 "connected_accounts.refresh(): the API no longer accepts "
57 "validate_credentials; the argument is ignored."
58 )
59
60
61 def _retry_after_seconds(error: RateLimitError) -> float:
62 """Seconds a 429 asks the caller to wait, from its ``Retry-After`` header (seconds or an HTTP date); 0 if unusable."""
63 value = error.response.headers.get("retry-after", "").strip()
64 try:
65 seconds = float(value)
66 except ValueError:
67 try:
68 seconds = parsedate_to_datetime(value).timestamp() - time.time()
69 except (TypeError, ValueError):
70 return 0.0
71 # `float()` also accepts "nan" and "inf", which aren't waits.
72 return max(0.0, seconds) if math.isfinite(seconds) else 0.0
73
74
75 class ConnectionRequest(Resource):
76 """
77 A connection request.
78
79 This class is used to manage connection requests.
80 """
81
82 DEFAULT_WAIT_TIMEOUT = 60.0 # Seconds
83
84 def __init__(
85 self,
86 id: str,
87 status: str,
88 redirect_url: t.Optional[str],
89 client: HttpClient,
90 ):
91 """
92 Initialize the connection request.
93
94 :param id: The ID of the connection request.
95 :param status: The status of the connection request.
96 :param redirect_url: The redirect URL of the connection request.
97 :param client: The client to use for the connection request.
98 """
99 super().__init__(client)
100 self.id = id
101 self.status = status
102 self.redirect_url = redirect_url
103
104 def wait_for_connection(
105 self,
106 timeout: t.Optional[float] = None,
107 ) -> connected_account_retrieve_response.ConnectedAccountRetrieveResponse:
108 """
109 Wait for the connection to be established.
110
111 The delay between polls grows from 1 second to 5 seconds, so a connection
112 can be up to 5 seconds old when this returns. A rate-limited poll doesn't
113 fail the wait: once the client's own retries run out, it waits as long as
114 the response asks before polling again. If that delay reaches the timeout,
115 the wait times out without another poll. The client's retries can carry
116 the wait past the timeout, because they aren't bound by it.
117
118 :param timeout: The timeout to wait for the connection to be established.
119 :return: Connected account object.
120 """
121 timeout = self.DEFAULT_WAIT_TIMEOUT if timeout is None else timeout
122 deadline = time.time() + timeout
123 poll_delay = _INITIAL_POLL_DELAY_SECONDS
124 while True:
125 delay = poll_delay
126 rate_limited = False
127 try:
128 connection = self._client.connected_accounts.retrieve(nanoid=self.id)
129 except RateLimitError as error:
130 rate_limited = True
131 delay = max(delay, _retry_after_seconds(error))
132 else:
133 self.status = connection.status
134 if self.status == "ACTIVE":
135 return connection
136 if self.status in _TERMINAL_CONNECTION_STATES:
137 raise exceptions.SDKError(
138 message=(
139 f"Connection {self.id} entered terminal state "
140 f"{self.status!r} before becoming active"
141 ),
142 )
143
144 remaining = deadline - time.time()
145 # Written so a NaN timeout times out rather than polling forever.
146 if not remaining > 0:
147 break
148 time.sleep(min(delay, remaining))
149 # Don't start a fresh client retry cycle after a rate-limited wait expires.
150 if rate_limited and time.time() >= deadline:
151 break
152 poll_delay = min(poll_delay * _POLL_DELAY_GROWTH, _MAX_POLL_DELAY_SECONDS)
153
154 raise exceptions.ComposioSDKTimeoutError(
155 message=f"Timeout while waiting for connection {self.id} to be active",
156 )
157
158 @classmethod
159 def from_id(cls, id: str, client: HttpClient) -> te.Self:
160 return cls(
161 id=id,
162 status=client.connected_accounts.retrieve(nanoid=id).status,
163 redirect_url=None,
164 client=client,
165 )
166
167
168 class AuthScheme:
169 """
170 Collection of auth scheme helpers.
171 """
172
173 def oauth1(
174 self, options: connected_account_create_params.ConnectionStateUnionMember0Val
175 ) -> connected_account_create_params.ConnectionState:
176 """
177 Create a new connected account using OAuth 1.0.
178
179 When both ``oauth_token`` and ``oauth_token_secret`` are provided,
180 status defaults to ACTIVE (token import). When either is omitted,
181 status defaults to INITIALIZING (redirect-based OAuth flow).
182 Pass an explicit ``status`` in options to override.
183 """
184 has_tokens = bool(
185 options.get("oauth_token") # type: ignore[union-attr]
186 ) and bool(
187 options.get("oauth_token_secret") # type: ignore[union-attr]
188 )
189 status = "ACTIVE" if has_tokens else "INITIALIZING"
190 return {
191 "auth_scheme": "OAUTH1",
192 "val": t.cast(
193 connected_account_create_params.ConnectionStateUnionMember0Val,
194 {
195 "status": status,
196 **options,
197 },
198 ),
199 }
200
201 def oauth2(
202 self, options: connected_account_create_params.ConnectionStateUnionMember1Val
203 ) -> connected_account_create_params.ConnectionState:
204 """
205 Create a new connected account using OAuth 2.0.
206
207 When ``access_token`` is provided, status defaults to ACTIVE
208 (token import). When omitted, status defaults to INITIALIZING
209 (redirect-based OAuth flow). Pass an explicit ``status`` in
210 options to override.
211 """
212 has_token = bool(options.get("access_token")) # type: ignore[union-attr]
213 status = "ACTIVE" if has_token else "INITIALIZING"
214 return {
215 "auth_scheme": "OAUTH2",
216 "val": t.cast(
217 connected_account_create_params.ConnectionStateUnionMember1Val,
218 {
219 "status": status,
220 **options,
221 },
222 ),
223 }
224
225 def composio_link(
226 self, options: connected_account_create_params.ConnectionStateUnionMember2Val
227 ) -> connected_account_create_params.ConnectionState:
228 """
229 Create a new connected account using Composio Link.
230 """
231 return t.cast(
232 connected_account_create_params.ConnectionState,
233 {
234 "auth_scheme": "COMPOSIO_LINK",
235 "val": t.cast(
236 connected_account_create_params.ConnectionStateUnionMember2Val,
237 {
238 "status": "INITIALIZING",
239 **options,
240 },
241 ),
242 },
243 )
244
245 def api_key(
246 self, options: connected_account_create_params.ConnectionStateUnionMember3Val
247 ) -> connected_account_create_params.ConnectionState:
248 """
249 Create a new connected account using an API key.
250 """
251 return t.cast(
252 connected_account_create_params.ConnectionState,
253 {
254 "auth_scheme": "API_KEY",
255 "val": t.cast(
256 connected_account_create_params.ConnectionStateUnionMember3Val,
257 {
258 "status": "ACTIVE",
259 **options,
260 },
261 ),
262 },
263 )
264
265 def basic(
266 self, options: connected_account_create_params.ConnectionStateUnionMember4Val
267 ) -> connected_account_create_params.ConnectionState:
268 """
269 Create a new connected account using basic auth.
270 """
271 return t.cast(
272 connected_account_create_params.ConnectionState,
273 {
274 "auth_scheme": "BASIC",
275 "val": t.cast(
276 connected_account_create_params.ConnectionStateUnionMember4Val,
277 {
278 "status": "ACTIVE",
279 **options,
280 },
281 ),
282 },
283 )
284
285 def bearer_token(
286 self, options: connected_account_create_params.ConnectionStateUnionMember5Val
287 ) -> connected_account_create_params.ConnectionState:
288 """
289 Create a new connected account using a bearer token.
290 """
291 return t.cast(
292 connected_account_create_params.ConnectionState,
293 {
294 "auth_scheme": "BEARER_TOKEN",
295 "val": t.cast(
296 connected_account_create_params.ConnectionStateUnionMember5Val,
297 {
298 "status": "ACTIVE",
299 **options,
300 },
301 ),
302 },
303 )
304
305 def google_service_account(
306 self, options: connected_account_create_params.ConnectionStateUnionMember6Val
307 ) -> connected_account_create_params.ConnectionState:
308 """
309 Create a new connected account using a Google service account.
310 """
311 return t.cast(
312 connected_account_create_params.ConnectionState,
313 {
314 "auth_scheme": "GOOGLE_SERVICE_ACCOUNT",
315 "val": t.cast(
316 connected_account_create_params.ConnectionStateUnionMember6Val,
317 {
318 "status": "ACTIVE",
319 **options,
320 },
321 ),
322 },
323 )
324
325 def no_auth(
326 self, options: connected_account_create_params.ConnectionStateUnionMember7Val
327 ) -> connected_account_create_params.ConnectionState:
328 """
329 Create a new connected account using no auth.
330 """
331 return {
332 "auth_scheme": "NO_AUTH",
333 "val": t.cast(
334 connected_account_create_params.ConnectionStateUnionMember7Val,
335 {
336 "status": "ACTIVE",
337 **options,
338 },
339 ),
340 }
341
342 def calcom_auth(
343 self, options: connected_account_create_params.ConnectionStateUnionMember8Val
344 ) -> connected_account_create_params.ConnectionState:
345 """
346 Create a new connected account using Cal.com auth.
347 """
348 return {
349 "auth_scheme": "CALCOM_AUTH",
350 "val": t.cast(
351 connected_account_create_params.ConnectionStateUnionMember8Val,
352 {
353 "status": "ACTIVE",
354 **options,
355 },
356 ),
357 }
358
359 def billcom_auth(
360 self, options: connected_account_create_params.ConnectionStateUnionMember9Val
361 ) -> connected_account_create_params.ConnectionState:
362 """
363 Create a new connected account using Bill.com auth.
364 """
365 return t.cast(
366 connected_account_create_params.ConnectionState,
367 {
368 "auth_scheme": "BILLCOM_AUTH",
369 "val": t.cast(
370 connected_account_create_params.ConnectionStateUnionMember9Val,
371 {
372 "status": "ACTIVE",
373 **options,
374 },
375 ),
376 },
377 )
378
379 def basic_with_jwt(
380 self, options: connected_account_create_params.ConnectionStateUnionMember10Val
381 ) -> connected_account_create_params.ConnectionState:
382 """
383 Create a new connected account using basic auth with JWT.
384 """
385 return t.cast(
386 connected_account_create_params.ConnectionState,
387 {
388 "auth_scheme": "BASIC_WITH_JWT",
389 "val": t.cast(
390 connected_account_create_params.ConnectionStateUnionMember10Val,
391 {
392 "status": "ACTIVE",
393 **options,
394 },
395 ),
396 },
397 )
398
399
400 class ConnectedAccounts:
401 """
402 Manage connected accounts.
403
404 This class is used to manage connected accounts in the Composio SDK.
405 These are used to authenticate with third-party services.
406 """
407
408 enable: t.Callable[
409 [str],
410 connected_account_update_status_response.ConnectedAccountUpdateStatusResponse,
411 ]
412 """Enable a connected account."""
413
414 disable: t.Callable[
415 [str],
416 connected_account_update_status_response.ConnectedAccountUpdateStatusResponse,
417 ]
418 """Disable a connected account."""
419
420 def __init__(self, client: HttpClient):
421 """
422 Initialize the connected accounts resource.
423
424 :param client: The client to use for the connected accounts resource.
425 """
426 self._client = client
427 self.get = self._client.connected_accounts.retrieve
428 self.list = self._client.connected_accounts.list
429 self.delete = self._client.connected_accounts.delete
430 self.update_status = self._client.connected_accounts.update_status
431 self.enable = functools.partial(
432 self._client.connected_accounts.update_status,
433 enabled=True,
434 )
435 self.disable = functools.partial(
436 self._client.connected_accounts.update_status,
437 enabled=False,
438 )
439
440 @te.deprecated(_REFRESH_DEPRECATION, category=None)
441 def refresh(
442 self,
443 nanoid: str,
444 **params: te.Unpack[
445 connected_account_refresh_params.ConnectedAccountRefreshParams
446 ],
447 ) -> connected_account_refresh_response.ConnectedAccountRefreshResponse:
448 """
449 Refresh the credentials of a connected account.
450
451 .. deprecated::
452 The API marks ``POST /connected_accounts/{id}/refresh`` as
453 deprecated. Re-initiate authentication with
454 :meth:`link` or ``composio.toolkits.authorize()`` instead.
455
456 :param nanoid: The connected account ID (``ca_xxx``).
457 :return: The refresh response.
458
459 Example:
460 composio.connected_accounts.refresh("ca_abc123")
461 """
462 warnings.warn(
463 _REFRESH_DEPRECATION, exceptions.ComposioDeprecationWarning, stacklevel=2
464 )
465 # The API no longer accepts validate_credentials; forward every other
466 # kwarg (timeout, extra_headers, ...) unchanged.
467 forwarded: t.Dict[str, t.Any] = dict(params)
468 if forwarded.pop("validate_credentials", None) is not None:
469 warnings.warn(
470 _REFRESH_VALIDATE_CREDENTIALS_IGNORED,
471 exceptions.ComposioDeprecationWarning,
472 stacklevel=2,
473 )
474 return self._client.connected_accounts.refresh(nanoid, **forwarded)
475
476 def revoke(
477 self, nanoid: str
478 ) -> connected_account_revoke_response.ConnectedAccountRevokeResponse:
479 """
480 Revoke a connected account's upstream tokens (best effort) and mark
481 the connection ``REVOKED``.
482
483 Raises :class:`composio.exceptions.ComposioConnectedAccountRevocationNotSupportedError`
484 when the toolkit does not support programmatic revocation (API 400)
485 and :class:`composio.exceptions.ComposioConnectedAccountNotRevokableError`
486 when the connection is not in a revokable state (API 409).
487
488 :param nanoid: The connected account ID (``ca_xxx``).
489 :return: The revoked tokens and the updated connected account.
490
491 Example:
492 result = composio.connected_accounts.revoke("ca_abc123")
493 print(result.connected_account.status) # "REVOKED"
494 """
495 try:
496 return self._client.connected_accounts.revoke(nanoid)
497 except BadRequestError as error:
498 raise exceptions.ComposioConnectedAccountRevocationNotSupportedError(
499 f"Connected account {nanoid!r} cannot be revoked programmatically: "
500 f"the toolkit does not support token revocation ({error})"
501 ) from error
502 except ConflictError as error:
503 raise exceptions.ComposioConnectedAccountNotRevokableError(
504 f"Connected account {nanoid!r} is not in a revokable state ({error})"
505 ) from error
506
507 def complete_auth(
508 self, *, user_id: str, session_uri: str
509 ) -> connected_account_complete_auth_response.ConnectedAccountCompleteAuthResponse:
510 """
511 Complete a deferred OAuth connection once you have verified the
512 user's identity.
513
514 When your project has an OAuth callback verifier configured, Composio
515 does not activate a new OAuth connection by itself: it redirects to
516 your verifier with a single-use session URI. After confirming who the
517 user is, redeem it here; Composio checks that your project owns the
518 pending connection and that ``user_id`` is its owner, completes the
519 token exchange, and the connection becomes ``ACTIVE``. Redeeming a
520 session twice, or after it expires, fails with a 404 from the API.
521
522 :param user_id: The user the connection was initiated for.
523 :param session_uri: The session URI from the verifier redirect.
524 :return: The completed ``connected_account_id`` and its ``toolkit_slug``.
525
526 Example:
527 result = composio.connected_accounts.complete_auth(
528 user_id="user_123",
529 session_uri=session_uri, # from the verifier redirect
530 )
531 print(result.connected_account_id)
532 """
533 return self._client.connected_accounts.complete_auth(
534 user_id=user_id, session_uri=session_uri
535 )
536
537 def update(
538 self,
539 nanoid: str,
540 *,
541 alias: t.Optional[str] = None,
542 connection: t.Optional[connected_account_patch_params.Connection] = None,
543 ) -> connected_account_patch_response.ConnectedAccountPatchResponse:
544 """
545 Update a connected account's alias and/or credentials.
546
547 :param nanoid: The connected account ID (ca_xxx).
548 :param alias: Human-readable alias. Pass an empty string to clear.
549 Must be unique per entity and toolkit within the project.
550 :param connection: Credential update with authScheme and val fields.
551 :return: Response with ``id``, ``status``, and ``success``.
552
553 Example:
554 # Set an alias
555 composio.connected_accounts.update('ca_abc123', alias='work-gmail')
556
557 # Clear an alias
558 composio.connected_accounts.update('ca_abc123', alias='')
559 """
560 return self._client.connected_accounts.patch(
561 nanoid,
562 alias=alias if alias is not None else omit,
563 connection=connection if connection is not None else omit,
564 )
565
566 def update_acl(
567 self,
568 nanoid: str,
569 *,
570 allow_all_users: t.Optional[bool] = None,
571 allowed_user_ids: t.Optional[t.List[str]] = None,
572 not_allowed_user_ids: t.Optional[t.List[str]] = None,
573 ) -> connected_account_patch_response.ConnectedAccountPatchResponse:
574 """
575 Update the per-user ACL on a SHARED connected account. Experimental —
576 shape may change in future releases.
577
578 Only valid on SHARED connections; raises
579 ``ComposioAclOnlyForSharedError`` on a PRIVATE connection. Omit a
580 parameter to leave it unchanged; pass an empty list to clear an
581 allow/deny list. At least one parameter must be provided.
582
583 :param nanoid: The connected account ID (``ca_xxx``).
584 :param allow_all_users: When True, any ``user_id`` may use this
585 SHARED connection (subject to the deny list).
586 :param allowed_user_ids: Explicit list of allowed ``user_id`` strings.
587 Pass ``[]`` to clear.
588 :param not_allowed_user_ids: Explicit deny list (wins over allow on
589 conflict). Pass ``[]`` to clear — note that clearing the deny
590 list silently re-grants access to previously-blocked users.
591 :return: Response with ``id``, ``status``, and ``success``.
592
593 Example:
594 composio.connected_accounts.update_acl(
595 'ca_abc',
596 allow_all_users=True,
597 not_allowed_user_ids=['user_bob'],
598 )
599 """
600 if (
601 allow_all_users is None
602 and allowed_user_ids is None
603 and not_allowed_user_ids is None
604 ):
605 raise exceptions.ValidationError(
606 "update_acl requires at least one of allow_all_users, "
607 "allowed_user_ids, or not_allowed_user_ids"
608 )
609
610 acl: t.Dict[str, t.Any] = {}
611 if allow_all_users is not None:
612 acl["allow_all_users"] = allow_all_users
613 if allowed_user_ids is not None:
614 acl["allowed_user_ids"] = allowed_user_ids
615 if not_allowed_user_ids is not None:
616 acl["not_allowed_user_ids"] = not_allowed_user_ids
617
618 try:
619 return self._client.connected_accounts.patch(
620 nanoid,
621 experimental={
622 "acl_config_for_shared": t.cast(
623 connected_account_patch_params.ExperimentalACLConfigForShared,
624 acl,
625 ),
626 },
627 )
628 except BadRequestError as error:
629 message = str(error)
630 if ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT in message:
631 raise exceptions.ComposioAclOnlyForSharedError(message) from error
632 raise
633
634 def initiate(
635 self,
636 user_id: str,
637 auth_config_id: str,
638 *,
639 callback_url: t.Optional[str] = None,
640 allow_multiple: bool = False,
641 config: t.Optional[connected_account_create_params.ConnectionState] = None,
642 alias: t.Optional[str] = None,
643 ) -> ConnectionRequest:
644 """
645 Compound function to create a new connected account. This function creates
646 a new connected account and returns a connection request.
647
648 Users can then wait for the connection to be established using the
649 ``wait_for_connection`` method.
650
651 .. deprecated::
652 For Composio-managed (default) auth configs on redirectable OAuth
653 schemes (OAuth1, OAuth2, DCR_OAUTH), the legacy endpoint this
654 method wraps is being retired: **2026-05-08** for new
655 organizations and **2026-07-03** for all remaining organizations.
656 After your org's cutover, this method will raise
657 :class:`composio.exceptions.ComposioLegacyConnectedAccountsEndpointRetiredError`
658 for that specific combination.
659
660 Use :meth:`ConnectedAccounts.link` for Composio-managed OAuth — it
661 works for every redirectable scheme regardless of whether the
662 auth config is Composio-managed or custom, and the return shape
663 is the same.
664
665 Custom auth configs (your own OAuth app) and non-OAuth schemes
666 (API key, bearer token, basic auth) are unaffected and continue
667 to work on ``initiate()``. See
668 https://docs.composio.dev/docs/changelog/2026/04/24
669
670 :param user_id: The user ID to create the connected account for.
671 :param auth_config_id: The auth config ID to create the connected account for.
672 :param callback_url: Callback URL to use for OAuth apps.
673 :param config: The configuration to create the connected account with.
674 :param allow_multiple: Whether to allow multiple connected accounts for the same user and auth config.
675 :param alias: Optional human-readable alias for the account. Must be unique per userId and toolkit within the project.
676 :return: The connection request.
677 """
678 # Check if there are multiple connected accounts for the authConfig of the user
679 connected_accounts = self.list(
680 user_ids=[user_id], auth_config_ids=[auth_config_id], statuses=["ACTIVE"]
681 )
682 if connected_accounts.items and not allow_multiple:
683 raise exceptions.ComposioMultipleConnectedAccountsError(
684 f"Multiple connected accounts found for user {user_id} in auth config {auth_config_id}. "
685 "Please use the allow_multiple option to allow multiple connected accounts."
686 )
687 elif connected_accounts.items:
688 logger.warning(
689 "[Warn:AllowMultiple] Multiple connected accounts found for user %s in auth config %s",
690 user_id,
691 auth_config_id,
692 )
693
694 connection: dict[str, t.Any] = {"user_id": user_id}
695 if callback_url is not None:
696 connection["callback_url"] = callback_url
697 if config is not None:
698 connection["state"] = config
699 if alias is not None:
700 connection["alias"] = alias
701
702 # Use `with_raw_response.create` so we can read the SEC-339
703 # `Deprecation` header (RFC 9745) the apollo retiring branch sets —
704 # that header is emitted only when the auth config is Composio-managed
705 # AND on a redirectable OAuth scheme, so it's the canonical signal
706 # that this caller needs to migrate. Custom auth configs and non-OAuth
707 # schemes never see the header, eliminating the false-positive warning
708 # that an auth_scheme-only check produced for link()-unaffected callers.
709 deprecation_header: t.Optional[str] = None
710 try:
711 ca_client = self._client.connected_accounts
712 raw_create = getattr(
713 getattr(ca_client, "with_raw_response", None), "create", None
714 )
715 if callable(raw_create):
716 raw = raw_create(
717 auth_config={"id": auth_config_id},
718 connection=t.cast(
719 connected_account_create_params.Connection, connection
720 ),
721 )
722 response = raw.parse() if callable(getattr(raw, "parse", None)) else raw
723 headers = getattr(raw, "headers", None)
724 if headers is not None and hasattr(headers, "get"):
725 value = headers.get("Deprecation") or headers.get("deprecation")
726 if isinstance(value, str):
727 deprecation_header = value
728 else:
729 # Test mocks may not stub `with_raw_response`. Fall back to
730 # the parsed-only path; the deprecation gate stays off (no
731 # header to read).
732 response = ca_client.create(
733 auth_config={"id": auth_config_id},
734 connection=t.cast(
735 connected_account_create_params.Connection, connection
736 ),
737 )
738 except BadRequestError as error:
739 # When the server has flipped this org to the retired path, the
740 # legacy endpoint returns 400 with a stable migration message.
741 # Surface it as a typed error so callers get an actionable hint
742 # instead of a generic BadRequestError.
743 message = str(error)
744 if (
745 "no longer supported" in message
746 and "/api/v3/connected_accounts/link" in message
747 ):
748 raise exceptions.ComposioLegacyConnectedAccountsEndpointRetiredError(
749 message
750 ) from error
751 raise
752
753 # Warn once per process when apollo flags this response as on the
754 # retiring path. Header presence is a 1:1 signal — custom auth
755 # configs and non-OAuth schemes get a clean response and stay silent,
756 # fixing the false-positive that auth_scheme-based detection
757 # produced.
758 global _legacy_initiate_warning_emitted
759 if not _legacy_initiate_warning_emitted and deprecation_header:
760 _legacy_initiate_warning_emitted = True
761 warnings.warn(
762 "composio.connected_accounts.initiate() will stop working "
763 "for this auth config on or before 2026-07-03 (see Sunset "
764 "header on the response). Switch to "
765 "composio.connected_accounts.link() — same return shape, "
766 "same allow_multiple semantics. "
767 "https://docs.composio.dev/docs/changelog/2026/04/24",
768 exceptions.ComposioDeprecationWarning,
769 stacklevel=2,
770 )
771
772 return ConnectionRequest(
773 id=response.id,
774 status=response.connection_data.val.status,
775 redirect_url=getattr(response.connection_data.val, "redirect_url", None),
776 client=self._client,
777 )
778
779 def link(
780 self,
781 user_id: str,
782 auth_config_id: str,
783 *,
784 callback_url: t.Optional[str] = None,
785 alias: t.Optional[str] = None,
786 allow_multiple: bool = False,
787 experimental: t.Optional[link_create_params.Experimental] = None,
788 ) -> ConnectionRequest:
789 """
790 Create a Composio Connect Link for a user to connect their account to a given auth config.
791
792 This method will return an external link which you can use for the user to connect their account.
793
794 :param user_id: The external user ID to create the connected account for.
795 :param auth_config_id: The auth config ID to create the connected account for.
796 :param callback_url: The URL to redirect the user to post connecting their account.
797 :param alias: Optional human-readable alias for the connection. Must be unique
798 per userId and toolkit within the project.
799 :param allow_multiple: Whether to allow multiple connected accounts for the same
800 user and auth config. When False (default), raises
801 ``ComposioMultipleConnectedAccountsError`` if the user already has an
802 ``ACTIVE`` connection on this auth config. Pair with ``alias`` and a
803 session-level ``multi_account`` config to disambiguate at execution time.
804 :param experimental: Experimental options for this connection. Pass an
805 ``Experimental`` dict with ``account_type`` and/or
806 ``acl_config_for_shared`` to create a SHARED connection with a
807 per-user ACL. Experimental — shape may change in future releases.
808 :return: Connection request object.
809
810 Example:
811 # Create a connection request and redirect the user to the redirect url
812 connection_request = composio.connected_accounts.link('user_123', 'auth_config_123')
813 redirect_url = connection_request.redirect_url
814 print(f"Visit: {redirect_url} to authenticate your account")
815
816 # Wait for the connection to be established
817 connected_account = connection_request.wait_for_connection()
818
819 Example with callback URL:
820 # Create a connection request with callback URL
821 connection_request = composio.connected_accounts.link(
822 'user_123',
823 'auth_config_123',
824 callback_url='https://your-app.com/callback'
825 )
826 redirect_url = connection_request.redirect_url
827 print(f"Visit: {redirect_url} to authenticate your account")
828
829 # Wait for the connection to be established
830 connected_account = composio.connected_accounts.wait_for_connection(connection_request.id)
831
832 Example creating a SHARED connection with an ACL (experimental):
833 connection_request = composio.connected_accounts.link(
834 'user_creator',
835 'auth_config_123',
836 experimental={
837 'account_type': 'SHARED',
838 'acl_config_for_shared': {
839 'allow_all_users': True,
840 'not_allowed_user_ids': ['user_bob'],
841 },
842 },
843 )
844 """
845 # Mirror ``initiate()``: guard against silently creating extra
846 # connections on the same auth config.
847 connected_accounts = self.list(
848 user_ids=[user_id], auth_config_ids=[auth_config_id], statuses=["ACTIVE"]
849 )
850 if connected_accounts.items and not allow_multiple:
851 raise exceptions.ComposioMultipleConnectedAccountsError(
852 f"Multiple connected accounts found for user {user_id} in auth config {auth_config_id}. "
853 "Please use the allow_multiple option to allow multiple connected accounts."
854 )
855 elif connected_accounts.items:
856 logger.warning(
857 "[Warn:AllowMultiple] Multiple connected accounts found for user %s in auth config %s",
858 user_id,
859 auth_config_id,
860 )
861
862 try:
863 response = self._client.link.create(
864 auth_config_id=auth_config_id,
865 user_id=user_id,
866 callback_url=callback_url if callback_url is not None else omit,
867 alias=alias if alias is not None else omit,
868 experimental=experimental if experimental is not None else omit,
869 )
870 except BadRequestError as error:
871 # The server rejects ACL on PRIVATE connections — surface that
872 # as a typed error so callers can ``except`` instead of grepping
873 # messages.
874 message = str(error)
875 if ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT in message:
876 raise exceptions.ComposioAclOnlyForSharedError(message) from error
877 raise
878
879 return ConnectionRequest(
880 id=response.connected_account_id,
881 status="INITIATED",
882 redirect_url=getattr(response, "redirect_url", None),
883 client=self._client,
884 )
885
886 def wait_for_connection(
887 self,
888 id: str,
889 timeout: t.Optional[float] = None,
890 ) -> connected_account_retrieve_response.ConnectedAccountRetrieveResponse:
891 """
892 Wait for connected account with given ID to be active
893 """
894 # No fetch first: a 429 on it would end the wait before polling starts.
895 return ConnectionRequest(
896 id=id,
897 status="INITIATED",
898 redirect_url=None,
899 client=self._client,
900 ).wait_for_connection(
901 timeout=timeout,
902 )
903
904
905 auth_scheme = AuthScheme()