@devries-cameron20 / composio Mirror · read-only / commits / 5d075823e
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, 11:00 UTC

fix(sdk): stop sending expected_config_version by default on session update (#4603)

This PR: - makes `session.update()` work again with default options in both SDKs. Since `@composio/core` 0.20.0 and the matching Python release, every call sent the session's last observed version as `expected_config_version`, and the live API rejects it with a 400 (`Error in payload: Unrecognized key(s) in object: 'expected_config_version'`) - makes the precondition opt-in: pass `expectedConfigVersion` / `expected_config_version` (for example the session's `configVersion`) to make an update conditional; omitting it, or passing `false`, sends no precondition (last writer wins) - keeps the 409 handling, the no-retry rule and the conflict messages unchanged for callers who opt in - adds live regression tests that send a default `session.update()` to the real API: a Node e2e suite (`ts/e2e-tests/runtimes/node/tool-router-session-update`) and a Python integration test (`python/composio/integration_test/test_tool_router_session_update.py`). Mocked unit tests could not catch this bug because they never reach the API's payload validation - updates the "Concurrent updates" docs, JSDoc/docstrings and the generated references; adds a patch changeset for `@composio/core` ## Testing - `pnpm --filter @composio/core test` (1512 passed) and `pnpm --filter @composio/core typecheck` - `pytest tests/test_tool_router.py` (127 passed); ruff with `config/ruff.toml` is clean; mypy reports nothing in the touched files - Tests now assert that the default sends no precondition; the conflict and two-handle tests pass the version explicitly - Regression tests: both fail on `next` with the 400 above and pass with this fix; the Node suite also passes in the Docker e2e harness (6/6) - Live, against a real project: default `update()` succeeds in TypeScript (version 1 -> 2) and Python; an explicit `expectedConfigVersion` still gets the 400 above until the API supports the field Out of scope, found during the same live run: the API also rejects `toolkits: null` on update (`Error in payload.toolkits: Invalid …`), which the SDK documents as "remove the stored policy". ## Why this shipped #4579 made the precondition the default while the backend support (ComposioHQ/platform#13157) and the client regeneration (ComposioHQ/composio-client#59) were still open. The pinned client does not type the field, so the SDK sent it through a widened body cast (TS) and `extra_body` (Python), and only mocked tests covered it. CI e2e runs against staging (`COMPOSIO_BASE_URL_STAGING`), so a production-only mismatch still needs a nightly run against production; that is not part of this PR.

