@devries-cameron20 / composio-1 / commits / 20a4711ee
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.

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

## What `triggers.create()` used to make an extra **`connectedAccounts.list()`** call to turn a `user_id` into a `connected_account_id` before calling upsert. The backend now resolves the connection from `user_id` directly (picks the first active connection for the user + the trigger's toolkit, parity with tool execution), so the SDK passes `user_id` straight through and drops the round-trip. - **TS** (`ts/packages/core`): removed the `connectedAccounts.list()` block in `Triggers.create()`. `user_id` was already forwarded to upsert (for 2FA); this just removes the now-redundant lookup. `getType` is kept for an early, clear "trigger type not found" error. `connected_account_id` is passed when the caller pins one. - **Python** (`python/composio`): dropped `_get_connected_account_for_user`; `user_id` is sent via `extra_body` and `connected_account_id` is omitted when not provided. ## Why The SDK only ever holds a `user_id`, so every `triggers.create()` paid an extra API call to find a connection. The backend change (ComposioHQ/platform#10932) makes trigger upsert accept `user_id` and auto-resolve — this PR consumes that. ## Behavior notes - When `connected_account_id` is omitted, the backend picks the first active connection ordered by `created_at desc`. The TS SDK's old `list()[0]` ordering was unspecified — selection is now deterministic and consistent with tool execution. - "No connected account found" / "connected account not found" now surface from the **backend** instead of a client-side pre-check. - When 2FA is enabled and `connected_account_id` is pinned, the backend validates that `user_id` owns it (unchanged; `user_id` was already forwarded). - The `extra_body` / `& { user_id }` bridges are still needed only until `@composio/client` / `composio_client` regenerate with `user_id` on the upsert type (the field is already in the OpenAPI contract). ## Tests - TS: `vitest run test/models/triggers.test.ts` → **58 passed** (create tests rewritten to assert no `connectedAccounts.list()` call + `user_id` forwarded). - Python: `pytest tests/test_triggers.py` → **66 passed** (same). ## Depends on Backend: ComposioHQ/platform#10932 (`feat(apollo): resolve trigger connection from user_id on upsert (PLEN-2580)`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

