@devries-cameron20 / composio Mirror · read-only / commits / 6b986cd8f
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 22:15 UTC

feat(sdk): add allow_multiple guard to connectedAccounts.link()

Bring `link()` to parity with `initiate()` so the duplicate-connection guard moves with customers as Composio-managed redirectable-OAuth callers migrate from `connected_accounts/create` to `connected_accounts/link` (SEC-339). - TS: add `allowMultiple?: boolean` to `CreateConnectedAccountLinkOptions`. `link()` now pre-flights `connectedAccounts.list({ statuses: ['ACTIVE'] })` and throws `ComposioMultipleConnectedAccountsError` when an active connection exists and `allowMultiple` is not `true`. - Python: add `allow_multiple: bool = False` to `connected_accounts.link()` with the same guard and the same `ComposioMultipleConnectedAccountsError`. - Tests: existing `link()` tests now mock `list` returning empty (default no-existing-connection path); new tests cover the raise path and the opt-in `allowMultiple=True` skip path. Also add multi_account parity tests on the Python tool_router create() to mirror the TS suite. Behavior change is intentional and patched separately with `.changeset/sdk-link-allow-multiple.md`. The user-facing changelog entry is split into a separate docs PR alongside the sandbox-size docs. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

Zen Agent committed Apr 28, 2026 at 11:48 UTC 6b986cd8f9ee2c52a86649d3ad6da687c78cf99a
7 files changed +209
.changeset/sdk-link-allow-multiple.md new
+10
@@ -0,0 +1,10 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Bring `connectedAccounts.link()` to parity with `connectedAccounts.initiate()` by adding the `allowMultiple` option and the matching active-connection guard. With customers being migrated off `connected_accounts/create` (initiate) onto `connected_accounts/link` ([SEC-339](https://github.com/ComposioHQ/composio/pull/3274)), the guard moves with them.
6 +
7 +- **Added:** `link(userId, authConfigId, { allowMultiple })`. When `allowMultiple` is `false` (default) and the user already has an `ACTIVE` connection on the auth config, `link()` throws `ComposioMultipleConnectedAccountsError` — same behavior as `initiate()`. Pair with `alias` and a session-level `multiAccount` config to disambiguate at execution time.
8 +- **Behavior change:** `link()` now performs a `connectedAccounts.list({ userIds, authConfigIds, statuses: ['ACTIVE'] })` pre-flight before calling `client.link.create`. Callers that intentionally create multiple connections per auth config must pass `allowMultiple: true`.
9 +
10 +Python parity: same option (`allow_multiple: bool = False`) and same guard added to `composio.connected_accounts.link()`.
python/composio/core/models/connected_accounts.py
+25
@@ -455,6 +455,7 @@ class ConnectedAccounts:
455 *,
456 callback_url: t.Optional[str] = None,
457 alias: t.Optional[str] = None,
458 + allow_multiple: bool = False,
459 ) -> ConnectionRequest:
460 """
461 Create a Composio Connect Link for a user to connect their account to a given auth config.
@@ -464,6 +465,13 @@ class ConnectedAccounts:
465 :param user_id: The external user ID to create the connected account for.
466 :param auth_config_id: The auth config ID to create the connected account for.
467 :param callback_url: The URL to redirect the user to post connecting their account.
468 + :param alias: Optional human-readable alias for the connection. Must be unique
469 + per userId and toolkit within the project.
470 + :param allow_multiple: Whether to allow multiple connected accounts for the same
471 + user and auth config. When False (default), raises
472 + ``ComposioMultipleConnectedAccountsError`` if the user already has an
473 + ``ACTIVE`` connection on this auth config. Pair with ``alias`` and a
474 + session-level ``multi_account`` config to disambiguate at execution time.
475 :return: Connection request object.
476
477 Example:
@@ -488,6 +496,23 @@ class ConnectedAccounts:
496 # Wait for the connection to be established
497 connected_account = composio.connected_accounts.wait_for_connection(connection_request.id)
498 """
499 + # Mirror ``initiate()``: guard against silently creating extra
500 + # connections on the same auth config.
501 + connected_accounts = self.list(
502 + user_ids=[user_id], auth_config_ids=[auth_config_id], statuses=["ACTIVE"]
503 + )
504 + if connected_accounts.items and not allow_multiple:
505 + raise exceptions.ComposioMultipleConnectedAccountsError(
506 + f"Multiple connected accounts found for user {user_id} in auth config {auth_config_id}. "
507 + "Please use the allow_multiple option to allow multiple connected accounts."
508 + )
509 + elif connected_accounts.items:
510 + logger.warning(
511 + "[Warn:AllowMultiple] Multiple connected accounts found for user %s in auth config %s",
512 + user_id,
513 + auth_config_id,
514 + )
515 +
516 response = self._client.link.create(
517 auth_config_id=auth_config_id,
518 user_id=user_id,
python/tests/test_connected_accounts.py
+50
@@ -310,6 +310,12 @@ class TestConnectedAccounts:
310 def test_link_builds_payload_and_returns_connection_request(
311 self, connected_accounts, mock_client
312 ):
313 + # link() now mirrors initiate() and pre-flights list() to enforce the
314 + # allow_multiple guard; default to no existing connections here.
315 + no_accounts = Mock()
316 + no_accounts.items = []
317 + mock_client.connected_accounts.list.return_value = no_accounts
318 +
319 mock_response = Mock()
320 mock_response.connected_account_id = "conn-999"
321 mock_response.redirect_url = "https://redirect"
@@ -334,6 +340,10 @@ class TestConnectedAccounts:
340 def test_link_omits_callback_url_when_not_provided(
341 self, connected_accounts, mock_client
342 ):
343 + no_accounts = Mock()
344 + no_accounts.items = []
345 + mock_client.connected_accounts.list.return_value = no_accounts
346 +
347 mock_response = Mock()
348 mock_response.connected_account_id = "conn-000"
349 mock_response.redirect_url = None
@@ -346,6 +356,46 @@ class TestConnectedAccounts:
356 assert call_kwargs["user_id"] == "user-1"
357 assert call_kwargs["callback_url"] is omit
358
359 + def test_link_raises_when_active_connection_exists_and_not_allow_multiple(
360 + self, connected_accounts, mock_client
361 + ):
362 + """link() guards against duplicate connections, mirroring initiate()."""
363 + existing = Mock()
364 + existing.items = [Mock()]
365 + mock_client.connected_accounts.list.return_value = existing
366 +
367 + with pytest.raises(exceptions.ComposioMultipleConnectedAccountsError):
368 + connected_accounts.link(user_id="user-1", auth_config_id="auth-1")
369 +
370 + mock_client.connected_accounts.list.assert_called_once_with(
371 + user_ids=["user-1"], auth_config_ids=["auth-1"], statuses=["ACTIVE"]
372 + )
373 + mock_client.link.create.assert_not_called()
374 +
375 + def test_link_skips_guard_when_allow_multiple_is_true(
376 + self, connected_accounts, mock_client
377 + ):
378 + """allow_multiple=True bypasses the guard and proceeds with link.create."""
379 + existing = Mock()
380 + existing.items = [Mock()]
381 + mock_client.connected_accounts.list.return_value = existing
382 +
383 + mock_response = Mock()
384 + mock_response.connected_account_id = "conn-new"
385 + mock_response.redirect_url = "https://redirect"
386 + mock_client.link.create.return_value = mock_response
387 +
388 + result = connected_accounts.link(
389 + user_id="user-1",
390 + auth_config_id="auth-1",
391 + alias="work",
392 + allow_multiple=True,
393 + )
394 +
395 + call_kwargs = mock_client.link.create.call_args.kwargs
396 + assert call_kwargs["alias"] == "work"
397 + assert result.id == "conn-new"
398 +
399 def test_initiate_with_oauth2_tokens_returns_active_connection_request(
400 self, connected_accounts, mock_client
401 ):
python/tests/test_tool_router.py
+28
@@ -564,6 +564,29 @@ class TestToolRouter:
564 kwargs = mock_client.tool_router.session.create.call_args.kwargs
565 assert "sandbox_size" not in kwargs["workbench"]
566
567 + def test_create_session_with_multi_account(self, tool_router, mock_client):
568 + """multi_account is forwarded on the wire when set, omitted otherwise."""
569 + # Forwarded as-is when provided (TypedDict already uses snake_case keys).
570 + tool_router.create(
571 + user_id="user_123",
572 + multi_account={
573 + "enable": True,
574 + "max_accounts_per_toolkit": 3,
575 + "require_explicit_selection": True,
576 + },
577 + )
578 + kwargs = mock_client.tool_router.session.create.call_args.kwargs
579 + assert kwargs["multi_account"] == {
580 + "enable": True,
581 + "max_accounts_per_toolkit": 3,
582 + "require_explicit_selection": True,
583 + }
584 +
585 + # Omitted entirely when not provided.
586 + tool_router.create(user_id="user_123")
587 + kwargs = mock_client.tool_router.session.create.call_args.kwargs
588 + assert "multi_account" not in kwargs
589 +
590 def test_create_session_complex_config(self, tool_router, mock_client):
591 """Test creating a session with complex configuration."""
592 session = tool_router.create(
@@ -580,6 +603,7 @@ class TestToolRouter:
603 auth_configs={"github": "ac_xxx"},
604 connected_accounts={"slack": "ca_yyy"},
605 workbench={"enable_proxy_execution": True, "auto_offload_threshold": 600},
606 + multi_account={"enable": True, "max_accounts_per_toolkit": 5},
607 )
608
609 assert session.session_id == "session_123"
@@ -596,6 +620,10 @@ class TestToolRouter:
620 assert "auth_configs" in kwargs
621 assert "connected_accounts" in kwargs
622 assert "workbench" in kwargs
623 + assert kwargs["multi_account"] == {
624 + "enable": True,
625 + "max_accounts_per_toolkit": 5,
626 + }
627
628 def test_create_session_with_experimental_config(self, tool_router, mock_client):
629 """Test creating a session with experimental configuration."""
ts/packages/core/src/models/ConnectedAccounts.ts
+17
@@ -263,6 +263,23 @@ export class ConnectedAccounts {
263 });
264 }
265
266 + // Mirror initiate(): guard against silently creating extra connections on
267 + // the same auth config unless the caller explicitly opts in.
268 + const existing = await this.list({
269 + userIds: [userId],
270 + authConfigIds: [authConfigId],
271 + statuses: [ConnectedAccountStatuses.ACTIVE],
272 + });
273 + if (existing.items.length > 0 && !requestOptions.data.allowMultiple) {
274 + throw new ComposioMultipleConnectedAccountsError(
275 + `Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.`
276 + );
277 + } else if (existing.items.length > 0) {
278 + logger.warn(
279 + `[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}`
280 + );
281 + }
282 +
283 try {
284 const response = await this.client.link.create({
285 auth_config_id: authConfigId,
ts/packages/core/src/types/connectedAccounts.types.ts
+8
@@ -195,6 +195,14 @@ export const CreateConnectedAccountLinkOptionsSchema = z.object({
195 * Human-readable alias for the connected account. Must be unique per userId and toolkit within the project.
196 */
197 alias: z.string().optional(),
198 + /**
199 + * Whether to allow multiple connected accounts for the same user and auth config.
200 + * When `false` (default), `link()` throws `ComposioMultipleConnectedAccountsError`
201 + * if the user already has an `ACTIVE` connection on this auth config — matching
202 + * the guard on `initiate()`. Pair with `alias` and a session-level
203 + * `multiAccount` config to disambiguate at execution time.
204 + */
205 + allowMultiple: z.boolean().optional(),
206 });
207 export type CreateConnectedAccountLinkOptions = z.infer<
208 typeof CreateConnectedAccountLinkOptionsSchema
ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+71
@@ -972,6 +972,17 @@ describe('ConnectedAccounts', () => {
972 });
973
974 describe('link', () => {
975 + beforeEach(() => {
976 + // link() now mirrors initiate() and pre-flights connectedAccounts.list to
977 + // enforce the allowMultiple guard. Default to no existing connections so
978 + // existing tests don't need to mock the list call themselves.
979 + extendedMockClient.connectedAccounts.list.mockResolvedValue({
980 + items: [],
981 + next_cursor: null,
982 + total_pages: 0,
983 + });
984 + });
985 +
986 it('should create a connected account link without options and return a ConnectionRequest', async () => {
987 const userId = 'user_123';
988 const authConfigId = 'auth_config_123';
@@ -1304,5 +1315,65 @@ describe('ConnectedAccounts', () => {
1315 callback_url: 'https://example.com/callback',
1316 });
1317 });
1318 +
1319 + it('throws ComposioMultipleConnectedAccountsError when an active connection exists and allowMultiple is false', async () => {
1320 + const userId = 'user_123';
1321 + const authConfigId = 'auth_config_123';
1322 +
1323 + extendedMockClient.connectedAccounts.list.mockReset();
1324 + extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
1325 + items: [
1326 + {
1327 + id: 'conn_existing',
1328 + status: ConnectedAccountStatuses.ACTIVE,
1329 + auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },
1330 + toolkit: { slug: 'gmail' },
1331 + },
1332 + ],
1333 + next_cursor: null,
1334 + total_pages: 1,
1335 + });
1336 +
1337 + await expect(connectedAccounts.link(userId, authConfigId)).rejects.toThrow(
1338 + ComposioMultipleConnectedAccountsError
1339 + );
1340 +
1341 + expect(extendedMockClient.link.create).not.toHaveBeenCalled();
1342 + });
1343 +
1344 + it('skips the guard when allowMultiple is true and proceeds with link.create', async () => {
1345 + const userId = 'user_123';
1346 + const authConfigId = 'auth_config_123';
1347 +
1348 + extendedMockClient.connectedAccounts.list.mockReset();
1349 + extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
1350 + items: [
1351 + {
1352 + id: 'conn_existing',
1353 + status: ConnectedAccountStatuses.ACTIVE,
1354 + auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },
1355 + toolkit: { slug: 'gmail' },
1356 + },
1357 + ],
1358 + next_cursor: null,
1359 + total_pages: 1,
1360 + });
1361 + extendedMockClient.link.create.mockResolvedValueOnce({
1362 + connected_account_id: 'conn_new',
1363 + redirect_url: 'https://connect.composio.dev/auth?token=xyz',
1364 + });
1365 +
1366 + const connectionRequest = await connectedAccounts.link(userId, authConfigId, {
1367 + allowMultiple: true,
1368 + alias: 'work-gmail',
1369 + });
1370 +
1371 + expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1372 + auth_config_id: authConfigId,
1373 + user_id: userId,
1374 + alias: 'work-gmail',
1375 + });
1376 + expect(connectionRequest).toHaveProperty('id', 'conn_new');
1377 + });
1378 });
1379 });