Alberto Schiabel committed Sep 23, 2026 at 21:38 UTC 5d075823e6bc559a28897f3d13048b5cbd3a0c80
20 files changed +363 -91
.changeset/session-update-no-default-precondition.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +`session.update()` no longer sends `expected_config_version` by default. Since 0.20.0 it sent the session's last observed `configVersion` on every call, and the API rejects that field with a 400 (`Unrecognized key(s) in object: 'expected_config_version'`), so every default `update()` failed. The default is now last writer wins. Pass `expectedConfigVersion` (for example `session.configVersion`) to make an update conditional where the API supports it; `expectedConfigVersion: false` is the same as omitting it.
docs/content/docs/configuring-sessions.mdx
+23 -7
@@ -952,9 +952,13 @@ await session.update({
952
953 ### Concurrent updates
954
955 -Every session response carries a config version (`session.configVersion` in TypeScript, `session.config_version` in Python, `config_version` on the wire). `session.update()` sends the version the session object last observed as the `expected_config_version` precondition, and the API applies the update only when the stored version still matches. Otherwise it answers `409` and writes nothing: no config change, no history entry, no cache update. The SDK never retries that request, so a conflict is reported exactly once.
955 +Every session response carries a config version (`session.configVersion` in TypeScript, `session.config_version` in Python, `config_version` on the wire). By default, `session.update()` sends no precondition, so the last writer wins. To make an update conditional, pass the version you read as `expectedConfigVersion` (`expected_config_version` in Python). The API then applies the update only when the stored version still matches. Otherwise it answers `409` and writes nothing: no config change, no history entry, no cache update. The SDK never retries that request, so a conflict is reported exactly once.
956
957 -The SDK raises `ComposioSessionConfigConflictError` (TypeScript) or `SessionConfigConflictError` (Python) and leaves the session object as it was. Re-read the session with `sessions.use()`, reapply your change on top of the fresh config, and retry:
957 +<Callout type="info">
958 +The API must support `expected_config_version`. If it doesn't, it rejects a conditional update with a `400`.
959 +</Callout>
960 +
961 +On a conflict, the SDK raises `ComposioSessionConfigConflictError` (TypeScript) or `SessionConfigConflictError` (Python) and leaves the session object as it was. Re-read the session with `sessions.use()`, reapply your change on top of the fresh config, and retry:
962
963 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
964 <Tab value="Python">
@@ -964,11 +968,17 @@ from composio.exceptions import SessionConfigConflictError
968 session = composio.sessions.use("session_id")
969
970 try:
967 - session.update(toolkits={"enable": ["gmail", "github"]})
971 + session.update(
972 + toolkits={"enable": ["gmail", "github"]},
973 + expected_config_version=session.config_version,
974 + )
975 except SessionConfigConflictError:
976 # Another client changed the session first. Nothing was written.
977 session = composio.sessions.use("session_id")
971 - session.update(toolkits={"enable": ["gmail", "github"]})
978 + session.update(
979 + toolkits={"enable": ["gmail", "github"]},
980 + expected_config_version=session.config_version,
981 + )
982 ```
983 </Tab>
984 <Tab value="TypeScript">
@@ -980,18 +990,24 @@ const composio = new Composio({ apiKey: 'your_api_key' });
990 let session = await composio.sessions.use("session_id");
991
992 try {
983 - await session.update({ toolkits: { enable: ["gmail", "github"] } });
993 + await session.update({
994 + toolkits: { enable: ["gmail", "github"] },
995 + expectedConfigVersion: session.configVersion,
996 + });
997 } catch (error) {
998 if (!(error instanceof ComposioSessionConfigConflictError)) throw error;
999 // Another client changed the session first. Nothing was written.
1000 session = await composio.sessions.use("session_id");
988 - await session.update({ toolkits: { enable: ["gmail", "github"] } });
1001 + await session.update({
1002 + toolkits: { enable: ["gmail", "github"] },
1003 + expectedConfigVersion: session.configVersion,
1004 + });
1005 }
1006 ```
1007 </Tab>
1008 </Tabs>
1009
994 -Pass `expectedConfigVersion` (`expected_config_version` in Python) to send a version you read elsewhere, for example one stored with a queued job. Pass `expectedConfigVersion: false` (`expected_config_version=False`) on a call that should apply regardless: the last writer then wins. The API still commits only a fully validated configuration, so a losing update never leaves a half-applied session behind.
1010 +You can also pass a version you read elsewhere, for example one stored with a queued job. `expectedConfigVersion: false` (`expected_config_version=False`) is the same as omitting it. The API still commits only a fully validated configuration, so a losing update never leaves a half-applied session behind.
1011
1012 Raw HTTP callers set `expected_config_version` in the `PATCH` body themselves; without it the last writer wins.
1013
docs/content/reference/sdk-reference/python/session.mdx
+1 -1
@@ -185,7 +185,7 @@ def proxy_execute(toolkit: str, endpoint: str, method: Literal['GET', 'POST', 'P
185
186 ### update()
187
188 -Partially update the session configuration. Only the fields provided are changed; omitted fields are preserved. For each policy block `None` removes the stored override (which can increase access: `toolkits=None` restores the unrestricted default, while `toolkits={"enable": []}` denies every app toolkit and is sent as-is). Supplied `tools`, `auth_configs` and `connected_accounts` maps replace the stored map entirely. Inside `manage_connections`, `callback_url=None` removes only the stored callback URL. The request carries the `config_version` this object last observed as the `expected_config_version` precondition, so a concurrent change raises `SessionConfigConflictError` (HTTP 409) instead of being overwritten. Pass an `int` to send another version, or `expected_config_version=False` to send no precondition (last writer wins). The PATCH is never retried by the transport, so a 409 is reported exactly once. On conflict this object stays unchanged: re-fetch the session with `composio.sessions.use(session_id)` and retry against the fresh `config_version`. `config`, `config_version` and `preload` are refreshed in place only after a successful response, and the updated `config` is returned. `workbench` is a backwards-compatible alias for `sandbox`. Prefer `sandbox` in new code. All other parameters use the same types as the generated `client.tool_router.session.patch()` method.
188 +Partially update the session configuration. Only the fields provided are changed; omitted fields are preserved. For each policy block `None` removes the stored override (which can increase access: `toolkits=None` restores the unrestricted default, while `toolkits={"enable": []}` denies every app toolkit and is sent as-is). Supplied `tools`, `auth_configs` and `connected_accounts` maps replace the stored map entirely. Inside `manage_connections`, `callback_url=None` removes only the stored callback URL. By default the request carries no precondition: the last writer wins. Pass `expected_config_version` (for example this object's `config_version`) to make the update conditional: the API then applies it only when the stored version still matches, and a concurrent change raises `SessionConfigConflictError` (HTTP 409) instead of being overwritten. The API must support the `expected_config_version` field; otherwise it rejects the request with a 400. `expected_config_version=False` is the same as omitting it. The PATCH is never retried by the transport, so a 409 is reported exactly once. On conflict this object stays unchanged: re-fetch the session with `composio.sessions.use(session_id)` and retry against the fresh `config_version`. `config`, `config_version` and `preload` are refreshed in place only after a successful response, and the updated `config` is returned. `workbench` is a backwards-compatible alias for `sandbox`. Prefer `sandbox` in new code. All other parameters use the same types as the generated `client.tool_router.session.patch()` method.
189
190 ```python
191 def update(toolkits: Union[session_patch_params.Toolkits | None, 'Omit'] = ..., tools: Union[Dict[str, session_patch_params.Tools | None], 'Omit'] = ..., tags: Union[session_patch_params.Tags | None, 'Omit'] = ..., auth_configs: Union[Dict[str, str | None], 'Omit'] = ..., connected_accounts: Union[Dict[str, SequenceNotStr[str | None]], 'Omit'] = ..., manage_connections: Union[session_patch_params.ManageConnections | None, ToolRouterUpdateManageConnectionsConfig | None, 'Omit'] = ..., sandbox: Union[session_patch_params.Workbench | None, 'Omit'] = ..., workbench: Union[session_patch_params.Workbench | None, 'Omit'] = ..., multi_account: Union[session_patch_params.MultiAccount | None, ToolRouterUpdateMultiAccountConfig | None, 'Omit'] = ..., preload: Union[session_patch_params.Preload | None, 'Omit'] = ..., search: Union[session_patch_params.Search | None, 'Omit'] = ..., execute: Union[session_patch_params.Execute | None, 'Omit'] = ..., experimental: Union[session_patch_params.Experimental | None, ToolRouterUpdateExperimentalConfig | None, 'Omit'] = ..., expected_config_version: Union[int, None, Literal[False]] = ...) -> ToolRouterSessionConfig
docs/content/reference/sdk-reference/typescript/session.mdx
+11 -9
@@ -8,7 +8,7 @@ description: "A Composio session — the object returned by `composio.sessions.c
8 | Name | Type | Description |
9 |------|------|-------------|
10 | `config` | `Config` | Server-side session configuration (toolkit/tool allowlists, tags, preload, sandbox, manage_connections) as returned by the API. Refreshed in place by `update()`. |
11 -| `configVersion` | `number` | Version of the server-side configuration this object last observed. Refreshed in place by `update()`, which sends it as the `expected_config_version` precondition by default. |
11 +| `configVersion` | `number` | Version of the server-side configuration this object last observed. Refreshed in place by `update()`. Pass it as `expectedConfigVersion` to make an update conditional. |
12 | `experimental` | `SessionExperimental` | |
13 | `mcp` | `\{ headers?: Record<string, string>; type: 'http' \| 'sse'; url: string \}` | Hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`). Exists on every session at runtime, but only surfaced in the type when the session is created with `\{ mcp: true \}` (which returns `Session`); the default `SessionWithoutMcp` omits `mcp`, so MCP is an explicit opt-in. See https://docs.composio.dev/docs/sessions-via-mcp |
14 | `preload` | `\{ tools: string[] \| 'all' \}` | |
@@ -314,15 +314,17 @@ access: `toolkits: null` restores the unrestricted default, while
314 map entirely. `manageConnections.callbackUrl: null` removes only the
315 stored callback URL.
316
317 -The request carries the `configVersion` this object last observed as the
318 -`expected_config_version` precondition, so a concurrent change surfaces as
317 +By default the request carries no precondition: the last writer wins.
318 +Pass `expectedConfigVersion` (for example `session.configVersion`) to make
319 +the update conditional: the API then applies it only when the stored
320 +version still matches, and a concurrent change surfaces as
321 ComposioSessionConfigConflictError (HTTP 409) instead of being
320 -overwritten. Pass `expectedConfigVersion` to send another version, or
321 -`expectedConfigVersion: false` to send no precondition (last writer
322 -wins). The PATCH is never retried by the transport, so a 409 is reported
323 -exactly once. On conflict this object is left unchanged: re-fetch the
324 -session with `sessions.use(sessionId)` and retry against the fresh
325 -`configVersion`.
322 +overwritten. The API must support the `expected_config_version` field;
323 +otherwise it rejects the request with a 400. `expectedConfigVersion: false`
324 +is the same as omitting it. The PATCH is never retried by the transport,
325 +so a 409 is reported exactly once. On conflict this object is left
326 +unchanged: re-fetch the session with `sessions.use(sessionId)` and retry
327 +against the fresh `configVersion`.
328
329 `config`, `configVersion`, `preload`, `sandbox` and `warnings` are
330 refreshed in place only after a successful response, and the updated
pnpm-lock.yaml
+10
@@ -573,6 +573,16 @@ importers:
573 specifier: workspace:*
574 version: link:../../../_utils
575
576 + ts/e2e-tests/runtimes/node/tool-router-session-update:
577 + dependencies:
578 + '@composio/core':
579 + specifier: workspace:*
580 + version: link:../../../../packages/core
581 + devDependencies:
582 + '@e2e-tests/utils':
583 + specifier: workspace:*
584 + version: link:../../../_utils
585 +
586 ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext:
587 devDependencies:
588 '@composio/cli':
python/composio/core/models/tool_router_session.py
+15 -14
@@ -183,8 +183,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
183 #: Experimental capabilities available on this session.
184 experimental: "ToolRouterSessionExperimental"
185 #: Version of the server-side configuration this object last observed.
186 - #: Refreshed in place by :meth:`update`, which sends it as the
187 - #: ``expected_config_version`` precondition by default.
186 + #: Refreshed in place by :meth:`update`. Pass it as ``expected_config_version``
187 + #: to make an update conditional.
188 config_version: t.Optional[int]
189
190 def __init__(
@@ -1022,15 +1022,18 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1022 maps replace the stored map entirely. Inside ``manage_connections``,
1023 ``callback_url=None`` removes only the stored callback URL.
1024
1025 - The request carries the ``config_version`` this object last observed
1026 - as the ``expected_config_version`` precondition, so a concurrent change
1027 - raises :class:`~composio.exceptions.SessionConfigConflictError`
1028 - (HTTP 409) instead of being overwritten. Pass an ``int`` to send another
1029 - version, or ``expected_config_version=False`` to send no precondition
1030 - (last writer wins). The PATCH is never retried by the transport, so a
1031 - 409 is reported exactly once. On conflict this object stays unchanged:
1032 - re-fetch the session with ``composio.sessions.use(session_id)`` and
1033 - retry against the fresh ``config_version``.
1025 + By default the request carries no precondition: the last writer wins.
1026 + Pass ``expected_config_version`` (for example this object's
1027 + ``config_version``) to make the update conditional: the API then
1028 + applies it only when the stored version still matches, and a concurrent
1029 + change raises :class:`~composio.exceptions.SessionConfigConflictError`
1030 + (HTTP 409) instead of being overwritten. The API must support the
1031 + ``expected_config_version`` field; otherwise it rejects the request with
1032 + a 400. ``expected_config_version=False`` is the same as omitting it.
1033 + The PATCH is never retried by the transport, so a 409 is reported
1034 + exactly once. On conflict this object stays unchanged: re-fetch the
1035 + session with ``composio.sessions.use(session_id)`` and retry against
1036 + the fresh ``config_version``.
1037
1038 ``config``, ``config_version`` and ``preload`` are refreshed in place
1039 only after a successful response, and the updated ``config`` is
@@ -1051,10 +1054,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1054 )
1055
1056 precondition: t.Union[int, "Omit"]
1054 - if expected_config_version is False:
1057 + if expected_config_version is None or expected_config_version is False:
1058 precondition = omit
1056 - elif expected_config_version is None:
1057 - precondition = omit if self.config_version is None else self.config_version
1059 elif isinstance(expected_config_version, bool) or expected_config_version < 1:
1060 raise exceptions.InvalidParams(
1061 "`expected_config_version` must be a positive integer, or False to "
python/composio/exceptions.py
+2 -3
@@ -360,9 +360,8 @@ class MCPDestinationError(ComposioClientError):
360
361 class SessionConfigConflictError(ComposioClientError):
362 """Raised when a session update is rejected with HTTP 409 because the
363 - session configuration changed since it was last read: the
364 - ``expected_config_version`` precondition (the session's last observed
365 - ``config_version`` by default) is stale.
363 + session configuration changed since it was last read, for example when an
364 + ``expected_config_version`` precondition passed to ``update()`` is stale.
365
366 The local session object is left as it was before the call. Re-fetch the
367 session with ``composio.sessions.use(session_id)`` and retry the update
python/composio/integration_test/README.md
+1
@@ -28,6 +28,7 @@ uv run pytest composio/integration_test/ -v
28
29 - **`test_mcp.py`** - MCP (Model Context Protocol) functionality tests
30 - **`test_tool_router.py`** - ToolRouter experimental feature tests
31 +- **`test_tool_router_session_update.py`** - `session.update()` with default options against the live API
32
33 ## Requirements
34
python/composio/integration_test/test_tool_router_session_update.py new
+35
@@ -0,0 +1,35 @@
1 +"""
2 +Live regression test for ``session.update()`` with default options.
3 +
4 +``composio`` sent ``expected_config_version`` on every ``update()`` call, and
5 +the API rejected that field with a 400, so no default update could succeed.
6 +Unit tests mock the transport and cannot catch a payload the API refuses, so
7 +this test sends a default update to the real API.
8 +"""
9 +
10 +import time
11 +
12 +import pytest
13 +
14 +
15 +@pytest.mark.integration
16 +def test_default_update_applies_and_persists(composio_client):
17 + session = composio_client.sessions.create(
18 + user_id=f"pytest-session-update-{int(time.time())}",
19 + toolkits=["github", "gmail"],
20 + )
21 + try:
22 + version_before = session.config_version
23 + assert isinstance(version_before, int)
24 +
25 + # Default options: no precondition, so this must succeed on any project.
26 + config = session.update(toolkits={"enable": ["github"]})
27 +
28 + assert config.toolkits.enabled == ["github"]
29 + assert session.config_version > version_before
30 +
31 + reread = composio_client.sessions.use(session_id=session.session_id)
32 + assert reread.config.toolkits.enabled == ["github"]
33 + assert reread.config_version == session.config_version
34 + finally:
35 + composio_client.sessions.delete(session.session_id)
python/tests/test_tool_router.py
+21 -10
@@ -2520,13 +2520,13 @@ class TestSessionUpdateContract:
2520 def test_session_tracks_config_version(self, session):
2521 assert session.config_version == 7
2522
2523 - def test_update_sends_the_observed_version_by_default_without_retries(
2523 + def test_update_sends_no_precondition_by_default_without_retries(
2524 self, session, mock_client
2525 ):
2526 session.update(toolkits={"enable": ["gmail"]})
2527
2528 kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2529 - assert kwargs["extra_body"] == {"expected_config_version": 7}
2529 + assert kwargs["extra_body"] is None
2530 assert kwargs["request_options"] == {"max_retries": 0}
2531 assert session.config_version == 8
2532 assert session.preload.tools == ["SLACK_SEND_MESSAGE"]
@@ -2596,7 +2596,10 @@ class TestSessionUpdateContract:
2596 mock_client.tool_router.session.patch.side_effect = self._conflict()
2597
2598 with pytest.raises(SessionConfigConflictError) as excinfo:
2599 - session.update(toolkits={"enable": ["gmail"]})
2599 + session.update(
2600 + toolkits={"enable": ["gmail"]},
2601 + expected_config_version=session.config_version,
2602 + )
2603
2604 assert "re-fetch" in str(excinfo.value).lower()
2605 assert "retry" in str(excinfo.value).lower()
@@ -2606,16 +2609,15 @@ class TestSessionUpdateContract:
2609 assert session.preload is preload_before
2610 assert session.config_version == 7
2611
2612 + @pytest.mark.parametrize("opt_out", [{}, {"expected_config_version": False}])
2613 def test_update_conflict_without_precondition_reports_in_flight_change(
2610 - self, session, mock_client
2614 + self, session, mock_client, opt_out
2615 ):
2616 config_before = session.config
2617 mock_client.tool_router.session.patch.side_effect = self._conflict()
2618
2619 with pytest.raises(SessionConfigConflictError) as excinfo:
2616 - session.update(
2617 - toolkits={"enable": ["gmail"]}, expected_config_version=False
2618 - )
2620 + session.update(toolkits={"enable": ["gmail"]}, **opt_out)
2621
2622 message = str(excinfo.value)
2623 assert "changed while this update was in flight" in message
@@ -2630,7 +2632,10 @@ class TestSessionUpdateContract:
2632 second = tool_router.use(session_id="session_123")
2633 assert first.config_version == second.config_version == 7
2634
2633 - first.update(toolkits={"enable": ["gmail"]})
2635 + first.update(
2636 + toolkits={"enable": ["gmail"]},
2637 + expected_config_version=first.config_version,
2638 + )
2639 assert mock_client.tool_router.session.patch.call_args.kwargs["extra_body"] == {
2640 "expected_config_version": 7
2641 }
@@ -2638,7 +2643,10 @@ class TestSessionUpdateContract:
2643
2644 mock_client.tool_router.session.patch.side_effect = self._conflict()
2645 with pytest.raises(SessionConfigConflictError):
2641 - second.update(toolkits={"enable": ["slack"]})
2646 + second.update(
2647 + toolkits={"enable": ["slack"]},
2648 + expected_config_version=second.config_version,
2649 + )
2650 assert second.config_version == 7
2651
2652 mock_client.tool_router.session.patch.side_effect = None
@@ -2646,7 +2654,10 @@ class TestSessionUpdateContract:
2654 mock_client.tool_router.session.patch.return_value.config_version = 9
2655 reread = tool_router.use(session_id="session_123")
2656 assert reread.config_version == 8
2649 - reread.update(toolkits={"enable": ["slack"]})
2657 + reread.update(
2658 + toolkits={"enable": ["slack"]},
2659 + expected_config_version=reread.config_version,
2660 + )
2661 assert mock_client.tool_router.session.patch.call_args.kwargs["extra_body"] == {
2662 "expected_config_version": 8
2663 }
ts/e2e-tests/README.md
+1
@@ -37,6 +37,7 @@ ts/e2e-tests/
37 │ ├── openai-zod4-compat/ # OpenAI + Zod v4 compatibility tests
38 │ ├── tool-router-files/ # Tool Router session files (list, upload, download, delete)
39 │ ├── tool-router-pagination/ # Tool Router session.toolkits() cursor pagination
40 + │ ├── tool-router-session-update/ # Tool Router session.update() with default options (live API)
41 │ └── typescript-mjs-import-nodenext/ # TypeScript moduleResolution: nodenext tests
42 ├── deno/ # Deno runtime tests
43 │ └── esm-basic/ # ESM compatibility tests via npm: specifier
ts/e2e-tests/runtimes/node/tool-router-session-update/README.md new
+27
@@ -0,0 +1,27 @@
1 +# Tool Router Session Update E2E Test
2 +
3 +End-to-end regression test for `session.update()` with default options.
4 +
5 +## Prerequisites
6 +
7 +- Docker (for running tests in containers)
8 +- `COMPOSIO_API_KEY` environment variable (any Composio project works)
9 +
10 +## Running
11 +
12 +```bash
13 +# From repo root
14 +COMPOSIO_API_KEY=your_key pnpm test:e2e:node --filter=@e2e-tests/node-tool-router-session-update
15 +
16 +# Or from this directory
17 +COMPOSIO_API_KEY=your_key bun test e2e.test.ts
18 +```
19 +
20 +## What it tests
21 +
22 +`@composio/core` 0.20.0 sent `expected_config_version` on every `session.update()` call. The API rejected that field with a 400, so no default update could succeed, and mocked unit tests could not see it.
23 +
24 +1. **Create** – Create a session with `toolkits: ['github', 'gmail']`
25 +2. **Update** – Call `session.update({ toolkits: ['github'] })` with default options and assert the returned toolkits and a higher `configVersion`
26 +3. **Persisted** – Re-read the session with `sessions.use()` and assert the server kept the change
27 +4. **Cleanup** – Delete the session
ts/e2e-tests/runtimes/node/tool-router-session-update/e2e.test.ts new
+62
@@ -0,0 +1,62 @@
1 +/**
2 + * Tool Router session.update() E2E test.
3 + *
4 + * Regression test for @composio/core 0.20.0, where update() sent
5 + * `expected_config_version` by default and the live API rejected every call
6 + * with a 400. Unit tests mock the transport and cannot catch a payload the API
7 + * refuses, so this test sends a default update to the real API.
8 + *
9 + * Project-agnostic: creates its own session and deletes it afterwards.
10 + *
11 + * Requires COMPOSIO_API_KEY in environment.
12 + */
13 +
14 +import { e2e, type E2ETestResult } from '@e2e-tests/utils';
15 +import { describe, it, expect, beforeAll } from 'bun:test';
16 +
17 +declare module 'bun' {
18 + interface Env {
19 + COMPOSIO_API_KEY: string;
20 + }
21 +}
22 +
23 +e2e(import.meta.url, {
24 + versions: { node: ['current'] },
25 + usesFixtures: true,
26 + env: {
27 + COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
28 + },
29 + defineTests: ({ runFixture }) => {
30 + let result: E2ETestResult;
31 +
32 + beforeAll(async () => {
33 + result = await runFixture({ filename: 'index.mjs' });
34 + }, 120_000);
35 +
36 + describe('session.update with default options', () => {
37 + it('exits successfully', () => {
38 + expect(result.exitCode).toBe(0);
39 + });
40 +
41 + it('creates a session', () => {
42 + expect(result.stdout).toContain('CREATE_OK');
43 + });
44 +
45 + it('applies the update and advances configVersion', () => {
46 + expect(result.stdout).toContain('UPDATE_OK');
47 + });
48 +
49 + it('persists the update on the server', () => {
50 + expect(result.stdout).toContain('PERSISTED_OK');
51 + });
52 +
53 + it('deletes the session', () => {
54 + expect(result.stdout).toContain('DELETE_OK');
55 + });
56 +
57 + it('all operations complete', () => {
58 + expect(result.stdout).toContain('ALL_OK');
59 + });
60 + });
61 + },
62 +});
ts/e2e-tests/runtimes/node/tool-router-session-update/fixtures/index.mjs new
+68
@@ -0,0 +1,68 @@
1 +/**
2 + * E2E fixture: session.update() with default options against the live API.
3 + *
4 + * Reproduces the @composio/core 0.20.0 regression: update() sent
5 + * `expected_config_version` on every call, and the API rejected the field with
6 + * a 400, so no default update could succeed. Mocked unit tests could not see
7 + * this because they never reach the API's payload validation.
8 + *
9 + * Requires COMPOSIO_API_KEY in environment.
10 + */
11 +import { Composio } from '@composio/core';
12 +
13 +const apiKey = process.env.COMPOSIO_API_KEY;
14 +if (!apiKey) {
15 + console.error('COMPOSIO_API_KEY is required');
16 + process.exit(1);
17 +}
18 +
19 +const composio = new Composio({ apiKey });
20 +
21 +const toolkitsOf = config => JSON.stringify(config.toolkits);
22 +
23 +async function main() {
24 + const userId = `e2e-tool-router-session-update-${Date.now()}`;
25 + const session = await composio.sessions.create(userId, { toolkits: ['github', 'gmail'] });
26 +
27 + try {
28 + const versionBefore = session.configVersion;
29 + if (typeof versionBefore !== 'number') {
30 + throw new Error(`expected a numeric configVersion after create, got ${versionBefore}`);
31 + }
32 + console.log('CREATE_OK');
33 +
34 + // Default options: no precondition, so this must succeed on any project.
35 + const config = await session.update({ toolkits: ['github'] });
36 + const expected = JSON.stringify({ enabled: ['github'] });
37 + if (toolkitsOf(config) !== expected) {
38 + throw new Error(`update returned toolkits ${toolkitsOf(config)}, expected ${expected}`);
39 + }
40 + if (!(session.configVersion > versionBefore)) {
41 + throw new Error(
42 + `configVersion did not advance: ${versionBefore} -> ${session.configVersion}`
43 + );
44 + }
45 + console.log('UPDATE_OK');
46 +
47 + const reread = await composio.sessions.use(session.sessionId);
48 + if (toolkitsOf(reread.config) !== expected) {
49 + throw new Error(`server kept toolkits ${toolkitsOf(reread.config)}, expected ${expected}`);
50 + }
51 + if (reread.configVersion !== session.configVersion) {
52 + throw new Error(
53 + `server configVersion ${reread.configVersion} != local ${session.configVersion}`
54 + );
55 + }
56 + console.log('PERSISTED_OK');
57 + } finally {
58 + await composio.sessions.delete(session.sessionId);
59 + console.log('DELETE_OK');
60 + }
61 +
62 + console.log('ALL_OK');
63 +}
64 +
65 +main().catch(err => {
66 + console.log('ERROR:', err?.message || err);
67 + process.exit(1);
68 +});
ts/e2e-tests/runtimes/node/tool-router-session-update/package.json new
+17
@@ -0,0 +1,17 @@
1 +{
2 + "name": "@e2e-tests/node-tool-router-session-update",
3 + "version": "0.0.0",
4 + "private": true,
5 + "type": "module",
6 + "scripts": {
7 + "typecheck": "tsc --noEmit",
8 + "test:e2e": "bun test e2e.test.ts",
9 + "test:e2e:node": "bun test e2e.test.ts"
10 + },
11 + "dependencies": {
12 + "@composio/core": "workspace:*"
13 + },
14 + "devDependencies": {
15 + "@e2e-tests/utils": "workspace:*"
16 + }
17 +}
ts/e2e-tests/runtimes/node/tool-router-session-update/tsconfig.json new
+12
@@ -0,0 +1,12 @@
1 +{
2 + "$schema": "https://json.schemastore.org/tsconfig",
3 + "compilerOptions": {
4 + "target": "es2022",
5 + "module": "esnext",
6 + "moduleResolution": "bundler",
7 + "strict": true,
8 + "skipLibCheck": true,
9 + "noEmit": true
10 + },
11 + "include": ["e2e.test.ts"]
12 +}
ts/packages/core/src/errors/ToolRouterErrors.ts
+6 -6
@@ -32,11 +32,11 @@ export class ComposioMCPDestinationError extends ComposioError {
32
33 /**
34 * Thrown when a session update is rejected with HTTP 409 because the session
35 - * configuration changed since it was last read: the `expected_config_version`
36 - * precondition (the session's last observed `configVersion` by default) is
37 - * stale. The local session object is left as it was before the call.
38 - * Re-fetch the session with `sessions.use(sessionId)` and retry the update
39 - * against the fresh `configVersion`.
35 + * configuration changed since it was last read, for example when an
36 + * `expectedConfigVersion` precondition passed to `update()` is stale. The
37 + * local session object is left as it was before the call. Re-fetch the session
38 + * with `sessions.use(sessionId)` and retry the update against the fresh
39 + * `configVersion`.
40 */
41 export class ComposioSessionConfigConflictError extends ComposioError {
42 constructor(
@@ -49,7 +49,7 @@ export class ComposioSessionConfigConflictError extends ComposioError {
49 statusCode: 409,
50 possibleFixes: options.possibleFixes ?? [
51 'Re-fetch the session with `composio.sessions.use(sessionId)` to observe the current configVersion, then retry the update',
52 - 'Pass `expectedConfigVersion: false` to apply the update regardless of concurrent changes (last writer wins)',
52 + 'Omit `expectedConfigVersion` to apply the update regardless of concurrent changes (last writer wins)',
53 ],
54 });
55 this.name = 'ComposioSessionConfigConflictError';
ts/packages/core/src/models/ToolRouterSession.ts
+13 -13
@@ -139,8 +139,8 @@ export class ToolRouterSession<
139 public sandbox?: ToolRouterSessionWorkbenchConfig;
140 /**
141 * Version of the server-side configuration this object last observed.
142 - * Refreshed in place by `update()`, which sends it as the
143 - * `expected_config_version` precondition by default.
142 + * Refreshed in place by `update()`. Pass it as `expectedConfigVersion` to
143 + * make an update conditional.
144 */
145 public configVersion?: number;
146 public warnings: ToolRouterSessionWarning[];
@@ -778,15 +778,17 @@ export class ToolRouterSession<
778 * map entirely. `manageConnections.callbackUrl: null` removes only the
779 * stored callback URL.
780 *
781 - * The request carries the `configVersion` this object last observed as the
782 - * `expected_config_version` precondition, so a concurrent change surfaces as
781 + * By default the request carries no precondition: the last writer wins.
782 + * Pass `expectedConfigVersion` (for example `session.configVersion`) to make
783 + * the update conditional: the API then applies it only when the stored
784 + * version still matches, and a concurrent change surfaces as
785 * {@link ComposioSessionConfigConflictError} (HTTP 409) instead of being
784 - * overwritten. Pass `expectedConfigVersion` to send another version, or
785 - * `expectedConfigVersion: false` to send no precondition (last writer
786 - * wins). The PATCH is never retried by the transport, so a 409 is reported
787 - * exactly once. On conflict this object is left unchanged: re-fetch the
788 - * session with `sessions.use(sessionId)` and retry against the fresh
789 - * `configVersion`.
786 + * overwritten. The API must support the `expected_config_version` field;
787 + * otherwise it rejects the request with a 400. `expectedConfigVersion: false`
788 + * is the same as omitting it. The PATCH is never retried by the transport,
789 + * so a 409 is reported exactly once. On conflict this object is left
790 + * unchanged: re-fetch the session with `sessions.use(sessionId)` and retry
791 + * against the fresh `configVersion`.
792 *
793 * `config`, `configVersion`, `preload`, `sandbox` and `warnings` are
794 * refreshed in place only after a successful response, and the updated
@@ -799,9 +801,7 @@ export class ToolRouterSession<
801 const parsed = ToolRouterUpdateSessionConfigSchema.parse(config);
802 const body = transformToolRouterUpdateParams(parsed);
803 const expectedConfigVersion =
802 - parsed.expectedConfigVersion === false
803 - ? undefined
804 - : (parsed.expectedConfigVersion ?? this.configVersion);
804 + parsed.expectedConfigVersion === false ? undefined : parsed.expectedConfigVersion;
805 if (expectedConfigVersion !== undefined) {
806 body.expected_config_version = expectedConfigVersion;
807 }
ts/packages/core/src/types/toolRouter.types.ts
+1 -1
@@ -843,7 +843,7 @@ export const ToolRouterUpdateSessionConfigSchema = z
843 .union([z.number().int().positive(), z.literal(false)])
844 .optional()
845 .describe(
846 - 'Precondition sent as `expected_config_version`. Omitted: the session sends the configVersion it last observed, so a concurrent change surfaces as ComposioSessionConfigConflictError instead of being overwritten. A positive integer sends that version instead. `false` sends no precondition (last writer wins)'
846 + 'Precondition sent as `expected_config_version`. A positive integer (for example `session.configVersion`) makes the update conditional, so a concurrent change surfaces as ComposioSessionConfigConflictError instead of being overwritten; the API must support the field. Omitted or `false`: no precondition (last writer wins)'
847 ),
848 })
849 .partial()
ts/packages/core/test/models/toolRouter.test.ts
+32 -27
@@ -3801,7 +3801,7 @@ describe('ToolRouter', () => {
3801
3802 expect(mockClient.toolRouter.session.patch).toHaveBeenCalledWith(
3803 sessionId,
3804 - expect.objectContaining({ toolkits: { enable: ['gmail'] }, expected_config_version: 7 }),
3804 + expect.objectContaining({ toolkits: { enable: ['gmail'] } }),
3805 { maxRetries: 0 }
3806 );
3807 expect(config).toEqual(patchedConfig);
@@ -3942,14 +3942,14 @@ describe('ToolRouter', () => {
3942 mockClient.toolRouter.session.patch.mockResolvedValue(patchResponse(8));
3943 });
3944
3945 - it('sends the last observed config version as the precondition by default, without retries', async () => {
3945 + it('sends no precondition by default, without retries', async () => {
3946 const session = await toolRouter.use(sessionId);
3947 expect(session.configVersion).toBe(7);
3948
3949 await session.update({ toolkits: ['gmail'] });
3950
3951 const { body, options } = patchCall();
3952 - expect(body.expected_config_version).toBe(7);
3952 + expect(body).not.toHaveProperty('expected_config_version');
3953 expect(body).not.toHaveProperty('expectedConfigVersion');
3954 expect(body.toolkits).toEqual({ enable: ['gmail'] });
3955 expect(options).toEqual({ maxRetries: 0 });
@@ -3974,7 +3974,7 @@ describe('ToolRouter', () => {
3974 expect(patchCall().body).not.toHaveProperty('expected_config_version');
3975 });
3976
3977 - it('sends an explicit expectedConfigVersion instead of the observed one', async () => {
3977 + it('sends an explicit expectedConfigVersion as the precondition', async () => {
3978 const session = await toolRouter.use(sessionId);
3979
3980 await session.update({ toolkits: ['gmail'], expectedConfigVersion: 9 });
@@ -4034,7 +4034,6 @@ describe('ToolRouter', () => {
4034 search: null,
4035 execute: null,
4036 experimental: null,
4037 - expected_config_version: 7,
4037 });
4038 });
4039
@@ -4043,7 +4042,9 @@ describe('ToolRouter', () => {
4042 const preloadBefore = session.preload;
4043 mockClient.toolRouter.session.patch.mockRejectedValueOnce(conflict());
4044
4046 - const failure = await session.update({ toolkits: ['gmail'] }).catch(e => e);
4045 + const failure = await session
4046 + .update({ toolkits: ['gmail'], expectedConfigVersion: session.configVersion })
4047 + .catch(e => e);
4048
4049 expect(failure).toBeInstanceOf(ComposioSessionConfigConflictError);
4050 expect(failure.message).toMatch(/re-fetch/i);
@@ -4055,22 +4056,26 @@ describe('ToolRouter', () => {
4056 expect(session.preload.tools).toEqual(['GMAIL_FETCH_EMAILS']);
4057 });
4058
4058 - it('reports an in-flight change when a 409 arrives without a precondition', async () => {
4059 - const session = await toolRouter.use(sessionId);
4060 - const configBefore = session.config;
4061 - mockClient.toolRouter.session.patch.mockRejectedValueOnce(conflict());
4062 -
4063 - const failure = await session
4064 - .update({ toolkits: ['gmail'], expectedConfigVersion: false })
4065 - .catch(e => e);
4066 -
4067 - expect(failure).toBeInstanceOf(ComposioSessionConfigConflictError);
4068 - expect(failure.message).toMatch(/changed while this update was in flight/);
4069 - expect(failure.message).not.toMatch(/no longer at version/);
4070 - expect(failure.meta?.expectedConfigVersion).toBeUndefined();
4071 - expect(session.config).toBe(configBefore);
4072 - expect(session.configVersion).toBe(7);
4073 - });
4059 + it.each([
4060 + ['by default', {}],
4061 + ['with expectedConfigVersion: false', { expectedConfigVersion: false as const }],
4062 + ])(
4063 + 'reports an in-flight change when a 409 arrives without a precondition (%s)',
4064 + async (_label, optOut) => {
4065 + const session = await toolRouter.use(sessionId);
4066 + const configBefore = session.config;
4067 + mockClient.toolRouter.session.patch.mockRejectedValueOnce(conflict());
4068 +
4069 + const failure = await session.update({ toolkits: ['gmail'], ...optOut }).catch(e => e);
4070 +
4071 + expect(failure).toBeInstanceOf(ComposioSessionConfigConflictError);
4072 + expect(failure.message).toMatch(/changed while this update was in flight/);
4073 + expect(failure.message).not.toMatch(/no longer at version/);
4074 + expect(failure.meta?.expectedConfigVersion).toBeUndefined();
4075 + expect(session.config).toBe(configBefore);
4076 + expect(session.configVersion).toBe(7);
4077 + }
4078 + );
4079
4080 it('lets the first of two handles at version N win and the stale one conflict until re-read', async () => {
4081 const first = await toolRouter.use(sessionId);
@@ -4078,14 +4083,14 @@ describe('ToolRouter', () => {
4083 expect(first.configVersion).toBe(7);
4084 expect(second.configVersion).toBe(7);
4085
4081 - await first.update({ toolkits: ['gmail'] });
4086 + await first.update({ toolkits: ['gmail'], expectedConfigVersion: first.configVersion });
4087 expect(patchCall(0).body.expected_config_version).toBe(7);
4088 expect(first.configVersion).toBe(8);
4089
4090 mockClient.toolRouter.session.patch.mockRejectedValueOnce(conflict());
4086 - await expect(second.update({ toolkits: ['slack'] })).rejects.toBeInstanceOf(
4087 - ComposioSessionConfigConflictError
4088 - );
4091 + await expect(
4092 + second.update({ toolkits: ['slack'], expectedConfigVersion: second.configVersion })
4093 + ).rejects.toBeInstanceOf(ComposioSessionConfigConflictError);
4094 expect(patchCall(1).body.expected_config_version).toBe(7);
4095 expect(second.configVersion).toBe(7);
4096 expect(second.preload.tools).toEqual(['GMAIL_FETCH_EMAILS']);
@@ -4097,7 +4102,7 @@ describe('ToolRouter', () => {
4102 const reread = await toolRouter.use(sessionId);
4103 expect(reread.configVersion).toBe(8);
4104 mockClient.toolRouter.session.patch.mockResolvedValueOnce(patchResponse(9));
4100 - await reread.update({ toolkits: ['slack'] });
4105 + await reread.update({ toolkits: ['slack'], expectedConfigVersion: reread.configVersion });
4106 expect(patchCall(2).body.expected_config_version).toBe(8);
4107 expect(reread.configVersion).toBe(9);
4108 });