Anshu Garg committed Jul 2, 2026 at 02:35 UTC 20a4711ee064d96c8ee2c1fa4089d2505102b364
5 files changed +59 -247
.changeset/triggers-create-user-id-resolution.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/core": patch
3 +---
4 +
5 +`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.
python/composio/core/models/triggers.py
+13 -33
@@ -1134,49 +1134,29 @@ class Triggers(Resource):
1134 :param trigger_config: The configuration of the trigger
1135 :return: The trigger instance
1136 """
1137 - if user_id is not None:
1138 - connected_account_id = self._get_connected_account_for_user(
1139 - trigger=slug,
1140 - user_id=user_id,
1141 - )
1142 -
1143 - if connected_account_id is None:
1137 + if user_id is None and connected_account_id is None:
1138 raise exceptions.InvalidParams(
1145 - "please provide valid `connected_account` or `user_id`"
1139 + "please provide valid `connected_account_id` or `user_id`"
1140 )
1141
1148 - # Forward user_id so 2FA-enabled projects can verify the pinned connected
1149 - # account belongs to this user (backends without 2FA ignore it). Sent via
1150 - # extra_body until composio-client regenerates with the field.
1151 - extra_body = {"user_id": user_id} if user_id is not None else {}
1152 -
1142 + # Pass user_id straight through: when connected_account_id is omitted the
1143 + # backend resolves the first active connection for this user and the
1144 + # trigger's toolkit (parity with tool execution). This removes the extra
1145 + # connected_accounts.list() round-trip the SDK used to make. When 2FA is
1146 + # enabled and connected_account_id is pinned, the backend validates that
1147 + # user_id owns it. Sent via extra_body until composio-client regenerates
1148 + # with the field.
1149 return self._client.trigger_instances.upsert(
1150 slug=slug,
1155 - connected_account_id=connected_account_id,
1151 + connected_account_id=(
1152 + connected_account_id if connected_account_id is not None else omit
1153 + ),
1154 toolkit_versions=self._toolkit_versions,
1155 body_trigger_config_1=(
1156 trigger_config if trigger_config is not None else omit
1157 ),
1160 - extra_body=extra_body,
1161 - )
1162 -
1163 - def _get_connected_account_for_user(self, trigger: str, user_id: str) -> str:
1164 - toolkit = self.get_type(slug=trigger).toolkit.slug
1165 - connected_accounts = self._client.connected_accounts.list(
1166 - toolkit_slugs=[toolkit],
1167 - user_ids=[user_id],
1168 - )
1169 - if len(connected_accounts.items) == 0:
1170 - raise exceptions.NoItemsFound(
1171 - f"No connected accounts found for {trigger} and {user_id}"
1172 - )
1173 -
1174 - account, *_ = sorted(
1175 - connected_accounts.items,
1176 - key=lambda x: x.created_at,
1177 - reverse=True,
1158 + extra_body=({"user_id": user_id} if user_id is not None else {}),
1159 )
1179 - return account.id
1160
1161 def subscribe(self, timeout: float = 15.0) -> TriggerSubscription:
1162 """
python/tests/test_triggers.py
+21 -90
@@ -288,6 +288,8 @@ class TestTriggers:
288 trigger_config={"webhook_url": "https://example.com/webhook"},
289 )
290
291 + # No extra lookup when an explicit connection is pinned.
292 + mock_client.connected_accounts.list.assert_not_called()
293 mock_client.trigger_instances.upsert.assert_called_once()
294 call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs
295 assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
@@ -296,22 +298,19 @@ class TestTriggers:
298 "webhook_url": "https://example.com/webhook"
299 }
300 assert call_kwargs["toolkit_versions"] is None
301 + # No user_id supplied → empty extra_body.
302 + assert call_kwargs["extra_body"] == {}
303 assert result == mock_response
304
301 - def test_create_with_user_id(self, triggers, mock_client, mock_trigger_type):
302 - """Test create trigger with user_id."""
305 + def test_create_with_user_id(self, triggers, mock_client):
306 + """Test create trigger with user_id only.
307 +
308 + The backend resolves the connection from ``user_id``, so the SDK passes
309 + it through (via ``extra_body``) and no longer lists connected accounts.
310 + """
311 mock_response = Mock()
312 mock_response.trigger_id = "trigger-123"
313 mock_client.trigger_instances.upsert.return_value = mock_response
306 - mock_client.triggers_types.retrieve.return_value = mock_trigger_type
307 -
308 - # Mock connected accounts list
309 - mock_accounts = Mock()
310 - mock_account = Mock()
311 - mock_account.id = "conn-456"
312 - mock_account.created_at = "2024-01-01T00:00:00Z"
313 - mock_accounts.items = [mock_account]
314 - mock_client.connected_accounts.list.return_value = mock_accounts
314
315 result = triggers.create(
316 slug="GITHUB_COMMIT_EVENT",
@@ -319,25 +318,20 @@ class TestTriggers:
318 trigger_config={"webhook_url": "https://example.com/webhook"},
319 )
320
322 - # Verify get_type was called to get toolkit
323 - # Note: toolkit_versions=None gets converted to omit
324 - call_kwargs = mock_client.triggers_types.retrieve.call_args.kwargs
325 - assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
326 - assert call_kwargs["toolkit_versions"] is omit
327 -
328 - # Verify connected accounts were fetched
329 - mock_client.connected_accounts.list.assert_called_once_with(
330 - toolkit_slugs=["github"],
331 - user_ids=["user-123"],
332 - )
321 + # The SDK no longer makes an extra round-trip to find a connection.
322 + mock_client.connected_accounts.list.assert_not_called()
323 + mock_client.triggers_types.retrieve.assert_not_called()
324
334 - # Verify trigger was created with found connected account
325 mock_client.trigger_instances.upsert.assert_called_once()
326 call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs
337 - assert call_kwargs["connected_account_id"] == "conn-456"
338 - assert call_kwargs["toolkit_versions"] is None
339 - # user_id forwarded for trigger 2FA ownership verification
327 + assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
328 + # No explicit connection pinned → omitted; user_id rides in extra_body.
329 + assert call_kwargs["connected_account_id"] is omit
330 assert call_kwargs["extra_body"] == {"user_id": "user-123"}
331 + assert call_kwargs["body_trigger_config_1"] == {
332 + "webhook_url": "https://example.com/webhook"
333 + }
334 + assert call_kwargs["toolkit_versions"] is None
335 assert result == mock_response
336
337 def test_create_with_custom_toolkit_versions(
@@ -375,73 +369,10 @@ class TestTriggers:
369 trigger_config={"webhook_url": "https://example.com/webhook"},
370 )
371
378 - assert "please provide valid `connected_account` or `user_id`" in str(
372 + assert "please provide valid `connected_account_id` or `user_id`" in str(
373 exc_info.value
374 )
375
382 - def test_create_with_user_id_no_connected_accounts_raises_error(
383 - self, triggers, mock_client, mock_trigger_type
384 - ):
385 - """Test create trigger with user_id but no connected accounts raises error."""
386 - mock_client.triggers_types.retrieve.return_value = mock_trigger_type
387 -
388 - # Mock empty connected accounts list
389 - mock_accounts = Mock()
390 - mock_accounts.items = []
391 - mock_client.connected_accounts.list.return_value = mock_accounts
392 -
393 - with pytest.raises(exceptions.NoItemsFound) as exc_info:
394 - triggers.create(
395 - slug="GITHUB_COMMIT_EVENT",
396 - user_id="user-123",
397 - )
398 -
399 - assert "No connected accounts found" in str(exc_info.value)
400 -
401 - def test_get_connected_account_for_user(
402 - self, triggers, mock_client, mock_trigger_type
403 - ):
404 - """Test _get_connected_account_for_user method."""
405 - mock_client.triggers_types.retrieve.return_value = mock_trigger_type
406 -
407 - # Mock connected accounts
408 - mock_accounts = Mock()
409 - mock_account1 = Mock()
410 - mock_account1.id = "conn-old"
411 - mock_account1.created_at = "2024-01-01T00:00:00Z"
412 - mock_account2 = Mock()
413 - mock_account2.id = "conn-new"
414 - mock_account2.created_at = "2024-01-02T00:00:00Z"
415 - mock_accounts.items = [mock_account1, mock_account2]
416 - mock_client.connected_accounts.list.return_value = mock_accounts
417 -
418 - result = triggers._get_connected_account_for_user(
419 - trigger="GITHUB_COMMIT_EVENT",
420 - user_id="user-123",
421 - )
422 -
423 - # Should return the most recent account
424 - assert result == "conn-new"
425 -
426 - def test_get_connected_account_for_user_no_accounts(
427 - self, triggers, mock_client, mock_trigger_type
428 - ):
429 - """Test _get_connected_account_for_user with no accounts raises error."""
430 - mock_client.triggers_types.retrieve.return_value = mock_trigger_type
431 -
432 - # Mock empty connected accounts
433 - mock_accounts = Mock()
434 - mock_accounts.items = []
435 - mock_client.connected_accounts.list.return_value = mock_accounts
436 -
437 - with pytest.raises(exceptions.NoItemsFound) as exc_info:
438 - triggers._get_connected_account_for_user(
439 - trigger="GITHUB_COMMIT_EVENT",
440 - user_id="user-123",
441 - )
442 -
443 - assert "No connected accounts found" in str(exc_info.value)
444 -
376 def test_enable_trigger(self, triggers, mock_client):
377 """Test enable trigger."""
378 mock_response = Mock()
ts/packages/core/src/models/Triggers.ts
+12 -70
@@ -40,7 +40,7 @@ import {
40 } from '../types/triggers.types';
41 import logger from '../utils/logger';
42 import { telemetry } from '../telemetry/Telemetry';
43 -import { ComposioConnectedAccountNotFoundError, ValidationError } from '../errors';
43 +import { ValidationError } from '../errors';
44 import { PusherService } from '../services/pusher/Pusher';
45 import {
46 ComposioTriggerTypeNotFoundError,
@@ -336,12 +336,10 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
336 });
337 }
338
339 - // Get the connected account id from the user id
340 - let triggerType: TriggersTypeRetrieveResponse;
341 - let toolkitSlug: string;
339 + // Validate the trigger slug up-front so callers get a clear client-side
340 + // error (the backend would also reject an unknown slug).
341 try {
343 - triggerType = await this.getType(slug, requestOptions);
344 - toolkitSlug = triggerType.toolkit.slug;
342 + await this.getType(slug, requestOptions);
343 } catch (error) {
344 // for some reason, the triggers types list endpoint returns 400 for invalid user ids
345 if (error instanceof APIError && (error.status === 400 || error.status === 404)) {
@@ -358,74 +356,18 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
356 }
357 }
358
361 - // Attempt to get connected account ID
362 - let connectedAccountId: string | undefined = body?.connectedAccountId;
363 -
364 - try {
365 - const connectedAccountListParams = {
366 - user_ids: [userId],
367 - toolkit_slugs: [toolkitSlug],
368 - };
369 - const { items: connectedAccounts } = await withCancellation(
370 - () => this.client.connectedAccounts.list(connectedAccountListParams, requestOptions),
371 - requestOptions?.signal
372 - );
373 -
374 - if (connectedAccounts.length === 0) {
375 - throw new ComposioConnectedAccountNotFoundError(
376 - `No connected account found for user ${userId} for toolkit ${toolkitSlug}`,
377 - {
378 - cause: new Error(`No connected account found for user ${userId}`),
379 - possibleFixes: [`Create a new connected account for user ${userId}`],
380 - }
381 - );
382 - }
383 -
384 - const accountExists = connectedAccounts.some(acc => acc.id === connectedAccountId);
385 - // if the connected account id is provided and it does not exist, throw an error
386 - if (connectedAccountId && !accountExists) {
387 - throw new ComposioConnectedAccountNotFoundError(
388 - `Connected account ID ${connectedAccountId} not found for user ${userId}`,
389 - {
390 - cause: new Error(
391 - `Connected account ID ${connectedAccountId} not found for user ${userId}`
392 - ),
393 - possibleFixes: [
394 - `Create a new connected account for user ${userId}`,
395 - `Verify the connected account ID`,
396 - ],
397 - }
398 - );
399 - }
400 -
401 - // if the connected account id is not provided, use the first connected account
402 - if (!connectedAccountId) {
403 - connectedAccountId = connectedAccounts[0].id;
404 - logger.warn(
405 - `[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`
406 - );
407 - }
408 - } catch (error) {
409 - if (error instanceof APIError && [400, 404].includes(error.status)) {
410 - throw new ComposioConnectedAccountNotFoundError(
411 - `No connected account found for user ${userId} for toolkit ${toolkitSlug}`,
412 - {
413 - cause: error,
414 - possibleFixes: [`Create a new connected account for user ${userId}`],
415 - }
416 - );
417 - }
418 - throw error;
419 - }
420 -
421 - // Forward user_id so 2FA-enabled projects can verify the pinned connected
422 - // account is owned by this user (backends without 2FA ignore it). The
423 - // `& { user_id }` bridges until @composio/client regenerates from the
359 + // Pass `user_id` straight through: when `connected_account_id` is omitted the
360 + // backend resolves the first active connection for this user and the
361 + // trigger's toolkit, mirroring tool execution. This removes the extra
362 + // `connectedAccounts.list()` round-trip the SDK used to make. When 2FA is
363 + // enabled and `connected_account_id` is pinned, the backend validates that
364 + // `user_id` owns it.
365 + // The `& { user_id }` bridges until @composio/client regenerates from the
366 // updated OpenAPI spec; drop it once the field lands on the generated type.
367 const upsertParams: ClientTriggerInstanceUpsertParams & {
368 user_id?: string;
369 } = {
428 - connected_account_id: connectedAccountId,
370 + connected_account_id: body?.connectedAccountId,
371 trigger_config: parsedBody.data.triggerConfig,
372 toolkit_versions: this.toolkitVersions,
373 user_id: userId,
ts/packages/core/test/models/triggers.test.ts
+8 -54
@@ -9,7 +9,7 @@ import {
9 IncomingTriggerPayloadSchema,
10 } from '../../src/types/triggers.types';
11 import { telemetry } from '../../src/telemetry/Telemetry';
12 -import { ComposioConnectedAccountNotFoundError, ValidationError } from '../../src/errors';
12 +import { ValidationError } from '../../src/errors';
13 import { PusherService } from '../../src/services/pusher/Pusher';
14 import {
15 ComposioFailedToSubscribeToPusherChannelError,
@@ -481,11 +481,7 @@ describe('Triggers', () => {
481 mockClient.triggerInstances.upsert.mockResolvedValue(mockTriggerUpsertResponse);
482 });
483
484 - it('should create a new trigger instance with provided connected account ID', async () => {
485 - mockClient.connectedAccounts.list.mockResolvedValue({
486 - items: [{ id: 'conn-123' }],
487 - });
488 -
484 + it('should pass user_id and the explicit connected account ID to upsert (no extra lookup)', async () => {
485 const result = await triggers.create(userId, slug, body);
486
487 expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(
@@ -495,13 +491,9 @@ describe('Triggers', () => {
491 },
492 undefined
493 );
498 - expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith(
499 - {
500 - user_ids: [userId],
501 - toolkit_slugs: [mockTriggerType.toolkit.slug],
502 - },
503 - undefined
504 - );
494 + // The backend now resolves/validates the connection — the SDK no longer
495 + // lists connected accounts to find one.
496 + expect(mockClient.connectedAccounts.list).not.toHaveBeenCalled();
497 expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(
498 slug,
499 {
@@ -515,29 +507,24 @@ describe('Triggers', () => {
507 expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
508 });
509
518 - it('should use first connected account if no connected account ID is provided', async () => {
510 + it('should let the backend auto-resolve the connection when no connected account ID is provided', async () => {
511 const bodyWithoutConnectedAccount = {
512 triggerConfig: body.triggerConfig,
513 };
522 - mockClient.connectedAccounts.list.mockResolvedValue({
523 - items: [{ id: 'conn-456' }, { id: 'conn-789' }],
524 - });
514
515 const result = await triggers.create(userId, slug, bodyWithoutConnectedAccount);
516
517 + expect(mockClient.connectedAccounts.list).not.toHaveBeenCalled();
518 expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(
519 slug,
520 {
531 - connected_account_id: 'conn-456',
521 + connected_account_id: undefined,
522 trigger_config: bodyWithoutConnectedAccount.triggerConfig,
523 toolkit_versions: 'latest',
524 user_id: userId,
525 },
526 undefined
527 );
538 - expect(logger.warn).toHaveBeenCalledWith(
539 - `[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`
540 - );
528 expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
529 });
530
@@ -563,39 +550,6 @@ describe('Triggers', () => {
550 );
551 expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
552 });
566 -
567 - it('should throw error when no connected accounts are found', async () => {
568 - mockClient.connectedAccounts.list.mockResolvedValue({
569 - items: [],
570 - });
571 -
572 - await expect(triggers.create(userId, slug, body)).rejects.toThrow(
573 - 'No connected account found for user user-123'
574 - );
575 - expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
576 - });
577 -
578 - it('should throw error when provided connected account ID is not found', async () => {
579 - mockClient.connectedAccounts.list.mockResolvedValue({
580 - items: [{ id: 'conn-456' }],
581 - });
582 -
583 - await expect(triggers.create(userId, slug, body)).rejects.toThrow(
584 - 'Connected account ID conn-123 not found for user user-123'
585 - );
586 - expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
587 - });
588 -
589 - it('should throw error when connected accounts list request fails', async () => {
590 - mockClient.connectedAccounts.list.mockRejectedValue(
591 - new APIError(404, 'Not Connected Account', 'Not Connected Account', new Headers())
592 - );
593 -
594 - await expect(triggers.create(userId, slug, body)).rejects.toThrow(
595 - ComposioConnectedAccountNotFoundError
596 - );
597 - expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
598 - });
553 });
554
555 describe('update', () => {