@devries-cameron20 / composio Mirror · read-only / commits / a69c3edea
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, 19:45 UTC

fix(triggers): align create() user_id resolution across SDKs (#3723)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/3714 — addresses its code-review findings - restores TS/Python parity on slug validation: Python `create()` now validates the slug up-front and raises a new `TriggerTypeNotFound`, mirroring the TS `ComposioTriggerTypeNotFoundError` - switches both SDKs to the native `user_id` upsert field — TS drops the `& { user_id }` intersection and Python drops the `extra_body` shim (both pinned clients already expose the field) - treats a blank/whitespace `userId` (TS) or `user_id`/`connected_account_id` (Python) as missing instead of forwarding it to the backend - documents the error-contract change (`create()` no longer throws `ComposioConnectedAccountNotFoundError` — that case now surfaces from the backend) in the changeset and `ts/docs/api/triggers.md`, and bumps the changeset from `patch` to `minor` - adds Python tests for the 2FA (both-provided) path, unknown-slug, and blank `userId`; tightens the TS auto-resolve assertion and adds an empty-`userId` case ## ⚠️ Release gating Since #3714, `triggers.create()` (both SDKs) relies on the backend resolving the trigger connection from `user_id` on upsert ([ComposioHQ/platform#10932](https://github.com/ComposioHQ/platform/pull/10932)). There is **no client-side fallback** — reintroducing one would undo #3714's intent, so this is a release-sequencing requirement, not a code change here. - Do not release `@composio/core` or the Python SDK until #10932 is live in all regions. - Self-hosted / on-prem deployments must be on a backend version that includes #10932. ## Review findings addressed | # | Finding | Resolution | |---|---------|------------| | P1-1 | Coupled to unreleased backend, no fallback | Documented dependency in changeset; flagged release-gating above (no fallback by design) | | P2-2 | Cross-SDK parity on slug validation | Kept `getType` in both; added Python `TriggerTypeNotFound` mirroring TS | | P2-3 | `user_id` bridge redundant in both SDKs | TS uses native field directly; Python uses `user_id=` kwarg | | P2-4 | Error-contract change shipped silently | Documented in changeset + docs `Throws` section; `minor` bump | | P2-5 | Python missing 2FA (both-provided) test | Added `test_create_with_user_id_and_connected_account_id` | | P3 6–13 | Cleanups | undefined-assertion, `none_to_omit`, docstring, `parsedBody.data`, redundant `else`, stale comments, blank-string guard | ## Verification - TS: `vitest` 59 passed, `typecheck` clean, `eslint`/`prettier` clean - Python: `pytest tests/test_triggers.py` 69 passed, `nox -s chk` (ruff + mypy) clean

Alberto Schiabel committed Jul 2, 2026 at 11:40 UTC a69c3edea3179cc5bcff22a6a0ebf6f547984ffe
7 files changed +141 -50
.changeset/triggers-create-user-id-resolution.md
+6 -2
@@ -1,5 +1,9 @@
1 ---
2 -"@composio/core": patch
2 +"@composio/core": minor
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.
5 +`triggers.create` now resolves the connection from `user_id` on the backend instead of client-side.
6 +
7 +- 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.
8 +- **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.
9 +- **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.
python/composio/core/models/triggers.py
+29 -14
@@ -14,7 +14,7 @@ from enum import Enum
14 from unittest import mock
15
16 import typing_extensions as te
17 -from composio_client import Omit, omit
17 +from composio_client import APIStatusError, Omit, omit
18 from composio_client.types import TriggersTypeRetrieveResponse
19 from pysher import Pusher
20 from pysher.channel import Channel as PusherChannel
@@ -1130,32 +1130,47 @@ class Triggers(Resource):
1130 Create a trigger instance
1131
1132 :param slug: The slug of the trigger
1133 - :param connected_account_id: The ID of the connected account
1133 + :param user_id: The ID of the user that owns the connected account. When
1134 + ``connected_account_id`` is omitted, the backend resolves the first
1135 + active connection for this user and the trigger's toolkit.
1136 + :param connected_account_id: The ID of the connected account to pin
1137 :param trigger_config: The configuration of the trigger
1138 :return: The trigger instance
1139 """
1140 + # Treat blank strings as missing so an empty or whitespace-only
1141 + # `user_id` / `connected_account_id` does not slip past the guard below
1142 + # or reach the backend (parity with the TypeScript SDK's `userId` check).
1143 + if isinstance(user_id, str) and not user_id.strip():
1144 + user_id = None
1145 + if isinstance(connected_account_id, str) and not connected_account_id.strip():
1146 + connected_account_id = None
1147 +
1148 if user_id is None and connected_account_id is None:
1149 raise exceptions.InvalidParams(
1150 "please provide valid `connected_account_id` or `user_id`"
1151 )
1152
1153 + # Validate the trigger slug up-front so callers get a clear
1154 + # `TriggerTypeNotFound` (parity with the TypeScript SDK).
1155 + try:
1156 + self.get_type(slug=slug)
1157 + except APIStatusError as error:
1158 + if error.status_code in (400, 404):
1159 + raise exceptions.TriggerTypeNotFound(
1160 + f"Trigger type {slug} not found"
1161 + ) from error
1162 + raise
1163 +
1164 # Pass user_id straight through: when connected_account_id is omitted the
1165 # 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.
1166 + # trigger's toolkit (parity with tool execution). When 2FA is enabled and
1167 + # connected_account_id is pinned, the backend validates that user_id owns it.
1168 return self._client.trigger_instances.upsert(
1169 slug=slug,
1151 - connected_account_id=(
1152 - connected_account_id if connected_account_id is not None else omit
1153 - ),
1170 + connected_account_id=none_to_omit(connected_account_id),
1171 toolkit_versions=self._toolkit_versions,
1155 - body_trigger_config_1=(
1156 - trigger_config if trigger_config is not None else omit
1157 - ),
1158 - extra_body=({"user_id": user_id} if user_id is not None else {}),
1172 + body_trigger_config_1=none_to_omit(trigger_config),
1173 + user_id=none_to_omit(user_id),
1174 )
1175
1176 def subscribe(self, timeout: float = 15.0) -> TriggerSubscription:
python/composio/exceptions.py
+9
@@ -257,6 +257,15 @@ class WebhookPayloadError(TriggerError):
257 pass
258
259
260 +class TriggerTypeNotFound(TriggerError, NotFoundError):
261 + """Raised when a trigger type cannot be found for the given slug.
262 +
263 + Mirrors the TypeScript SDK's ``ComposioTriggerTypeNotFoundError``.
264 + """
265 +
266 + pass
267 +
268 +
269 class ActionError(ToolkitError):
270 pass
271
python/tests/test_triggers.py
+62 -8
@@ -8,8 +8,9 @@ import time
8 from datetime import datetime, timezone
9 from unittest.mock import Mock, patch
10
11 +import httpx
12 import pytest
12 -from composio_client import omit
13 +from composio_client import NotFoundError, omit
14
15 from composio import exceptions
16 from composio.core.models.triggers import (
@@ -298,15 +299,15 @@ class TestTriggers:
299 "webhook_url": "https://example.com/webhook"
300 }
301 assert call_kwargs["toolkit_versions"] is None
301 - # No user_id supplied → empty extra_body.
302 - assert call_kwargs["extra_body"] == {}
302 + # No user_id supplied → omitted from the request (native kwarg, not extra_body).
303 + assert call_kwargs["user_id"] is omit
304 assert result == mock_response
305
306 def test_create_with_user_id(self, triggers, mock_client):
307 """Test create trigger with user_id only.
308
309 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 + it straight through and no longer lists connected accounts.
311 """
312 mock_response = Mock()
313 mock_response.trigger_id = "trigger-123"
@@ -318,22 +319,75 @@ class TestTriggers:
319 trigger_config={"webhook_url": "https://example.com/webhook"},
320 )
321
321 - # The SDK no longer makes an extra round-trip to find a connection.
322 + # The SDK no longer lists connected accounts to resolve the connection,
323 + # but it still validates the slug up-front (parity with the TS SDK).
324 mock_client.connected_accounts.list.assert_not_called()
323 - mock_client.triggers_types.retrieve.assert_not_called()
325 + mock_client.triggers_types.retrieve.assert_called_once()
326
327 mock_client.trigger_instances.upsert.assert_called_once()
328 call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs
329 assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
328 - # No explicit connection pinned → omitted; user_id rides in extra_body.
330 + # No explicit connection pinned → omitted; user_id is sent as a native kwarg.
331 assert call_kwargs["connected_account_id"] is omit
330 - assert call_kwargs["extra_body"] == {"user_id": "user-123"}
332 + assert call_kwargs["user_id"] == "user-123"
333 assert call_kwargs["body_trigger_config_1"] == {
334 "webhook_url": "https://example.com/webhook"
335 }
336 assert call_kwargs["toolkit_versions"] is None
337 assert result == mock_response
338
339 + def test_create_with_user_id_and_connected_account_id(self, triggers, mock_client):
340 + """Test create trigger with both user_id and a pinned connected_account_id.
341 +
342 + When a connection is pinned and 2FA is enabled, the backend validates the
343 + connection is owned by ``user_id``. Both values are forwarded natively
344 + (no ``extra_body``). Mirrors the TS ``create`` test.
345 + """
346 + mock_response = Mock()
347 + mock_response.trigger_id = "trigger-123"
348 + mock_client.trigger_instances.upsert.return_value = mock_response
349 +
350 + result = triggers.create(
351 + slug="GITHUB_COMMIT_EVENT",
352 + user_id="user-123",
353 + connected_account_id="conn-123",
354 + trigger_config={"webhook_url": "https://example.com/webhook"},
355 + )
356 +
357 + mock_client.connected_accounts.list.assert_not_called()
358 + mock_client.trigger_instances.upsert.assert_called_once()
359 + call_kwargs = mock_client.trigger_instances.upsert.call_args.kwargs
360 + assert call_kwargs["slug"] == "GITHUB_COMMIT_EVENT"
361 + assert call_kwargs["connected_account_id"] == "conn-123"
362 + assert call_kwargs["user_id"] == "user-123"
363 + assert call_kwargs["body_trigger_config_1"] == {
364 + "webhook_url": "https://example.com/webhook"
365 + }
366 + assert result == mock_response
367 +
368 + def test_create_raises_trigger_type_not_found_for_unknown_slug(
369 + self, triggers, mock_client
370 + ):
371 + """An unknown slug surfaces as TriggerTypeNotFound (parity with the TS SDK)."""
372 + request = httpx.Request("GET", "https://backend.composio.dev")
373 + response = httpx.Response(404, request=request)
374 + mock_client.triggers_types.retrieve.side_effect = NotFoundError(
375 + "not found", response=response, body=None
376 + )
377 +
378 + with pytest.raises(exceptions.TriggerTypeNotFound):
379 + triggers.create(slug="UNKNOWN_TRIGGER", user_id="user-123")
380 +
381 + mock_client.trigger_instances.upsert.assert_not_called()
382 +
383 + def test_create_treats_blank_user_id_as_missing(self, triggers, mock_client):
384 + """A blank user_id is rejected like a missing one, before any request."""
385 + with pytest.raises(exceptions.InvalidParams):
386 + triggers.create(slug="GITHUB_COMMIT_EVENT", user_id=" ")
387 +
388 + mock_client.triggers_types.retrieve.assert_not_called()
389 + mock_client.trigger_instances.upsert.assert_not_called()
390 +
391 def test_create_with_custom_toolkit_versions(
392 self, triggers_with_versions, mock_client
393 ):
ts/docs/api/triggers.md
+10 -12
@@ -33,7 +33,7 @@ const triggers = await composio.triggers.listActive({
33
34 ### Create Trigger Instance
35
36 -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.
36 +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.
37
38 **With Connected Account ID:**
39
@@ -57,17 +57,17 @@ const trigger = await composio.triggers.create('default', 'GMAIL_NEW_GMAIL_MESSA
57 userId: 'me',
58 interval: 60,
59 },
60 -}); // Will use the first available connected account
60 +}); // The backend resolves the first active connection for the user and toolkit
61 ```
62
63 -> **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.
63 +> **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).
64
65 **Parameters:**
66
67 - `userId` (string, required): The ID of the user to create the trigger instance for
68 - `slug` (string, required): The slug of the trigger type to create
69 - `body` (TriggerInstanceUpsertParams, optional): Configuration for the trigger instance
70 - - `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
70 + - `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
71 - `triggerConfig` (object, optional): Trigger-specific configuration parameters
72
73 **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
86
87 **Throws:**
88
89 -- `ValidationError`: If the provided parameters are invalid
89 +- `ValidationError`: If `userId` is empty or the provided parameters are invalid
90 - `ComposioTriggerTypeNotFoundError`: If the trigger type with the given slug is not found
91 -- `ComposioConnectedAccountNotFoundError`: If no connected account is found for the user, or if the specified connected account ID is not found
91 +
92 +> **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`.
93
94 **Example with Specific Toolkit Version:**
95
@@ -132,16 +133,13 @@ try {
133 if (error instanceof ComposioTriggerTypeNotFoundError) {
134 console.error('Trigger type not found:', error.message);
135 // Handle invalid trigger type
135 - } else if (error instanceof ComposioConnectedAccountNotFoundError) {
136 - console.error('Connected account issue:', error.message);
137 - // Handle missing or invalid connected account
138 - // This can happen if:
139 - // 1. No connected accounts exist for the user and toolkit
140 - // 2. The specified connectedAccountId was not found
136 } else if (error instanceof ValidationError) {
137 console.error('Invalid parameters:', error.message);
138 // Handle validation errors
139 } else {
140 + // Connection problems now surface here as backend errors, for example when
141 + // no active connection exists for the user and toolkit, or the pinned
142 + // connectedAccountId is invalid.
143 console.error('Unexpected error:', error);
144 // Handle other errors
145 }
ts/packages/core/src/models/Triggers.ts
+12 -14
@@ -328,6 +328,10 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
328 body?: TriggerInstanceUpsertParams,
329 requestOptions?: ComposioRequestOptions
330 ): Promise<TriggerInstanceUpsertResponse> {
331 + if (!userId?.trim()) {
332 + throw new ValidationError(`A non-empty userId is required to create a trigger`);
333 + }
334 +
335 const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body ?? {});
336
337 if (!parsedBody.success) {
@@ -337,11 +341,11 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
341 }
342
343 // Validate the trigger slug up-front so callers get a clear client-side
340 - // error (the backend would also reject an unknown slug).
344 + // `ComposioTriggerTypeNotFoundError`. The Python SDK mirrors this behavior.
345 try {
346 await this.getType(slug, requestOptions);
347 } catch (error) {
344 - // for some reason, the triggers types list endpoint returns 400 for invalid user ids
348 + // The trigger types endpoint returns 400 (not 404) for an unknown slug.
349 if (error instanceof APIError && (error.status === 400 || error.status === 404)) {
350 throw new ComposioTriggerTypeNotFoundError(`Trigger type ${slug} not found`, {
351 cause: error,
@@ -351,23 +355,17 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
355 `Visit the toolkit page to see the available triggers`,
356 ],
357 });
354 - } else {
355 - throw error;
358 }
359 + throw error;
360 }
361
362 // Pass `user_id` straight through: when `connected_account_id` is omitted the
363 // 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 - } = {
370 - connected_account_id: body?.connectedAccountId,
364 + // trigger's toolkit, mirroring tool execution. When 2FA is enabled and
365 + // `connected_account_id` is pinned, the backend validates that `user_id`
366 + // owns it.
367 + const upsertParams: ClientTriggerInstanceUpsertParams = {
368 + connected_account_id: parsedBody.data.connectedAccountId,
369 trigger_config: parsedBody.data.triggerConfig,
370 toolkit_versions: this.toolkitVersions,
371 user_id: userId,
ts/packages/core/test/models/triggers.test.ts
+13
@@ -525,9 +525,22 @@ describe('Triggers', () => {
525 },
526 undefined
527 );
528 + // `toEqual` treats a present-but-undefined key the same as an absent one,
529 + // so assert explicitly that the SDK does not invent a connected account id
530 + // (the client drops the undefined field on the wire, letting the backend
531 + // resolve it).
532 + const upsertParams = mockClient.triggerInstances.upsert.mock.calls[0][1];
533 + expect(upsertParams.connected_account_id).toBeUndefined();
534 expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
535 });
536
537 + it('should throw a validation error when userId is empty', async () => {
538 + await expect(triggers.create('', slug, body)).rejects.toThrow(ValidationError);
539 + await expect(triggers.create(' ', slug, body)).rejects.toThrow(ValidationError);
540 + expect(mockClient.triggersTypes.retrieve).not.toHaveBeenCalled();
541 + expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
542 + });
543 +
544 it('should throw validation error for invalid body parameters', async () => {
545 const invalidBody = {
546 connectedAccountId: 123, // should be string