Skip to content

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

feat(triggers): resolve connection from user_id server-side in create() (#3714)

Anshu Garg20a4711ee064
diff --git a/.changeset/triggers-create-user-id-resolution.md b/.changeset/triggers-create-user-id-resolution.md
new file mode 100644
index 000000000..239c7f606
--- /dev/null
+++ b/.changeset/triggers-create-user-id-resolution.md
@@ -0,0 +1,5 @@
+---
+"@composio/core": patch
+---
+
+`triggers.create` no longer makes an extra `connectedAccounts.list()` call to resolve a connection from `user_id`. The backend now resolves the first active connection for the user and the trigger's toolkit when `connected_account_id` is omitted (parity with tool execution), so the SDK passes `user_id` straight through to the upsert call.
diff --git a/python/composio/core/models/triggers.py b/python/composio/core/models/triggers.py
index 997bc0505..0647c2ea0 100644
--- a/python/composio/core/models/triggers.py
+++ b/python/composio/core/models/triggers.py
@@ -1134,49 +1134,29 @@ class Triggers(Resource):
:param trigger_config: The configuration of the trigger
:return: The trigger instance
"""
- if user_id is not None:
- connected_account_id = self._get_connected_account_for_user(
- trigger=slug,
- user_id=user_id,
- )
-
- if connected_account_id is None:
+ if user_id is None and connected_account_id is None:
raise exceptions.InvalidParams(
- "please provide valid `connected_account` or `user_id`"
+ "please provide valid `connected_account_id` or `user_id`"
)
- # Forward user_id so 2FA-enabled projects can verify the pinned connected
- # account belongs to this user (backends without 2FA ignore it). Sent via
- # extra_body until composio-client regenerates with the field.
- extra_body = {"user_id": user_id} if user_id is not None else {}
-
+ # Pass user_id straight through: when connected_account_id is omitted the
+ # backend resolves the first active connection for this user and the
+ # trigger's toolkit (parity with tool execution). This removes the extra
+ # connected_accounts.list() round-trip the SDK used to make. When 2FA is
+ # enabled and connected_account_id is pinned, the backend validates that
+ # user_id owns it. Sent via extra_body until composio-client regenerates
+ # with the field.
return self._client.trigger_instances.upsert(
slug=slug,
- connected_account_id=connected_account_id,
+ connected_account_id=(
+ connected_account_id if connected_account_id is not None else omit
+ ),
toolkit_versions=self._toolkit_versions,
body_trigger_config_1=(
trigger_config if trigger_config is not None else omit
),
- extra_body=extra_body,
- )
-
- def _get_connected_account_for_user(self, trigger: str, user_id: str) -> str:
- toolkit = self.get_type(slug=trigger).toolkit.slug
- connected_accounts = self._client.connected_accounts.list(
- toolkit_slugs=[toolkit],
- user_ids=[user_id],
- )
- if len(connected_accounts.items) == 0:
- raise exceptions.NoItemsFound(
- f"No connected accounts found for {trigger} and {user_id}"
- )
-
- account, *_ = sorted(
- connected_accounts.items,
- key=lambda x: x.created_at,
- reverse=True,
+ extra_body=({"user_id": user_id} if user_id is not None else {}),
)
- return account.id
def subscribe(self, timeout: float = 15.0) -> TriggerSubscription:
"""
diff --git a/python/tests/test_triggers.py b/python/tests/test_triggers.py
index dc6e1652b..24cf20f03 100644
--- a/python/tests/test_triggers.py
+++ b/python/tests/test_triggers.py
@@ -288,6 +288,8 @@ class TestTriggers:
trigger_config={"webhook_url": "https://example.com/webhook"},
)
+ # No extra lookup when an explicit connection is pinned.
+ mock_client.connected_accounts.list.assert_not_called()
mock_client.trigger_instances.upsert.assert_called_once()
call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs
assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
@@ -296,22 +298,19 @@ class TestTriggers:
"webhook_url": "https://example.com/webhook"
}
assert call_kwargs["toolkit_versions"] is None
+ # No user_id supplied → empty extra_body.
+ assert call_kwargs["extra_body"] == {}
assert result == mock_response
- def test_create_with_user_id(self, triggers, mock_client, mock_trigger_type):
- """Test create trigger with user_id."""
+ def test_create_with_user_id(self, triggers, mock_client):
+ """Test create trigger with user_id only.
+
+ The backend resolves the connection from ``user_id``, so the SDK passes
+ it through (via ``extra_body``) and no longer lists connected accounts.
+ """
mock_response = Mock()
mock_response.trigger_id = "trigger-123"
mock_client.trigger_instances.upsert.return_value = mock_response
- mock_client.triggers_types.retrieve.return_value = mock_trigger_type
-
- # Mock connected accounts list
- mock_accounts = Mock()
- mock_account = Mock()
- mock_account.id = "conn-456"
- mock_account.created_at = "2024-01-01T00:00:00Z"
- mock_accounts.items = [mock_account]
- mock_client.connected_accounts.list.return_value = mock_accounts
result = triggers.create(
slug="GITHUB_COMMIT_EVENT",
@@ -319,25 +318,20 @@ class TestTriggers:
trigger_config={"webhook_url": "https://example.com/webhook"},
)
- # Verify get_type was called to get toolkit
- # Note: toolkit_versions=None gets converted to omit
- call_kwargs = mock_client.triggers_types.retrieve.call_args.kwargs
- assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
- assert call_kwargs["toolkit_versions"] is omit
-
- # Verify connected accounts were fetched
- mock_client.connected_accounts.list.assert_called_once_with(
- toolkit_slugs=["github"],
- user_ids=["user-123"],
- )
+ # The SDK no longer makes an extra round-trip to find a connection.
+ mock_client.connected_accounts.list.assert_not_called()
+ mock_client.triggers_types.retrieve.assert_not_called()
- # Verify trigger was created with found connected account
mock_client.trigger_instances.upsert.assert_called_once()
call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs
- assert call_kwargs["connected_account_id"] == "conn-456"
- assert call_kwargs["toolkit_versions"] is None
- # user_id forwarded for trigger 2FA ownership verification
+ assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
+ # No explicit connection pinned → omitted; user_id rides in extra_body.
+ assert call_kwargs["connected_account_id"] is omit
assert call_kwargs["extra_body"] == {"user_id": "user-123"}
+ assert call_kwargs["body_trigger_config_1"] == {
+ "webhook_url": "https://example.com/webhook"
+ }
+ assert call_kwargs["toolkit_versions"] is None
assert result == mock_response
def test_create_with_custom_toolkit_versions(
@@ -375,73 +369,10 @@ class TestTriggers:
trigger_config={"webhook_url": "https://example.com/webhook"},
)
- assert "please provide valid `connected_account` or `user_id`" in str(
+ assert "please provide valid `connected_account_id` or `user_id`" in str(
exc_info.value
)
- def test_create_with_user_id_no_connected_accounts_raises_error(
- self, triggers, mock_client, mock_trigger_type
- ):
- """Test create trigger with user_id but no connected accounts raises error."""
- mock_client.triggers_types.retrieve.return_value = mock_trigger_type
-
- # Mock empty connected accounts list
- mock_accounts = Mock()
- mock_accounts.items = []
- mock_client.connected_accounts.list.return_value = mock_accounts
-
- with pytest.raises(exceptions.NoItemsFound) as exc_info:
- triggers.create(
- slug="GITHUB_COMMIT_EVENT",
- user_id="user-123",
- )
-
- assert "No connected accounts found" in str(exc_info.value)
-
- def test_get_connected_account_for_user(
- self, triggers, mock_client, mock_trigger_type
- ):
- """Test _get_connected_account_for_user method."""
- mock_client.triggers_types.retrieve.return_value = mock_trigger_type
-
- # Mock connected accounts
- mock_accounts = Mock()
- mock_account1 = Mock()
- mock_account1.id = "conn-old"
- mock_account1.created_at = "2024-01-01T00:00:00Z"
- mock_account2 = Mock()
- mock_account2.id = "conn-new"
- mock_account2.created_at = "2024-01-02T00:00:00Z"
- mock_accounts.items = [mock_account1, mock_account2]
- mock_client.connected_accounts.list.return_value = mock_accounts
-
- result = triggers._get_connected_account_for_user(
- trigger="GITHUB_COMMIT_EVENT",
- user_id="user-123",
- )
-
- # Should return the most recent account
- assert result == "conn-new"
-
- def test_get_connected_account_for_user_no_accounts(
- self, triggers, mock_client, mock_trigger_type
- ):
- """Test _get_connected_account_for_user with no accounts raises error."""
- mock_client.triggers_types.retrieve.return_value = mock_trigger_type
-
- # Mock empty connected accounts
- mock_accounts = Mock()
- mock_accounts.items = []
- mock_client.connected_accounts.list.return_value = mock_accounts
-
- with pytest.raises(exceptions.NoItemsFound) as exc_info:
- triggers._get_connected_account_for_user(
- trigger="GITHUB_COMMIT_EVENT",
- user_id="user-123",
- )
-
- assert "No connected accounts found" in str(exc_info.value)
-
def test_enable_trigger(self, triggers, mock_client):
"""Test enable trigger."""
mock_response = Mock()
diff --git a/ts/packages/core/src/models/Triggers.ts b/ts/packages/core/src/models/Triggers.ts
index fe7376e07..da29667b1 100644
--- a/ts/packages/core/src/models/Triggers.ts
+++ b/ts/packages/core/src/models/Triggers.ts
@@ -40,7 +40,7 @@ import {
} from '../types/triggers.types';
import logger from '../utils/logger';
import { telemetry } from '../telemetry/Telemetry';
-import { ComposioConnectedAccountNotFoundError, ValidationError } from '../errors';
+import { ValidationError } from '../errors';
import { PusherService } from '../services/pusher/Pusher';
import {
ComposioTriggerTypeNotFoundError,
@@ -336,12 +336,10 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
});
}
- // Get the connected account id from the user id
- let triggerType: TriggersTypeRetrieveResponse;
- let toolkitSlug: string;
+ // Validate the trigger slug up-front so callers get a clear client-side
+ // error (the backend would also reject an unknown slug).
try {
- triggerType = await this.getType(slug, requestOptions);
- toolkitSlug = triggerType.toolkit.slug;
+ await this.getType(slug, requestOptions);
} catch (error) {
// for some reason, the triggers types list endpoint returns 400 for invalid user ids
if (error instanceof APIError && (error.status === 400 || error.status === 404)) {
@@ -358,74 +356,18 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
}
}
- // Attempt to get connected account ID
- let connectedAccountId: string | undefined = body?.connectedAccountId;
-
- try {
- const connectedAccountListParams = {
- user_ids: [userId],
- toolkit_slugs: [toolkitSlug],
- };
- const { items: connectedAccounts } = await withCancellation(
- () => this.client.connectedAccounts.list(connectedAccountListParams, requestOptions),
- requestOptions?.signal
- );
-
- if (connectedAccounts.length === 0) {
- throw new ComposioConnectedAccountNotFoundError(
- `No connected account found for user ${userId} for toolkit ${toolkitSlug}`,
- {
- cause: new Error(`No connected account found for user ${userId}`),
- possibleFixes: [`Create a new connected account for user ${userId}`],
- }
- );
- }
-
- const accountExists = connectedAccounts.some(acc => acc.id === connectedAccountId);
- // if the connected account id is provided and it does not exist, throw an error
- if (connectedAccountId && !accountExists) {
- throw new ComposioConnectedAccountNotFoundError(
- `Connected account ID ${connectedAccountId} not found for user ${userId}`,
- {
- cause: new Error(
- `Connected account ID ${connectedAccountId} not found for user ${userId}`
- ),
- possibleFixes: [
- `Create a new connected account for user ${userId}`,
- `Verify the connected account ID`,
- ],
- }
- );
- }
-
- // if the connected account id is not provided, use the first connected account
- if (!connectedAccountId) {
- connectedAccountId = connectedAccounts[0].id;
- logger.warn(
- `[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`
- );
- }
- } catch (error) {
- if (error instanceof APIError && [400, 404].includes(error.status)) {
- throw new ComposioConnectedAccountNotFoundError(
- `No connected account found for user ${userId} for toolkit ${toolkitSlug}`,
- {
- cause: error,
- possibleFixes: [`Create a new connected account for user ${userId}`],
- }
- );
- }
- throw error;
- }
-
- // Forward user_id so 2FA-enabled projects can verify the pinned connected
- // account is owned by this user (backends without 2FA ignore it). The
- // `& { user_id }` bridges until @composio/client regenerates from the
+ // Pass `user_id` straight through: when `connected_account_id` is omitted the
+ // backend resolves the first active connection for this user and the
+ // trigger's toolkit, mirroring tool execution. This removes the extra
+ // `connectedAccounts.list()` round-trip the SDK used to make. When 2FA is
+ // enabled and `connected_account_id` is pinned, the backend validates that
+ // `user_id` owns it.
+ // The `& { user_id }` bridges until @composio/client regenerates from the
// updated OpenAPI spec; drop it once the field lands on the generated type.
const upsertParams: ClientTriggerInstanceUpsertParams & {
user_id?: string;
} = {
- connected_account_id: connectedAccountId,
+ connected_account_id: body?.connectedAccountId,
trigger_config: parsedBody.data.triggerConfig,
toolkit_versions: this.toolkitVersions,
user_id: userId,
diff --git a/ts/packages/core/test/models/triggers.test.ts b/ts/packages/core/test/models/triggers.test.ts
index e069a46db..31627354f 100644
--- a/ts/packages/core/test/models/triggers.test.ts
+++ b/ts/packages/core/test/models/triggers.test.ts
@@ -9,7 +9,7 @@ import {
IncomingTriggerPayloadSchema,
} from '../../src/types/triggers.types';
import { telemetry } from '../../src/telemetry/Telemetry';
-import { ComposioConnectedAccountNotFoundError, ValidationError } from '../../src/errors';
+import { ValidationError } from '../../src/errors';
import { PusherService } from '../../src/services/pusher/Pusher';
import {
ComposioFailedToSubscribeToPusherChannelError,
@@ -481,11 +481,7 @@ describe('Triggers', () => {
mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerUpsertResponse);
});
- it('should create a new trigger instance with provided connected account ID', async () => {
- mockClient.connectedAccounts.list.mockResolvedValue({
- items: [{ id: 'conn-123' }],
- });
-
+ it('should pass user_id and the explicit connected account ID to upsert (no extra lookup)', async () => {
const result = await triggers.create(userId, slug, body);
expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(
@@ -495,13 +491,9 @@ describe('Triggers', () => {
},
undefined
);
- expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith(
- {
- user_ids: [userId],
- toolkit_slugs: [mockTriggerType.toolkit.slug],
- },
- undefined
- );
+ // The backend now resolves/validates the connection — the SDK no longer
+ // lists connected accounts to find one.
+ expect(mockClient.connectedAccounts.list).not.toHaveBeenCalled();
expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(
slug,
{
@@ -515,29 +507,24 @@ describe('Triggers', () => {
expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
});
- it('should use first connected account if no connected account ID is provided', async () => {
+ it('should let the backend auto-resolve the connection when no connected account ID is provided', async () => {
const bodyWithoutConnectedAccount = {
triggerConfig: body.triggerConfig,
};
- mockClient.connectedAccounts.list.mockResolvedValue({
- items: [{ id: 'conn-456' }, { id: 'conn-789' }],
- });
const result = await triggers.create(userId, slug, bodyWithoutConnectedAccount);
+ expect(mockClient.connectedAccounts.list).not.toHaveBeenCalled();
expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(
slug,
{
- connected_account_id: 'conn-456',
+ connected_account_id: undefined,
trigger_config: bodyWithoutConnectedAccount.triggerConfig,
toolkit_versions: 'latest',
user_id: userId,
},
undefined
);
- expect(logger.warn).toHaveBeenCalledWith(
- `[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`
- );
expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
});
@@ -563,39 +550,6 @@ describe('Triggers', () => {
);
expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
});
-
- it('should throw error when no connected accounts are found', async () => {
- mockClient.connectedAccounts.list.mockResolvedValue({
- items: [],
- });
-
- await expect(triggers.create(userId, slug, body)).rejects.toThrow(
- 'No connected account found for user user-123'
- );
- expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
- });
-
- it('should throw error when provided connected account ID is not found', async () => {
- mockClient.connectedAccounts.list.mockResolvedValue({
- items: [{ id: 'conn-456' }],
- });
-
- await expect(triggers.create(userId, slug, body)).rejects.toThrow(
- 'Connected account ID conn-123 not found for user user-123'
- );
- expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
- });
-
- it('should throw error when connected accounts list request fails', async () => {
- mockClient.connectedAccounts.list.mockRejectedValue(
- new APIError(404, 'Not Connected Account', 'Not Connected Account', new Headers())
- );
-
- await expect(triggers.create(userId, slug, body)).rejects.toThrow(
- ComposioConnectedAccountNotFoundError
- );
- expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
- });
});
describe('update', () => {