Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(sdk): add allow_multiple guard to connectedAccounts.link()
Zen Agent6b986cd8f9ee
diff --git a/.changeset/sdk-link-allow-multiple.md b/.changeset/sdk-link-allow-multiple.mdnew file mode 100644index 000000000..4cce5522f--- /dev/null+++ b/.changeset/sdk-link-allow-multiple.md@@ -0,0 +1,10 @@+---+'@composio/core': patch+---++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.++- **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.+- **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`.++Python parity: same option (`allow_multiple: bool = False`) and same guard added to `composio.connected_accounts.link()`.diff --git a/python/composio/core/models/connected_accounts.py b/python/composio/core/models/connected_accounts.pyindex 9322b6b17..4de8ae51b 100644--- a/python/composio/core/models/connected_accounts.py+++ b/python/composio/core/models/connected_accounts.py@@ -455,6 +455,7 @@ class ConnectedAccounts:*,callback_url: t.Optional[str] = None,alias: t.Optional[str] = None,+ allow_multiple: bool = False,) -> ConnectionRequest:"""Create a Composio Connect Link for a user to connect their account to a given auth config.@@ -464,6 +465,13 @@ class ConnectedAccounts::param user_id: The external user ID to create the connected account for.:param auth_config_id: The auth config ID to create the connected account for.:param callback_url: The URL to redirect the user to post connecting their account.+ :param alias: Optional human-readable alias for the connection. Must be unique+ per userId and toolkit within the project.+ :param allow_multiple: Whether to allow multiple connected accounts for the same+ user and auth config. When False (default), raises+ ``ComposioMultipleConnectedAccountsError`` if the user already has an+ ``ACTIVE`` connection on this auth config. Pair with ``alias`` and a+ session-level ``multi_account`` config to disambiguate at execution time.:return: Connection request object.Example:@@ -488,6 +496,23 @@ class ConnectedAccounts:# Wait for the connection to be establishedconnected_account = composio.connected_accounts.wait_for_connection(connection_request.id)"""+ # Mirror ``initiate()``: guard against silently creating extra+ # connections on the same auth config.+ connected_accounts = self.list(+ user_ids=[user_id], auth_config_ids=[auth_config_id], statuses=["ACTIVE"]+ )+ if connected_accounts.items and not allow_multiple:+ raise exceptions.ComposioMultipleConnectedAccountsError(+ f"Multiple connected accounts found for user {user_id} in auth config {auth_config_id}. "+ "Please use the allow_multiple option to allow multiple connected accounts."+ )+ elif connected_accounts.items:+ logger.warning(+ "[Warn:AllowMultiple] Multiple connected accounts found for user %s in auth config %s",+ user_id,+ auth_config_id,+ )+response = self._client.link.create(auth_config_id=auth_config_id,user_id=user_id,diff --git a/python/tests/test_connected_accounts.py b/python/tests/test_connected_accounts.pyindex 9d7130a0c..9a9e9ff98 100644--- a/python/tests/test_connected_accounts.py+++ b/python/tests/test_connected_accounts.py@@ -310,6 +310,12 @@ class TestConnectedAccounts:def test_link_builds_payload_and_returns_connection_request(self, connected_accounts, mock_client):+ # link() now mirrors initiate() and pre-flights list() to enforce the+ # allow_multiple guard; default to no existing connections here.+ no_accounts = Mock()+ no_accounts.items = []+ mock_client.connected_accounts.list.return_value = no_accounts+mock_response = Mock()mock_response.connected_account_id = "conn-999"mock_response.redirect_url = "https://redirect"@@ -334,6 +340,10 @@ class TestConnectedAccounts:def test_link_omits_callback_url_when_not_provided(self, connected_accounts, mock_client):+ no_accounts = Mock()+ no_accounts.items = []+ mock_client.connected_accounts.list.return_value = no_accounts+mock_response = Mock()mock_response.connected_account_id = "conn-000"mock_response.redirect_url = None@@ -346,6 +356,46 @@ class TestConnectedAccounts:assert call_kwargs["user_id"] == "user-1"assert call_kwargs["callback_url"] is omit+ def test_link_raises_when_active_connection_exists_and_not_allow_multiple(+ self, connected_accounts, mock_client+ ):+ """link() guards against duplicate connections, mirroring initiate()."""+ existing = Mock()+ existing.items = [Mock()]+ mock_client.connected_accounts.list.return_value = existing++ with pytest.raises(exceptions.ComposioMultipleConnectedAccountsError):+ connected_accounts.link(user_id="user-1", auth_config_id="auth-1")++ mock_client.connected_accounts.list.assert_called_once_with(+ user_ids=["user-1"], auth_config_ids=["auth-1"], statuses=["ACTIVE"]+ )+ mock_client.link.create.assert_not_called()++ def test_link_skips_guard_when_allow_multiple_is_true(+ self, connected_accounts, mock_client+ ):+ """allow_multiple=True bypasses the guard and proceeds with link.create."""+ existing = Mock()+ existing.items = [Mock()]+ mock_client.connected_accounts.list.return_value = existing++ mock_response = Mock()+ mock_response.connected_account_id = "conn-new"+ mock_response.redirect_url = "https://redirect"+ mock_client.link.create.return_value = mock_response++ result = connected_accounts.link(+ user_id="user-1",+ auth_config_id="auth-1",+ alias="work",+ allow_multiple=True,+ )++ call_kwargs = mock_client.link.create.call_args.kwargs+ assert call_kwargs["alias"] == "work"+ assert result.id == "conn-new"+def test_initiate_with_oauth2_tokens_returns_active_connection_request(self, connected_accounts, mock_client):diff --git a/python/tests/test_tool_router.py b/python/tests/test_tool_router.pyindex 35f9c9a60..971f474b0 100644--- a/python/tests/test_tool_router.py+++ b/python/tests/test_tool_router.py@@ -564,6 +564,29 @@ class TestToolRouter:kwargs = mock_client.tool_router.session.create.call_args.kwargsassert "sandbox_size" not in kwargs["workbench"]+ def test_create_session_with_multi_account(self, tool_router, mock_client):+ """multi_account is forwarded on the wire when set, omitted otherwise."""+ # Forwarded as-is when provided (TypedDict already uses snake_case keys).+ tool_router.create(+ user_id="user_123",+ multi_account={+ "enable": True,+ "max_accounts_per_toolkit": 3,+ "require_explicit_selection": True,+ },+ )+ kwargs = mock_client.tool_router.session.create.call_args.kwargs+ assert kwargs["multi_account"] == {+ "enable": True,+ "max_accounts_per_toolkit": 3,+ "require_explicit_selection": True,+ }++ # Omitted entirely when not provided.+ tool_router.create(user_id="user_123")+ kwargs = mock_client.tool_router.session.create.call_args.kwargs+ assert "multi_account" not in kwargs+def test_create_session_complex_config(self, tool_router, mock_client):"""Test creating a session with complex configuration."""session = tool_router.create(@@ -580,6 +603,7 @@ class TestToolRouter:auth_configs={"github": "ac_xxx"},connected_accounts={"slack": "ca_yyy"},workbench={"enable_proxy_execution": True, "auto_offload_threshold": 600},+ multi_account={"enable": True, "max_accounts_per_toolkit": 5},)assert session.session_id == "session_123"@@ -596,6 +620,10 @@ class TestToolRouter:assert "auth_configs" in kwargsassert "connected_accounts" in kwargsassert "workbench" in kwargs+ assert kwargs["multi_account"] == {+ "enable": True,+ "max_accounts_per_toolkit": 5,+ }def test_create_session_with_experimental_config(self, tool_router, mock_client):"""Test creating a session with experimental configuration."""diff --git a/ts/packages/core/src/models/ConnectedAccounts.ts b/ts/packages/core/src/models/ConnectedAccounts.tsindex d6096d0b7..fd1d9eaf3 100644--- a/ts/packages/core/src/models/ConnectedAccounts.ts+++ b/ts/packages/core/src/models/ConnectedAccounts.ts@@ -263,6 +263,23 @@ export class ConnectedAccounts {});}+ // Mirror initiate(): guard against silently creating extra connections on+ // the same auth config unless the caller explicitly opts in.+ const existing = await this.list({+ userIds: [userId],+ authConfigIds: [authConfigId],+ statuses: [ConnectedAccountStatuses.ACTIVE],+ });+ if (existing.items.length > 0 && !requestOptions.data.allowMultiple) {+ throw new ComposioMultipleConnectedAccountsError(+ `Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.`+ );+ } else if (existing.items.length > 0) {+ logger.warn(+ `[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}`+ );+ }+try {const response = await this.client.link.create({auth_config_id: authConfigId,diff --git a/ts/packages/core/src/types/connectedAccounts.types.ts b/ts/packages/core/src/types/connectedAccounts.types.tsindex d2bddc562..fff0328ef 100644--- a/ts/packages/core/src/types/connectedAccounts.types.ts+++ b/ts/packages/core/src/types/connectedAccounts.types.ts@@ -195,6 +195,14 @@ export const CreateConnectedAccountLinkOptionsSchema = z.object({* Human-readable alias for the connected account. Must be unique per userId and toolkit within the project.*/alias: z.string().optional(),+ /**+ * Whether to allow multiple connected accounts for the same user and auth config.+ * When `false` (default), `link()` throws `ComposioMultipleConnectedAccountsError`+ * if the user already has an `ACTIVE` connection on this auth config — matching+ * the guard on `initiate()`. Pair with `alias` and a session-level+ * `multiAccount` config to disambiguate at execution time.+ */+ allowMultiple: z.boolean().optional(),});export type CreateConnectedAccountLinkOptions = z.infer<typeof CreateConnectedAccountLinkOptionsSchemadiff --git a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.tsindex f8f39069d..db7b4f517 100644--- a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts+++ b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts@@ -972,6 +972,17 @@ describe('ConnectedAccounts', () => {});describe('link', () => {+ beforeEach(() => {+ // link() now mirrors initiate() and pre-flights connectedAccounts.list to+ // enforce the allowMultiple guard. Default to no existing connections so+ // existing tests don't need to mock the list call themselves.+ extendedMockClient.connectedAccounts.list.mockResolvedValue({+ items: [],+ next_cursor: null,+ total_pages: 0,+ });+ });+it('should create a connected account link without options and return a ConnectionRequest', async () => {const userId = 'user_123';const authConfigId = 'auth_config_123';@@ -1304,5 +1315,65 @@ describe('ConnectedAccounts', () => {callback_url: 'https://example.com/callback',});});++ it('throws ComposioMultipleConnectedAccountsError when an active connection exists and allowMultiple is false', async () => {+ const userId = 'user_123';+ const authConfigId = 'auth_config_123';++ extendedMockClient.connectedAccounts.list.mockReset();+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [+ {+ id: 'conn_existing',+ status: ConnectedAccountStatuses.ACTIVE,+ auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },+ toolkit: { slug: 'gmail' },+ },+ ],+ next_cursor: null,+ total_pages: 1,+ });++ await expect(connectedAccounts.link(userId, authConfigId)).rejects.toThrow(+ ComposioMultipleConnectedAccountsError+ );++ expect(extendedMockClient.link.create).not.toHaveBeenCalled();+ });++ it('skips the guard when allowMultiple is true and proceeds with link.create', async () => {+ const userId = 'user_123';+ const authConfigId = 'auth_config_123';++ extendedMockClient.connectedAccounts.list.mockReset();+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [+ {+ id: 'conn_existing',+ status: ConnectedAccountStatuses.ACTIVE,+ auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },+ toolkit: { slug: 'gmail' },+ },+ ],+ next_cursor: null,+ total_pages: 1,+ });+ extendedMockClient.link.create.mockResolvedValueOnce({+ connected_account_id: 'conn_new',+ redirect_url: 'https://connect.composio.dev/auth?token=xyz',+ });++ const connectionRequest = await connectedAccounts.link(userId, authConfigId, {+ allowMultiple: true,+ alias: 'work-gmail',+ });++ expect(extendedMockClient.link.create).toHaveBeenCalledWith({+ auth_config_id: authConfigId,+ user_id: userId,+ alias: 'work-gmail',+ });+ expect(connectionRequest).toHaveProperty('id', 'conn_new');+ });});});