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
fix(triggers): align create() user_id resolution across SDKs (#3723)
Alberto Schiabela69c3edea317
diff --git a/.changeset/triggers-create-user-id-resolution.md b/.changeset/triggers-create-user-id-resolution.mdindex 239c7f606..4cff5cceb 100644--- a/.changeset/triggers-create-user-id-resolution.md+++ b/.changeset/triggers-create-user-id-resolution.md@@ -1,5 +1,9 @@----"@composio/core": patch+"@composio/core": minor----`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.+`triggers.create` now resolves the connection from `user_id` on the backend instead of client-side.++- The SDK no longer makes an extra `connectedAccounts.list()` call. When `connectedAccountId` is omitted, the backend resolves the first active connection for the user and the trigger's toolkit (ordered by most recently created), matching tool execution.+- **Behavior change:** `create` no longer throws `ComposioConnectedAccountNotFoundError` for a missing or invalid connection. That case now surfaces as the backend error from the upsert call. `ComposioTriggerTypeNotFoundError` (invalid slug) and `ValidationError` (including empty `userId`) are still thrown client-side.+- **Requires a backend that resolves the trigger connection from `user_id` on upsert** ([ComposioHQ/platform#10932](https://github.com/ComposioHQ/platform/pull/10932)). Self-hosted deployments must be on a version that includes it.diff --git a/python/composio/core/models/triggers.py b/python/composio/core/models/triggers.pyindex 0647c2ea0..83b38409e 100644--- a/python/composio/core/models/triggers.py+++ b/python/composio/core/models/triggers.py@@ -14,7 +14,7 @@ from enum import Enumfrom unittest import mockimport typing_extensions as te-from composio_client import Omit, omit+from composio_client import APIStatusError, Omit, omitfrom composio_client.types import TriggersTypeRetrieveResponsefrom pysher import Pusherfrom pysher.channel import Channel as PusherChannel@@ -1130,32 +1130,47 @@ class Triggers(Resource):Create a trigger instance:param slug: The slug of the trigger- :param connected_account_id: The ID of the connected account+ :param user_id: The ID of the user that owns the connected account. When+ ``connected_account_id`` is omitted, the backend resolves the first+ active connection for this user and the trigger's toolkit.+ :param connected_account_id: The ID of the connected account to pin:param trigger_config: The configuration of the trigger:return: The trigger instance"""+ # Treat blank strings as missing so an empty or whitespace-only+ # `user_id` / `connected_account_id` does not slip past the guard below+ # or reach the backend (parity with the TypeScript SDK's `userId` check).+ if isinstance(user_id, str) and not user_id.strip():+ user_id = None+ if isinstance(connected_account_id, str) and not connected_account_id.strip():+ connected_account_id = None+if user_id is None and connected_account_id is None:raise exceptions.InvalidParams("please provide valid `connected_account_id` or `user_id`")+ # Validate the trigger slug up-front so callers get a clear+ # `TriggerTypeNotFound` (parity with the TypeScript SDK).+ try:+ self.get_type(slug=slug)+ except APIStatusError as error:+ if error.status_code in (400, 404):+ raise exceptions.TriggerTypeNotFound(+ f"Trigger type {slug} not found"+ ) from error+ raise+# 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.+ # trigger's toolkit (parity with tool execution). When 2FA is enabled and+ # connected_account_id is pinned, the backend validates that user_id owns it.return self._client.trigger_instances.upsert(slug=slug,- connected_account_id=(- connected_account_id if connected_account_id is not None else omit- ),+ connected_account_id=none_to_omit(connected_account_id),toolkit_versions=self._toolkit_versions,- body_trigger_config_1=(- trigger_config if trigger_config is not None else omit- ),- extra_body=({"user_id": user_id} if user_id is not None else {}),+ body_trigger_config_1=none_to_omit(trigger_config),+ user_id=none_to_omit(user_id),)def subscribe(self, timeout: float = 15.0) -> TriggerSubscription:diff --git a/python/composio/exceptions.py b/python/composio/exceptions.pyindex 91bdf8d61..34286fcf6 100644--- a/python/composio/exceptions.py+++ b/python/composio/exceptions.py@@ -257,6 +257,15 @@ class WebhookPayloadError(TriggerError):pass+class TriggerTypeNotFound(TriggerError, NotFoundError):+ """Raised when a trigger type cannot be found for the given slug.++ Mirrors the TypeScript SDK's ``ComposioTriggerTypeNotFoundError``.+ """++ pass++class ActionError(ToolkitError):passdiff --git a/python/tests/test_triggers.py b/python/tests/test_triggers.pyindex 24cf20f03..9f4c2d78b 100644--- a/python/tests/test_triggers.py+++ b/python/tests/test_triggers.py@@ -8,8 +8,9 @@ import timefrom datetime import datetime, timezonefrom unittest.mock import Mock, patch+import httpximport pytest-from composio_client import omit+from composio_client import NotFoundError, omitfrom composio import exceptionsfrom composio.core.models.triggers import (@@ -298,15 +299,15 @@ 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"] == {}+ # No user_id supplied → omitted from the request (native kwarg, not extra_body).+ assert call_kwargs["user_id"] is omitassert result == mock_responsedef 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.+ it straight through and no longer lists connected accounts."""mock_response = Mock()mock_response.trigger_id = "trigger-123"@@ -318,22 +319,75 @@ class TestTriggers:trigger_config={"webhook_url": "https://example.com/webhook"},)- # The SDK no longer makes an extra round-trip to find a connection.+ # The SDK no longer lists connected accounts to resolve the connection,+ # but it still validates the slug up-front (parity with the TS SDK).mock_client.connected_accounts.list.assert_not_called()- mock_client.triggers_types.retrieve.assert_not_called()+ mock_client.triggers_types.retrieve.assert_called_once()mock_client.trigger_instances.upsert.assert_called_once()call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargsassert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"- # No explicit connection pinned → omitted; user_id rides in extra_body.+ # No explicit connection pinned → omitted; user_id is sent as a native kwarg.assert call_kwargs["connected_account_id"] is omit- assert call_kwargs["extra_body"] == {"user_id": "user-123"}+ assert call_kwargs["user_id"] == "user-123"assert call_kwargs["body_trigger_config_1"] == {"webhook_url": "https://example.com/webhook"}assert call_kwargs["toolkit_versions"] is Noneassert result == mock_response+ def test_create_with_user_id_and_connected_account_id(self, triggers, mock_client):+ """Test create trigger with both user_id and a pinned connected_account_id.++ When a connection is pinned and 2FA is enabled, the backend validates the+ connection is owned by ``user_id``. Both values are forwarded natively+ (no ``extra_body``). Mirrors the TS ``create`` test.+ """+ mock_response = Mock()+ mock_response.trigger_id = "trigger-123"+ mock_client.trigger_instances.upsert.return_value = mock_response++ result = triggers.create(+ slug="GITHUB_COMMIT_EVENT",+ user_id="user-123",+ connected_account_id="conn-123",+ trigger_config={"webhook_url": "https://example.com/webhook"},+ )++ 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"+ assert call_kwargs["connected_account_id"] == "conn-123"+ assert call_kwargs["user_id"] == "user-123"+ assert call_kwargs["body_trigger_config_1"] == {+ "webhook_url": "https://example.com/webhook"+ }+ assert result == mock_response++ def test_create_raises_trigger_type_not_found_for_unknown_slug(+ self, triggers, mock_client+ ):+ """An unknown slug surfaces as TriggerTypeNotFound (parity with the TS SDK)."""+ request = httpx.Request("GET", "https://backend.composio.dev")+ response = httpx.Response(404, request=request)+ mock_client.triggers_types.retrieve.side_effect = NotFoundError(+ "not found", response=response, body=None+ )++ with pytest.raises(exceptions.TriggerTypeNotFound):+ triggers.create(slug="UNKNOWN_TRIGGER", user_id="user-123")++ mock_client.trigger_instances.upsert.assert_not_called()++ def test_create_treats_blank_user_id_as_missing(self, triggers, mock_client):+ """A blank user_id is rejected like a missing one, before any request."""+ with pytest.raises(exceptions.InvalidParams):+ triggers.create(slug="GITHUB_COMMIT_EVENT", user_id=" ")++ mock_client.triggers_types.retrieve.assert_not_called()+ mock_client.trigger_instances.upsert.assert_not_called()+def test_create_with_custom_toolkit_versions(self, triggers_with_versions, mock_client):diff --git a/ts/docs/api/triggers.md b/ts/docs/api/triggers.mdindex 8e71c0b3e..7ca73af9e 100644--- a/ts/docs/api/triggers.md+++ b/ts/docs/api/triggers.md@@ -33,7 +33,7 @@ const triggers = await composio.triggers.listActive({### Create Trigger Instance-Create a new trigger instance for a specific user and trigger type. The trigger instance version is determined by the global `toolkitVersions` configuration set during Composio initialization (defaults to `'latest'`). If a connected account ID is not provided, the SDK will automatically use the first available connected account for the user and toolkit.+Create a new trigger instance for a specific user and trigger type. The trigger instance version is determined by the global `toolkitVersions` configuration set during Composio initialization (defaults to `'latest'`). If a connected account ID is not provided, the backend resolves the first active connection for the user and toolkit.**With Connected Account ID:**@@ -57,17 +57,17 @@ const trigger = await composio.triggers.create('default', 'GMAIL_NEW_GMAIL_MESSAuserId: 'me',interval: 60,},-}); // Will use the first available connected account+}); // The backend resolves the first active connection for the user and toolkit```-> **Note:** It's recommended to provide a `connectedAccountId` when you have multiple connected accounts for the same toolkit to ensure the trigger is created for the intended account. If not provided, the SDK will use the first available connected account and log a warning.+> **Note:** It's recommended to provide a `connectedAccountId` when you have multiple connected accounts for the same toolkit to ensure the trigger is created for the intended account. If not provided, the backend resolves the first active connection for the user and toolkit (ordered by most recently created).**Parameters:**- `userId` (string, required): The ID of the user to create the trigger instance for- `slug` (string, required): The slug of the trigger type to create- `body` (TriggerInstanceUpsertParams, optional): Configuration for the trigger instance- - `connectedAccountId` (string, optional): ID of the connected account to use. If not provided, will use the first available connected account for the user and toolkit+ - `connectedAccountId` (string, optional): ID of the connected account to use. If not provided, the backend resolves the first active connection for the user and toolkit- `triggerConfig` (object, optional): Trigger-specific configuration parameters**Returns:** Promise<TriggerInstanceUpsertResponse> - The created trigger instance with the following structure:@@ -86,9 +86,10 @@ const trigger = await composio.triggers.create('default', 'GMAIL_NEW_GMAIL_MESSA**Throws:**-- `ValidationError`: If the provided parameters are invalid+- `ValidationError`: If `userId` is empty or the provided parameters are invalid- `ComposioTriggerTypeNotFoundError`: If the trigger type with the given slug is not found-- `ComposioConnectedAccountNotFoundError`: If no connected account is found for the user, or if the specified connected account ID is not found++> **Note:** Connection resolution now happens on the backend. If no active connection exists for the user and toolkit — or a pinned `connectedAccountId` is invalid — the upsert call rejects with the backend error, not a client-side `ComposioConnectedAccountNotFoundError`.**Example with Specific Toolkit Version:**@@ -132,16 +133,13 @@ try {if (error instanceof ComposioTriggerTypeNotFoundError) {console.error('Trigger type not found:', error.message);// Handle invalid trigger type- } else if (error instanceof ComposioConnectedAccountNotFoundError) {- console.error('Connected account issue:', error.message);- // Handle missing or invalid connected account- // This can happen if:- // 1. No connected accounts exist for the user and toolkit- // 2. The specified connectedAccountId was not found} else if (error instanceof ValidationError) {console.error('Invalid parameters:', error.message);// Handle validation errors} else {+ // Connection problems now surface here as backend errors, for example when+ // no active connection exists for the user and toolkit, or the pinned+ // connectedAccountId is invalid.console.error('Unexpected error:', error);// Handle other errors}diff --git a/ts/packages/core/src/models/Triggers.ts b/ts/packages/core/src/models/Triggers.tsindex da29667b1..ccf5dd764 100644--- a/ts/packages/core/src/models/Triggers.ts+++ b/ts/packages/core/src/models/Triggers.ts@@ -328,6 +328,10 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, ubody?: TriggerInstanceUpsertParams,requestOptions?: ComposioRequestOptions): Promise<TriggerInstanceUpsertResponse> {+ if (!userId?.trim()) {+ throw new ValidationError(`A non-empty userId is required to create a trigger`);+ }+const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body ?? {});if (!parsedBody.success) {@@ -337,11 +341,11 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u}// Validate the trigger slug up-front so callers get a clear client-side- // error (the backend would also reject an unknown slug).+ // `ComposioTriggerTypeNotFoundError`. The Python SDK mirrors this behavior.try {await this.getType(slug, requestOptions);} catch (error) {- // for some reason, the triggers types list endpoint returns 400 for invalid user ids+ // The trigger types endpoint returns 400 (not 404) for an unknown slug.if (error instanceof APIError && (error.status === 400 || error.status === 404)) {throw new ComposioTriggerTypeNotFoundError(`Trigger type ${slug} not found`, {cause: error,@@ -351,23 +355,17 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u`Visit the toolkit page to see the available triggers`,],});- } else {- throw error;}+ throw error;}// 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: body?.connectedAccountId,+ // trigger's toolkit, mirroring tool execution. When 2FA is enabled and+ // `connected_account_id` is pinned, the backend validates that `user_id`+ // owns it.+ const upsertParams: ClientTriggerInstanceUpsertParams = {+ connected_account_id: parsedBody.data.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.tsindex 31627354f..1747653e4 100644--- a/ts/packages/core/test/models/triggers.test.ts+++ b/ts/packages/core/test/models/triggers.test.ts@@ -525,9 +525,22 @@ describe('Triggers', () => {},undefined);+ // `toEqual` treats a present-but-undefined key the same as an absent one,+ // so assert explicitly that the SDK does not invent a connected account id+ // (the client drops the undefined field on the wire, letting the backend+ // resolve it).+ const upsertParams = mockClient.triggerInstances.upsert.mock.calls[0][1];+ expect(upsertParams.connected_account_id).toBeUndefined();expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });});+ it('should throw a validation error when userId is empty', async () => {+ await expect(triggers.create('', slug, body)).rejects.toThrow(ValidationError);+ await expect(triggers.create(' ', slug, body)).rejects.toThrow(ValidationError);+ expect(mockClient.triggersTypes.retrieve).not.toHaveBeenCalled();+ expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();+ });+it('should throw validation error for invalid body parameters', async () => {const invalidBody = {connectedAccountId: 123, // should be string