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

fix(core): credential intent, MCP auth context, and update preconditions (#4579)

This PR: - supersedes https://github.com/ComposioHQ/composio/pull/4580 now that `main` has been ported into `next` (https://github.com/ComposioHQ/composio/pull/4568); everything from the port (owned client 2.0.0-rc.8, `userApiKey`/`orgApiKey`, `session.update()` returning config, `ensureConnected`, catchable HTTP errors) is preserved and re-verified - resolves the project API key by explicit intent: a string is used as-is; omitted falls back to `COMPOSIO_API_KEY` then the CLI user config; a stored `uak_` user key is never sent as `x-api-key` and raises a redacted `ComposioAPIKeyKindError`; `apiKey: null` disables both fallbacks and authenticates with `userApiKey` / `orgApiKey` (option or env) or an `x-user-api-key` default header; clones keep their resolved credential - adds `orgId` / `projectId` (nano IDs, both together) emitted as `x-org-id` / `x-project-id` and kept on clones and the MCP export; Python `org_id` / `project_id` and `disable_api_key` - derives session MCP headers from the session's own credential and scope, only for a same-origin MCP URL; a cross-origin URL raises `ComposioMCPDestinationError` only when `mcp: true` was requested, otherwise the session exports no credential headers with a redacted warning; Pusher channel auth follows the same precedence and no longer reads the environment key - makes `session.update()` send the observed config version as `expected_config_version` by default (opt-out `expectedConfigVersion: false`, Python `expected_config_version=False`), map a 409 to `ComposioSessionConfigConflictError` / `SessionConfigConflictError` without touching local state, and accept `null` to clear every clearable policy block and leaf - documents session policy, the PATCH field matrix with whole-map replacement, credential intent, the MCP credential rule, the consumer resolve flow with nano IDs, and null webhook secrets as single-channel guidance (`@composio/core` >= 0.19.1, `composio` >= 0.22.1); rewrites both session-update examples and regenerates the session reference pages - breaking: - `apiKey: null` no longer behaves like omission; `apiKey: process.env.X ?? null` now throws unless a user or org credential is configured - `session.update()` fails with a typed 409 when another writer moved the config since the last read; pass `expectedConfigVersion: false` to keep last-writer-wins ## Context The owned clients pinned on `next` (2.0.0-rc.8) declare only `ApiKeyAuth` on session operations and do not type `expected_config_version` or the nullable PATCH blocks, so the SDK places the resolved user key as the `x-user-api-key` default header and passes the precondition through a widened body (TS) / `extra_body` (Python). Both go away when https://github.com/ComposioHQ/composio-client/pull/59 ships and the pin is bumped. Backend enforcement lives in https://github.com/ComposioHQ/platform/pull/13157. ## Testing `pnpm --filter @composio/core typecheck`; full core Vitest (66 files, 1505 passed, 2 expected fail); prettier and oxlint on changed files; Python pytest (291 across sdk, tool_router, response-shape, triggers, imports), ruff, mypy; `validate:agent-skills`, `validate:skill-routing`; docs `lint`, `lint:links`, `build`; example typecheck and py_compile. Transport captures use a stubbed fetch and httpx MockTransport, not constructor mocks. Sanitized evidence ledger (F1-F14) is in the first comment. ## Code review Completed `ce-code-review` runs `20260922-021046-d23e1e76` (this branch) and `20260922-021805-3ced6e19` (the folded-in 4580 branch); verdicts "Ready with fixes", 10 findings applied. Cross-model adversarial pass: Codex route, served model unverified. ## Unapplied review findings - [ ] P2 - `python/composio/sdk.py` - TS accepts `apiKey: null` with only `orgApiKey`; Python requires a user key; pick one contract and add the org-key-only test in both SDKs - [ ] P1 - `python/composio/core/models/tool_router_session.py` - `t.cast()` on update TypedDicts and the TS widened body cast hide mismatches against the published client pin; drop after the pin bump - [ ] P2 - `ts/packages/core/src/models/ToolRouterSession.ts` - consider extracting the patch-and-conflict logic into a sibling module - [ ] Informational - PATCH uses maxRetries 0 because both clients retry 409 by default; transient 5xx on that call are no longer retried - [ ] Docs - regenerating the SDK reference also rewrote 13 unrelated pages and added 7 (keyring, logs, webhooks); reverted here, needs its own docs-regeneration PR on `next` ## Checklist - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests - [x] I added a changeset ## Post-Deploy Monitoring & Validation - Log queries: `ConfigVersionConflict` (expect a small steady rate from concurrent writers, no spike), `MULTI_ACCOUNT_DISABLED_SETTINGS` 400s, `Stored preload.tools fall outside the effective toolkits/tools/tags policy` warnings (each one is a legacy session to inspect), `A user API key (uak**` wrong-kind 401s, `x-project-id must be a project nano ID` 400s, session-create 400s with `Unrecognized key`. - Metrics: session create 400 rate by version (strict create), PATCH 409 rate, sessions with `toolkits.enabled: []` (count before deploy is the rollout gate the plan requires), consumer resolve/connected_toolkits latency. - Healthy: 400/409 rates stay proportional to traffic; no increase in 5xx on session or consumer routes; connected-apps cache hit rate recovers within one TTL (24h) after the key change. - Failure signals and rollback trigger: sustained 400s from a first-party client on session create (a request builder sends an unknown root key) -> fix the builder before promoting further; 5xx from `patchToolRouterSessionConfig` -> roll back the platform deploy (the SDK changes are backward compatible and do not require the backend). - Window and owner: 48 hours after the production deploy; the coordinator of this change set.

Alberto Schiabel committed Sep 22, 2026 at 18:49 UTC a4a40a12e3338f0d33621fb6a6a9cad0b9d208ce
49 files changed +4487 -286
.changeset/core-credential-resolution.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Fix project API key resolution so the SDK never sends a Composio user API key (`uak_...`, as stored by `composio login`) as the `x-api-key` project credential. When that stored key is the only candidate, the constructor now throws a redacted `ComposioAPIKeyKindError` that explains the mismatch instead of making requests that fail with 401. `apiKey: null` now disables project-key authentication entirely, including the `COMPOSIO_API_KEY` and `~/.composio/user_data.json` fallbacks, and is accepted when the instance holds another credential: `userApiKey` or `orgApiKey` (explicit or from their environment variables), or an `x-user-api-key` entry in `defaultHeaders`. Requests then carry only that credential. Malformed or unexpectedly shaped user config files produce a diagnostic that names the file without echoing its contents, and cloned instances keep the credential they were resolved with instead of re-reading the environment. Code that resolves the key with `apiKey: process.env.COMPOSIO_API_KEY ?? null` (or any expression that yields `null` when the variable is unset) is affected: it used to fall back to the environment and the CLI config file and now throws unless another credential is configured; omit `apiKey` (or pass `undefined`) to keep the fallbacks. With `apiKey: null`, an `x-api-key` entry in `defaultHeaders` is rejected as well, including on `createSession()` clones: pass the project key as `apiKey` instead of a raw header.
.changeset/core-user-org-api-keys.md
+1 -1
@@ -2,4 +2,4 @@
2 '@composio/core': minor
3 ---
4
5 -Add `userApiKey` and `orgApiKey` to `ComposioConfig`. Both are forwarded to the underlying API client, which sends each one only on operations whose security scheme requires it (organization, consumer, and user-scoped endpoints reached through `getClient()`), never alongside the project key. They fall back to `COMPOSIO_USER_API_KEY` and `COMPOSIO_ORG_API_KEY`. A project `apiKey` is still required.
5 +Add `userApiKey` and `orgApiKey` to `ComposioConfig`. Both are forwarded to the underlying API client, which sends each one only on operations whose security scheme requires it (organization, consumer, and user-scoped endpoints reached through `getClient()`), never alongside the project key. They fall back to `COMPOSIO_USER_API_KEY` and `COMPOSIO_ORG_API_KEY`. A project `apiKey` is still required unless it is set to `null`, which opts into user-only authentication.
.changeset/session-auth-context-and-update-preconditions.md new
+9
@@ -0,0 +1,9 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Sessions now export their MCP config from the auth context the session request was actually made with: the project key as `x-api-key` when one is configured, otherwise the user API key (`userApiKey` or the `x-user-api-key` default header) as `x-user-api-key`, plus `x-org-id` / `x-project-id` when the instance is scoped. No other default header and no ambient `COMPOSIO_API_KEY` is ever copied. The headers are only attached when the MCP URL shares the origin of the configured API base URL (whatever its scheme). Any other destination (a different origin, an opaque origin such as a `data:` URL, or a URL that does not parse) never receives them: with `mcp: true`, `create()` / `use()` throw `ComposioMCPDestinationError`, which names both origins and never includes a key; without `mcp: true` the session is returned with `session.mcp.headers` empty and a warning naming both origins is logged, so native tools keep working. The SDK never connects to the MCP URL itself and does not follow redirects for it. Trigger subscriptions (Pusher channel auth) follow the same rule instead of falling back to the environment when the project key is disabled.
6 +
7 +`ComposioConfig` gains `orgId` and `projectId`: the organization and consumer project nano IDs, sent together as the `x-org-id` / `x-project-id` headers on every request and with the session MCP config. They may also be supplied through `defaultHeaders`; a half-configured or disagreeing scope throws `ComposioScopeConfigError`. Without a scope, a user API key keeps addressing the API default project.
8 +
9 +`session.update()` now sends the session's last observed `configVersion` as the `expected_config_version` precondition by default and never retries that request, so a concurrent change surfaces as `ComposioSessionConfigConflictError` (HTTP 409; re-fetch the session, then retry) while the local session object stays unchanged. Pass `expectedConfigVersion` to send another version or `expectedConfigVersion: false` to opt out (last writer wins). Every policy block (`toolkits`, `tools`, `tags`, `authConfigs`, `connectedAccounts`, `preload`, `manageConnections`, `multiAccount`, `search`, `execute`, `experimental`) accepts `null` to remove the stored override, `manageConnections.callbackUrl: null` removes only the stored callback URL, `multiAccount.maxAccountsPerToolkit: null` removes the stored maximum, and an empty toolkit allowlist (`toolkits: []`) is sent as-is so it denies every app toolkit.
docs/content/docs/configuring-sessions.mdx
+284
@@ -89,6 +89,45 @@ const session = await composio.create("user_123", {
89 </Tab>
90 </Tabs>
91
92 +## Denying every app toolkit
93 +
94 +An explicit empty allowlist means no app toolkits at all. Omitting `toolkits` keeps the unrestricted default, and an empty `disable` list is also unrestricted. The three requests are different:
95 +
96 +| Toolkit config | Effect |
97 +|---|---|
98 +| Omitted | Every toolkit in the catalog is available |
99 +| `{ enable: [] }` | No app toolkit is listed, searchable, executable, or served over MCP |
100 +| `{ disable: [] }` | Every toolkit in the catalog is available |
101 +
102 +Use an empty allowlist when a session should only run [custom tools](/docs/extending-sessions/custom-tools-and-toolkits) or session helpers. Meta tools such as `COMPOSIO_SEARCH_TOOLS`, connection management, and the sandbox keep their own enablement, so `session.tools()` can still return them.
103 +
104 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
105 +<Tab value="Python">
106 +```python
107 +session = composio.sessions.create(
108 + user_id="user_123",
109 + toolkits={"enable": []},
110 +)
111 +```
112 +</Tab>
113 +<Tab value="TypeScript">
114 +```typescript
115 +import { Composio } from '@composio/core';
116 +const composio = new Composio({ apiKey: 'your_api_key' });
117 +// ---cut---
118 +const session = await composio.create("user_123", {
119 + toolkits: { enable: [] },
120 +});
121 +```
122 +</Tab>
123 +</Tabs>
124 +
125 +<Callout type="info">
126 +Requires `@composio/core` ≥ `0.19.1` (TypeScript) or `composio` ≥ `0.22.1` (Python) when you narrow an existing session with `session.update()`. Both SDKs send the empty allowlist as `{ enable: [] }`; the backend previously read an empty allowlist as "allow every toolkit", which left the session unrestricted.
127 +</Callout>
128 +
129 +The session API rejects unknown root keys with a `400` before it creates anything. A typo such as a singular `toolkit` fails the request instead of silently creating an unrestricted session.
130 +
131 ## Direct tools preset
132
133 The direct tools preset preloads every tool allowed by session filters into the session's tool list and disables session meta tools by default. Use it for specialized agents with a narrow tool set that don't need dynamic tool discovery, in-chat auth, or workbench helpers.
@@ -685,6 +724,230 @@ const session = await composio.create("user_123", {
724
725 Changing `sandbox_size` on an existing session recreates the sandbox on the next access. The sandbox's in-memory filesystem state is lost, but the persistent [`/mnt/files/` mount](/docs/sandbox/remote#files-and-mounts) survives the restart.
726
727 +## Updating a session
728 +
729 +`session.update()` patches the stored configuration in place. Fields you omit are preserved, so you can widen or narrow one part of a session without restating the rest. The SDK refreshes `session.config` and the session's config version only after the API accepts the change.
730 +
731 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
732 +<Tab value="Python">
733 +```python
734 +session = composio.sessions.use("session_id")
735 +
736 +session.update(toolkits={"enable": ["gmail", "github"]})
737 +```
738 +</Tab>
739 +<Tab value="TypeScript">
740 +```typescript
741 +import { Composio } from '@composio/core';
742 +const composio = new Composio({ apiKey: 'your_api_key' });
743 +// ---cut---
744 +const session = await composio.sessions.use("session_id");
745 +
746 +await session.update({ toolkits: { enable: ["gmail", "github"] } });
747 +```
748 +</Tab>
749 +</Tabs>
750 +
751 +<Callout type="info">
752 +The update behavior below requires `@composio/core` ≥ `0.19.1` (TypeScript) or `composio` ≥ `0.22.1` (Python).
753 +</Callout>
754 +
755 +### Maps replace, they don't merge
756 +
757 +A `tools`, `authConfigs`, or `connectedAccounts` map you send replaces the stored map entirely. The API does not merge entries, so a Slack-only `tools` map removes a Gmail entry that was stored before it.
758 +
759 +Stored before the update:
760 +
761 +```json
762 +{
763 + "tools": {
764 + "gmail": { "enable": ["GMAIL_FETCH_EMAILS"] },
765 + "slack": { "enable": ["SLACK_SEND_MESSAGE"] }
766 + }
767 +}
768 +```
769 +
770 +The update:
771 +
772 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
773 +<Tab value="Python">
774 +```python
775 +session.update(
776 + tools={"slack": {"enable": ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]}},
777 +)
778 +```
779 +</Tab>
780 +<Tab value="TypeScript">
781 +```typescript
782 +import { Composio } from '@composio/core';
783 +const composio = new Composio({ apiKey: 'your_api_key' });
784 +const session = await composio.sessions.use("session_id");
785 +// ---cut---
786 +await session.update({
787 + tools: { slack: { enable: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"] } },
788 +});
789 +```
790 +</Tab>
791 +</Tabs>
792 +
793 +Stored after the update. The `gmail` entry is gone:
794 +
795 +```json
796 +{
797 + "tools": {
798 + "slack": { "enable": ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"] }
799 + }
800 +}
801 +```
802 +
803 +To change one entry, send the whole map with every entry you want to keep. An empty map (`{}`) is stored as an explicit empty map.
804 +
805 +The same rule applies to `toolkits`, `tags`, and `preload`: a value replaces the stored policy. `manageConnections`, `sandbox`, and `multiAccount` merge the subfields you send, and an empty object changes nothing.
806 +
807 +### Narrowing an existing session to no app toolkits
808 +
809 +An empty allowlist on update denies every app toolkit, exactly as it does on create. The SDK sends `{ "enable": [] }` as-is instead of dropping it from the request.
810 +
811 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
812 +<Tab value="Python">
813 +```python
814 +session.update(toolkits={"enable": []})
815 +```
816 +</Tab>
817 +<Tab value="TypeScript">
818 +```typescript
819 +import { Composio } from '@composio/core';
820 +const composio = new Composio({ apiKey: 'your_api_key' });
821 +const session = await composio.sessions.use("session_id");
822 +// ---cut---
823 +await session.update({ toolkits: { enable: [] } });
824 +```
825 +</Tab>
826 +</Tabs>
827 +
828 +### Removing a callback URL
829 +
830 +`manageConnections.callbackUrl: null` removes only the stored callback URL. `enable` and the other connection settings stay as they are. An empty string is rejected.
831 +
832 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
833 +<Tab value="Python">
834 +```python
835 +session.update(manage_connections={"callback_url": None})
836 +```
837 +</Tab>
838 +<Tab value="TypeScript">
839 +```typescript
840 +// @noErrors
841 +import { Composio } from '@composio/core';
842 +const composio = new Composio({ apiKey: 'your_api_key' });
843 +const session = await composio.sessions.use("session_id");
844 +// ---cut---
845 +await session.update({ manageConnections: { callbackUrl: null } });
846 +```
847 +</Tab>
848 +</Tabs>
849 +
850 +### Clearing a block with null
851 +
852 +Passing `null` (`None` in Python) for a whole block removes the stored override and the session falls back to the default for that block. Every policy block accepts it: `toolkits`, `tools`, `tags`, `authConfigs`, `connectedAccounts`, `preload`, `manageConnections`, `sandbox`, `multiAccount`, `search`, `execute`, and `experimental`.
853 +
854 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
855 +<Tab value="Python">
856 +```python
857 +session.update(manage_connections=None, multi_account=None)
858 +```
859 +</Tab>
860 +<Tab value="TypeScript">
861 +```typescript
862 +import { Composio } from '@composio/core';
863 +const composio = new Composio({ apiKey: 'your_api_key' });
864 +const session = await composio.sessions.use("session_id");
865 +// ---cut---
866 +await session.update({ manageConnections: null, multiAccount: null });
867 +```
868 +</Tab>
869 +</Tabs>
870 +
871 +Clearing a policy can widen access. `toolkits: null` removes the toolkit policy and restores the unrestricted default, which is the opposite of `{ "enable": [] }`; clearing `preload` does the same for preloaded tools, so the agent can reach more than before the update. Send `toolkits: []` when you want to deny every app toolkit. Clearing `multiAccount` resolves to disabled, while omitting it preserves the stored setting.
872 +
873 +### Multi-account mode after an update
874 +
875 +The canonical disabled state is `{ "enable": false, "require_explicit_selection": false }` with no maximum. Sending `enable: false` resets a stale maximum or selection setting, and reapplying that disabled configuration is accepted. Combining `enable: false` with `maxAccountsPerToolkit` or `requireExplicitSelection: true` is rejected with a `400`.
876 +
877 +### Preload must stay inside the policy
878 +
879 +An update that narrows `toolkits`, `tools`, or `tags` while leaving an explicitly preloaded tool outside the new policy is rejected with a `400`, and nothing changes. Fix `preload` in the same update:
880 +
881 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
882 +<Tab value="Python">
883 +```python
884 +session.update(
885 + toolkits={"enable": ["slack"]},
886 + preload={"tools": ["SLACK_SEND_MESSAGE"]},
887 +)
888 +```
889 +</Tab>
890 +<Tab value="TypeScript">
891 +```typescript
892 +import { Composio } from '@composio/core';
893 +const composio = new Composio({ apiKey: 'your_api_key' });
894 +const session = await composio.sessions.use("session_id");
895 +// ---cut---
896 +await session.update({
897 + toolkits: { enable: ["slack"] },
898 + preload: { tools: ["SLACK_SEND_MESSAGE"] },
899 +});
900 +```
901 +</Tab>
902 +</Tabs>
903 +
904 +### Concurrent updates
905 +
906 +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.
907 +
908 +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:
909 +
910 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
911 +<Tab value="Python">
912 +```python
913 +from composio.exceptions import SessionConfigConflictError
914 +
915 +session = composio.sessions.use("session_id")
916 +
917 +try:
918 + session.update(toolkits={"enable": ["gmail", "github"]})
919 +except SessionConfigConflictError:
920 + # Another client changed the session first. Nothing was written.
921 + session = composio.sessions.use("session_id")
922 + session.update(toolkits={"enable": ["gmail", "github"]})
923 +```
924 +</Tab>
925 +<Tab value="TypeScript">
926 +```typescript
927 +// @noErrors
928 +import { Composio, ComposioSessionConfigConflictError } from '@composio/core';
929 +const composio = new Composio({ apiKey: 'your_api_key' });
930 +// ---cut---
931 +let session = await composio.sessions.use("session_id");
932 +
933 +try {
934 + await session.update({ toolkits: { enable: ["gmail", "github"] } });
935 +} catch (error) {
936 + if (!(error instanceof ComposioSessionConfigConflictError)) throw error;
937 + // Another client changed the session first. Nothing was written.
938 + session = await composio.sessions.use("session_id");
939 + await session.update({ toolkits: { enable: ["gmail", "github"] } });
940 +}
941 +```
942 +</Tab>
943 +</Tabs>
944 +
945 +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.
946 +
947 +Raw HTTP callers set `expected_config_version` in the `PATCH` body themselves; without it the last writer wins.
948 +
949 +To roll a session back, read a previous configuration from its config history (`GET /api/v3.1/tool_router/session/{session_id}/config_history`) and convert it into an update request. A history entry is not a request body: it carries metadata and version fields, and it names toolkits and tools as `enabled` and `disabled`, which map to `enable` and `disable` in the update.
950 +
951 ## Session methods
952
953 For framework examples, see provider-specific documentation like [OpenAI](/docs/providers/openai) or [Vercel AI SDK](/docs/providers/vercel). To connect over MCP instead, see [Using sessions via MCP](/docs/sessions-via-mcp).
@@ -825,6 +1088,27 @@ do {
1088 </Tab>
1089 </Tabs>
1090
1091 +### update()
1092 +
1093 +Patch the session configuration in place. See [Updating a session](#updating-a-session) for what omitted fields, replaced maps, `null`, and `expectedConfigVersion` do.
1094 +
1095 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
1096 +<Tab value="Python">
1097 +```python
1098 +config = session.update(toolkits={"enable": ["gmail", "github"]})
1099 +```
1100 +</Tab>
1101 +<Tab value="TypeScript">
1102 +```typescript
1103 +import { Composio } from '@composio/core';
1104 +const composio = new Composio({ apiKey: 'your_api_key' });
1105 +const session = await composio.create("user_123");
1106 +// ---cut---
1107 +const config = await session.update({ toolkits: { enable: ["gmail", "github"] } });
1108 +```
1109 +</Tab>
1110 +</Tabs>
1111 +
1112 ### delete()
1113
1114 Delete a session when you're done with it. Deleted sessions immediately stop being retrievable or executable, and the call returns the deleted `session_id`. Deleting a missing or already-deleted session surfaces the backend `404`.
docs/content/docs/consumer-agents.mdx
+68 -1
@@ -73,11 +73,78 @@ Managed auth is the quickest way to start. Create a [custom auth config](/docs/a
73
74 Restrict the session to the toolkits and tools your feature needs. This makes discovery more relevant and prevents unrelated actions from appearing in the agent's available surface. Ask for user confirmation before destructive or externally visible actions.
75
76 +## Run sessions in your organization's consumer project
77 +
78 +Every Composio organization also has one consumer project: the project behind Composio Connect and the For You clients, where your members' own connections live. Sessions in it are created with a [user API key](/reference/authenticating-to-composio#user-api-key) and an explicit scope. Composio never mints or returns the consumer project's API key.
79 +
80 +Resolve the consumer project once to learn its nano IDs, then build the SDK instance with the user API key and that scope. The SDK sends `x-user-api-key`, `x-org-id`, and `x-project-id` on every request, carries the scope into session clones, and exports it with the session's MCP config:
81 +
82 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
83 +<Tab value="Python">
84 +```python
85 +import os
86 +
87 +from composio import Composio
88 +
89 +composio = Composio(
90 + disable_api_key=True,
91 + user_api_key=os.environ["COMPOSIO_USER_API_KEY"],
92 + org_id="org_9f2k1x",
93 + project_id="proj_4b8m2q",
94 +)
95 +
96 +session = composio.sessions.create(user_id="user_123", toolkits=["gmail"], mcp=True)
97 +# session.mcp.headers carries x-user-api-key, x-org-id, and x-project-id
98 +```
99 +</Tab>
100 +<Tab value="TypeScript">
101 +```typescript
102 +// @noErrors
103 +import { Composio } from "@composio/core";
104 +
105 +const composio = new Composio({
106 + apiKey: null,
107 + userApiKey: process.env.COMPOSIO_USER_API_KEY,
108 + orgId: "org_9f2k1x",
109 + projectId: "proj_4b8m2q",
110 +});
111 +
112 +const session = await composio.create("user_123", { toolkits: ["gmail"], mcp: true });
113 +// session.mcp.headers carries x-user-api-key, x-org-id, and x-project-id
114 +```
115 +</Tab>
116 +</Tabs>
117 +
118 +`orgId` and `projectId` (`org_id` and `project_id` in Python) must be set together, and the SDK rejects a scope that disagrees with `x-org-id` or `x-project-id` entries in `defaultHeaders`. Without a scope, a user API key addresses the API default (the developer project).
119 +
120 +<Callout type="info">
121 +Requires `@composio/core` ≥ `0.19.1` (TypeScript) or `composio` ≥ `0.22.1` (Python).
122 +</Callout>
123 +
124 +The nano IDs come from the consumer project resolve endpoint, which also provisions the project when it is absent. The same credential lists the toolkits a consumer user has already connected:
125 +
126 +```bash
127 +# Resolve the organization's consumer project
128 +curl -X POST https://backend.composio.dev/api/v3.1/org/consumer/project/resolve \
129 + -H "x-user-api-key: $COMPOSIO_USER_API_KEY" \
130 + -H "x-org-id: $COMPOSIO_ORG_ID"
131 +# {"project_id": "<uuid>", "project_nano_id": "proj_4b8m2q", "org_id": "org_9f2k1x",
132 +# "project_type": "CONSUMER", "config": {"consumer_experience_enabled": true, ...}}
133 +
134 +# List the toolkits this consumer user has already connected
135 +curl "https://backend.composio.dev/api/v3.1/org/consumer/connected_toolkits?user_id=user_123" \
136 + -H "x-user-api-key: $COMPOSIO_USER_API_KEY" \
137 + -H "x-org-id: $COMPOSIO_ORG_ID"
138 +# {"toolkits": ["gmail"], "project_id": "<uuid>", "project_nano_id": "proj_4b8m2q", "user_id": "user_123"}
139 +```
140 +
141 +Use the nano IDs from the resolve response (`org_id` and `project_nano_id`), always together. A UUID in either header is a `400`. A user with no connections yet gets an empty `toolkits` list with the project scope still filled in, so you can create their session before they connect anything. An organization without a consumer project gets `null` project identifiers from the listing, which never provisions one. Raw HTTP callers create the session with the same three headers on `POST /api/v3.1/tool_router/session`.
142 +
143 ## Before you launch
144
145 - Verify two different users cannot see or use each other's connected accounts.
146 - Test both the first-time connection flow and a returning user with an existing connection.
80 -- Store the Composio API key only on your server.
147 +- Store the Composio API key only on your server. A session created with a user API key exports that organization-wide key in its MCP config, so store that config as a secret too.
148 - Persist session IDs for multi-turn conversations.
149 - Test one safe, read-only call against a real connected account.
150 - Inspect the resulting tool call in [Logs](/reference/api-reference/logs).
docs/content/docs/sessions-via-mcp.mdx
+17
@@ -56,6 +56,23 @@ Resuming a stored session? Pass the same flag, `composio.use(sessionId, { mcp: t
56 The MCP endpoint and `session.tools()` are backed by the same session. Toolkits, auth configs, and connected accounts you set when [configuring the session](/docs/configuring-sessions) apply to both.
57 </Callout>
58
59 +## What the MCP headers carry
60 +
61 +`session.mcp.headers` holds the credential the SDK used to create or load the session, and nothing else. No other default header and no ambient `COMPOSIO_API_KEY` is copied in.
62 +
63 +| SDK credential | Exported header | What it can reach |
64 +|---|---|---|
65 +| Project API key (`apiKey`, `COMPOSIO_API_KEY`, or the project key stored by `composio login`) | `x-api-key` | That one project |
66 +| User API key only (`apiKey: null` with `userApiKey` in TypeScript, `disable_api_key=True` with `user_api_key` in Python, or an `x-user-api-key` default header) | `x-user-api-key` | Every project the user can reach across your organization |
67 +
68 +Treat the exported config as a secret and store it where you keep the project API key. A user-only session exports the user's organization-wide key, which makes it the broader credential: prefer a project-key session when an MCP client only needs one project. The SDK also exports `x-org-id` and `x-project-id` when the instance is scoped to a consumer project (see [Run sessions in your organization's consumer project](/docs/consumer-agents#run-sessions-in-your-organizations-consumer-project)).
69 +
70 +The SDK attaches the headers only when the MCP URL has the same origin as the API base URL it talks to, whatever the scheme, so a custom `baseURL` works as long as it serves the session MCP endpoint. For any other destination, `create()` and `use()` called with `mcp: true` (TypeScript) or `mcp=True` (Python) raise `ComposioMCPDestinationError` or `MCPDestinationError`; the error names both origins and never the key. Without the MCP flag the session is still returned, `session.mcp.headers` is empty, and the SDK logs a warning naming both origins, so agents that only use native tools keep working. The SDK never connects to the MCP URL itself and never follows redirects for it. Configure your MCP client so it does not forward these headers to a different origin either.
71 +
72 +<Callout type="info">
73 +Requires `@composio/core` ≥ `0.19.1` (TypeScript) or `composio` ≥ `0.22.1` (Python). Earlier releases only exported a project key, so a session driven with a user API key had no usable MCP headers. Pass `session.mcp.headers` through as returned instead of assembling an `x-api-key` header from an environment variable yourself.
74 +</Callout>
75 +
76 ## A single URL for a fixed set of tools
77
78 Combine `mcp: true` with the [direct-tools preset](/docs/configuring-sessions) to get one MCP URL that serves exactly the tools you list, with no search or meta tools in front of them. This is the closest equivalent to a classic hosted MCP server scoped to a handful of tools.
docs/content/reference/authenticating-to-composio/index.mdx
+86 -2
@@ -1,18 +1,21 @@
1 ---
2 title: Overview
3 description: Authenticate requests to the Composio API with an API key
4 -keywords: [API authentication, API key, x-api-key, x-org-api-key, scoped api key, Composio authentication, authorization]
4 +keywords: [API authentication, API key, x-api-key, x-org-api-key, x-user-api-key, user api key, scoped api key, consumer project, Composio authentication, authorization]
5 ---
6
7 Every Composio API request authenticates with an API key. Send the key in a request header and Composio resolves it to your project or organization.
8
9 -Composio has three kinds of API key. They share the same authentication flow — they differ in what they can reach.
9 +Composio has four kinds of API key. They share the same authentication flow and differ in what they can reach.
10
11 | Key | Header | Scope |
12 | --- | --- | --- |
13 | Project API key | `x-api-key` | Full access to a single project. |
14 | Organization API key | `x-org-api-key` | Access across every project in your organization. |
15 | Scoped project API key <span style={{ color: '#059669' }}>**· New**</span> | `x-api-key` | A chosen subset of a single project's resources. |
16 +| User API key | `x-user-api-key` | Sessions and consumer routes, as a member of your organization. |
17 +
18 +Send one credential per request, in the header that matches its kind. A user API key (`uak_...`) sent as `x-api-key` gets its own `401` that names the mismatch without echoing the key.
19
20 ## Project API key
21
@@ -57,6 +60,87 @@ curl https://backend.composio.dev/api/v3.1/tools/execute/HACKERNEWS_GET_USER \
60
61 See [Scoped project API keys](/reference/authenticating-to-composio/project-api-key-permissions) for the permission areas, access levels, and the routes each one covers.
62
63 +## User API key
64 +
65 +A user API key authenticates you as a member of your organization instead of as one project. It starts with `uak_`, and `composio login` stores one in `~/.composio/user_data.json`. Send it in the `x-user-api-key` header.
66 +
67 +Every session route accepts a user API key as an alternative to a project key: create, retrieve, update, delete, attach, link, search, execute, tools, toolkits, mounts, and config history. Without a scope header the key addresses your developer project:
68 +
69 +```bash
70 +curl -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
71 + -H "x-user-api-key: $COMPOSIO_USER_API_KEY" \
72 + -H "Content-Type: application/json" \
73 + -d '{"user_id": "user_123", "toolkits": {"enable": ["gmail"]}}'
74 +```
75 +
76 +To act in your organization's consumer project, add `x-org-id` and `x-project-id`, always together and always as nano IDs (`org_...` and `proj_...`, never UUIDs). The [consumer agent guide](/docs/consumer-agents#run-sessions-in-your-organizations-consumer-project) shows how to resolve those IDs first.
77 +
78 +A user API key reaches every project its owner can reach, so it is the broader credential. Keep it server-side, and prefer a project API key for application code that only needs one project.
79 +
80 +### Scope errors
81 +
82 +| Status | Meaning |
83 +| --- | --- |
84 +| `401` | The credential is missing or invalid, or a user key was sent as `x-api-key`. |
85 +| `400` | A scope header is missing or holds a UUID instead of a nano ID. |
86 +| `404` | The organization or project does not exist or is not accessible to this user. The two cases are deliberately indistinguishable. |
87 +| `500` | The scope lookup itself failed. Retry, then contact support if it persists. |
88 +
89 +## Choosing the key in the SDKs
90 +
91 +The SDKs resolve the project API key by intent, so an unexpected key never gets sent by accident.
92 +
93 +| `Composio` option | What the SDK sends |
94 +| --- | --- |
95 +| `apiKey: "ak_..."` | That key, as `x-api-key`. The environment and the CLI's stored key are not consulted. |
96 +| `apiKey` omitted | `COMPOSIO_API_KEY`, then the project key stored by `composio login` in `~/.composio/user_data.json`. A stored user key (`uak_...`) is never sent as `x-api-key`; the constructor throws `ComposioAPIKeyKindError` with the value redacted. |
97 +| `apiKey: null` | No project key at all. Both fallbacks are off, and the instance authenticates with the user API key you configure instead: `userApiKey`, its `COMPOSIO_USER_API_KEY` fallback, or an `x-user-api-key` entry in `defaultHeaders`. In Python, `disable_api_key=True` does the same with `user_api_key` or `COMPOSIO_USER_API_KEY`. |
98 +
99 +A user-only instance sends `x-user-api-key` on every request and no `x-api-key`. Only `x-user-api-key` in `defaultHeaders` counts as a credential; every other default header passes through untouched. Clones made with `createSession()` keep the credentials they were resolved with instead of re-reading the environment.
100 +
101 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
102 +<Tab value="Python">
103 +```python
104 +import os
105 +
106 +from composio import Composio
107 +
108 +# Project key: pass it, or omit api_key to fall back to COMPOSIO_API_KEY.
109 +composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"])
110 +
111 +# User key only: turn the project key off and use the user key alone.
112 +composio = Composio(
113 + disable_api_key=True,
114 + user_api_key=os.environ["COMPOSIO_USER_API_KEY"],
115 +)
116 +```
117 +</Tab>
118 +<Tab value="TypeScript">
119 +```typescript
120 +// @noErrors
121 +import { Composio } from "@composio/core";
122 +
123 +// Project key: pass it, or omit apiKey to fall back to COMPOSIO_API_KEY.
124 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
125 +
126 +// User key only: turn the project key off and use the user key alone.
127 +// userApiKey falls back to COMPOSIO_USER_API_KEY when omitted.
128 +const userScoped = new Composio({
129 + apiKey: null,
130 + userApiKey: process.env.COMPOSIO_USER_API_KEY,
131 +});
132 +```
133 +</Tab>
134 +</Tabs>
135 +
136 +<Callout type="info">
137 +Requires `@composio/core` ≥ `0.19.1` (TypeScript) or `composio` ≥ `0.22.1` (Python). In Python only an omitted `api_key` falls back to `COMPOSIO_API_KEY`; an explicit `api_key=None` raises `ApiKeyNotProvidedError`, and combining `disable_api_key=True` with an explicit `api_key` raises an error. Sessions created by a user-only SDK instance export `x-user-api-key` in their MCP config; see [What the MCP headers carry](/docs/sessions-via-mcp#what-the-mcp-headers-carry). Raw HTTP callers send the same `x-user-api-key` header themselves.
138 +</Callout>
139 +
140 +## Webhook secrets in responses
141 +
142 +Project listings and `GET /api/v3.1/auth/session/info` return `webhook_secret: null`. Read a signing secret from the [webhook subscription](/reference/api-reference/webhook-subscriptions/getWebhookSubscriptionsById) endpoints, or [rotate it](/reference/api-reference/webhook-subscriptions/postWebhookSubscriptionsByIdRotateSecret) there.
143 +
144 <Cards>
145 <Card title="Scoped project API keys" href="/reference/authenticating-to-composio/project-api-key-permissions">
146 Permission areas, access levels, and covered routes
docs/content/reference/sdk-reference/python/composio.mdx
+1 -1
@@ -14,4 +14,4 @@ description: "Composio SDK for Python. Generic parameters: TTool: The individua
14 | [`connected_accounts`](/reference/sdk-reference/python/connected-accounts) | `ConnectedAccounts` |
15 | [`mcp`](/reference/sdk-reference/python/mcp) | `MCP` |
16
17 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/sdk.py#L47)
17 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/sdk.py#L88)
docs/content/reference/sdk-reference/python/session.mdx
+43 -10
@@ -10,6 +10,7 @@ description: "A Composio session \u2014 the object returned by `composio.create(
10 | `session_id` | `str` |
11 | `config` | `ToolRouterSessionConfig` |
12 | `experimental` | `'ToolRouterSessionExperimental'` |
13 +| `config_version` | `int | None` |
14 | `preload` | `Any` |
15
16 ## Methods
@@ -184,26 +185,30 @@ def proxy_execute(toolkit: str, endpoint: str, method: Literal['GET', 'POST', 'P
185
186 ### update()
187
187 -Partially update the session configuration. Only the fields provided will be changed; omitted fields are preserved. Mutates this session's `config` and `preload` in-place and returns the updated session configuration. Pass `None` for `manage_connections`, `sandbox`/`workbench`, or `multi_account` to clear the stored value. `workbench` is a backwards-compatible alias for `sandbox`. Prefer `sandbox` in new code. All parameters use the same types as the Stainless-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. 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.
189
190 ```python
190 -def update(toolkits: Union[session_patch_params.Toolkits, 'Omit'] = ..., tools: Union[Dict[str, session_patch_params.Tools], 'Omit'] = ..., tags: Union[session_patch_params.Tags, 'Omit'] = ..., auth_configs: Union[Dict[str, str], 'Omit'] = ..., connected_accounts: Union[Dict[str, SequenceNotStr[str | None]], 'Omit'] = ..., manage_connections: Union[session_patch_params.ManageConnections | 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, 'Omit'] = ..., preload: Union[session_patch_params.Preload, 'Omit'] = ...) -> ToolRouterSessionConfig
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
192 ```
193
194 **Parameters**
195
196 | Name | Type |
197 |------|------|
197 -| `toolkits?` | `Union[session_patch_params.Toolkits, 'Omit']` |
198 -| `tools?` | `Union[Dict[str, session_patch_params.Tools], 'Omit']` |
199 -| `tags?` | `Union[session_patch_params.Tags, 'Omit']` |
200 -| `auth_configs?` | `Union[Dict[str, str], 'Omit']` |
198 +| `toolkits?` | `Union[session_patch_params.Toolkits \| None, 'Omit']` |
199 +| `tools?` | `Union[Dict[str, session_patch_params.Tools \| None], 'Omit']` |
200 +| `tags?` | `Union[session_patch_params.Tags \| None, 'Omit']` |
201 +| `auth_configs?` | `Union[Dict[str, str \| None], 'Omit']` |
202 | `connected_accounts?` | `Union[Dict[str, SequenceNotStr[str \| None]], 'Omit']` |
202 -| `manage_connections?` | `Union[session_patch_params.ManageConnections \| None, 'Omit']` |
203 +| `manage_connections?` | `Union[session_patch_params.ManageConnections \| None, ToolRouterUpdateManageConnectionsConfig \| None, 'Omit']` |
204 | `sandbox?` | `Union[session_patch_params.Workbench \| None, 'Omit']` |
205 | `workbench?` | `Union[session_patch_params.Workbench \| None, 'Omit']` |
205 -| `multi_account?` | `Union[session_patch_params.MultiAccount \| None, 'Omit']` |
206 -| `preload?` | `Union[session_patch_params.Preload, 'Omit']` |
206 +| `multi_account?` | `Union[session_patch_params.MultiAccount \| None, ToolRouterUpdateMultiAccountConfig \| None, 'Omit']` |
207 +| `preload?` | `Union[session_patch_params.Preload \| None, 'Omit']` |
208 +| `search?` | `Union[session_patch_params.Search \| None, 'Omit']` |
209 +| `execute?` | `Union[session_patch_params.Execute \| None, 'Omit']` |
210 +| `experimental?` | `Union[session_patch_params.Experimental \| None, ToolRouterUpdateExperimentalConfig \| None, 'Omit']` |
211 +| `expected_config_version?` | `Union[int, None, Literal[False]]` |
212
213 **Returns**
214
@@ -211,6 +216,34 @@ def update(toolkits: Union[session_patch_params.Toolkits, 'Omit'] = ..., tools:
216
217 ---
218
219 +### list_config_history()
220 +
221 +List the configuration history of this session, newest first. Every `update()` records a new config version; this returns those versions with cursor-based pagination.
222 +
223 +```python
224 +def list_config_history(query: session_config_history_params.SessionConfigHistoryParams = ...) -> session_config_history_response.SessionConfigHistoryResponse
225 +```
226 +
227 +**Parameters**
228 +
229 +| Name | Type |
230 +|------|------|
231 +| `query?` | `session_config_history_params.SessionConfigHistoryParams` |
232 +
233 +**Returns**
234 +
235 +`session_config_history_response.SessionConfigHistoryResponse` — The config versions under `.items` plus pagination fields.
236 +
237 +**Example**
238 +
239 +```python
240 +history = session.list_config_history(limit=10)
241 +for entry in history.items:
242 + print(entry.version, entry.is_current)
243 +```
244 +
245 +---
246 +
247 ### delete()
248
249 Delete this session. Deleted sessions immediately stop being retrievable or executable. An already-deleted session surfaces the backend 404.
@@ -225,4 +258,4 @@ def delete() -> ToolRouterSessionDeleteResponse
258
259 ---
260
228 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tool_router_session.py#L109)
261 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tool_router_session.py#L154)
docs/content/reference/sdk-reference/typescript/composio.mdx
+5 -2
@@ -56,6 +56,8 @@ const composio = new Composio({
56 | `create` | `(userId: string, config: \{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| ...[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; mcp?: boolean; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: ...[] \| 'all' \}; sandbox?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \}; sessionPreset?: 'direct_tools'; tags?: ... \| ... \| ... \| ...[] \| \{ disable?: ...[]; enable?: ...[] \}; toolkits?: string[] \| \{ disable: ...[] \} \| \{ enable: ...[] \}; tools?: Record<string, ...[] \| \{ enable: ... \} \| \{ disable: ... \} \| \{ tags: ... \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \} & \{ mcp: true \}, requestOptions: ComposioRequestOptions) => Promise<Session>` | Creates a new tool router session for a user. Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools should be exposed directly; see `ToolRouterCreateSessionConfig`. |
57 | `experimental` | `Experimental` | Experimental SDK methods whose shape may change in future releases. Prefer domain-specific mounts (for example `composio.connectedAccounts.updateAcl(...)`) when available; this namespace keeps compatibility aliases while APIs are experimental. Stateless experimental factories (e.g. `experimental_createTool`) stay at the top level. |
58 | `files` | `Files` | Upload and download files |
59 +| `keyring` | `Keyring` | Public transfer keys of the organization's customer-managed keyring |
60 +| `logs` | `Logs` | Search and inspect tool-execution logs |
61 | `mcp` | `MCP` | Model Context Protocol server management. |
62 | `provider` | `TProvider` | The tool provider instance used for wrapping tools in framework-specific formats |
63 | `sessions` | `Sessions` | Create and reuse Composio sessions. Prefer `composio.sessions.create(...)` for new code. The top-level `composio.create(...)` method is kept as an alias. |
@@ -64,6 +66,7 @@ const composio = new Composio({
66 | `tools` | `Tools` | List, retrieve, and execute tools |
67 | `triggers` | `Triggers` | Manage webhook triggers and event subscriptions |
68 | `use` | `(id: string, options: \{ customToolkits?: CustomToolkit[]; customTools?: CustomTool[]; mcp: true \}, requestOptions: ComposioRequestOptions) => Promise<Session>` | Use an existing tool router session |
69 +| `webhooks` | `Webhooks` | Manage the project's webhook subscription (`webhooks.subscriptions`) and inbound per-toolkit webhook endpoints (`webhooks.endpoints`). |
70
71 ## Methods
72
@@ -163,12 +166,12 @@ export default {
166 Get the Composio SDK client.
167
168 ```typescript
166 -getClient(): ComposioClient
169 +getClient(): Composio
170 ```
171
172 **Returns**
173
171 -`ComposioClient` — The Composio API client.
174 +`Composio` — The Composio API client.
175
176 ---
177
docs/content/reference/sdk-reference/typescript/session.mdx
+77 -27
@@ -8,13 +8,13 @@ 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` | |
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. |
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` | `Preload` | |
15 -| `sandbox` | `Workbench` | Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. |
14 +| `preload` | `\{ tools: string[] \| 'all' \}` | |
15 +| `sandbox` | `\{ auto_offload_threshold?: number; enable?: boolean; proxy_execution_enabled?: boolean; sandbox_size?: 'standard' \| 'medium' \| 'large' \| 'xlarge'; tool_execution_enabled?: boolean \}` | Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. |
16 | `sessionId` | `string` | |
17 -| `warnings` | `Warning[]` | |
17 +| `warnings` | `\{ code: 'PRELOAD_TOOLS_HIGH_CONTEXT_USAGE'; message: string \}[]` | |
18
19 ## Methods
20
@@ -35,7 +35,7 @@ Experimental — shape may change in future releases.
35 at the SDK boundary.
36
37 ```typescript
38 -async authorize(toolkit: string, options?: { callbackUrl?: string; alias?: string; experimental?: { accountType?: ConnectedAccountType; aclConfigForShared?: ConnectedAccountAclConfig; }; }, requestOptions?: ComposioRequestOptions): Promise<ConnectionRequest>
38 +async authorize(toolkit: string, options?: { alias?: string; callbackUrl?: string; experimental?: { accountType?: ConnectedAccountType; aclConfigForShared?: { allowAllUsers?: boolean; allowedUserIds?: string[]; notAllowedUserIds?: string[] } } }, requestOptions?: ComposioRequestOptions): Promise<ConnectionRequest>
39 ```
40
41 **Parameters**
@@ -43,7 +43,7 @@ async authorize(toolkit: string, options?: { callbackUrl?: string; alias?: strin
43 | Name | Type |
44 |------|------|
45 | `toolkit` | `string` |
46 -| `options?` | `\{ callbackUrl?: string; alias?: string; experimental?: \{ accountType?: ConnectedAccountType; aclConfigForShared?: ConnectedAccountAclConfig; \}; \}` |
46 +| `options?` | `\{ alias?: string; callbackUrl?: string; experimental?: \{ accountType?: ConnectedAccountType; aclConfigForShared?: \{ allowAllUsers?: boolean; allowedUserIds?: string[]; notAllowedUserIds?: string[] \} \} \}` |
47 | `requestOptions?` | `ComposioRequestOptions` |
48
49 **Returns**
@@ -96,7 +96,7 @@ Deleted sessions immediately stop being retrievable or executable. Deleting
96 an already-deleted session surfaces the backend 404.
97
98 ```typescript
99 -async delete(requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionDeleteResponse>
99 +async delete(requestOptions?: ComposioRequestOptions): Promise<{ deleted: true; sessionId: string }>
100 ```
101
102 **Parameters**
@@ -107,7 +107,7 @@ async delete(requestOptions?: ComposioRequestOptions): Promise<ToolRouterSession
107
108 **Returns**
109
110 -`Promise<ToolRouterSessionDeleteResponse>`
110 +`Promise<\{ deleted: true; sessionId: string \}>`
111
112 ---
113
@@ -126,7 +126,7 @@ For interactive flows that should surface the redirect URL instead of
126 blocking, use `authorize()` and its `waitForConnection()` directly.
127
128 ```typescript
129 -async ensureConnected(toolkit: string, options?: ToolRouterSessionEnsureConnectedOptions, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionEnsureConnectedResult>
129 +async ensureConnected(toolkit: string, options?: { alias?: string; callbackUrl?: string; experimental?: { accountType?: 'PRIVATE' | 'SHARED'; aclConfigForShared?: { allowAllUsers?: boolean; allowedUserIds?: string[]; notAllowedUserIds?: string[] } }; timeout?: number }, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionEnsureConnectedResult>
130 ```
131
132 **Parameters**
@@ -134,7 +134,7 @@ async ensureConnected(toolkit: string, options?: ToolRouterSessionEnsureConnecte
134 | Name | Type | Description |
135 |------|------|-------------|
136 | `toolkit` | `string` | The toolkit slug to ensure a connection for (e.g. 'github') |
137 -| `options?` | `ToolRouterSessionEnsureConnectedOptions` | Optional authorization options plus `timeout` (ms to wait for a newly-initiated connection, default 60000) |
137 +| `options?` | `\{ alias?: string; callbackUrl?: string; experimental?: \{ accountType?: 'PRIVATE' \| 'SHARED'; aclConfigForShared?: \{ allowAllUsers?: boolean; allowedUserIds?: string[]; notAllowedUserIds?: string[] \} \}; timeout?: number \}` | Optional authorization options plus `timeout` (ms to wait for a newly-initiated connection, default 60000) |
138 | `requestOptions?` | `ComposioRequestOptions` | |
139
140 **Returns**
@@ -162,7 +162,7 @@ the session's custom tools and toolkits. Custom tools are executed
162 in-process; remote tools are sent to the Composio backend.
163
164 ```typescript
165 -async execute(toolSlug: string, arguments_?: Record<string, unknown>, options?: ToolRouterSessionExecuteOptions, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionExecuteResponse>
165 +async execute(toolSlug: string, arguments_?: Record<string, unknown>, options?: ToolRouterSessionExecuteOptions, requestOptions?: ComposioRequestOptions): Promise<{ data: Record<string, unknown>; error: string | null; logId: string }>
166 ```
167
168 **Parameters**
@@ -176,7 +176,38 @@ async execute(toolSlug: string, arguments_?: Record<string, unknown>, options?:
176
177 **Returns**
178
179 -`Promise<ToolRouterSessionExecuteResponse>` — The tool execution result
179 +`Promise<\{ data: Record<string, unknown>; error: string \| null; logId: string \}>` — The tool execution result
180 +
181 +---
182 +
183 +### listConfigHistory()
184 +
185 +Page through this session's configuration history, newest first. The
186 +first page starts with the live config (`isCurrent: true`); every
187 +`session.update()` archives the previous version as a history row.
188 +
189 +```typescript
190 +async listConfigHistory(options?: { cursor?: string; limit?: number }, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionListConfigHistoryResponse>
191 +```
192 +
193 +**Parameters**
194 +
195 +| Name | Type | Description |
196 +|------|------|-------------|
197 +| `options?` | `\{ cursor?: string; limit?: number \}` | Optional `cursor` and `limit` (max 100) |
198 +| `requestOptions?` | `ComposioRequestOptions` | |
199 +
200 +**Returns**
201 +
202 +`Promise<ToolRouterSessionListConfigHistoryResponse>` — The config versions on this page plus pagination info
203 +
204 +**Example**
205 +
206 +```typescript
207 +const { items, nextCursor } = await session.listConfigHistory({ limit: 10 });
208 +console.log(items[0].version, items[0].isCurrent); // e.g. 3, true
209 +console.log(items[1].config.toolkits);
210 +```
211
212 ---
213
@@ -186,14 +217,14 @@ Proxy an API call through Composio's auth layer using the session's connected ac
217 The backend resolves the connected account from the toolkit within the session.
218
219 ```typescript
189 -async proxyExecute(params: SessionProxyExecuteParams, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionProxyExecuteResponse>
220 +async proxyExecute(params: { body?: unknown; endpoint: string; method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; parameters?: { in: 'query' | 'header'; name: string; value: string | number }[]; toolkit: string }, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionProxyExecuteResponse>
221 ```
222
223 **Parameters**
224
225 | Name | Type | Description |
226 |------|------|-------------|
196 -| `params` | `SessionProxyExecuteParams` | Proxy request parameters (toolkit, endpoint, method, body, headers/query params) |
227 +| `params` | `\{ body?: unknown; endpoint: string; method: 'GET' \| 'POST' \| 'PUT' \| 'DELETE' \| 'PATCH'; parameters?: \{ in: 'query' \| 'header'; name: string; value: string \| number \}[]; toolkit: string \}` | Proxy request parameters (toolkit, endpoint, method, body, headers/query params) |
228 | `requestOptions?` | `ComposioRequestOptions` | |
229
230 **Returns**
@@ -208,19 +239,19 @@ Search for tools by semantic use case.
239 Returns relevant tools for the given query with schemas and guidance.
240
241 ```typescript
211 -async search(params: { query: string; toolkits?: string[]; }, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionSearchResponse>
242 +async search(params: { query: string; toolkits?: string[] }, requestOptions?: ComposioRequestOptions): Promise<{ error: string | null; nextStepsGuidance: string[]; results: { difficulty?: string; error?: string | null; executionGuidance?: string; index: number; knownPitfalls?: string[]; memory?: Record<string, ...[]>; planId?: string; primaryToolSlugs: string[]; recommendedPlanSteps?: string[]; referenceWorkbenchSnippets?: { code: ...; description: ... }[]; relatedToolSlugs: string[]; toolkits: string[]; useCase: string }[]; session: { generateId: boolean; id: string; instructions: string }; success: boolean; timeInfo: { currentTimeUtc: string; currentTimeUtcEpochSeconds: number; message: string }; toolkitConnectionStatuses: { connectionDetails?: Record<string, unknown>; currentUserInfo?: Record<string, unknown>; description: string; hasActiveConnection: boolean; statusMessage: string; toolkit: string }[]; toolSchemas: Record<string, { description?: string; hasFullSchema?: boolean; inputSchema?: Record<string, unknown>; outputSchema?: Record<string, unknown>; schemaRef?: { args: { toolSlugs: ... }; message?: string; tool: 'COMPOSIO_GET_TOOL_SCHEMAS' }; toolkit: string; toolSlug: string }> }>
243 ```
244
245 **Parameters**
246
247 | Name | Type |
248 |------|------|
218 -| `params` | `\{ query: string; toolkits?: string[]; \}` |
249 +| `params` | `\{ query: string; toolkits?: string[] \}` |
250 | `requestOptions?` | `ComposioRequestOptions` |
251
252 **Returns**
253
223 -`Promise<ToolRouterSessionSearchResponse>`
254 +`Promise<\{ error: string \| null; nextStepsGuidance: string[]; results: \{ difficulty?: string; error?: string \| null; executionGuidance?: string; index: number; knownPitfalls?: string[]; memory?: Record<string, ...[]>; planId?: string; primaryToolSlugs: string[]; recommendedPlanSteps?: string[]; referenceWorkbenchSnippets?: \{ code: ...; description: ... \}[]; relatedToolSlugs: string[]; toolkits: string[]; useCase: string \}[]; session: \{ generateId: boolean; id: string; instructions: string \}; success: boolean; timeInfo: \{ currentTimeUtc: string; currentTimeUtcEpochSeconds: number; message: string \}; toolkitConnectionStatuses: \{ connectionDetails?: Record<string, unknown>; currentUserInfo?: Record<string, unknown>; description: string; hasActiveConnection: boolean; statusMessage: string; toolkit: string \}[]; toolSchemas: Record<string, \{ description?: string; hasFullSchema?: boolean; inputSchema?: Record<string, unknown>; outputSchema?: Record<string, unknown>; schemaRef?: \{ args: \{ toolSlugs: ... \}; message?: string; tool: 'COMPOSIO_GET_TOOL_SCHEMAS' \}; toolkit: string; toolSlug: string \}> \}>`
255
256 ---
257
@@ -230,14 +261,14 @@ Query the connection state of toolkits in the session.
261 Supports pagination and filtering by toolkit slugs.
262
263 ```typescript
233 -async toolkits(options?: ToolRouterToolkitsOptions, requestOptions?: ComposioRequestOptions): Promise<{ cursor: string | undefined; items: { connection?: { authConfig?: ... | ...; connectedAccount?: { id: ...; status: ... }; isActive: boolean }; isNoAuth: boolean; logo?: string; name: string; slug: string }[]; totalPages: number }>
264 +async toolkits(options?: { cursor?: string; isConnected?: boolean; limit?: number; search?: string; toolkits?: string[] }, requestOptions?: ComposioRequestOptions): Promise<{ cursor: string | undefined; items: { connection?: { authConfig?: ... | ...; connectedAccount?: { id: ...; status: ... }; isActive: boolean }; isNoAuth: boolean; logo?: string; name: string; slug: string }[]; totalPages: number }>
265 ```
266
267 **Parameters**
268
269 | Name | Type |
270 |------|------|
240 -| `options?` | `ToolRouterToolkitsOptions` |
271 +| `options?` | `\{ cursor?: string; isConnected?: boolean; limit?: number; search?: string; toolkits?: string[] \}` |
272 | `requestOptions?` | `ComposioRequestOptions` |
273
274 **Returns**
@@ -255,7 +286,7 @@ When custom tools are bound to the session, execution of COMPOSIO_MULTI_EXECUTE_
286 is intercepted: local tools are executed in-process, remote tools are sent to the backend.
287
288 ```typescript
258 -async tools(modifiers?: SessionMetaToolOptions, requestOptions?: ComposioRequestOptions): Promise<ReturnType<TProvider['wrapTools']>>
289 +async tools(modifiers?: SessionMetaToolOptions, requestOptions?: ComposioRequestOptions): Promise<ReturnType>
290 ```
291
292 **Parameters**
@@ -267,30 +298,49 @@ async tools(modifiers?: SessionMetaToolOptions, requestOptions?: ComposioRequest
298
299 **Returns**
300
270 -`Promise<ReturnType<TProvider['wrapTools']>>`
301 +`Promise<ReturnType>`
302
303 ---
304
305 ### update()
306
307 Partially update the session configuration.
277 -Only the fields provided will be changed; omitted fields are preserved.
278 -Mutates this session's `config`, `configVersion`, `preload`, `sandbox`,
279 -and `warnings` in-place, and resolves to the updated session `config`.
308 +
309 +Only the fields provided are changed; omitted fields are preserved. For
310 +each policy block `null` removes the stored override (which can increase
311 +access: `toolkits: null` restores the unrestricted default, while
312 +`toolkits: []` denies every app toolkit and is sent as-is). Supplied
313 +`tools`, `authConfigs` and `connectedAccounts` maps replace the stored
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
319 +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`.
326 +
327 +`config`, `configVersion`, `preload`, `sandbox` and `warnings` are
328 +refreshed in place only after a successful response, and the updated
329 +`config` is returned.
330
331 ```typescript
282 -async update(config: ToolRouterUpdateSessionConfig, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionConfig>
332 +async update(config: { authConfigs?: Record<string, string> | null; connectedAccounts?: Record<string, string[]> | null; execute?: { enableMultiExecute?: boolean } | null; expectedConfigVersion?: number | false; experimental?: { fastMode?: boolean | null; linkUrlOverwrite?: string | null; permissions?: { default: ... | ... | ...; overrides?: Record<..., ...> } | null; sessionConfigId?: string; submitFeedback?: { enable: boolean } | null } | null; manageConnections?: boolean | { callbackUrl?: string | null; enable?: boolean; enableConnectionRemoval?: boolean | null; waitForConnections?: boolean } | null; multiAccount?: { enable?: boolean; maxAccountsPerToolkit?: number | null; requireExplicitSelection?: boolean } | null; preload?: { tools?: string[] | 'all' } | null; sandbox?: { autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } | null; search?: { enable?: boolean } | null; tags?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] | { disable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[]; enable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] } | null; toolkits?: string[] | { disable: string[] } | { enable: string[] } | null; tools?: Record<string, string[] | { enable: ...[] } | { disable: ...[] } | { tags: ... | ... }> | null; workbench?: { autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } | null }, requestOptions?: ComposioRequestOptions): Promise<Config>
333 ```
334
335 **Parameters**
336
337 | Name | Type |
338 |------|------|
289 -| `config` | `ToolRouterUpdateSessionConfig` |
339 +| `config` | `\{ authConfigs?: Record<string, string> \| null; connectedAccounts?: Record<string, string[]> \| null; execute?: \{ enableMultiExecute?: boolean \} \| null; expectedConfigVersion?: number \| false; experimental?: \{ fastMode?: boolean \| null; linkUrlOverwrite?: string \| null; permissions?: \{ default: ... \| ... \| ...; overrides?: Record<..., ...> \} \| null; sessionConfigId?: string; submitFeedback?: \{ enable: boolean \} \| null \} \| null; manageConnections?: boolean \| \{ callbackUrl?: string \| null; enable?: boolean; enableConnectionRemoval?: boolean \| null; waitForConnections?: boolean \} \| null; multiAccount?: \{ enable?: boolean; maxAccountsPerToolkit?: number \| null; requireExplicitSelection?: boolean \} \| null; preload?: \{ tools?: string[] \| 'all' \} \| null; sandbox?: \{ autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \| null; search?: \{ enable?: boolean \} \| null; tags?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \| \{ disable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[]; enable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \} \| null; toolkits?: string[] \| \{ disable: string[] \} \| \{ enable: string[] \} \| null; tools?: Record<string, string[] \| \{ enable: ...[] \} \| \{ disable: ...[] \} \| \{ tags: ... \| ... \}> \| null; workbench?: \{ autoOffloadThreshold?: number; enable?: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \| null \}` |
340 | `requestOptions?` | `ComposioRequestOptions` |
341
342 **Returns**
343
294 -`Promise<ToolRouterSessionConfig>`
344 +`Promise<Config>`
345
346 ---
docs/content/reference/sdk-reference/typescript/sessions.mdx
+24 -10
@@ -20,10 +20,17 @@ Creates a new tool router session for a user.
20 Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools
21 should be exposed directly; see `ToolRouterCreateSessionConfig`.
22
23 +The session's MCP config carries the session credential only when the
24 +MCP URL shares the origin of the configured API base URL. When it does
25 +not, `mcp: true` makes the call throw `ComposioMCPDestinationError`
26 +(naming both origins, never a key); without `mcp: true` the session is
27 +returned with `session.mcp.headers` empty and a warning naming both
28 +origins is logged, so native tools keep working.
29 +
30 **Overload 1**
31
32 ```typescript
26 -async create(userId: string, config: ToolRouterCreateSessionConfig & { mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
33 +async create(userId: string, config: { authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string | string[]>; experimental?: { assistivePrompt?: { userTimezone?: string }; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] }; manageConnections?: boolean | { callbackUrl?: string; enable?: boolean; waitForConnections?: boolean }; mcp?: boolean; multiAccount?: { enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean }; preload?: { tools?: string[] | 'all' }; sandbox?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' }; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] | { disable?: ... | ... | ... | ...[]; enable?: ... | ... | ... | ...[] }; toolkits?: string[] | { disable: string[] } | { enable: string[] }; tools?: Record<string, string[] | { enable: ...[] } | { disable: ...[] } | { tags: ... | ... }>; workbench?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } } & { mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
34 ```
35
36 **Parameters**
@@ -31,7 +38,7 @@ async create(userId: string, config: ToolRouterCreateSessionConfig & { mcp: true
38 | Name | Type | Description |
39 |------|------|-------------|
40 | `userId` | `string` | \{string\} The user id to create the session for |
34 -| `config` | `ToolRouterCreateSessionConfig & \{ mcp: true \}` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
41 +| `config` | `\{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| string[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; mcp?: boolean; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: string[] \| 'all' \}; sandbox?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \}; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \| \{ disable?: ... \| ... \| ... \| ...[]; enable?: ... \| ... \| ... \| ...[] \}; toolkits?: string[] \| \{ disable: string[] \} \| \{ enable: string[] \}; tools?: Record<string, string[] \| \{ enable: ...[] \} \| \{ disable: ...[] \} \| \{ tags: ... \| ... \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \} & \{ mcp: true \}` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
42 | `requestOptions?` | `ComposioRequestOptions` | |
43
44 **Returns**
@@ -41,7 +48,7 @@ async create(userId: string, config: ToolRouterCreateSessionConfig & { mcp: true
48 **Overload 2**
49
50 ```typescript
44 -async create(userId: string, config?: ToolRouterCreateSessionConfig, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
51 +async create(userId: string, config?: { authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string | string[]>; experimental?: { assistivePrompt?: { userTimezone?: string }; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] }; manageConnections?: boolean | { callbackUrl?: string; enable?: boolean; waitForConnections?: boolean }; mcp?: boolean; multiAccount?: { enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean }; preload?: { tools?: string[] | 'all' }; sandbox?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' }; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] | { disable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[]; enable?: 'readOnlyHint' | 'destructiveHint' | 'idempotentHint' | 'openWorldHint'[] }; toolkits?: string[] | { disable: string[] } | { enable: string[] }; tools?: Record<string, string[] | { enable: string[] } | { disable: string[] } | { tags: ...[] | { disable?: ...; enable?: ... } }>; workbench?: { autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' | 'medium' | 'large' | 'xlarge' } }, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
52 ```
53
54 **Parameters**
@@ -49,7 +56,7 @@ async create(userId: string, config?: ToolRouterCreateSessionConfig, requestOpti
56 | Name | Type | Description |
57 |------|------|-------------|
58 | `userId` | `string` | \{string\} The user id to create the session for |
52 -| `config?` | `ToolRouterCreateSessionConfig` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
59 +| `config?` | `\{ authConfigs?: Record<string, string>; connectedAccounts?: Record<string, string \| string[]>; experimental?: \{ assistivePrompt?: \{ userTimezone?: string \}; customToolkits?: CustomToolkit[]; customTools?: CustomTool[] \}; manageConnections?: boolean \| \{ callbackUrl?: string; enable?: boolean; waitForConnections?: boolean \}; mcp?: boolean; multiAccount?: \{ enable: boolean; maxAccountsPerToolkit?: number; requireExplicitSelection?: boolean \}; preload?: \{ tools?: string[] \| 'all' \}; sandbox?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \}; sessionPreset?: 'direct_tools'; tags?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \| \{ disable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[]; enable?: 'readOnlyHint' \| 'destructiveHint' \| 'idempotentHint' \| 'openWorldHint'[] \}; toolkits?: string[] \| \{ disable: string[] \} \| \{ enable: string[] \}; tools?: Record<string, string[] \| \{ enable: string[] \} \| \{ disable: string[] \} \| \{ tags: ...[] \| \{ disable?: ...; enable?: ... \} \}>; workbench?: \{ autoOffloadThreshold?: number; enable: boolean; enableProxyExecution?: boolean; sandboxSize?: 'standard' \| 'medium' \| 'large' \| 'xlarge' \} \}` | \{ToolRouterCreateSessionConfig\} The config for the tool router session |
60 | `requestOptions?` | `ComposioRequestOptions` | |
61
62 **Returns**
@@ -83,7 +90,7 @@ Deleted sessions immediately stop being retrievable or executable. Deleting
90 a missing or already-deleted session surfaces the backend 404.
91
92 ```typescript
86 -async delete(id: string, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionDeleteResponse>
93 +async delete(id: string, requestOptions?: ComposioRequestOptions): Promise<{ deleted: true; sessionId: string }>
94 ```
95
96 **Parameters**
@@ -95,7 +102,7 @@ async delete(id: string, requestOptions?: ComposioRequestOptions): Promise<ToolR
102
103 **Returns**
104
98 -`Promise<ToolRouterSessionDeleteResponse>`
105 +`Promise<\{ deleted: true; sessionId: string \}>`
106
107 ---
108
@@ -103,10 +110,17 @@ async delete(id: string, requestOptions?: ComposioRequestOptions): Promise<ToolR
110
111 Use an existing session
112
113 +The session's MCP config carries the session credential only when the
114 +MCP URL shares the origin of the configured API base URL. When it does
115 +not, `mcp: true` makes the call throw `ComposioMCPDestinationError`
116 +(naming both origins, never a key); without `mcp: true` the session is
117 +returned with `session.mcp.headers` empty and a warning naming both
118 +origins is logged, so native tools keep working.
119 +
120 **Overload 1**
121
122 ```typescript
109 -async use(id: string, options: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
123 +async use(id: string, options: { customToolkits?: CustomToolkit[]; customTools?: CustomTool[]; mcp: true }, requestOptions?: ComposioRequestOptions): Promise<Session<TToolCollection, TTool, TProvider>>
124 ```
125
126 **Parameters**
@@ -114,7 +128,7 @@ async use(id: string, options: { customTools?: CustomTool[]; customToolkits?: Cu
128 | Name | Type | Description |
129 |------|------|-------------|
130 | `id` | `string` | \{string\} The id of the session to use |
117 -| `options` | `\{ customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp: true \}` | |
131 +| `options` | `\{ customToolkits?: CustomToolkit[]; customTools?: CustomTool[]; mcp: true \}` | |
132 | `requestOptions?` | `ComposioRequestOptions` | |
133
134 **Returns**
@@ -124,7 +138,7 @@ async use(id: string, options: { customTools?: CustomTool[]; customToolkits?: Cu
138 **Overload 2**
139
140 ```typescript
127 -async use(id: string, options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp?: boolean }, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
141 +async use(id: string, options?: { customToolkits?: CustomToolkit[]; customTools?: CustomTool[]; mcp?: boolean }, requestOptions?: ComposioRequestOptions): Promise<SessionWithoutMcp<TToolCollection, TTool, TProvider>>
142 ```
143
144 **Parameters**
@@ -132,7 +146,7 @@ async use(id: string, options?: { customTools?: CustomTool[]; customToolkits?: C
146 | Name | Type | Description |
147 |------|------|-------------|
148 | `id` | `string` | \{string\} The id of the session to use |
135 -| `options?` | `\{ customTools?: CustomTool[]; customToolkits?: CustomToolkit[]; mcp?: boolean \}` | |
149 +| `options?` | `\{ customToolkits?: CustomToolkit[]; customTools?: CustomTool[]; mcp?: boolean \}` | |
150 | `requestOptions?` | `ComposioRequestOptions` | |
151
152 **Returns**
python/composio/client/__init__.py
+60 -1
@@ -22,7 +22,11 @@ from composio_client import (
22 from composio_client import Composio as BaseComposio
23 from httpx import URL, Client, Request, Response, Timeout
24
25 -from composio.exceptions import ComposioError
25 +from composio.core.models.tool_router_constants import (
26 + PROJECT_API_KEY_HEADER,
27 + USER_API_KEY_HEADER,
28 +)
29 +from composio.exceptions import ComposioError, InvalidParams
30 from composio.utils.logging import LogLevel, WithLogger, _VerbosityWrapper
31
32 ComposioAPIError = APIError
@@ -312,6 +316,7 @@ class HttpClient(BaseComposio, WithLogger):
316 *,
317 provider: str,
318 api_key: t.Optional[str] = None,
319 + disable_api_key: bool = False,
320 user_api_key: t.Optional[str] = None,
321 org_api_key: t.Optional[str] = None,
322 environment: te.Union[NotGiven, APIEnvironment] = "production",
@@ -324,6 +329,7 @@ class HttpClient(BaseComposio, WithLogger):
329 logger: t.Optional[logging.Logger] = None,
330 logging_level: t.Optional[LogLevel] = None,
331 _strict_response_validation: bool = False,
332 + _environment_variables: t.Optional[t.Mapping[str, str]] = None,
333 ) -> None:
334 """
335 Initialize the client.
@@ -332,6 +338,11 @@ class HttpClient(BaseComposio, WithLogger):
338 :param logger: Logger that receives SDK and ``composio_client`` records.
339 :param logging_level: Level applied to the SDK and ``composio_client`` loggers.
340 :param api_key: The API key to use for the client.
341 + :param disable_api_key: Turn project-key authentication off, including the
342 + ``COMPOSIO_API_KEY`` fallback; ``None`` alone keeps that fallback.
343 + :param _environment_variables: Environment snapshot the generated client
344 + resolves its fallbacks from instead of ``os.environ``; clones of a
345 + client built from a snapshot receive an empty one.
346 :param user_api_key: User API key, sent only on operations that require it.
347 :param org_api_key: Organization API key, sent only on operations that require it.
348 :param environment: The environment to use for the client.
@@ -343,6 +354,50 @@ class HttpClient(BaseComposio, WithLogger):
354 :param http_client: The HTTP client to use for the client.
355 """
356 WithLogger.__init__(self, logger=logger, logging_level=logging_level)
357 + self._disable_api_key = disable_api_key
358 + if disable_api_key:
359 + # The project credential is only ever set from `api_key`: a raw
360 + # `x-api-key` default header would bypass the disabled project key.
361 + project_key_header = next(
362 + (
363 + name
364 + for name in (default_headers or {})
365 + if name.lower() == PROJECT_API_KEY_HEADER
366 + ),
367 + None,
368 + )
369 + if project_key_header is not None:
370 + raise InvalidParams(
371 + f"`disable_api_key=True` sends no project key, but "
372 + f"`default_headers` carries a `{project_key_header}` entry; "
373 + "pass the project API key as `api_key` instead of a raw "
374 + f"`{PROJECT_API_KEY_HEADER}` header, or remove the entry to "
375 + "authenticate with the user API key alone"
376 + )
377 + # The generated client reads COMPOSIO_API_KEY whenever `api_key` is
378 + # None, so hand it an environment without that variable. Clones
379 + # inherit the resolved values and an empty snapshot.
380 + api_key = None
381 + if _environment_variables is None:
382 + _environment_variables = {
383 + name: value
384 + for name, value in os.environ.items()
385 + if name != "COMPOSIO_API_KEY"
386 + }
387 + # The generated client sends its user key only on operations whose
388 + # security scheme names it, which excludes sessions. The resolved
389 + # user key is placed as the `x-user-api-key` default header instead,
390 + # so every request carries exactly that credential.
391 + resolved_user_api_key = user_api_key or _environment_variables.get(
392 + "COMPOSIO_USER_API_KEY"
393 + )
394 + if resolved_user_api_key and not any(
395 + name.lower() == USER_API_KEY_HEADER for name in (default_headers or {})
396 + ):
397 + default_headers = {
398 + **(default_headers or {}),
399 + USER_API_KEY_HEADER: resolved_user_api_key,
400 + }
401 BaseComposio.__init__(
402 self,
403 api_key=api_key,
@@ -356,6 +411,7 @@ class HttpClient(BaseComposio, WithLogger):
411 default_query=default_query,
412 http_client=http_client,
413 _strict_response_validation=_strict_response_validation,
414 + _environment_variables=_environment_variables,
415 )
416 _install_client_log_forwarder(self._logger)
417 self.provider = provider
@@ -387,6 +443,9 @@ class HttpClient(BaseComposio, WithLogger):
443 return super().copy( # type: ignore[misc]
444 _extra_kwargs={
445 "provider": self.provider,
446 + # Clones keep the project key disabled, so a default header
447 + # added through `with_options` goes through the same checks.
448 + "disable_api_key": self._disable_api_key,
449 # The generated `copy` does not re-pass `_strict_response_validation`,
450 # so without this the clone would silently fall back to the default
451 # (False) even when the original had it enabled — keeping the sibling
python/composio/core/models/base.py
+35
@@ -3,6 +3,7 @@ Base resource class for representing resources in the composio client.
3 """
4
5 import contextvars
6 +from collections.abc import Mapping
7 import functools
8 import os
9 import time
@@ -90,3 +91,37 @@ class Resource(WithLogger, metaclass=ResourceMeta):
91 def __init__(self, client: HttpClient):
92 super().__init__()
93 self._client = client
94 +
95 +
96 +def header_value(headers: t.Mapping[str, t.Any], name: str) -> t.Optional[str]:
97 + """The non-empty value of ``name`` in ``headers``, matched case-insensitively."""
98 + if not isinstance(headers, Mapping):
99 + return None
100 + wanted = name.lower()
101 + for key, value in headers.items():
102 + if isinstance(key, str) and key.lower() == wanted:
103 + if isinstance(value, str) and value:
104 + return value
105 + return None
106 +
107 +
108 +def credential_headers(client: HttpClient) -> t.Dict[str, str]:
109 + """The single credential header the client puts on the wire.
110 +
111 + A non-empty ``x-user-api-key`` default header wins: the client treats a
112 + caller-placed credential header as the credential and suppresses the
113 + configured keys. Otherwise the project key travels as ``x-api-key``,
114 + otherwise the resolved user API key as ``x-user-api-key``. Empty when no
115 + credential is held. The environment is never consulted here.
116 + """
117 + default_headers: t.Mapping[str, t.Any] = client.default_headers
118 + header_key = header_value(default_headers, "x-user-api-key")
119 + if header_key:
120 + return {"x-user-api-key": header_key}
121 + api_key = client.api_key
122 + if isinstance(api_key, str) and api_key:
123 + return {"x-api-key": api_key}
124 + user_api_key = client.user_api_key
125 + if isinstance(user_api_key, str) and user_api_key:
126 + return {"x-user-api-key": user_api_key}
127 + return {}
python/composio/core/models/tool_router.py
+139 -9
@@ -7,9 +7,11 @@ for creating isolated MCP sessions with provider-wrapped tools.
7
8 from __future__ import annotations
9
10 +import logging
11 import typing as t
12 from dataclasses import dataclass
13 from enum import Enum
14 +from urllib.parse import urlsplit
15
16 import typing_extensions as te
17 from composio_client import omit
@@ -22,7 +24,7 @@ from composio_client.types.tool_router.session_retrieve_response import (
24 )
25
26 from composio.client import HttpClient
25 -from composio.core.models.base import Resource
27 +from composio.core.models.base import Resource, credential_headers, header_value
28 from composio.core.models.custom_tool import (
29 ExperimentalToolkit,
30 assert_no_custom_tool_slugs_in_preload,
@@ -41,13 +43,18 @@ from composio.core.models.inline_custom_tools_payload import (
43 inline_custom_tools_attach_experimental,
44 )
45 from composio.core.models.tool_router_constants import (
46 + ORG_ID_HEADER,
47 PRELOAD_TOOLS_ALL,
48 + PROJECT_ID_HEADER,
49 SESSION_PRESET_DIRECT_TOOLS,
50 )
51 from composio.core.models.tool_router_session import (
52 ToolRouterSession,
53 ToolRouterSessionPreloadConfig,
54 ToolRouterSessionWithMcp,
55 + ToolRouterUpdateExperimentalConfig,
56 + ToolRouterUpdateManageConnectionsConfig,
57 + ToolRouterUpdateMultiAccountConfig,
58 )
59 from composio.core.models.tool_router_session_delete import (
60 ToolRouterSessionDeleteResponse,
@@ -56,7 +63,53 @@ from composio.core.models.tool_router_session_delete import (
63 from composio.core.models.tool_router_session_files import ToolRouterSessionFilesMount
64 from composio.core.provider import TTool, TToolCollection
65 from composio.core.provider.base import BaseProvider
59 -from composio.exceptions import InvalidParams
66 +from composio.exceptions import InvalidParams, MCPDestinationError
67 +
68 +logger = logging.getLogger(__name__)
69 +
70 +_DEFAULT_PORTS = {"http": 80, "https": 443}
71 +
72 +# Schemes whose URLs have a tuple origin (``scheme://host[:port]``) under the
73 +# WHATWG URL standard. Every other scheme (``data:``, ``file:``, ``blob:``
74 +# without a base, ...) has an opaque origin that serializes as ``null``, so two
75 +# such URLs would compare equal; they are rejected before any comparison.
76 +_TUPLE_ORIGIN_SCHEMES = frozenset({"ftp", "http", "https", "ws", "wss"})
77 +
78 +
79 +def _origin(url: str, role: str) -> str:
80 + """Return the origin of an absolute URL.
81 +
82 + The origin is ``scheme://host[:port]`` in lowercase with the scheme's
83 + default port dropped, matching the WHATWG ``URL.origin`` used by the
84 + TypeScript SDK. ``role`` names the URL in the error; the URL itself is
85 + never echoed, since it may carry a query token.
86 + """
87 + parts = urlsplit(url)
88 + try:
89 + port = parts.port
90 + except ValueError as exc:
91 + raise MCPDestinationError(
92 + f"The {role} is not a valid absolute URL", mcp_origin="", api_origin=""
93 + ) from exc
94 + if not parts.scheme:
95 + raise MCPDestinationError(
96 + f"The {role} is not a valid absolute URL", mcp_origin="", api_origin=""
97 + )
98 + if parts.scheme.lower() not in _TUPLE_ORIGIN_SCHEMES:
99 + raise MCPDestinationError(
100 + f"The {role} has an opaque origin", mcp_origin="", api_origin=""
101 + )
102 + if not parts.hostname:
103 + raise MCPDestinationError(
104 + f"The {role} is not a valid absolute URL", mcp_origin="", api_origin=""
105 + )
106 + scheme = parts.scheme.lower()
107 + hostname = parts.hostname.lower()
108 + host = f"[{hostname}]" if ":" in hostname else hostname
109 + if port is not None and port != _DEFAULT_PORTS.get(scheme):
110 + host = f"{host}:{port}"
111 + return f"{scheme}://{host}"
112 +
113
114 # Type alias for MCP tag literals
115 ToolRouterTag = t.Literal[
@@ -534,25 +587,77 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
587 dangerously_allow_auto_upload_download_files
588 )
589
590 + def _mcp_destination_rejection(self, url: str) -> t.Optional[MCPDestinationError]:
591 + """The error describing why ``url`` must not receive the session
592 + credential, or ``None`` when it shares the client's API origin."""
593 + try:
594 + api_origin = _origin(str(self._client.base_url), "API base URL")
595 + mcp_origin = _origin(url, "MCP URL")
596 + except MCPDestinationError as exc:
597 + return exc
598 + if mcp_origin == api_origin:
599 + return None
600 + return MCPDestinationError(
601 + f"The session MCP endpoint origin {mcp_origin} does not match the "
602 + f"API origin {api_origin}; the session credential was not attached",
603 + mcp_origin=mcp_origin,
604 + api_origin=api_origin,
605 + )
606 +
607 def _create_mcp_server_config(
608 self,
609 mcp_type: ToolRouterMCPServerType,
610 url: str,
611 + mcp_requested: bool,
612 ) -> ToolRouterMCPServerConfig:
613 """
614 Create an MCP server config object with authentication headers.
615
616 + The headers mirror the effective auth of the underlying client: the
617 + ``x-user-api-key`` default header when one is placed (the client sends
618 + it and suppresses the configured keys), otherwise its project key as
619 + ``x-api-key``, otherwise the resolved ``user_api_key`` option as
620 + ``x-user-api-key``, plus ``x-org-id`` / ``x-project-id`` when the
621 + client carries an explicit scope. No other default header is copied
622 + and the environment is never re-read.
623 +
624 + The headers are only attached when the MCP URL has the same origin as
625 + the client's API base URL, whatever scheme is configured: that origin
626 + already receives them on every SDK request. Any other destination (a
627 + different origin, an opaque origin, or a URL that does not parse)
628 + never receives them. When the caller asked for MCP
629 + (``mcp_requested``), that raises
630 + :class:`~composio.exceptions.MCPDestinationError` naming both origins;
631 + otherwise the config is returned with empty headers and a warning
632 + naming both origins is logged, so callers who only use the native
633 + tools are not blocked by an endpoint they never consume. The SDK
634 + itself never connects to the MCP URL and does not follow redirects for
635 + it; an MCP client consuming this config must not forward these headers
636 + to a different origin.
637 +
638 :param mcp_type: The type of MCP server (HTTP or SSE)
639 :param url: The URL of the MCP server
640 + :param mcp_requested: Whether the caller passed ``mcp=True``
641 :return: MCP server config with headers
642 """
549 - return ToolRouterMCPServerConfig(
550 - type=mcp_type,
551 - url=url,
552 - headers={
553 - "x-api-key": self._client.api_key,
554 - },
555 - )
643 + rejection = self._mcp_destination_rejection(url)
644 + if rejection is not None:
645 + if mcp_requested:
646 + raise rejection
647 + logger.warning(
648 + "%s. session.mcp.headers was left empty; pass mcp=True to make "
649 + "this an error",
650 + rejection,
651 + )
652 + return ToolRouterMCPServerConfig(type=mcp_type, url=url, headers={})
653 +
654 + default_headers: t.Mapping[str, t.Any] = self._client.default_headers
655 + headers: t.Dict[str, t.Optional[str]] = dict(credential_headers(self._client))
656 + for scope_header in (ORG_ID_HEADER, PROJECT_ID_HEADER):
657 + scope_value = header_value(default_headers, scope_header)
658 + if scope_value:
659 + headers[scope_header] = scope_value
660 + return ToolRouterMCPServerConfig(type=mcp_type, url=url, headers=headers)
661
662 def _transform_tags_params(
663 self, tags: t.Optional[ToolRouterConfigTags]
@@ -788,8 +893,17 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
893 the type (returns ToolRouterSessionWithMcp). The endpoint
894 exists on every session at runtime regardless of this flag;
895 native tools (``session.tools()``) are unaffected.
896 + The session credential is exported in ``session.mcp.headers``
897 + only when the MCP URL shares the origin of the configured
898 + API base URL. When it does not, ``mcp=True`` raises
899 + :class:`~composio.exceptions.MCPDestinationError` (naming
900 + both origins, never a key); otherwise the session is
901 + returned with empty ``session.mcp.headers`` and a warning
902 + naming both origins is logged.
903 See https://docs.composio.dev/docs/sessions-via-mcp
904 :return: Tool router session object
905 + :raises MCPDestinationError: When ``mcp=True`` and the MCP URL is not
906 + on the API origin.
907
908 Example:
909 ```python
@@ -1119,9 +1233,11 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1233 file_upload_dirs=self._file_upload_dirs,
1234 session_id=session.session_id,
1235 config=session.config,
1236 + config_version=session.config_version,
1237 mcp=self._create_mcp_server_config(
1238 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
1239 url=session.mcp.url,
1240 + mcp_requested=mcp,
1241 ),
1242 experimental=experimental_response,
1243 custom_tools_map=custom_tools_map,
@@ -1177,8 +1293,17 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1293 :param custom_toolkits: Optional custom toolkits to bind to the session.
1294 :param mcp: When True, the returned session surfaces its hosted MCP
1295 endpoint in the type (returns ToolRouterSessionWithMcp).
1296 + The session credential is exported in ``session.mcp.headers``
1297 + only when the MCP URL shares the origin of the configured
1298 + API base URL. When it does not, ``mcp=True`` raises
1299 + :class:`~composio.exceptions.MCPDestinationError` (naming
1300 + both origins, never a key); otherwise the session is
1301 + returned with empty ``session.mcp.headers`` and a warning
1302 + naming both origins is logged.
1303 See https://docs.composio.dev/docs/sessions-via-mcp
1304 :return: Tool router session object
1305 + :raises MCPDestinationError: When ``mcp=True`` and the MCP URL is not
1306 + on the API origin.
1307
1308 Example:
1309 ```python
@@ -1268,9 +1393,11 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1393 file_upload_dirs=self._file_upload_dirs,
1394 session_id=session.session_id,
1395 config=session.config,
1396 + config_version=session.config_version,
1397 mcp=self._create_mcp_server_config(
1398 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
1399 url=session.mcp.url,
1400 + mcp_requested=mcp,
1401 ),
1402 experimental=experimental_response,
1403 custom_tools_map=custom_tools_map,
@@ -1306,6 +1433,9 @@ __all__ = [
1433 "ToolRouterTagsEnableDisableConfig",
1434 "ToolRouterConfigTags",
1435 "ToolRouterManageConnectionsConfig",
1436 + "ToolRouterUpdateManageConnectionsConfig",
1437 + "ToolRouterUpdateMultiAccountConfig",
1438 + "ToolRouterUpdateExperimentalConfig",
1439 "ToolRouterSandboxConfig",
1440 "ToolRouterWorkbenchConfig",
1441 "SandboxSize",
python/composio/core/models/tool_router_constants.py
+11
@@ -2,3 +2,14 @@ import typing as t
2
3 SESSION_PRESET_DIRECT_TOOLS: t.Literal["direct_tools"] = "direct_tools"
4 PRELOAD_TOOLS_ALL: t.Literal["all"] = "all"
5 +
6 +#: Header that carries the project API key. The SDK only ever sets it from the
7 +#: resolved ``api_key``; a caller-placed default header is rejected when
8 +#: project-key authentication is disabled.
9 +PROJECT_API_KEY_HEADER = "x-api-key"
10 +#: Header that carries a Composio user API key (``uak_...``) instead of a
11 +#: project API key. It is the only credential default header the MCP export reads.
12 +USER_API_KEY_HEADER = "x-user-api-key"
13 +#: Headers that carry the explicit organization / project scope.
14 +ORG_ID_HEADER = "x-org-id"
15 +PROJECT_ID_HEADER = "x-project-id"
python/composio/core/models/tool_router_session.py
+168 -27
@@ -13,7 +13,7 @@ from concurrent.futures import ThreadPoolExecutor
13 from dataclasses import dataclass
14
15 import typing_extensions as te
16 -from composio_client import BadRequestError, Omit, omit
16 +from composio_client import BadRequestError, ConflictError, Omit, omit
17 from composio_client._types import SequenceNotStr
18 from composio_client.types.tool_list_response import (
19 ItemDeprecated,
@@ -102,7 +102,7 @@ class ToolRouterSessionPreloadConfig:
102 #: Server-side session configuration as returned by the API: toolkit and tool
103 #: allowlists, tags, auth configs, connected accounts, ``manage_connections``,
104 #: preload, sandbox (``workbench``), search and execute settings. The four
105 -#: Stainless response models carry the same fields.
105 +#: generated response models carry the same fields.
106 ToolRouterSessionConfig = t.Union[
107 session_create_response.Config,
108 session_retrieve_response.Config,
@@ -111,6 +111,46 @@ ToolRouterSessionConfig = t.Union[
111 ]
112
113
114 +class ToolRouterUpdateManageConnectionsConfig(te.TypedDict, total=False):
115 + """``manage_connections`` shape accepted by :meth:`ToolRouterSession.update`.
116 +
117 + Only the supplied subfields travel. Unlike the create-time config,
118 + ``callback_url=None`` removes the stored callback URL while leaving the
119 + sibling connection settings untouched.
120 + """
121 +
122 + enable: t.Optional[bool]
123 + callback_url: t.Optional[str]
124 + enable_connection_removal: t.Optional[bool]
125 + enable_wait_for_connections: t.Optional[bool]
126 +
127 +
128 +class ToolRouterUpdateMultiAccountConfig(te.TypedDict, total=False):
129 + """``multi_account`` shape accepted by :meth:`ToolRouterSession.update`.
130 +
131 + ``max_accounts_per_toolkit=None`` removes the stored maximum so the
132 + default applies again.
133 + """
134 +
135 + enable: bool
136 + max_accounts_per_toolkit: t.Optional[int]
137 + require_explicit_selection: bool
138 +
139 +
140 +class ToolRouterUpdateExperimentalConfig(te.TypedDict, total=False):
141 + """``experimental`` shape accepted by :meth:`ToolRouterSession.update`.
142 +
143 + Each leaf follows the PATCH contract: omit to keep the stored value,
144 + ``None`` to remove it, a value to replace it.
145 + """
146 +
147 + permissions: t.Optional[t.Dict[str, t.Any]]
148 + link_url_overwrite: t.Optional[str]
149 + fast_mode: t.Optional[bool]
150 + submit_feedback: t.Optional[t.Dict[str, bool]]
151 + session_config_id: str
152 +
153 +
154 class ToolRouterSession(t.Generic[TTool, TToolCollection]):
155 """
156 A Composio session — the object returned by ``composio.create(...)`` /
@@ -142,6 +182,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
182 config: ToolRouterSessionConfig
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.
188 + config_version: t.Optional[int]
189
190 def __init__(
191 self,
@@ -156,6 +200,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
200 mcp: t.Any,
201 experimental: "ToolRouterSessionExperimental",
202 config: t.Optional[ToolRouterSessionConfig] = None,
203 + config_version: t.Optional[int] = None,
204 custom_tools_map: t.Optional[CustomToolsMap] = None,
205 user_id: t.Optional[str] = None,
206 preload: t.Optional[ToolRouterSessionPreloadConfig] = None,
@@ -185,6 +230,9 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
230 # not surface `mcp` on the base class — MCP is an explicit opt-in.
231 setattr(self, "mcp", mcp)
232 self.experimental = experimental
233 + self.config_version = (
234 + config_version if isinstance(config_version, int) else None
235 + )
236 self._custom_tools_map = custom_tools_map
237 self._user_id = user_id
238 self._preloaded_custom_tool_slugs = preloaded_custom_tool_slugs or []
@@ -933,36 +981,65 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
981 def update(
982 self,
983 *,
936 - toolkits: t.Union[session_patch_params.Toolkits, "Omit"] = omit,
937 - tools: t.Union[t.Dict[str, session_patch_params.Tools], "Omit"] = omit,
938 - tags: t.Union[session_patch_params.Tags, "Omit"] = omit,
939 - auth_configs: t.Union[t.Dict[str, str], "Omit"] = omit,
984 + toolkits: t.Union[t.Optional[session_patch_params.Toolkits], "Omit"] = omit,
985 + tools: t.Union[
986 + t.Optional[t.Dict[str, session_patch_params.Tools]], "Omit"
987 + ] = omit,
988 + tags: t.Union[t.Optional[session_patch_params.Tags], "Omit"] = omit,
989 + auth_configs: t.Union[t.Optional[t.Dict[str, str]], "Omit"] = omit,
990 connected_accounts: t.Union[
991 t.Optional[t.Dict[str, SequenceNotStr[str]]], "Omit"
992 ] = omit,
993 manage_connections: t.Union[
944 - t.Optional[session_patch_params.ManageConnections], "Omit"
994 + t.Optional[session_patch_params.ManageConnections],
995 + t.Optional[ToolRouterUpdateManageConnectionsConfig],
996 + "Omit",
997 ] = omit,
998 sandbox: t.Union[t.Optional[session_patch_params.Workbench], "Omit"] = omit,
999 workbench: t.Union[t.Optional[session_patch_params.Workbench], "Omit"] = omit,
1000 multi_account: t.Union[
949 - t.Optional[session_patch_params.MultiAccount], "Omit"
1001 + t.Optional[session_patch_params.MultiAccount],
1002 + t.Optional[ToolRouterUpdateMultiAccountConfig],
1003 + "Omit",
1004 + ] = omit,
1005 + preload: t.Union[t.Optional[session_patch_params.Preload], "Omit"] = omit,
1006 + search: t.Union[t.Optional[session_patch_params.Search], "Omit"] = omit,
1007 + execute: t.Union[t.Optional[session_patch_params.Execute], "Omit"] = omit,
1008 + experimental: t.Union[
1009 + t.Optional[session_patch_params.Experimental],
1010 + t.Optional[ToolRouterUpdateExperimentalConfig],
1011 + "Omit",
1012 ] = omit,
951 - preload: t.Union[session_patch_params.Preload, "Omit"] = omit,
1013 + expected_config_version: t.Union[int, None, t.Literal[False]] = None,
1014 ) -> ToolRouterSessionConfig:
1015 """Partially update the session configuration.
1016
955 - Only the fields provided will be changed; omitted fields are preserved.
956 - Mutates this session's ``config`` and ``preload`` in-place and returns
957 - the updated session configuration.
958 -
959 - Pass ``None`` for ``manage_connections``, ``sandbox``/``workbench``, or
960 - ``multi_account`` to clear the stored value.
1017 + Only the fields provided are changed; omitted fields are preserved.
1018 + For each policy block ``None`` removes the stored override (which can
1019 + increase access: ``toolkits=None`` restores the unrestricted default,
1020 + while ``toolkits={"enable": []}`` denies every app toolkit and is sent
1021 + as-is). Supplied ``tools``, ``auth_configs`` and ``connected_accounts``
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``.
1034 +
1035 + ``config``, ``config_version`` and ``preload`` are refreshed in place
1036 + only after a successful response, and the updated ``config`` is
1037 + returned.
1038
1039 ``workbench`` is a backwards-compatible alias for ``sandbox``. Prefer
1040 ``sandbox`` in new code.
1041
965 - All parameters use the same types as the Stainless-generated
1042 + All other parameters use the same types as the generated
1043 ``client.tool_router.session.patch()`` method.
1044 """
1045 from composio.core.models.tool_router import _session_preload_config
@@ -973,21 +1050,85 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1050 "`workbench` is a backwards-compatible alias for `sandbox`."
1051 )
1052
1053 + precondition: t.Union[int, "Omit"]
1054 + if expected_config_version is False:
1055 + precondition = omit
1056 + elif expected_config_version is None:
1057 + precondition = omit if self.config_version is None else self.config_version
1058 + elif isinstance(expected_config_version, bool) or expected_config_version < 1:
1059 + raise exceptions.InvalidParams(
1060 + "`expected_config_version` must be a positive integer, or False to "
1061 + "send no precondition"
1062 + )
1063 + else:
1064 + precondition = expected_config_version
1065 +
1066 workbench_payload = sandbox if sandbox is not omit else workbench
1067
978 - response = self._client.tool_router.session.patch(
979 - session_id=self.session_id,
980 - toolkits=toolkits,
981 - tools=tools,
982 - tags=tags,
983 - auth_configs=auth_configs,
984 - connected_accounts=connected_accounts,
985 - manage_connections=manage_connections,
986 - workbench=workbench_payload,
987 - multi_account=multi_account,
988 - preload=preload,
1068 + # The generated client has no typed parameter for the precondition, so
1069 + # it travels as an extra root body field.
1070 + extra_body = (
1071 + None
1072 + if isinstance(precondition, Omit)
1073 + else {"expected_config_version": precondition}
1074 )
1075 +
1076 + # The generated client does not type ``None`` for every policy block
1077 + # although the API accepts it (it removes the stored override), nor the
1078 + # subfield removals inside ``manage_connections``, ``multi_account`` and
1079 + # ``experimental``; the values are serialized as-is.
1080 + try:
1081 + response = self._client.tool_router.session.patch(
1082 + session_id=self.session_id,
1083 + toolkits=t.cast(
1084 + t.Union[session_patch_params.Toolkits, "Omit"], toolkits
1085 + ),
1086 + tools=t.cast(
1087 + t.Union[t.Dict[str, session_patch_params.Tools], "Omit"], tools
1088 + ),
1089 + tags=t.cast(t.Union[session_patch_params.Tags, "Omit"], tags),
1090 + auth_configs=t.cast(t.Union[t.Dict[str, str], "Omit"], auth_configs),
1091 + connected_accounts=connected_accounts,
1092 + manage_connections=t.cast(
1093 + t.Union[t.Optional[session_patch_params.ManageConnections], "Omit"],
1094 + manage_connections,
1095 + ),
1096 + workbench=workbench_payload,
1097 + multi_account=t.cast(
1098 + t.Union[t.Optional[session_patch_params.MultiAccount], "Omit"],
1099 + multi_account,
1100 + ),
1101 + preload=t.cast(t.Union[session_patch_params.Preload, "Omit"], preload),
1102 + search=t.cast(t.Union[session_patch_params.Search, "Omit"], search),
1103 + execute=t.cast(t.Union[session_patch_params.Execute, "Omit"], execute),
1104 + experimental=t.cast(
1105 + t.Union[t.Optional[session_patch_params.Experimental], "Omit"],
1106 + experimental,
1107 + ),
1108 + extra_body=extra_body,
1109 + # A stale precondition is a deterministic 409: never retry it.
1110 + request_options={"max_retries": 0},
1111 + )
1112 + except ConflictError as exc:
1113 + if precondition is omit:
1114 + message = (
1115 + f"Session {self.session_id} configuration changed while this "
1116 + "update was in flight; re-fetch the session and retry the update"
1117 + )
1118 + else:
1119 + message = (
1120 + f"Session {self.session_id} configuration is no longer at "
1121 + f"version {precondition}; re-fetch the session and retry the update"
1122 + )
1123 + raise exceptions.SessionConfigConflictError(
1124 + message,
1125 + session_id=self.session_id,
1126 + expected_config_version=(
1127 + None if isinstance(precondition, Omit) else precondition
1128 + ),
1129 + ) from exc
1130 self.config = response.config
1131 + self.config_version = response.config_version
1132 self.preload = _session_preload_config(response.config.preload)
1133 return self.config
1134
python/composio/core/models/triggers.py
+2 -2
@@ -25,7 +25,7 @@ from pysher.connection import Connection as PusherConnection
25 from composio import exceptions
26 from composio.client import HttpClient
27 from composio.client.types import trigger_instance_upsert_response
28 -from composio.core.models.base import Resource
28 +from composio.core.models.base import Resource, credential_headers
29 from composio.core.models.internal import Internal
30 from composio.core.models.webhooks import (
31 DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS,
@@ -1066,7 +1066,7 @@ class _SubcriptionBuilder(WithLogger):
1066 cluster=_validate_pusher_cluster(cluster),
1067 auth_endpoint=PUSHER_AUTH_URL.format(base_url=self._client.base_url),
1068 auth_endpoint_headers={
1069 - "x-api-key": self._client.api_key,
1069 + **credential_headers(self._client),
1070 "x-request-id": str(uuid.uuid4()),
1071 },
1072 auto_sub=True,
python/composio/exceptions.py
+56
@@ -327,6 +327,62 @@ class ApiKeyNotProvidedError(ApiKeyError, NotFoundError):
327 )
328
329
330 +class UserApiKeyNotProvidedError(ApiKeyError):
331 + """Raised when the project key is disabled and no user API key is available."""
332 +
333 + def __init__(self) -> None:
334 + super().__init__(
335 + message=(
336 + "`disable_api_key=True` turns off the project API key, but no user "
337 + "API key was provided: pass `user_api_key` or export it as "
338 + "`COMPOSIO_USER_API_KEY`"
339 + )
340 + )
341 +
342 +
343 +class MCPDestinationError(ComposioClientError):
344 + """Raised when a session's hosted MCP endpoint is not a destination the
345 + SDK will hand the session headers to.
346 +
347 + The credential and scope headers are only attached when the MCP URL shares
348 + the origin of the API base URL the session was created against. The error
349 + is raised only when the caller asked for the endpoint with ``mcp=True``;
350 + otherwise the session is returned with empty ``mcp.headers`` and a warning
351 + is logged instead. The message names both origins and never includes a
352 + credential value.
353 + """
354 +
355 + def __init__(self, message: str, *, mcp_origin: str, api_origin: str) -> None:
356 + super().__init__(message)
357 + self.mcp_origin = mcp_origin
358 + self.api_origin = api_origin
359 +
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.
366 +
367 + The local session object is left as it was before the call. Re-fetch the
368 + session with ``composio.sessions.use(session_id)`` and retry the update
369 + against the fresh ``config_version``.
370 + """
371 +
372 + status_code = 409
373 +
374 + def __init__(
375 + self,
376 + message: str,
377 + *,
378 + session_id: str,
379 + expected_config_version: t.Optional[int] = None,
380 + ) -> None:
381 + super().__init__(message)
382 + self.session_id = session_id
383 + self.expected_config_version = expected_config_version
384 +
385 +
386 class ResourceError(ComposioClientError):
387 pass
388
python/composio/sdk.py
+76 -7
@@ -23,6 +23,7 @@ from composio.core.models import (
23 )
24 from composio.core.models.base import allow_tracking
25 from composio.core.models.mcp import MCP
26 +from composio.core.models.tool_router_constants import ORG_ID_HEADER, PROJECT_ID_HEADER
27 from composio.core.provider import TTool, TToolCollection
28 from composio.core.provider._openai import (
29 OpenAIProvider,
@@ -43,8 +44,11 @@ _TOOL_ROUTER_DEPRECATION = (
44 class SDKConfig(te.TypedDict):
45 environment: te.NotRequired[APIEnvironment]
46 api_key: te.NotRequired[str]
47 + disable_api_key: te.NotRequired[bool]
48 user_api_key: te.NotRequired[str]
49 org_api_key: te.NotRequired[str]
50 + org_id: te.NotRequired[str]
51 + project_id: te.NotRequired[str]
52 base_url: te.NotRequired[str]
53 timeout: te.NotRequired[int]
54 max_retries: te.NotRequired[int]
@@ -60,6 +64,27 @@ class SDKConfig(te.TypedDict):
64 logging_level: te.NotRequired[LogLevel]
65
66
67 +def _scope_headers(
68 + *, org_id: t.Optional[str], project_id: t.Optional[str]
69 +) -> t.Dict[str, str]:
70 + """The ``x-org-id`` / ``x-project-id`` default headers for an explicit scope.
71 +
72 + The two nano IDs scope requests together: a user API key without an
73 + explicit scope keeps the API default (the developer project), so a
74 + half-configured scope is rejected instead of silently selecting a project.
75 + """
76 + org_id = org_id or None
77 + project_id = project_id or None
78 + if (org_id is None) != (project_id is None):
79 + raise exceptions.InvalidParams(
80 + "`org_id` and `project_id` scope requests together; pass both "
81 + "(the organization and consumer project nano IDs) or neither"
82 + )
83 + if org_id is None or project_id is None:
84 + return {}
85 + return {ORG_ID_HEADER: org_id, PROJECT_ID_HEADER: project_id}
86 +
87 +
88 class Composio(t.Generic[TTool, TToolCollection], WithLogger):
89 """
90 Composio SDK for Python.
@@ -111,17 +136,40 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
136
137 :param provider: The provider to use for the SDK. Defaults to OpenAIProvider.
138 :param environment: The environment to use for the SDK.
114 - :param api_key: The API key to use for the SDK.
139 + :param api_key: The project API key, sent as ``x-api-key``. When the
140 + argument is omitted it falls back to ``COMPOSIO_API_KEY``, as it
141 + always has. Passing ``api_key=None`` explicitly does not fall back
142 + and raises :class:`~composio.exceptions.ApiKeyNotProvidedError`;
143 + use ``disable_api_key=True`` to opt out of project-key
144 + authentication.
145 + :param disable_api_key: Turn project-key authentication off entirely,
146 + including the ``COMPOSIO_API_KEY`` fallback. The SDK then authenticates
147 + with the user API key alone (``user_api_key`` or
148 + ``COMPOSIO_USER_API_KEY``) and sends no ``x-api-key``; requests that
149 + require a project key keep their operation-specific errors. Combining
150 + it with an explicit ``api_key`` is an error. Defaults to ``False``.
151 :param user_api_key: User API key (``uak_*``) for the organization, consumer,
116 - and user-scoped endpoints reached through ``composio.client``. Sent as
117 - ``x-user-api-key`` only on operations whose security scheme requires it,
152 + and user-scoped endpoints reached through ``composio.client``, and for
153 + every session operation when ``disable_api_key=True``. Sent as
154 + ``x-user-api-key`` only on operations whose security scheme accepts it,
155 never alongside the project key. Falls back to ``COMPOSIO_USER_API_KEY``.
119 - A project ``api_key`` is still required.
156 :param org_api_key: Organization API key (``oak_*``) for the organization-owner
157 endpoints reached through ``composio.client``. Sent as ``x-org-api-key`` only
158 on operations whose security scheme requires it, never alongside the
159 project key. Falls back to ``COMPOSIO_ORG_API_KEY``. A project ``api_key``
160 is still required.
161 + :param org_id: Organization nano ID that scopes user-key requests, sent as the
162 + ``x-org-id`` header on every request and exported with the session MCP
163 + config. This is the short public identifier the API returns as
164 + ``org_id`` (for example from the consumer project resolve endpoint), not
165 + a UUID. Must be supplied together with ``project_id``; without an
166 + explicit scope a user API key addresses the API default (the developer
167 + project).
168 + :param project_id: Project nano ID that scopes user-key requests, sent as the
169 + ``x-project-id`` header on every request and exported with the session
170 + MCP config. This is the short public identifier the API returns as
171 + ``project_nano_id``, not the project UUID. Must be supplied together
172 + with ``org_id``.
173 :param base_url: The base URL to use for the SDK.
174 :param timeout: The timeout to use for the SDK.
175 :param max_retries: The maximum number of retries to use for the SDK.
@@ -166,9 +214,28 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
214 logger = kwargs.get("logger")
215 logging_level = kwargs.get("logging_level")
216 WithLogger.__init__(self, logger=logger, logging_level=logging_level)
169 - api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY"))
170 - if not api_key:
171 - raise exceptions.ApiKeyNotProvidedError()
217 + disable_api_key = kwargs.get("disable_api_key", False)
218 + api_key: t.Optional[str]
219 + if disable_api_key:
220 + if kwargs.get("api_key") is not None:
221 + raise exceptions.InvalidParams(
222 + "`disable_api_key=True` cannot be combined with an explicit "
223 + "`api_key`; pass one or the other"
224 + )
225 + api_key = None
226 + user_api_key = kwargs.get("user_api_key") or os.environ.get(
227 + "COMPOSIO_USER_API_KEY"
228 + )
229 + if not user_api_key:
230 + raise exceptions.UserApiKeyNotProvidedError()
231 + else:
232 + api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY"))
233 + if not api_key:
234 + raise exceptions.ApiKeyNotProvidedError()
235 +
236 + default_headers = _scope_headers(
237 + org_id=kwargs.get("org_id"), project_id=kwargs.get("project_id")
238 + )
239
240 # Each instance gets its own provider so that the execute_tool_fn binding
241 # performed by Tools.__init__ cannot leak across SDK instances (issue #4369).
@@ -185,11 +252,13 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
252 environment=kwargs.get("environment", "production"),
253 provider=actual_provider.name,
254 api_key=api_key,
255 + disable_api_key=disable_api_key,
256 user_api_key=kwargs.get("user_api_key"),
257 org_api_key=kwargs.get("org_api_key"),
258 base_url=kwargs.get("base_url") or os.environ.get("COMPOSIO_BASE_URL"),
259 timeout=kwargs.get("timeout"),
260 max_retries=kwargs.get("max_retries", DEFAULT_MAX_RETRIES),
261 + default_headers=default_headers or None,
262 http_client=kwargs.get("http_client"),
263 logger=logger,
264 logging_level=logging_level,
python/examples/tool_router/session_update.py
+59 -21
@@ -1,48 +1,86 @@
1 """
2 Tool Router - Session Update Example
3
4 -Demonstrates using session.update() to modify a session's configuration
5 -after creation — e.g. adding toolkits, changing workbench settings, or
6 -updating preload config without creating a new session.
4 +Demonstrates session.update(): what omitted fields, replaced maps, None,
5 +an empty toolkit allowlist, and expected_config_version do to a stored
6 +session, without creating a new one.
7 """
8
9 import os
10
11 from composio import Composio
12 +from composio.exceptions import SessionConfigConflictError
13
14 composio = Composio()
15
15 -# Create a session with gmail only
16 +# Create a session with a per-toolkit tools map and a stored callback URL
17 session = composio.create(
18 # The provisioned examples user (raises KeyError when unset)
19 user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
19 - toolkits=["gmail"],
20 - manage_connections=False,
20 + toolkits=["gmail", "slack"],
21 + tools={
22 + "gmail": {"enable": ["GMAIL_FETCH_EMAILS"]},
23 + "slack": {"enable": ["SLACK_SEND_MESSAGE"]},
24 + },
25 + manage_connections={"enable": True, "callback_url": "https://example.com/callback"},
26 )
27
28 print(f"Session created: {session.session_id}")
24 -print(f"Preload: {session.preload}")
29 +print(f"Config version: {session.config_version}")
30 +print(f"Tools: {session.config.tools}")
31
26 -# Update: add github toolkit, enable workbench, and preload a tool
32 +# 1. Maps replace, they don't merge: a slack-only tools map removes the gmail entry
33 session.update(
28 - toolkits={"enable": ["gmail", "github"]},
29 - workbench={"enable": True, "sandbox_size": "medium"},
30 - preload={"tools": ["GITHUB_CREATE_AN_ISSUE"]},
34 + tools={"slack": {"enable": ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]}},
35 )
36
33 -print("\nAfter update:")
34 -print(f"Preload: {session.preload}")
37 +print("\nAfter the slack-only tools map (gmail entry is gone):")
38 +print(f"Tools: {session.config.tools}")
39
36 -# Update: disable workbench entirely
37 -session.update(
38 - workbench={"enable": False},
39 -)
40 +# 2. Remove only the stored callback URL; `enable` and the other settings stay as stored
41 +session.update(manage_connections={"callback_url": None})
42
41 -print("\nAfter disabling workbench: done")
43 +print("\nAfter clearing the callback URL:")
44 +print(f"Manage connections: {session.config.manage_connections}")
45
43 -# Update: clear manage_connections by passing None
46 +# 3. Narrow the policy and fix preload in the same update. A preloaded tool that
47 +# falls outside the new policy would be rejected with a 400.
48 session.update(
45 - manage_connections=None,
49 + toolkits={"enable": ["slack"]},
50 + preload={"tools": ["SLACK_SEND_MESSAGE"]},
51 )
52
48 -print("\nAfter clearing manage_connections: done")
53 +print("\nAfter narrowing to slack:")
54 +print(f"Config version: {session.config_version}")
55 +print(f"Preload: {session.preload}")
56 +
57 +# 4. Concurrent updates. Every update sends the config version this handle last
58 +# observed as its precondition; a stale value is a 409 and nothing is written.
59 +# A second handle on the same session plays the concurrent writer.
60 +observed_version = session.config_version
61 +other_client = composio.sessions.use(session.session_id)
62 +other_client.update(workbench={"enable": False})
63 +
64 +try:
65 + session.update(toolkits={"enable": ["gmail", "slack"]}, preload={"tools": []})
66 +except SessionConfigConflictError as error:
67 + print(f"\nConflict at version {observed_version}: {error}")
68 + # Recover: re-read the session, then retry against the fresh version
69 + session = composio.sessions.use(session.session_id)
70 + session.update(toolkits={"enable": ["gmail", "slack"]}, preload={"tools": []})
71 + print(f"Retried at version {session.config_version}")
72 +
73 +# 5. Deny every app toolkit. The empty allowlist is sent as-is; an omitted
74 +# `toolkits` would have left the policy unchanged instead.
75 +session.update(toolkits={"enable": []}, preload={"tools": []})
76 +
77 +print("\nAfter denying every app toolkit:")
78 +print(f"Toolkits: {session.config.toolkits}")
79 +
80 +# 6. Clear a whole block with None: manage_connections falls back to its default.
81 +# expected_config_version=False skips the precondition, so this write applies
82 +# whatever version the session is at (last writer wins).
83 +session.update(manage_connections=None, expected_config_version=False)
84 +
85 +print("\nAfter clearing manage_connections:")
86 +print(f"Config version: {session.config_version}")
python/scripts/generate-docs.py
+11 -6
@@ -143,8 +143,13 @@ def get_source_link(obj: griffe_t.Object) -> str | None:
143 return f"{GITHUB_BASE}/{rel_path}#L{line}"
144
145
146 -def format_type(annotation: Any) -> str:
147 - """Format a type annotation to readable string."""
146 +def format_type(annotation: Any, *, max_length: int | None = 60) -> str:
147 + """Format a type annotation to readable string.
148 +
149 + Types longer than ``max_length`` are elided; pass ``None`` to keep the
150 + full type, which parameter signatures need so quoted forward references
151 + such as ``'Omit'`` are never cut mid-token.
152 + """
153 if annotation is None:
154 return "Any"
155
@@ -159,8 +164,8 @@ def format_type(annotation: Any) -> str:
164 type_str = re.sub(r"Unpack\[([^\]]+)\]", r"\1", type_str)
165
166 # Truncate very long types
162 - if len(type_str) > 60:
163 - return type_str[:57] + "..."
167 + if max_length is not None and len(type_str) > max_length:
168 + return type_str[: max_length - 3] + "..."
169 return type_str
170
171
@@ -359,7 +364,7 @@ def extract_class_info(
364 params.append(
365 {
366 "name": p.name,
362 - "type": format_type(p.annotation),
367 + "type": format_type(p.annotation, max_length=None),
368 "optional": p.default is not None,
369 "description": method_doc["params"].get(p.name, ""),
370 }
@@ -742,7 +747,7 @@ def main():
747 params.append(
748 {
749 "name": p.name,
745 - "type": format_type(p.annotation),
750 + "type": format_type(p.annotation, max_length=None),
751 "optional": p.default is not None,
752 "description": doc["params"].get(p.name, ""),
753 }
python/tests/test_generated_client_response_shape.py
+7 -1
@@ -16,6 +16,8 @@ mappings fails locally.
16 import typing as t
17 from unittest.mock import MagicMock
18
19 +import httpx
20 +
21 import pytest
22 from composio_client.types.mcp.custom_create_response import CustomCreateResponse
23 from composio_client.types.tool_router.session_toolkits_response import (
@@ -107,10 +109,14 @@ def test_generated_client_builds_nested_response_models(
109 def _client_with_session() -> MagicMock:
110 """A mocked client whose session.create is just real enough to build a session."""
111 client = MagicMock()
112 + client.base_url = httpx.URL("https://backend.composio.dev")
113 + client.default_headers = {}
114 session_response = MagicMock()
115 session_response.session_id = "session_123"
116 session_response.mcp.type = "http"
113 - session_response.mcp.url = "https://mcp.example.com/session_123"
117 + session_response.mcp.url = (
118 + "https://backend.composio.dev/api/v3/tool_router/session/session_123"
119 + )
120 session_response.config.preload.tools = []
121 session_response.experimental = None
122 client.tool_router.session.create.return_value = session_response
python/tests/test_sdk.py
+178
@@ -1,11 +1,15 @@
1 """Test SDK functionality."""
2
3 import os
4 +import typing as t
5 from unittest.mock import patch
6
7 +import composio_client
8 +import httpx
9 import pytest
10
11 from composio import Composio, exceptions
12 +from composio.client import HttpClient
13 from composio.core.provider._openai import OpenAIProvider
14 from composio.core.types import ToolkitVersionParam
15
@@ -19,6 +23,12 @@ class TestComposioSDK:
23 with pytest.raises(exceptions.ApiKeyNotProvidedError):
24 Composio()
25
26 + def test_sdk_explicit_none_api_key_does_not_fall_back_to_env(self):
27 + """Only an omitted ``api_key`` falls back to COMPOSIO_API_KEY."""
28 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "test-key"}):
29 + with pytest.raises(exceptions.ApiKeyNotProvidedError):
30 + Composio(api_key=None)
31 +
32 def test_sdk_accepts_api_key_from_env(self):
33 """Test that SDK accepts API key from environment."""
34 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "test-key"}):
@@ -74,8 +84,11 @@ class TestComposioSDK:
84 expected_fields = {
85 "environment",
86 "api_key",
87 + "disable_api_key",
88 "user_api_key",
89 "org_api_key",
90 + "org_id",
91 + "project_id",
92 "base_url",
93 "timeout",
94 "max_retries",
@@ -286,3 +299,168 @@ class TestComposioSDK:
299 "jira": "user_jira", # User provided
300 }
301 assert toolkit_versions == expected
302 +
303 +
304 +MCP_URL = "https://backend.composio.dev/api/v3/tool_router/session/session_123/mcp"
305 +
306 +
307 +def _session_transport() -> t.Tuple[httpx.Client, t.List[httpx.Request]]:
308 + requests: t.List[httpx.Request] = []
309 +
310 + def handler(request: httpx.Request) -> httpx.Response:
311 + requests.append(request)
312 + return httpx.Response(
313 + 200,
314 + json={
315 + "session_id": "session_123",
316 + "mcp": {"type": "http", "url": MCP_URL},
317 + "config": {
318 + "user_id": "user_123",
319 + "execute": {},
320 + "search": {},
321 + "preload": {"tools": []},
322 + },
323 + "config_version": 3,
324 + "warnings": [],
325 + },
326 + )
327 +
328 + return httpx.Client(transport=httpx.MockTransport(handler)), requests
329 +
330 +
331 +class TestUserOnlyInitialization:
332 + """``disable_api_key`` turns the project key off and keeps one credential."""
333 +
334 + def test_user_key_session_carries_only_the_user_key(self):
335 + http_client, requests = _session_transport()
336 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
337 + sdk = Composio(
338 + disable_api_key=True,
339 + user_api_key="uak_user_key",
340 + base_url="https://backend.composio.dev",
341 + http_client=http_client,
342 + )
343 + assert sdk.client.api_key is None
344 + session = sdk.sessions.create(user_id="user_123", mcp=True)
345 +
346 + assert "x-api-key" not in requests[0].headers
347 + assert requests[0].headers["x-user-api-key"] == "uak_user_key"
348 + assert "x-org-id" not in requests[0].headers
349 + assert "x-project-id" not in requests[0].headers
350 + assert session.mcp.headers == {"x-user-api-key": "uak_user_key"}
351 +
352 + def test_user_key_session_carries_the_org_and_project_scope(self):
353 + http_client, requests = _session_transport()
354 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
355 + sdk = Composio(
356 + disable_api_key=True,
357 + user_api_key="uak_user_key",
358 + org_id="org_nano_abc",
359 + project_id="proj_nano_xyz",
360 + base_url="https://backend.composio.dev",
361 + http_client=http_client,
362 + )
363 + session = sdk.sessions.create(user_id="user_123", mcp=True)
364 +
365 + assert "x-api-key" not in requests[0].headers
366 + assert requests[0].headers["x-user-api-key"] == "uak_user_key"
367 + assert requests[0].headers["x-org-id"] == "org_nano_abc"
368 + assert requests[0].headers["x-project-id"] == "proj_nano_xyz"
369 + assert session.mcp.headers == {
370 + "x-user-api-key": "uak_user_key",
371 + "x-org-id": "org_nano_abc",
372 + "x-project-id": "proj_nano_xyz",
373 + }
374 +
375 + def test_user_key_is_read_from_the_environment_when_disabled(self):
376 + with patch.dict(
377 + os.environ,
378 + {
379 + "COMPOSIO_API_KEY": "ak_foreign_env_key",
380 + "COMPOSIO_USER_API_KEY": "uak_env",
381 + },
382 + ):
383 + sdk = Composio(disable_api_key=True)
384 +
385 + assert sdk.client.api_key is None
386 + assert sdk.client.user_api_key == "uak_env"
387 +
388 + def test_disable_without_a_user_key_raises(self):
389 + with patch.dict(
390 + os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}, clear=True
391 + ):
392 + with pytest.raises(exceptions.UserApiKeyNotProvidedError):
393 + Composio(disable_api_key=True)
394 +
395 + def test_disable_beside_a_raw_project_key_header_raises(self):
396 + http_client, requests = _session_transport()
397 + with pytest.raises(exceptions.InvalidParams) as excinfo:
398 + HttpClient(
399 + provider="test",
400 + disable_api_key=True,
401 + user_api_key="uak_user_key",
402 + default_headers={"X-Api-Key": "ak_raw_header"},
403 + http_client=http_client,
404 + )
405 +
406 + assert "`X-Api-Key`" in str(excinfo.value)
407 + assert "ak_raw_header" not in str(excinfo.value)
408 + assert requests == []
409 +
410 + def test_client_clones_cannot_reintroduce_a_raw_project_key_header(self):
411 + http_client, requests = _session_transport()
412 + sdk = Composio(
413 + disable_api_key=True,
414 + user_api_key="uak_user_key",
415 + base_url="https://backend.composio.dev",
416 + http_client=http_client,
417 + )
418 +
419 + with pytest.raises(exceptions.InvalidParams):
420 + sdk.client.with_options(default_headers={"x-api-key": "ak_raw_header"})
421 + sdk.sessions.create(user_id="user_123")
422 +
423 + assert len(requests) == 1
424 + assert "x-api-key" not in requests[0].headers
425 + assert requests[0].headers["x-user-api-key"] == "uak_user_key"
426 +
427 + def test_disable_beside_an_explicit_project_key_raises(self):
428 + with pytest.raises(exceptions.InvalidParams):
429 + Composio(disable_api_key=True, api_key="ak_explicit", user_api_key="uak")
430 +
431 + def test_half_scope_raises(self):
432 + with pytest.raises(exceptions.InvalidParams):
433 + Composio(api_key="ak_test", org_id="org_nano_abc")
434 + with pytest.raises(exceptions.InvalidParams):
435 + Composio(api_key="ak_test", project_id="proj_nano_xyz")
436 +
437 + def test_empty_scope_id_counts_as_unset(self):
438 + with pytest.raises(exceptions.InvalidParams):
439 + Composio(api_key="ak_test", org_id="org_nano_abc", project_id="")
440 + with pytest.raises(exceptions.InvalidParams):
441 + Composio(api_key="ak_test", org_id="", project_id="proj_nano_xyz")
442 +
443 + sdk = Composio(api_key="ak_test", org_id="", project_id="")
444 + assert "x-org-id" not in sdk.client.default_headers
445 + assert "x-project-id" not in sdk.client.default_headers
446 +
447 + def test_omitted_api_key_keeps_the_environment_fallback(self):
448 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_env"}):
449 + sdk = Composio(user_api_key="uak")
450 + assert sdk.client.api_key == "ak_env"
451 +
452 + def test_client_clones_stay_user_only_when_the_environment_changes(self):
453 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
454 + sdk = Composio(disable_api_key=True, user_api_key="uak_user_key")
455 + clone = sdk.client.with_options(max_retries=0)
456 +
457 + assert (sdk.client.api_key, sdk.client.user_api_key) == (None, "uak_user_key")
458 + assert (clone.api_key, clone.user_api_key) == (None, "uak_user_key")
459 + assert clone.max_retries == 0
460 +
461 + def test_generated_client_keeps_its_environment_fallback_for_a_bare_none(self):
462 + """The SDK, not the generated client, turns the project key off."""
463 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_env"}):
464 + client = composio_client.Composio(api_key=None, user_api_key="uak")
465 +
466 + assert (client.api_key, client.user_api_key) == ("ak_env", "uak")
python/tests/test_tool_router.py
+506 -15
@@ -1,11 +1,13 @@
1 """Test ToolRouter functionality."""
2
3 +import logging
4 +import os
5 import typing as t
6 from unittest.mock import MagicMock, patch
7
8 import httpx
9 import pytest
8 -from composio_client import omit
10 +from composio_client import ConflictError, omit
11 from pydantic import BaseModel, Field
12
13 from composio.client import HttpClient
@@ -28,7 +30,12 @@ from composio.core.models.tool_router_session import (
30 ToolRouterSession,
31 ToolRouterSessionWithMcp,
32 )
31 -from composio.exceptions import InvalidParams, ValidationError
33 +from composio.exceptions import (
34 + InvalidParams,
35 + MCPDestinationError,
36 + SessionConfigConflictError,
37 + ValidationError,
38 +)
39
40 experimental_api = ExperimentalAPI()
41
@@ -42,13 +49,19 @@ def mock_client():
49 """Create a mock HTTP client."""
50 client = MagicMock()
51 client.api_key = "test-api-key"
52 + client.user_api_key = None
53 + client.base_url = httpx.URL("https://backend.composio.dev")
54 + client.default_headers = {}
55
56 # Mock session responses
57 mock_session_response = MagicMock()
58 mock_session_response.session_id = "session_123"
59 + mock_session_response.config_version = 7
60 mock_session_response.mcp = MagicMock()
61 mock_session_response.mcp.type = "http"
51 - mock_session_response.mcp.url = "https://mcp.example.com/session_123"
62 + mock_session_response.mcp.url = (
63 + "https://backend.composio.dev/api/v3/tool_router/session/session_123"
64 + )
65 mock_session_response.tool_router_tools = [
66 "GMAIL_FETCH_EMAILS",
67 "SLACK_SEND_MESSAGE",
@@ -147,7 +160,10 @@ class TestToolRouter:
160 # Verify session properties
161 assert session.session_id == "session_123"
162 assert session.mcp.type == ToolRouterMCPServerType.HTTP
150 - assert session.mcp.url == "https://mcp.example.com/session_123"
163 + assert (
164 + session.mcp.url
165 + == "https://backend.composio.dev/api/v3/tool_router/session/session_123"
166 + )
167 assert session.mcp.headers == {"x-api-key": "test-api-key"}
168 assert callable(session.tools)
169 assert callable(session.authorize)
@@ -173,7 +189,10 @@ class TestToolRouter:
189 assert isinstance(session, ToolRouterSessionWithMcp)
190 # The MCP endpoint is populated on the runtime object either way.
191 assert session.mcp.type == ToolRouterMCPServerType.HTTP
176 - assert session.mcp.url == "https://mcp.example.com/session_123"
192 + assert (
193 + session.mcp.url
194 + == "https://backend.composio.dev/api/v3/tool_router/session/session_123"
195 + )
196
197 def test_use_session_default_returns_base_session(self, tool_router):
198 """Default use() (mcp omitted) returns the base ToolRouterSession."""
@@ -187,7 +206,10 @@ class TestToolRouter:
206 session = tool_router.use("session_123", mcp=True)
207
208 assert isinstance(session, ToolRouterSessionWithMcp)
190 - assert session.mcp.url == "https://mcp.example.com/session_123"
209 + assert (
210 + session.mcp.url
211 + == "https://backend.composio.dev/api/v3/tool_router/session/session_123"
212 + )
213
214 def test_delete_session_by_id(self, tool_router, mock_client):
215 """delete() removes a session by ID."""
@@ -1037,7 +1059,9 @@ class TestToolRouter:
1059 mock_response_with_experimental.session_id = "session_exp"
1060 mock_response_with_experimental.mcp = MagicMock()
1061 mock_response_with_experimental.mcp.type = "http"
1040 - mock_response_with_experimental.mcp.url = "https://mcp.example.com/session_exp"
1062 + mock_response_with_experimental.mcp.url = (
1063 + "https://backend.composio.dev/api/v3/tool_router/session/session_exp"
1064 + )
1065 mock_response_with_experimental.tool_router_tools = ["TOOL_1"]
1066 mock_response_with_experimental.experimental = MagicMock()
1067 mock_response_with_experimental.experimental.assistive_prompt = (
@@ -1103,7 +1127,10 @@ class TestToolRouter:
1127 # Verify session properties
1128 assert session.session_id == "session_123"
1129 assert session.mcp.type == ToolRouterMCPServerType.HTTP
1106 - assert session.mcp.url == "https://mcp.example.com/session_123"
1130 + assert (
1131 + session.mcp.url
1132 + == "https://backend.composio.dev/api/v3/tool_router/session/session_123"
1133 + )
1134 assert session.mcp.headers == {"x-api-key": "test-api-key"}
1135 assert session.experimental.files is not None
1136 assert hasattr(session.experimental.files, "list")
@@ -1323,7 +1350,9 @@ class TestToolRouter:
1350 mock_attach_response.session_id = "session_456"
1351 mock_attach_response.mcp = MagicMock()
1352 mock_attach_response.mcp.type = "http"
1326 - mock_attach_response.mcp.url = "https://mcp.example.com/session_456"
1353 + mock_attach_response.mcp.url = (
1354 + "https://backend.composio.dev/api/v3/tool_router/session/session_456"
1355 + )
1356 mock_attach_response.tool_router_tools = ["TOOL_1"]
1357 mock_attach_response.config = MagicMock()
1358 mock_attach_response.config.user_id = "custom_user_789"
@@ -1719,7 +1748,9 @@ class TestToolRouter:
1748 mock_sse_response.session_id = "session_sse"
1749 mock_sse_response.mcp = MagicMock()
1750 mock_sse_response.mcp.type = "sse"
1722 - mock_sse_response.mcp.url = "https://mcp.example.com/sse/session_sse"
1751 + mock_sse_response.mcp.url = (
1752 + "https://backend.composio.dev/api/v3/tool_router/session/sse/session_sse"
1753 + )
1754 mock_sse_response.tool_router_tools = ["TOOL_1"]
1755
1756 mock_client.tool_router.session.create.return_value = mock_sse_response
@@ -1728,7 +1759,10 @@ class TestToolRouter:
1759
1760 assert session.mcp.type == ToolRouterMCPServerType.SSE
1761 assert session.mcp.type.value == "sse"
1731 - assert session.mcp.url == "https://mcp.example.com/sse/session_sse"
1762 + assert (
1763 + session.mcp.url
1764 + == "https://backend.composio.dev/api/v3/tool_router/session/sse/session_sse"
1765 + )
1766
1767 def test_multiple_sessions_independently(self, tool_router, mock_client):
1768 """Test that multiple sessions can be created independently."""
@@ -1736,14 +1770,18 @@ class TestToolRouter:
1770 mock_session_1.session_id = "session_1"
1771 mock_session_1.mcp = MagicMock()
1772 mock_session_1.mcp.type = "http"
1739 - mock_session_1.mcp.url = "https://mcp.example.com/session_1"
1773 + mock_session_1.mcp.url = (
1774 + "https://backend.composio.dev/api/v3/tool_router/session/session_1"
1775 + )
1776 mock_session_1.tool_router_tools = ["TOOL_1"]
1777
1778 mock_session_2 = MagicMock()
1779 mock_session_2.session_id = "session_2"
1780 mock_session_2.mcp = MagicMock()
1781 mock_session_2.mcp.type = "http"
1746 - mock_session_2.mcp.url = "https://mcp.example.com/session_2"
1782 + mock_session_2.mcp.url = (
1783 + "https://backend.composio.dev/api/v3/tool_router/session/session_2"
1784 + )
1785 mock_session_2.tool_router_tools = ["TOOL_2"]
1786
1787 mock_client.tool_router.session.create.side_effect = [
@@ -1765,14 +1803,18 @@ class TestToolRouter:
1803 mock_create_response.session_id = "created_session"
1804 mock_create_response.mcp = MagicMock()
1805 mock_create_response.mcp.type = "http"
1768 - mock_create_response.mcp.url = "https://mcp.example.com/created"
1806 + mock_create_response.mcp.url = (
1807 + "https://backend.composio.dev/api/v3/tool_router/session/created"
1808 + )
1809 mock_create_response.tool_router_tools = ["TOOL_1"]
1810
1811 mock_attach_response = MagicMock()
1812 mock_attach_response.session_id = "retrieved_session"
1813 mock_attach_response.mcp = MagicMock()
1814 mock_attach_response.mcp.type = "http"
1775 - mock_attach_response.mcp.url = "https://mcp.example.com/retrieved"
1815 + mock_attach_response.mcp.url = (
1816 + "https://backend.composio.dev/api/v3/tool_router/session/retrieved"
1817 + )
1818 mock_attach_response.tool_router_tools = ["TOOL_2"]
1819 mock_attach_response.config = MagicMock()
1820 mock_attach_response.config.user_id = "user_456"
@@ -2160,3 +2202,452 @@ class TestToolRouterIntegration:
2202
2203 assert created_session.session_id == retrieved_session.session_id
2204 assert created_session.mcp.url == retrieved_session.mcp.url
2205 +
2206 +
2207 +MCP_SAME_ORIGIN_URL = (
2208 + "https://backend.composio.dev/api/v3/tool_router/session/session_123/mcp"
2209 +)
2210 +
2211 +
2212 +def _session_json(mcp_url: str) -> t.Dict[str, t.Any]:
2213 + return {
2214 + "session_id": "session_123",
2215 + "mcp": {"type": "http", "url": mcp_url},
2216 + "config": {
2217 + "user_id": "user_123",
2218 + "execute": {},
2219 + "search": {},
2220 + "preload": {"tools": []},
2221 + },
2222 + "config_version": 3,
2223 + "warnings": [],
2224 + }
2225 +
2226 +
2227 +def _transport_client(
2228 + *,
2229 + api_key: t.Optional[str],
2230 + base_url: str,
2231 + disable_api_key: bool = False,
2232 + user_api_key: t.Optional[str] = None,
2233 + default_headers: t.Optional[t.Dict[str, str]] = None,
2234 + mcp_url: str = MCP_SAME_ORIGIN_URL,
2235 +) -> t.Tuple[HttpClient, t.List[httpx.Request]]:
2236 + requests: t.List[httpx.Request] = []
2237 +
2238 + def handler(request: httpx.Request) -> httpx.Response:
2239 + requests.append(request)
2240 + return httpx.Response(200, json=_session_json(mcp_url))
2241 +
2242 + client = HttpClient(
2243 + provider="test",
2244 + api_key=api_key,
2245 + disable_api_key=disable_api_key,
2246 + user_api_key=user_api_key,
2247 + base_url=base_url,
2248 + default_headers=default_headers,
2249 + http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2250 + )
2251 + return client, requests
2252 +
2253 +
2254 +class TestMcpAuthContext:
2255 + """The exported MCP headers match the effective session auth context."""
2256 +
2257 + def test_project_key_session_exports_only_the_project_key(self):
2258 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
2259 + client, requests = _transport_client(
2260 + api_key="ak_project_key",
2261 + base_url="https://backend.composio.dev",
2262 + default_headers={"x-request-id": "req-1"},
2263 + )
2264 + session = ToolRouter(client=client, provider=MagicMock()).create(
2265 + user_id="user_123", mcp=True
2266 + )
2267 +
2268 + assert requests[0].headers["x-api-key"] == "ak_project_key"
2269 + assert session.mcp.headers == {"x-api-key": "ak_project_key"}
2270 +
2271 + def test_user_key_option_session_exports_only_the_user_key(self):
2272 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
2273 + client, requests = _transport_client(
2274 + api_key=None,
2275 + disable_api_key=True,
2276 + user_api_key="uak_user_key",
2277 + base_url="https://backend.composio.dev",
2278 + default_headers={"x-request-id": "r"},
2279 + )
2280 + session = ToolRouter(client=client, provider=MagicMock()).create(
2281 + user_id="user_123", mcp=True
2282 + )
2283 +
2284 + assert "x-api-key" not in requests[0].headers
2285 + assert requests[0].headers["x-user-api-key"] == "uak_user_key"
2286 + assert session.mcp.headers == {"x-user-api-key": "uak_user_key"}
2287 +
2288 + def test_user_key_header_session_exports_only_the_user_key(self):
2289 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
2290 + client, requests = _transport_client(
2291 + api_key=None,
2292 + disable_api_key=True,
2293 + base_url="https://backend.composio.dev",
2294 + default_headers={"x-user-api-key": "uak_user_key", "x-request-id": "r"},
2295 + )
2296 + session = ToolRouter(client=client, provider=MagicMock()).create(
2297 + user_id="user_123", mcp=True
2298 + )
2299 +
2300 + assert "x-api-key" not in requests[0].headers
2301 + assert requests[0].headers["x-user-api-key"] == "uak_user_key"
2302 + assert session.mcp.headers == {"x-user-api-key": "uak_user_key"}
2303 +
2304 + def test_scope_headers_are_exported_with_the_user_key(self):
2305 + client, requests = _transport_client(
2306 + api_key=None,
2307 + disable_api_key=True,
2308 + user_api_key="uak_user_key",
2309 + base_url="https://backend.composio.dev",
2310 + default_headers={
2311 + "x-org-id": "org_nano_abc",
2312 + "x-project-id": "proj_nano_xyz",
2313 + "x-request-id": "r",
2314 + },
2315 + )
2316 + session = ToolRouter(client=client, provider=MagicMock()).use(
2317 + "session_123", mcp=True
2318 + )
2319 +
2320 + assert requests[0].headers["x-org-id"] == "org_nano_abc"
2321 + assert requests[0].headers["x-project-id"] == "proj_nano_xyz"
2322 + assert session.mcp.headers == {
2323 + "x-user-api-key": "uak_user_key",
2324 + "x-org-id": "org_nano_abc",
2325 + "x-project-id": "proj_nano_xyz",
2326 + }
2327 +
2328 + def test_retrieve_preserves_the_user_key_after_environment_changes(self):
2329 + with patch.dict(os.environ, {}, clear=True):
2330 + client, requests = _transport_client(
2331 + api_key=None,
2332 + disable_api_key=True,
2333 + base_url="https://backend.composio.dev",
2334 + default_headers={"X-User-Api-Key": "uak_user_key"},
2335 + )
2336 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_later_env_key"}):
2337 + session = ToolRouter(client=client, provider=MagicMock()).use(
2338 + "session_123", mcp=True
2339 + )
2340 +
2341 + assert "x-api-key" not in requests[0].headers
2342 + assert session.mcp.headers == {"x-user-api-key": "uak_user_key"}
2343 +
2344 + def test_no_credential_exports_no_headers_without_reading_the_environment(
2345 + self, tool_router, mock_client
2346 + ):
2347 + mock_client.api_key = None
2348 + with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_ambient"}):
2349 + session = tool_router.create(user_id="user_123", mcp=True)
2350 +
2351 + assert session.mcp.headers == {}
2352 +
2353 + def test_cross_origin_mcp_url_raises_without_leaking_the_key(
2354 + self, tool_router, mock_client
2355 + ):
2356 + response = mock_client.tool_router.session.create.return_value
2357 + response.mcp.url = "https://mcp.example.com/session_123"
2358 +
2359 + with pytest.raises(MCPDestinationError) as excinfo:
2360 + tool_router.create(user_id="user_123", mcp=True)
2361 +
2362 + message = str(excinfo.value)
2363 + assert message == (
2364 + "The session MCP endpoint origin https://mcp.example.com does not match the API origin https://backend.composio.dev; the session credential was not attached"
2365 + )
2366 + assert "test-api-key" not in message
2367 + assert excinfo.value.mcp_origin == "https://mcp.example.com"
2368 + assert excinfo.value.api_origin == "https://backend.composio.dev"
2369 +
2370 + def test_cross_origin_mcp_url_raises_on_use_when_mcp_is_requested(
2371 + self, tool_router, mock_client
2372 + ):
2373 + response = mock_client.tool_router.session.retrieve.return_value
2374 + response.mcp.url = "https://mcp.example.com/session_123"
2375 +
2376 + with pytest.raises(MCPDestinationError) as excinfo:
2377 + tool_router.use("session_123", mcp=True)
2378 +
2379 + message = str(excinfo.value)
2380 + assert message == (
2381 + "The session MCP endpoint origin https://mcp.example.com does not match the API origin https://backend.composio.dev; the session credential was not attached"
2382 + )
2383 + assert "test-api-key" not in message
2384 +
2385 + def test_cross_origin_mcp_url_without_mcp_flag_exports_no_headers_and_warns(
2386 + self, tool_router, mock_client, caplog
2387 + ):
2388 + for response in (
2389 + mock_client.tool_router.session.create.return_value,
2390 + mock_client.tool_router.session.retrieve.return_value,
2391 + ):
2392 + response.mcp.url = "https://mcp.example.com/session_123"
2393 +
2394 + with caplog.at_level(logging.WARNING):
2395 + created = tool_router.create(user_id="user_123")
2396 + used = tool_router.use("session_123")
2397 +
2398 + assert created.mcp.url == "https://mcp.example.com/session_123"
2399 + assert created.mcp.headers == {}
2400 + assert used.mcp.headers == {}
2401 + warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
2402 + assert len(warnings) == 2
2403 + message = warnings[0].getMessage()
2404 + assert message == (
2405 + "The session MCP endpoint origin https://mcp.example.com does not match the API origin https://backend.composio.dev; the session credential was not attached"
2406 + ". session.mcp.headers was left empty; pass mcp=True to make this an error"
2407 + )
2408 + assert "test-api-key" not in caplog.text
2409 +
2410 + def test_opaque_origin_mcp_url_is_rejected_before_comparison(
2411 + self, tool_router, mock_client, caplog
2412 + ):
2413 + response = mock_client.tool_router.session.create.return_value
2414 + response.mcp.url = "data:text/plain,session_123"
2415 +
2416 + with pytest.raises(MCPDestinationError) as excinfo:
2417 + tool_router.create(user_id="user_123", mcp=True)
2418 + assert str(excinfo.value) == "The MCP URL has an opaque origin"
2419 + assert excinfo.value.mcp_origin == ""
2420 +
2421 + with caplog.at_level(logging.WARNING):
2422 + session = tool_router.create(user_id="user_123")
2423 + assert session.mcp.headers == {}
2424 + assert "The MCP URL has an opaque origin" in caplog.text
2425 + assert "test-api-key" not in caplog.text
2426 +
2427 + def test_user_key_default_header_wins_over_the_configured_project_key(self):
2428 + client, requests = _transport_client(
2429 + api_key="ak_project_key",
2430 + base_url="https://backend.composio.dev",
2431 + default_headers={"x-user-api-key": "uak_header_key"},
2432 + )
2433 + session = ToolRouter(client=client, provider=MagicMock()).create(
2434 + user_id="user_123", mcp=True
2435 + )
2436 +
2437 + assert "x-api-key" not in requests[0].headers
2438 + assert requests[0].headers["x-user-api-key"] == "uak_header_key"
2439 + assert session.mcp.headers == {"x-user-api-key": "uak_header_key"}
2440 +
2441 + def test_invalid_port_in_mcp_url_raises_the_typed_error(self):
2442 + client, _ = _transport_client(
2443 + api_key="ak_project_key",
2444 + base_url="https://backend.composio.dev",
2445 + mcp_url="https://backend.composio.dev:bad/mcp",
2446 + )
2447 + with pytest.raises(MCPDestinationError) as excinfo:
2448 + ToolRouter(client=client, provider=MagicMock()).create(
2449 + user_id="user_123", mcp=True
2450 + )
2451 +
2452 + assert str(excinfo.value) == "The MCP URL is not a valid absolute URL"
2453 +
2454 + def test_malformed_mcp_url_is_not_echoed_in_the_error(self):
2455 + client, _ = _transport_client(
2456 + api_key="ak_project_key",
2457 + base_url="https://backend.composio.dev",
2458 + mcp_url="not-a-url?token=secret_value",
2459 + )
2460 + with pytest.raises(MCPDestinationError) as excinfo:
2461 + ToolRouter(client=client, provider=MagicMock()).create(
2462 + user_id="user_123", mcp=True
2463 + )
2464 +
2465 + assert str(excinfo.value) == "The MCP URL is not a valid absolute URL"
2466 + assert "secret_value" not in str(excinfo.value)
2467 +
2468 + def test_same_origin_mcp_url_does_not_warn(self, tool_router, caplog):
2469 + with caplog.at_level(logging.WARNING):
2470 + session = tool_router.create(user_id="user_123")
2471 +
2472 + assert session.mcp.headers == {"x-api-key": "test-api-key"}
2473 + assert not [r for r in caplog.records if r.levelno == logging.WARNING]
2474 +
2475 + def test_same_origin_plain_http_base_url_exports_credentials(self):
2476 + client, requests = _transport_client(
2477 + api_key="ak_project_key",
2478 + base_url="http://localhost:3000",
2479 + mcp_url="http://localhost:3000/api/v3/tool_router/session/session_123/mcp",
2480 + )
2481 + session = ToolRouter(client=client, provider=MagicMock()).create(
2482 + user_id="user_123", mcp=True
2483 + )
2484 +
2485 + assert requests[0].headers["x-api-key"] == "ak_project_key"
2486 + assert session.mcp.headers == {"x-api-key": "ak_project_key"}
2487 +
2488 + def test_same_origin_https_mcp_url_behaves_as_before(self, tool_router):
2489 + session = tool_router.create(user_id="user_123", mcp=True)
2490 +
2491 + assert session.mcp.url == (
2492 + "https://backend.composio.dev/api/v3/tool_router/session/session_123"
2493 + )
2494 + assert session.mcp.headers == {"x-api-key": "test-api-key"}
2495 +
2496 +
2497 +class TestSessionUpdateContract:
2498 + """update() nullable fields, empty allowlists, and version preconditions."""
2499 +
2500 + @pytest.fixture
2501 + def session(self, tool_router, mock_client):
2502 + patched = MagicMock()
2503 + patched.preload = MagicMock()
2504 + patched.preload.tools = ["SLACK_SEND_MESSAGE"]
2505 + mock_client.tool_router.session.patch.return_value.config = patched
2506 + mock_client.tool_router.session.patch.return_value.config_version = 8
2507 + return tool_router.use(session_id="session_123")
2508 +
2509 + @staticmethod
2510 + def _conflict() -> ConflictError:
2511 + response = httpx.Response(
2512 + 409,
2513 + request=httpx.Request("PATCH", "https://backend.composio.dev/patch"),
2514 + json={"error": "version conflict"},
2515 + )
2516 + return ConflictError(
2517 + "Conflict", response=response, body={"error": "version conflict"}
2518 + )
2519 +
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(
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}
2530 + assert kwargs["request_options"] == {"max_retries": 0}
2531 + assert session.config_version == 8
2532 + assert session.preload.tools == ["SLACK_SEND_MESSAGE"]
2533 +
2534 + def test_update_opt_out_sends_no_precondition(self, session, mock_client):
2535 + session.update(toolkits={"enable": ["gmail"]}, expected_config_version=False)
2536 +
2537 + kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2538 + assert kwargs["extra_body"] is None
2539 +
2540 + def test_update_sends_an_explicit_expected_version(self, session, mock_client):
2541 + session.update(toolkits={"enable": ["gmail"]}, expected_config_version=9)
2542 +
2543 + kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2544 + assert kwargs["extra_body"] == {"expected_config_version": 9}
2545 +
2546 + def test_update_rejects_non_positive_expected_version(self, session, mock_client):
2547 + with pytest.raises(InvalidParams):
2548 + session.update(toolkits={"enable": ["gmail"]}, expected_config_version=0)
2549 + mock_client.tool_router.session.patch.assert_not_called()
2550 +
2551 + def test_update_passes_null_callback_url_through(self, session, mock_client):
2552 + session.update(manage_connections={"callback_url": None})
2553 +
2554 + kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2555 + assert kwargs["manage_connections"] == {"callback_url": None}
2556 +
2557 + def test_update_preserves_empty_toolkit_allowlist(self, session, mock_client):
2558 + session.update(toolkits={"enable": []})
2559 +
2560 + kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2561 + assert kwargs["toolkits"] == {"enable": []}
2562 +
2563 + def test_update_sends_none_for_cleared_blocks(self, session, mock_client):
2564 + session.update(
2565 + toolkits=None,
2566 + tools=None,
2567 + tags=None,
2568 + auth_configs=None,
2569 + connected_accounts=None,
2570 + preload=None,
2571 + multi_account=None,
2572 + search=None,
2573 + execute=None,
2574 + experimental=None,
2575 + )
2576 +
2577 + kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2578 + for name in (
2579 + "toolkits",
2580 + "tools",
2581 + "tags",
2582 + "auth_configs",
2583 + "connected_accounts",
2584 + "preload",
2585 + "multi_account",
2586 + "search",
2587 + "execute",
2588 + "experimental",
2589 + ):
2590 + assert kwargs[name] is None, name
2591 + assert kwargs["manage_connections"] is omit
2592 + assert kwargs["workbench"] is omit
2593 +
2594 + def test_update_conflict_is_typed_and_keeps_local_state(self, session, mock_client):
2595 + preload_before = session.preload
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"]})
2600 +
2601 + assert "re-fetch" in str(excinfo.value).lower()
2602 + assert "retry" in str(excinfo.value).lower()
2603 + assert excinfo.value.status_code == 409
2604 + assert excinfo.value.session_id == "session_123"
2605 + assert excinfo.value.expected_config_version == 7
2606 + assert session.preload is preload_before
2607 + assert session.config_version == 7
2608 +
2609 + def test_update_conflict_without_precondition_reports_in_flight_change(
2610 + self, session, mock_client
2611 + ):
2612 + config_before = session.config
2613 + mock_client.tool_router.session.patch.side_effect = self._conflict()
2614 +
2615 + with pytest.raises(SessionConfigConflictError) as excinfo:
2616 + session.update(
2617 + toolkits={"enable": ["gmail"]}, expected_config_version=False
2618 + )
2619 +
2620 + message = str(excinfo.value)
2621 + assert "changed while this update was in flight" in message
2622 + assert "no longer at version" not in message
2623 + assert excinfo.value.expected_config_version is None
2624 + assert session.config is config_before
2625 + assert session.config_version == 7
2626 +
2627 + def test_two_handles_at_the_same_version(self, tool_router, mock_client):
2628 + mock_client.tool_router.session.patch.return_value.config_version = 8
2629 + first = tool_router.use(session_id="session_123")
2630 + second = tool_router.use(session_id="session_123")
2631 + assert first.config_version == second.config_version == 7
2632 +
2633 + first.update(toolkits={"enable": ["gmail"]})
2634 + assert mock_client.tool_router.session.patch.call_args.kwargs["extra_body"] == {
2635 + "expected_config_version": 7
2636 + }
2637 + assert first.config_version == 8
2638 +
2639 + mock_client.tool_router.session.patch.side_effect = self._conflict()
2640 + with pytest.raises(SessionConfigConflictError):
2641 + second.update(toolkits={"enable": ["slack"]})
2642 + assert second.config_version == 7
2643 +
2644 + mock_client.tool_router.session.patch.side_effect = None
2645 + mock_client.tool_router.session.retrieve.return_value.config_version = 8
2646 + mock_client.tool_router.session.patch.return_value.config_version = 9
2647 + reread = tool_router.use(session_id="session_123")
2648 + assert reread.config_version == 8
2649 + reread.update(toolkits={"enable": ["slack"]})
2650 + assert mock_client.tool_router.session.patch.call_args.kwargs["extra_body"] == {
2651 + "expected_config_version": 8
2652 + }
2653 + assert reread.config_version == 9
python/tests/test_triggers.py
+30
@@ -2074,6 +2074,36 @@ class TestPusherClusterValidation:
2074 assert pusher.host == f"ws-{cluster}.pusher.com"
2075 assert pusher.auth_endpoint_headers["x-api-key"] == "sk-secret-value"
2076
2077 + def test_user_only_client_authorizes_the_channel_with_the_user_key(self):
2078 + client = Mock()
2079 + client.base_url = "https://api.example.com"
2080 + client.api_key = None
2081 + client.user_api_key = "uak_user_key"
2082 + client.default_headers = {}
2083 +
2084 + pusher = _SubcriptionBuilder(client=client)._get_pusher_instance(
2085 + key="app-key", cluster="mt1"
2086 + )
2087 +
2088 + assert "x-api-key" not in pusher.auth_endpoint_headers
2089 + assert pusher.auth_endpoint_headers["x-user-api-key"] == "uak_user_key"
2090 +
2091 + def test_user_key_default_header_authorizes_the_channel_over_the_project_key(
2092 + self,
2093 + ):
2094 + client = Mock()
2095 + client.base_url = "https://api.example.com"
2096 + client.api_key = "sk-secret-value"
2097 + client.user_api_key = None
2098 + client.default_headers = {"X-User-Api-Key": "uak_header_key"}
2099 +
2100 + pusher = _SubcriptionBuilder(client=client)._get_pusher_instance(
2101 + key="app-key", cluster="mt1"
2102 + )
2103 +
2104 + assert "x-api-key" not in pusher.auth_endpoint_headers
2105 + assert pusher.auth_endpoint_headers["x-user-api-key"] == "uak_header_key"
2106 +
2107 @pytest.mark.parametrize(
2108 ("cluster", "reason"),
2109 [
ts/examples/tool-router/src/session-update.ts
+63 -19
@@ -1,52 +1,96 @@
1 /**
2 * Session Update Example
3 *
4 - * Demonstrates using session.update() to modify a session's configuration
5 - * after creation — e.g. adding toolkits, changing workbench settings, or
6 - * updating preload config without creating a new session.
4 + * Demonstrates session.update(): what omitted fields, replaced maps, null,
5 + * an empty toolkit allowlist, and expectedConfigVersion do to a stored
6 + * session, without creating a new one.
7 *
8 * Usage:
9 * COMPOSIO_API_KEY=... bun src/session-update.ts
10 */
11 -import { Composio } from "@composio/core";
11 +import { Composio, ComposioSessionConfigConflictError } from "@composio/core";
12
13 const composio = new Composio({
14 apiKey: process.env.COMPOSIO_API_KEY,
15 baseURL: process.env.COMPOSIO_BASE_URL || undefined,
16 });
17
18 -// Create a session with gmail only
19 -const session = await composio.create("session-update-demo", {
20 - toolkits: ["gmail"],
21 - manageConnections: false,
18 +// Create a session with a per-toolkit tools map and a stored callback URL
19 +let session = await composio.create("session-update-demo", {
20 + toolkits: ["gmail", "slack"],
21 + tools: {
22 + gmail: { enable: ["GMAIL_FETCH_EMAILS"] },
23 + slack: { enable: ["SLACK_SEND_MESSAGE"] },
24 + },
25 + manageConnections: { enable: true, callbackUrl: "https://example.com/callback" },
26 });
27
28 console.log(`Session created: ${session.sessionId}`);
29 console.log(`Config version: ${session.configVersion}`);
26 -console.log(`Preload: ${JSON.stringify(session.preload)}`);
30 +console.log(`Tools: ${JSON.stringify(session.config.tools)}`);
31 +
32 +// 1. Maps replace, they don't merge: a slack-only tools map removes the gmail entry
33 +await session.update({
34 + tools: { slack: { enable: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"] } },
35 +});
36 +
37 +console.log(`\nAfter the slack-only tools map (gmail entry is gone):`);
38 +console.log(`Tools: ${JSON.stringify(session.config.tools)}`);
39 +
40 +// 2. Remove only the stored callback URL; `enable` and the other settings stay as stored
41 +await session.update({
42 + manageConnections: { callbackUrl: null },
43 +});
44 +
45 +console.log(`\nAfter clearing the callback URL:`);
46 +console.log(`Manage connections: ${JSON.stringify(session.config.manage_connections)}`);
47
28 -// Update: add github toolkit, enable workbench, and preload a tool
48 +// 3. Narrow the policy and fix preload in the same update. A preloaded tool that
49 +// falls outside the new policy would be rejected with a 400.
50 await session.update({
30 - toolkits: { enable: ["gmail", "github"] },
31 - workbench: { enable: true, sandboxSize: "medium" },
32 - preload: { tools: ["GITHUB_CREATE_AN_ISSUE"] },
51 + toolkits: { enable: ["slack"] },
52 + preload: { tools: ["SLACK_SEND_MESSAGE"] },
53 });
54
35 -console.log(`\nAfter update:`);
55 +console.log(`\nAfter narrowing to slack:`);
56 console.log(`Config version: ${session.configVersion}`);
57 console.log(`Preload: ${JSON.stringify(session.preload)}`);
58
39 -// Update: disable workbench entirely
59 +// 4. Concurrent updates. Every update sends the config version this handle last
60 +// observed as its precondition; a stale value is a 409 and nothing is written.
61 +// A second handle on the same session plays the concurrent writer.
62 +const observedVersion = session.configVersion;
63 +const otherClient = await composio.sessions.use(session.sessionId);
64 +await otherClient.update({ workbench: { enable: false } });
65 +
66 +const widen = { toolkits: { enable: ["gmail", "slack"] }, preload: { tools: [] } };
67 +try {
68 + await session.update(widen);
69 +} catch (error) {
70 + if (!(error instanceof ComposioSessionConfigConflictError)) throw error;
71 + console.log(`\nConflict at version ${observedVersion}: ${error.message}`);
72 + // Recover: re-read the session, then retry against the fresh version
73 + session = await composio.sessions.use(session.sessionId);
74 + await session.update(widen);
75 + console.log(`Retried at version ${session.configVersion}`);
76 +}
77 +
78 +// 5. Deny every app toolkit. The empty allowlist is sent as-is; an omitted
79 +// `toolkits` would have left the policy unchanged instead.
80 await session.update({
41 - workbench: { enable: false },
81 + toolkits: { enable: [] },
82 + preload: { tools: [] },
83 });
84
44 -console.log(`\nAfter disabling workbench:`);
45 -console.log(`Config version: ${session.configVersion}`);
85 +console.log(`\nAfter denying every app toolkit:`);
86 +console.log(`Toolkits: ${JSON.stringify(session.config.toolkits)}`);
87
47 -// Update: clear manage_connections by passing null
88 +// 6. Clear a whole block with null: manageConnections falls back to its default.
89 +// expectedConfigVersion: false skips the precondition, so this write applies
90 +// whatever version the session is at (last writer wins).
91 await session.update({
92 manageConnections: null,
93 + expectedConfigVersion: false,
94 });
95
96 console.log(`\nAfter clearing manageConnections:`);
ts/packages/core/src/composio.ts
+99 -12
@@ -12,7 +12,15 @@ import { Webhooks } from './models/Webhooks';
12 import { Logs } from './models/Logs';
13 import { Keyring } from './models/Keyring';
14 import { telemetry } from './telemetry/Telemetry';
15 -import { getSDKConfig, getToolkitVersionsFromEnv } from './utils/sdk';
15 +import {
16 + getScopeHeaders,
17 + getSDKConfig,
18 + getToolkitVersionsFromEnv,
19 + getUserApiKeyHeader,
20 + resolveSDKScope,
21 + resolveUserApiKey,
22 + USER_API_KEY_HEADER,
23 +} from './utils/sdk';
24 import logger from './utils/logger';
25 import type { ComposioLogger, LogLevel } from './utils/logger';
26 import { IS_DEVELOPMENT_OR_CI } from './utils/constants';
@@ -32,28 +40,62 @@ export type ComposioConfig<
40 TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
41 > = {
42 /**
35 - * The API key for the Composio API.
36 - * @example 'sk-1234567890'
43 + * The project API key for the Composio API, sent as the `x-api-key` header.
44 + *
45 + * - A string is used as-is; the environment and the CLI user config file are not consulted.
46 + * - Omitted: falls back to `COMPOSIO_API_KEY`, then to the project key stored by the Composio
47 + * CLI in `~/.composio/user_data.json`. A stored user key (`uak_...`) is never used as a
48 + * project key; the SDK throws instead of sending it.
49 + * - `null`: disables project-key authentication entirely, including both fallbacks. The SDK
50 + * then requires another credential (`userApiKey`, `orgApiKey`, or an `x-user-api-key`
51 + * entry in `defaultHeaders`) and sends no `x-api-key`; an `x-api-key` entry in
52 + * `defaultHeaders` is rejected, also on `createSession()` clones.
53 + *
54 + * @example 'ak_1234567890'
55 */
56 apiKey?: string | null;
57 /**
58 * User API key (`uak_*`) for the organization, consumer, and user-scoped
59 * endpoints reached through `getClient()` (for example `client.org.list()`).
42 - * Sent as `x-user-api-key` only on operations whose security scheme requires
60 + * Sent as `x-user-api-key` only on operations whose security scheme accepts
61 * it, never alongside the project key. Falls back to
44 - * `process.env['COMPOSIO_USER_API_KEY']`. A project `apiKey` is still required.
62 + * `process.env['COMPOSIO_USER_API_KEY']`; `null` disables that fallback.
63 + * Combine with `apiKey: null` to authenticate with the user key alone.
64 * @example 'uak_1234567890'
65 */
66 userApiKey?: string | null;
67 /**
68 * Organization API key (`oak_*`) for the organization-owner endpoints reached
69 * through `getClient()` (for example `client.org.owner.project.list()`).
51 - * Sent as `x-org-api-key` only on operations whose security scheme requires
70 + * Sent as `x-org-api-key` only on operations whose security scheme accepts
71 * it, never alongside the project key. Falls back to
53 - * `process.env['COMPOSIO_ORG_API_KEY']`. A project `apiKey` is still required.
72 + * `process.env['COMPOSIO_ORG_API_KEY']`; `null` disables that fallback.
73 + * Combine with `apiKey: null` to authenticate with the organization key alone.
74 * @example 'oak_1234567890'
75 */
76 orgApiKey?: string | null;
77 + /**
78 + * Organization nano ID that scopes user-key requests, sent as the
79 + * `x-org-id` header on every request and exported with the session MCP
80 + * config. This is the short public identifier the API returns as `org_id`
81 + * (for example from the consumer project resolve endpoint), not a UUID.
82 + * Must be supplied together with `projectId`; without an explicit scope a
83 + * user API key addresses the API default (the developer project). May also
84 + * be supplied as the `x-org-id` entry in `defaultHeaders`; the two must
85 + * agree.
86 + * @example 'org_9f2k1x'
87 + */
88 + orgId?: string;
89 + /**
90 + * Project nano ID that scopes user-key requests, sent as the
91 + * `x-project-id` header on every request and exported with the session MCP
92 + * config. This is the short public identifier the API returns as
93 + * `project_nano_id`, not the project UUID. Must be supplied together with
94 + * `orgId`. May also be supplied as the `x-project-id` entry in
95 + * `defaultHeaders`; the two must agree.
96 + * @example 'proj_4b8m2q'
97 + */
98 + projectId?: string;
99 /**
100 * The base URL of the Composio API.
101 * @example 'https://backend.composio.dev'
@@ -123,8 +165,13 @@ export type ComposioConfig<
165 */
166 host?: string;
167 /**
126 - * Request options to be passed to the Composio API client.
127 - * This is useful for passing in a custom fetch implementation.
168 + * Default headers attached to every request made through this instance.
169 + *
170 + * `x-user-api-key` is the one header the SDK treats as a credential: together
171 + * with `apiKey: null` it authenticates requests with a Composio user API key
172 + * instead of a project key. The project key is only ever set from `apiKey`:
173 + * an `x-api-key` entry is rejected when `apiKey` is `null`. Every other
174 + * header is passed through untouched.
175 * @example
176 * ```typescript
177 * const composio = new Composio({
@@ -396,11 +443,32 @@ export class Composio<
443 * ```
444 */
445 constructor(config?: ComposioConfig<TProvider>) {
446 + const scope = resolveSDKScope({
447 + orgId: config?.orgId,
448 + projectId: config?.projectId,
449 + defaultHeaders: config?.defaultHeaders,
450 + });
451 const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
452 config?.baseURL,
401 - config?.apiKey
453 + config?.apiKey,
454 + {
455 + defaultHeaders: config?.defaultHeaders,
456 + userApiKey: config?.userApiKey,
457 + orgApiKey: config?.orgApiKey,
458 + }
459 );
460
461 + // The API client sends its user key only on operations whose security
462 + // scheme names it, which excludes sessions. With the project key disabled
463 + // the resolved user key is placed as the `x-user-api-key` default header
464 + // instead, so every request carries exactly that credential and clones,
465 + // the MCP export, and trigger subscriptions read the same header.
466 + const userApiKey = apiKeyParsed === null ? resolveUserApiKey(config?.userApiKey) : undefined;
467 + const defaultHeadersInput =
468 + userApiKey !== undefined && !getUserApiKeyHeader(config?.defaultHeaders)
469 + ? { ...config?.defaultHeaders, [USER_API_KEY_HEADER]: userApiKey }
470 + : config?.defaultHeaders;
471 +
472 if (config?.logger !== undefined || config?.logLevel !== undefined) {
473 logger.configure({ level: config.logLevel, sink: config.logger });
474 }
@@ -422,6 +490,7 @@ export class Composio<
490 ...config,
491 baseURL: baseURLParsed,
492 apiKey: apiKeyParsed,
493 + defaultHeaders: defaultHeadersInput,
494 toolkitVersions: getToolkitVersionsFromEnv(config?.toolkitVersions),
495 allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking,
496 dangerouslyAllowAutoUploadDownloadFiles:
@@ -432,9 +501,16 @@ export class Composio<
501 fileUploadDirs: expandHomeAndResolveMany(config?.fileUploadDirs),
502 fileDownloadDir: expandHomeAndResolve(config?.fileDownloadDir),
503 provider: config?.provider ?? this.provider,
504 + orgId: scope.orgId,
505 + projectId: scope.projectId,
506 };
507
437 - const defaultHeaders = getDefaultHeaders(this.config.defaultHeaders, this.provider);
508 + // The resolved scope is the single source of the x-org-id / x-project-id
509 + // headers: it travels via `this.config` to clones and to the MCP export.
510 + const defaultHeaders = getDefaultHeaders(
511 + { ...this.config.defaultHeaders, ...getScopeHeaders(scope) },
512 + this.provider
513 + );
514
515 /**
516 * Initialize the Composio SDK client.
@@ -579,7 +655,18 @@ export class Composio<
655 * ```
656 */
657 createSession(options?: { headers?: ComposioRequestHeaders }): Composio<TProvider> {
582 - const sessionHeaders = getDefaultHeaders(options?.headers, this.provider);
658 + // The clone inherits the resolved credentials: the project, user, and
659 + // organization keys travel via `this.config`; a user API key placed in the
660 + // default headers travels via its header unless the caller overrides it.
661 + const userApiKeyHeader = getUserApiKeyHeader(options?.headers)
662 + ? undefined
663 + : getUserApiKeyHeader(this.config.defaultHeaders);
664 + const sessionHeaders = getDefaultHeaders(
665 + userApiKeyHeader
666 + ? { [userApiKeyHeader.name]: userApiKeyHeader.value, ...options?.headers }
667 + : options?.headers,
668 + this.provider
669 + );
670 return new Composio({
671 ...this.config,
672 defaultHeaders: sessionHeaders,
ts/packages/core/src/errors/SDKErrors.ts
+52
@@ -3,6 +3,8 @@ import { ComposioError, ComposioErrorOptions } from './ComposioError';
3
4 export const SDKErrorCodes = {
5 NO_API_KEY_PROVIDED: 'NO_API_KEY_PROVIDED',
6 + API_KEY_KIND_MISMATCH: 'API_KEY_KIND_MISMATCH',
7 + SCOPE_CONFIG_INVALID: 'SCOPE_CONFIG_INVALID',
8 REQUEST_CANCELLED: 'REQUEST_CANCELLED',
9 };
10
@@ -29,6 +31,56 @@ export class ComposioNoAPIKeyError extends ComposioError {
31 }
32 }
33
34 +/**
35 + * Thrown when the organization/project scope of an SDK instance is
36 + * inconsistent: only one of `orgId` / `projectId` was supplied, or a scope
37 + * option disagrees with the same header placed in `defaultHeaders`.
38 + */
39 +export class ComposioScopeConfigError extends ComposioError {
40 + constructor(
41 + message: string = 'Invalid organization/project scope configuration',
42 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
43 + ) {
44 + super(message, {
45 + ...options,
46 + code: SDKErrorCodes.SCOPE_CONFIG_INVALID,
47 + possibleFixes: options.possibleFixes || [
48 + 'Pass both `orgId` and `projectId` (the organization and consumer project nano IDs), or neither',
49 + 'Supply the scope through the options or through the `x-org-id` / `x-project-id` default headers, not both with different values',
50 + ],
51 + });
52 + this.name = 'ComposioScopeConfigError';
53 + }
54 +}
55 +
56 +/**
57 + * Thrown when the only API key the SDK could find is a Composio user key
58 + * (`uak_...`, as stored by `composio login`) rather than a project key.
59 + * User keys authenticate a person, not a project, so the SDK refuses to send
60 + * one as `x-api-key`. The error never includes the key value.
61 + */
62 +export class ComposioAPIKeyKindError extends ComposioError {
63 + constructor(
64 + message: string = 'The stored Composio API key is a user API key, not a project API key',
65 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
66 + ) {
67 + super(message, {
68 + ...options,
69 + code: SDKErrorCodes.API_KEY_KIND_MISMATCH,
70 + cause:
71 + options.cause ||
72 + 'The user config file holds a user API key written by the Composio CLI; it cannot authenticate SDK requests as a project',
73 + possibleFixes: options.possibleFixes || [
74 + 'Pass a project API key via `apiKey` or the COMPOSIO_API_KEY environment variable',
75 + 'Create a project API key in the Composio dashboard at https://platform.composio.dev',
76 + 'To authenticate with the user API key instead, pass `apiKey: null` together with `userApiKey`',
77 + ],
78 + statusCode: 401,
79 + });
80 + this.name = 'ComposioAPIKeyKindError';
81 + }
82 +}
83 +
84 /**
85 * Thrown when an SDK call is cancelled via the caller-supplied `AbortSignal`.
86 *
ts/packages/core/src/errors/ToolRouterErrors.ts new
+57
@@ -0,0 +1,57 @@
1 +import { ComposioError, ComposioErrorOptions } from './ComposioError';
2 +
3 +export const ToolRouterErrorCodes = {
4 + MCP_DESTINATION_REJECTED: 'MCP_DESTINATION_REJECTED',
5 + SESSION_CONFIG_CONFLICT: 'SESSION_CONFIG_CONFLICT',
6 +};
7 +
8 +/**
9 + * Thrown when a session's hosted MCP endpoint is not a destination the SDK
10 + * will hand the session credential to. The SDK only attaches its credential
11 + * and scope headers when the MCP URL shares the origin of the API base URL
12 + * the session was created against. The error is raised only when the caller
13 + * asked for the endpoint with `mcp: true`; otherwise the session is returned
14 + * with empty `mcp.headers` and a warning is logged instead. The error names
15 + * both origins and never includes a credential value.
16 + */
17 +export class ComposioMCPDestinationError extends ComposioError {
18 + constructor(
19 + message: string = 'The session MCP endpoint is not a trusted destination for the session credential',
20 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
21 + ) {
22 + super(message, {
23 + ...options,
24 + code: ToolRouterErrorCodes.MCP_DESTINATION_REJECTED,
25 + possibleFixes: options.possibleFixes ?? [
26 + 'Point `baseURL` at the API origin that serves the session MCP endpoint; a custom base URL yields a matching MCP origin',
27 + ],
28 + });
29 + this.name = 'ComposioMCPDestinationError';
30 + }
31 +}
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`.
40 + */
41 +export class ComposioSessionConfigConflictError extends ComposioError {
42 + constructor(
43 + message: string = 'The session configuration changed since it was last read; re-fetch the session and retry the update',
44 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
45 + ) {
46 + super(message, {
47 + ...options,
48 + code: ToolRouterErrorCodes.SESSION_CONFIG_CONFLICT,
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)',
53 + ],
54 + });
55 + this.name = 'ComposioSessionConfigConflictError';
56 + }
57 +}
ts/packages/core/src/errors/index.ts
+3
@@ -42,3 +42,6 @@ export * from './FileModifierErrors';
42
43 // SSRF guard (URL file inputs)
44 export * from './SsrfErrors';
45 +
46 +// Session (tool router) errors
47 +export * from './ToolRouterErrors';
ts/packages/core/src/lib/toolRouterMcp.ts new
+132
@@ -0,0 +1,132 @@
1 +import { ComposioMCPDestinationError } from '../errors/ToolRouterErrors';
2 +import type { ComposioRequestHeaders } from '../types/composio.types';
3 +import type { MCPServerType, ToolRouterMCPServerConfig } from '../types/toolRouter.types';
4 +import logger from '../utils/logger';
5 +import { ORG_ID_HEADER, PROJECT_ID_HEADER, resolveCredentialHeaders } from '../utils/sdk';
6 +
7 +type OriginRole = 'API base URL' | 'MCP URL';
8 +
9 +type ParsedOrigin = { origin: string } | { error: ComposioMCPDestinationError };
10 +
11 +/**
12 + * Returns the tuple origin (`scheme://host[:port]`) of an absolute URL.
13 + *
14 + * URLs without a tuple origin (`data:`, `file:`, `blob:` without a base, and
15 + * similar) serialize their origin as the opaque string `null`. Two such URLs
16 + * would compare equal, so they are rejected before any comparison happens.
17 + */
18 +const parseOrigin = (url: string, role: OriginRole): ParsedOrigin => {
19 + let parsed: URL;
20 + try {
21 + parsed = new URL(url);
22 + } catch (_error) {
23 + return {
24 + error: new ComposioMCPDestinationError(`The ${role} is not a valid absolute URL`, {
25 + meta: { role },
26 + }),
27 + };
28 + }
29 + if (parsed.origin === 'null') {
30 + return {
31 + error: new ComposioMCPDestinationError(`The ${role} has an opaque origin`, {
32 + meta: { role },
33 + }),
34 + };
35 + }
36 + return { origin: parsed.origin };
37 +};
38 +
39 +/**
40 + * Returns the error describing why the MCP URL must not receive the session
41 + * credential, or `undefined` when it shares the API origin.
42 + */
43 +const destinationRejection = (
44 + apiBaseURL: string,
45 + mcpUrl: string
46 +): ComposioMCPDestinationError | undefined => {
47 + const api = parseOrigin(apiBaseURL, 'API base URL');
48 + if ('error' in api) {
49 + return api.error;
50 + }
51 + const mcp = parseOrigin(mcpUrl, 'MCP URL');
52 + if ('error' in mcp) {
53 + return mcp.error;
54 + }
55 + if (mcp.origin === api.origin) {
56 + return undefined;
57 + }
58 + return new ComposioMCPDestinationError(
59 + `The session MCP endpoint origin ${mcp.origin} does not match the API origin ${api.origin}; the session credential was not attached`,
60 + { meta: { mcpOrigin: mcp.origin, apiOrigin: api.origin } }
61 + );
62 +};
63 +
64 +export type MCPServerConfigInput = {
65 + type: MCPServerType;
66 + /** The MCP URL returned by the API for this session. */
67 + url: string;
68 + /** The API base URL the session request was sent to. */
69 + apiBaseURL: string;
70 + /** The project API key the session request authenticated with, or `null` when disabled. */
71 + apiKey: string | null | undefined;
72 + /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */
73 + userApiKey: string | null | undefined;
74 + /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */
75 + defaultHeaders: ComposioRequestHeaders | undefined;
76 + /** Organization nano ID the instance is scoped to, if any. */
77 + orgId: string | undefined;
78 + /** Project nano ID the instance is scoped to, if any. */
79 + projectId: string | undefined;
80 + /**
81 + * Whether the caller asked for the MCP endpoint (`mcp: true`). Decides how
82 + * a rejected destination is reported: as a thrown error when `true`, as a
83 + * warning and an empty header set otherwise.
84 + */
85 + mcpRequested: boolean;
86 +};
87 +
88 +/**
89 + * Builds the MCP server config exported on a session.
90 + *
91 + * The headers mirror the effective auth context of the session request: the
92 + * project key as `x-api-key` when one is configured, otherwise the resolved
93 + * user API key (the `userApiKey` option, then the `x-user-api-key` default
94 + * header) as `x-user-api-key`, plus `x-org-id` / `x-project-id` when the
95 + * instance carries an explicit scope. No other default header is copied and
96 + * the environment is never re-read.
97 + *
98 + * The headers are only attached when the MCP URL has the same origin as the
99 + * API base URL the session was created against, whatever scheme the caller
100 + * configured: that origin already receives them on every SDK request. Any
101 + * other destination (a different origin, an opaque origin, or a URL that does
102 + * not parse) never receives the credential. When the caller asked for MCP
103 + * (`mcpRequested`), that raises {@link ComposioMCPDestinationError} naming
104 + * both origins; otherwise the session is returned with empty `headers` and a
105 + * warning naming both origins is logged, so callers who only use the native
106 + * tools are not blocked by an endpoint they never consume. The SDK itself
107 + * never connects to the MCP URL and does not follow redirects for it; an MCP
108 + * client consuming this config must not forward these headers to a different
109 + * origin.
110 + */
111 +export const buildMCPServerConfig = (input: MCPServerConfigInput): ToolRouterMCPServerConfig => {
112 + const rejection = destinationRejection(input.apiBaseURL, input.url);
113 + if (rejection) {
114 + if (input.mcpRequested) {
115 + throw rejection;
116 + }
117 + logger.warn(
118 + `${rejection.message}. session.mcp.headers was left empty; pass \`mcp: true\` to make this an error`
119 + );
120 + return { type: input.type, url: input.url, headers: {} };
121 + }
122 +
123 + const headers = resolveCredentialHeaders(input);
124 + if (input.orgId) {
125 + headers[ORG_ID_HEADER] = input.orgId;
126 + }
127 + if (input.projectId) {
128 + headers[PROJECT_ID_HEADER] = input.projectId;
129 + }
130 +
131 + return { type: input.type, url: input.url, headers };
132 +};
ts/packages/core/src/lib/toolRouterParams.ts
+116 -29
@@ -13,6 +13,9 @@ import {
13 ToolRouterToolkitsDisabledConfigSchema,
14 ToolRouterToolkitsEnabledConfigSchema,
15 ToolRouterUpdateSessionConfig,
16 + ToolRouterUpdateManageConnectionsConfig,
17 + ToolRouterUpdateManageConnectionsSchema,
18 + ToolRouterUpdateExperimentalConfig,
19 ToolRouterSandboxConfig,
20 } from '../types/toolRouter.types';
21 import { ValidationError } from '../errors';
@@ -149,14 +152,58 @@ export const transformToolRouterWorkbenchParams = transformToolRouterSandboxPara
152 * PATCH-safe variant of transformToolRouterManageConnectionsParams.
153 * Does NOT apply defaults — only includes fields explicitly present in the input.
154 */
155 +/** Widens the listed keys of a generated request type so `null` can travel on the wire. */
156 +type WithNull<T, K extends keyof T> = Omit<T, K> & { [P in K]?: NonNullable<T[P]> | null };
157 +
158 +/**
159 + * `manage_connections` as sent by `session.update()`. Only the supplied
160 + * subfields travel; `callback_url: null` removes the stored callback, which
161 + * the generated client types as string-only.
162 + */
163 +export type SessionPatchManageConnectionsBody = WithNull<
164 + SessionPatchParams.ManageConnections,
165 + 'callback_url'
166 +>;
167 +
168 +/** `multi_account` as sent by `session.update()`; `null` removes the stored maximum. */
169 +export type SessionPatchMultiAccountBody = WithNull<
170 + SessionPatchParams.MultiAccount,
171 + 'max_accounts_per_toolkit'
172 +>;
173 +
174 +/** `experimental` as sent by `session.update()`; `null` removes a stored leaf. */
175 +export type SessionPatchExperimentalBody = WithNull<
176 + SessionPatchParams.Experimental,
177 + 'permissions' | 'link_url_overwrite' | 'fast_mode' | 'submit_feedback'
178 +>;
179 +
180 +/**
181 + * Request body of `session.update()`. Extends the generated `SessionPatchParams`
182 + * with the nullable policy blocks (`null` removes the stored override) and the
183 + * `expected_config_version` root precondition, none of which the generated
184 + * client types yet.
185 + */
186 +export type SessionPatchBody = Omit<
187 + WithNull<
188 + SessionPatchParams,
189 + 'toolkits' | 'tools' | 'tags' | 'auth_configs' | 'preload' | 'search' | 'execute'
190 + >,
191 + 'manage_connections' | 'multi_account' | 'experimental'
192 +> & {
193 + manage_connections?: SessionPatchManageConnectionsBody | null;
194 + multi_account?: SessionPatchMultiAccountBody | null;
195 + experimental?: SessionPatchExperimentalBody | null;
196 + expected_config_version?: number;
197 +};
198 +
199 export const transformToolRouterUpdateManageConnectionsParams = (
153 - params: boolean | z.infer<typeof ToolRouterConfigManageConnectionsSchema>
154 -): SessionPatchParams.ManageConnections => {
200 + params: boolean | ToolRouterUpdateManageConnectionsConfig
201 +): SessionPatchManageConnectionsBody => {
202 if (typeof params === 'boolean') {
203 return { enable: params };
204 }
205
159 - const parsedResult = ToolRouterConfigManageConnectionsSchema.safeParse(params);
206 + const parsedResult = ToolRouterUpdateManageConnectionsSchema.safeParse(params);
207 if (!parsedResult.success) {
208 throw new ValidationError('Failed to parse manage connections config', {
209 cause: parsedResult.error,
@@ -164,7 +211,7 @@ export const transformToolRouterUpdateManageConnectionsParams = (
211 }
212
213 const config = parsedResult.data;
167 - const result: Record<string, unknown> = {};
214 + const result: SessionPatchManageConnectionsBody = {};
215 if (config.enable !== undefined) {
216 result.enable = config.enable;
217 }
@@ -174,7 +221,32 @@ export const transformToolRouterUpdateManageConnectionsParams = (
221 if (config.waitForConnections !== undefined) {
222 result.enable_wait_for_connections = config.waitForConnections;
223 }
177 - return result as SessionPatchParams.ManageConnections;
224 + if (config.enableConnectionRemoval !== undefined) {
225 + result.enable_connection_removal = config.enableConnectionRemoval;
226 + }
227 + return result;
228 +};
229 +
230 +const transformToolRouterUpdateExperimentalParams = (
231 + config: ToolRouterUpdateExperimentalConfig
232 +): SessionPatchExperimentalBody => {
233 + const result: SessionPatchExperimentalBody = {};
234 + if (config.permissions !== undefined) {
235 + result.permissions = config.permissions;
236 + }
237 + if (config.linkUrlOverwrite !== undefined) {
238 + result.link_url_overwrite = config.linkUrlOverwrite;
239 + }
240 + if (config.fastMode !== undefined) {
241 + result.fast_mode = config.fastMode;
242 + }
243 + if (config.submitFeedback !== undefined) {
244 + result.submit_feedback = config.submitFeedback;
245 + }
246 + if (config.sessionConfigId !== undefined) {
247 + result.session_config_id = config.sessionConfigId;
248 + }
249 + return result;
250 };
251
252 /**
@@ -244,63 +316,78 @@ export const transformToolRouterToolkitsParams = (
316 return params as SessionCreateParams.Enable | SessionCreateParams.Disable;
317 };
318
319 +/**
320 + * Request body of `session.update()`. Every key present in `config` is sent,
321 + * including `null` (remove the stored override) and empty collections (an
322 + * empty toolkit allowlist denies every app toolkit). The
323 + * `expectedConfigVersion` option is not a body field here: the session
324 + * resolves the precondition against its observed `configVersion`.
325 + */
326 export const transformToolRouterUpdateParams = (
327 config: ToolRouterUpdateSessionConfig
249 -): SessionPatchParams => {
250 - const params: SessionPatchParams = {};
328 +): SessionPatchBody => {
329 + const params: SessionPatchBody = {};
330
331 if (config.toolkits !== undefined) {
253 - params.toolkits = transformToolRouterToolkitsParams(config.toolkits);
332 + params.toolkits =
333 + config.toolkits === null ? null : transformToolRouterToolkitsParams(config.toolkits);
334 }
335 if (config.tools !== undefined) {
256 - params.tools = transformToolRouterToolsParams(config.tools);
336 + params.tools = config.tools === null ? null : transformToolRouterToolsParams(config.tools);
337 }
338 if (config.tags !== undefined) {
259 - params.tags = transformToolRouterTagsParams(config.tags);
339 + params.tags = config.tags === null ? null : transformToolRouterTagsParams(config.tags);
340 }
341 if (config.authConfigs !== undefined) {
342 params.auth_configs = config.authConfigs;
343 }
344 if (config.connectedAccounts !== undefined) {
265 - const coerced: Record<string, string[]> = {};
266 - for (const [k, v] of Object.entries(config.connectedAccounts)) {
267 - coerced[k] = typeof v === 'string' ? [v] : v;
268 - }
269 - params.connected_accounts = coerced;
345 + params.connected_accounts = config.connectedAccounts;
346 }
347 if (config.manageConnections !== undefined) {
272 - if (config.manageConnections === null) {
273 - params.manage_connections = null;
274 - } else {
275 - params.manage_connections = transformToolRouterUpdateManageConnectionsParams(
276 - config.manageConnections
277 - );
278 - }
348 + params.manage_connections =
349 + config.manageConnections === null
350 + ? null
351 + : transformToolRouterUpdateManageConnectionsParams(config.manageConnections);
352 }
353 const sandboxConfig = config.sandbox !== undefined ? config.sandbox : config.workbench;
354 if (sandboxConfig !== undefined) {
282 - if (sandboxConfig === null) {
283 - params.workbench = null;
284 - } else {
285 - params.workbench = transformToolRouterUpdateSandboxParams(sandboxConfig);
286 - }
355 + params.workbench =
356 + sandboxConfig === null ? null : transformToolRouterUpdateSandboxParams(sandboxConfig);
357 }
358 if (config.multiAccount !== undefined) {
359 if (config.multiAccount === null) {
360 params.multi_account = null;
361 } else {
292 - const ma: Record<string, unknown> = {};
362 + const ma: SessionPatchMultiAccountBody = {};
363 if (config.multiAccount.enable !== undefined) ma.enable = config.multiAccount.enable;
364 if (config.multiAccount.maxAccountsPerToolkit !== undefined)
365 ma.max_accounts_per_toolkit = config.multiAccount.maxAccountsPerToolkit;
366 if (config.multiAccount.requireExplicitSelection !== undefined)
367 ma.require_explicit_selection = config.multiAccount.requireExplicitSelection;
298 - params.multi_account = ma as SessionPatchParams.MultiAccount;
368 + params.multi_account = ma;
369 }
370 }
371 if (config.preload !== undefined) {
372 params.preload = config.preload;
373 }
374 + if (config.search !== undefined) {
375 + params.search = config.search;
376 + }
377 + if (config.execute !== undefined) {
378 + params.execute =
379 + config.execute === null
380 + ? null
381 + : config.execute.enableMultiExecute === undefined
382 + ? {}
383 + : { enable_multi_execute: config.execute.enableMultiExecute };
384 + }
385 + if (config.experimental !== undefined) {
386 + params.experimental =
387 + config.experimental === null
388 + ? null
389 + : transformToolRouterUpdateExperimentalParams(config.experimental);
390 + }
391
392 return params;
393 };
ts/packages/core/src/models/ToolRouter.ts
+42 -14
@@ -53,6 +53,7 @@ import {
53 resolveToolRouterSandboxConfig,
54 } from '../lib/toolRouterParams';
55 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
56 +import { buildMCPServerConfig } from '../lib/toolRouterMcp';
57 import { ToolRouterSession } from './ToolRouterSession';
58 import { ComposioRequestOptions } from '../types/requestOptions.types';
59 import { withCancellation } from '../utils/cancellation';
@@ -131,20 +132,30 @@ export class ToolRouter<
132 telemetry.instrument(this, 'ToolRouter');
133 }
134
134 - private createMCPServerConfig({
135 - type,
136 - url,
137 - }: {
138 - type: MCPServerType;
139 - url: string;
140 - }): ToolRouterMCPServerConfig {
141 - return {
135 + /**
136 + * Derives the MCP config for a session from the auth context the session
137 + * request was made with: the project key when one is configured, otherwise
138 + * the resolved user API key, plus the org/project scope when configured.
139 + * Headers are only attached when the MCP URL shares the client's API
140 + * origin. Any other destination throws when the caller passed `mcp: true`
141 + * and otherwise yields empty headers plus a warning; see
142 + * `buildMCPServerConfig`.
143 + */
144 + private createMCPServerConfig(
145 + { type, url }: { type: MCPServerType; url: string },
146 + mcpRequested: boolean
147 + ): ToolRouterMCPServerConfig {
148 + return buildMCPServerConfig({
149 type,
150 url,
144 - headers: {
145 - ...(this.config?.apiKey ? { 'x-api-key': this.config.apiKey } : {}),
146 - },
147 - };
151 + apiBaseURL: this.client.baseURL,
152 + apiKey: this.config?.apiKey,
153 + userApiKey: this.config?.userApiKey,
154 + defaultHeaders: this.config?.defaultHeaders,
155 + orgId: this.config?.orgId,
156 + projectId: this.config?.projectId,
157 + mcpRequested,
158 + });
159 }
160
161 /**
@@ -152,9 +163,17 @@ export class ToolRouter<
163 * Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools
164 * should be exposed directly; see `ToolRouterCreateSessionConfig`.
165 *
166 + * The session's MCP config carries the session credential only when the
167 + * MCP URL shares the origin of the configured API base URL. When it does
168 + * not, `mcp: true` makes the call throw `ComposioMCPDestinationError`
169 + * (naming both origins, never a key); without `mcp: true` the session is
170 + * returned with `session.mcp.headers` empty and a warning naming both
171 + * origins is logged, so native tools keep working.
172 + *
173 * @param userId {string} The user id to create the session for
174 * @param config {ToolRouterCreateSessionConfig} The config for the tool router session
175 * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
176 + * @throws {ComposioMCPDestinationError} When `mcp: true` is passed and the MCP URL is not on the API origin
177 *
178 * @example
179 * ```typescript
@@ -282,7 +301,7 @@ export class ToolRouter<
301 this.client,
302 this.config,
303 session.session_id,
285 - this.createMCPServerConfig(session.mcp),
304 + this.createMCPServerConfig(session.mcp, routerConfig.mcp === true),
305 { assistivePrompt },
306 customToolsMap,
307 userId,
@@ -292,8 +311,17 @@ export class ToolRouter<
311
312 /**
313 * Use an existing session
314 + *
315 + * The session's MCP config carries the session credential only when the
316 + * MCP URL shares the origin of the configured API base URL. When it does
317 + * not, `mcp: true` makes the call throw `ComposioMCPDestinationError`
318 + * (naming both origins, never a key); without `mcp: true` the session is
319 + * returned with `session.mcp.headers` empty and a warning naming both
320 + * origins is logged, so native tools keep working.
321 + *
322 * @param id {string} The id of the session to use
323 * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
324 + * @throws {ComposioMCPDestinationError} When `mcp: true` is passed and the MCP URL is not on the API origin
325 *
326 * @example
327 * ```typescript
@@ -384,7 +412,7 @@ export class ToolRouter<
412 this.client,
413 this.config,
414 session.session_id,
387 - this.createMCPServerConfig(session.mcp),
415 + this.createMCPServerConfig(session.mcp, options?.mcp === true),
416 undefined,
417 customToolsMap,
418 userId,
ts/packages/core/src/models/ToolRouterSession.ts
+68 -9
@@ -1,10 +1,11 @@
1 import { telemetry } from '../telemetry/Telemetry';
2 -import { Composio as ComposioClient, BadRequestError } from '@composio/client';
2 +import { Composio as ComposioClient, BadRequestError, ConflictError } from '@composio/client';
3 import type { BaseComposioProvider } from '../provider/BaseProvider';
4 import type { ComposioConfig } from '../composio';
5 import type { ComposioRequestOptions } from '../types/requestOptions.types';
6 import { withCancellation } from '../utils/cancellation';
7 import { ComposioRequestCancelledError } from '../errors/SDKErrors';
8 +import { ComposioSessionConfigConflictError } from '../errors/ToolRouterErrors';
9 import {
10 ToolRouterMCPServerConfig,
11 SessionExperimental,
@@ -67,6 +68,8 @@ import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
68 import type {
69 SessionExecuteParams,
70 SessionLinkParams,
71 + SessionPatchParams,
72 + SessionPatchResponse,
73 SessionSearchParams,
74 } from '@composio/client/resources/tool-router/session/session.mjs';
75 import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
@@ -134,6 +137,11 @@ export class ToolRouterSession<
137 public preload: ToolRouterSessionPreloadConfig;
138 /** Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. */
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.
144 + */
145 public configVersion?: number;
146 public warnings: ToolRouterSessionWarning[];
147 private readonly preloadedCustomToolSlugs: string[];
@@ -761,20 +769,71 @@ export class ToolRouterSession<
769
770 /**
771 * Partially update the session configuration.
764 - * Only the fields provided will be changed; omitted fields are preserved.
765 - * Mutates this session's `config`, `configVersion`, `preload`, `sandbox`,
766 - * and `warnings` in-place, and resolves to the updated session `config`.
772 + *
773 + * Only the fields provided are changed; omitted fields are preserved. For
774 + * each policy block `null` removes the stored override (which can increase
775 + * access: `toolkits: null` restores the unrestricted default, while
776 + * `toolkits: []` denies every app toolkit and is sent as-is). Supplied
777 + * `tools`, `authConfigs` and `connectedAccounts` maps replace the stored
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
783 + * {@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`.
790 + *
791 + * `config`, `configVersion`, `preload`, `sandbox` and `warnings` are
792 + * refreshed in place only after a successful response, and the updated
793 + * `config` is returned.
794 */
795 async update(
796 config: ToolRouterUpdateSessionConfig,
797 requestOptions?: ComposioRequestOptions
798 ): Promise<ToolRouterSessionConfig> {
799 const parsed = ToolRouterUpdateSessionConfigSchema.parse(config);
773 - const params = transformToolRouterUpdateParams(parsed);
774 - const response = await withCancellation(
775 - () => this.client.toolRouter.session.patch(this.sessionId, params, requestOptions),
776 - requestOptions?.signal
777 - );
800 + const body = transformToolRouterUpdateParams(parsed);
801 + const expectedConfigVersion =
802 + parsed.expectedConfigVersion === false
803 + ? undefined
804 + : (parsed.expectedConfigVersion ?? this.configVersion);
805 + if (expectedConfigVersion !== undefined) {
806 + body.expected_config_version = expectedConfigVersion;
807 + }
808 +
809 + let response: SessionPatchResponse;
810 + try {
811 + response = await withCancellation(
812 + () =>
813 + this.client.toolRouter.session.patch(
814 + this.sessionId,
815 + // The generated client does not type `expected_config_version` or
816 + // the nullable policy blocks; the body is serialized as-is.
817 + body as SessionPatchParams,
818 + { ...requestOptions, maxRetries: 0 }
819 + ),
820 + requestOptions?.signal
821 + );
822 + } catch (error) {
823 + if (error instanceof ConflictError) {
824 + throw new ComposioSessionConfigConflictError(
825 + expectedConfigVersion === undefined
826 + ? `Session ${this.sessionId} configuration changed while this update was in flight; re-fetch the session and retry the update`
827 + : `Session ${this.sessionId} configuration is no longer at version ${expectedConfigVersion}; re-fetch the session and retry the update`,
828 + {
829 + cause: error,
830 + meta: { sessionId: this.sessionId, expectedConfigVersion },
831 + }
832 + );
833 + }
834 + throw error;
835 + }
836 +
837 this.configVersion = response.config_version;
838 this.config = response.config;
839 this.preload = response.config.preload;
ts/packages/core/src/models/Triggers.ts
+1 -1
@@ -157,7 +157,7 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
157
158 constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
159 this.client = client;
160 - this.pusherService = new PusherService(client);
160 + this.pusherService = new PusherService(client, { defaultHeaders: config?.defaultHeaders });
161 this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
162 telemetry.instrument(this, 'Triggers');
163 }
ts/packages/core/src/services/pusher/Pusher.ts
+17 -6
@@ -9,6 +9,13 @@ import {
9 } from '../../errors/TriggerErrors';
10 import logger from '../../utils/logger';
11 import { telemetry } from '../../telemetry/Telemetry';
12 +import { resolveCredentialHeaders } from '../../utils/sdk';
13 +import type { ComposioRequestHeaders } from '../../types/composio.types';
14 +
15 +export type PusherServiceOptions = {
16 + /** Default headers of the owning SDK instance; only `x-user-api-key` is consulted. */
17 + defaultHeaders?: ComposioRequestHeaders;
18 +};
19
20 export class PusherService {
21 // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
@@ -18,14 +25,20 @@ export class PusherService {
25 private pusherChannel!: string;
26 // these details are set via the client SDK
27 private pusherBaseURL!: string;
21 - private apiKey!: string;
28 + private authHeaders!: Record<string, string>;
29 private pusherClient!: PusherClient;
30 private composioClient!: ComposioClient;
31
25 - constructor(client: ComposioClient) {
32 + constructor(client: ComposioClient, options: PusherServiceOptions = {}) {
33 this.composioClient = client;
34 this.pusherBaseURL = client.baseURL;
28 - this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? '';
35 + // Channel authorization mirrors the client's effective auth; the
36 + // environment is never consulted here.
37 + this.authHeaders = resolveCredentialHeaders({
38 + apiKey: client.apiKey,
39 + userApiKey: client.userApiKey,
40 + defaultHeaders: options.defaultHeaders,
41 + });
42 telemetry.instrument(this, 'PusherService');
43 }
44
@@ -66,9 +79,7 @@ export class PusherService {
79 cluster: this.pusherCluster,
80 channelAuthorization: {
81 endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
69 - headers: {
70 - 'x-api-key': this.apiKey,
71 - },
82 + headers: { ...this.authHeaders },
83 transport: 'ajax',
84 },
85 });
ts/packages/core/src/types/toolRouter.types.ts
+156 -10
@@ -217,7 +217,7 @@ const ToolRouterCreateSessionConfigBaseSchema = z
217 .boolean()
218 .optional()
219 .describe(
220 - 'When true, the returned session surfaces its hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`) in the type. The endpoint exists on every session at runtime regardless of this flag, but is only typed when `mcp: true` is passed. Default native tools (`session.tools()`) are unaffected. See https://docs.composio.dev/docs/sessions-via-mcp'
220 + 'When true, the returned session surfaces its hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`) in the type, and an MCP URL that is not on the API base URL origin throws `ComposioMCPDestinationError` instead of leaving `session.mcp.headers` empty with a warning. The endpoint exists on every session at runtime regardless of this flag, but is only typed when `mcp: true` is passed. Default native tools (`session.tools()`) are unaffected. See https://docs.composio.dev/docs/sessions-via-mcp'
221 ),
222
223 tools: z
@@ -655,6 +655,107 @@ export type ToolRouterSessionProxyExecuteFn = (
655 params: SessionProxyExecuteParams
656 ) => Promise<ToolRouterSessionProxyExecuteResponse>;
657
658 +/**
659 + * `manageConnections` shape accepted by `session.update()`. Unlike the create
660 + * schema, `callbackUrl: null` removes the stored callback URL while leaving
661 + * the sibling connection settings untouched.
662 + */
663 +export const ToolRouterUpdateManageConnectionsSchema = z
664 + .object({
665 + enable: z
666 + .boolean()
667 + .optional()
668 + .describe(
669 + 'Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually'
670 + ),
671 + callbackUrl: z
672 + .string()
673 + .nullable()
674 + .optional()
675 + .describe(
676 + 'The callback url to use in the tool router session. `null` removes the stored callback url; sibling settings are untouched'
677 + ),
678 + waitForConnections: z
679 + .boolean()
680 + .optional()
681 + .describe(
682 + 'Whether to wait for users to finish authenticating connections before proceeding to the next step. Defaults to false, if set to true, a wait for connections tool call will happen and finish when the connections are ready'
683 + ),
684 + enableConnectionRemoval: z
685 + .boolean()
686 + .nullable()
687 + .optional()
688 + .describe(
689 + 'Whether the session exposes the connection removal tool. `null` removes the stored override'
690 + ),
691 + })
692 + .strict();
693 +export type ToolRouterUpdateManageConnectionsConfig = z.infer<
694 + typeof ToolRouterUpdateManageConnectionsSchema
695 +>;
696 +
697 +const ToolRouterElicitationDefaultSchema = z.enum([
698 + 'allow_all',
699 + 'ask_every_call',
700 + 'ask_once_per_session',
701 +]);
702 +const ToolRouterElicitationOverrideSchema = z.enum([
703 + 'always_allow',
704 + 'always_deny',
705 + 'ask_once',
706 + 'ask_always',
707 +]);
708 +
709 +/**
710 + * `experimental` block accepted by `session.update()`. Each leaf follows the
711 + * PATCH contract of the API: omit to keep the stored value, `null` to remove
712 + * it, a value to replace it.
713 + */
714 +export const ToolRouterUpdateExperimentalSchema = z
715 + .object({
716 + permissions: z
717 + .object({
718 + default: ToolRouterElicitationDefaultSchema,
719 + overrides: z.record(z.string(), ToolRouterElicitationOverrideSchema).optional(),
720 + })
721 + .strict()
722 + .nullable()
723 + .optional()
724 + .describe('Per-tool elicitation permission config. `null` removes the stored block'),
725 + linkUrlOverwrite: z
726 + .string()
727 + .nullable()
728 + .optional()
729 + .describe(
730 + 'Base URL override for connection link redirects. `null` removes the stored override'
731 + ),
732 + fastMode: z
733 + .boolean()
734 + .nullable()
735 + .optional()
736 + .describe('Fast search mode. `null` removes the stored override'),
737 + submitFeedback: z
738 + .object({ enable: z.boolean() })
739 + .strict()
740 + .nullable()
741 + .optional()
742 + .describe(
743 + 'Exposes the COMPOSIO_SUBMIT_FEEDBACK helper tool. `null` removes the stored block'
744 + ),
745 + sessionConfigId: z
746 + .string()
747 + .optional()
748 + .describe('Apply the latest active Session config from this project to this session'),
749 + })
750 + .strict();
751 +export type ToolRouterUpdateExperimentalConfig = z.infer<typeof ToolRouterUpdateExperimentalSchema>;
752 +
753 +/**
754 + * Options for `session.update()`. For every policy block, omitting the key
755 + * preserves the stored value and `null` removes the stored override (which can
756 + * increase access: `toolkits: null` restores the unrestricted default, unlike
757 + * `toolkits: []`, which denies every app toolkit).
758 + */
759 export const ToolRouterUpdateSessionConfigSchema = z
760 .object({
761 toolkits: z
@@ -663,12 +764,24 @@ export const ToolRouterUpdateSessionConfigSchema = z
764 ToolRouterToolkitsDisabledConfigSchema,
765 ToolRouterToolkitsEnabledConfigSchema,
766 ])
666 - .optional(),
767 + .nullable()
768 + .optional()
769 + .describe(
770 + 'Toolkit policy. An empty allowlist (`[]` or `{ enable: [] }`) is sent as-is and denies every app toolkit; `null` removes the stored policy and restores the unrestricted default'
771 + ),
772 tools: z
773 .record(z.string(), z.union([ToolRouterToolsParamSchema, ToolRouterConfigToolsSchema]))
669 - .optional(),
670 - tags: ToolRouterConfigTagsSchema.optional(),
671 - authConfigs: z.record(z.string(), z.string()).optional(),
774 + .nullable()
775 + .optional()
776 + .describe('Replaces the entire stored tools map; `null` removes the override'),
777 + tags: ToolRouterConfigTagsSchema.nullable()
778 + .optional()
779 + .describe('Replaces the global tag policy; `null` removes the override'),
780 + authConfigs: z
781 + .record(z.string(), z.string())
782 + .nullable()
783 + .optional()
784 + .describe('Replaces the entire stored auth config map; `null` removes the override'),
785 connectedAccounts: z
786 .record(z.string(), z.union([z.string(), z.array(z.string())]))
787 .transform(rec => {
@@ -678,9 +791,11 @@ export const ToolRouterUpdateSessionConfigSchema = z
791 }
792 return out;
793 })
681 - .optional(),
794 + .nullable()
795 + .optional()
796 + .describe('Replaces the entire stored connected accounts map; `null` removes the override'),
797 manageConnections: z
683 - .union([z.boolean(), ToolRouterConfigManageConnectionsSchema])
798 + .union([z.boolean(), ToolRouterUpdateManageConnectionsSchema])
799 .nullable()
800 .optional(),
801 sandbox: ToolRouterSandboxConfigSchema.partial().nullable().optional(),
@@ -688,17 +803,48 @@ export const ToolRouterUpdateSessionConfigSchema = z
803 multiAccount: z
804 .object({
805 enable: z.boolean().optional(),
691 - maxAccountsPerToolkit: z.number().int().min(2).max(10).optional(),
806 + maxAccountsPerToolkit: z
807 + .number()
808 + .int()
809 + .min(2)
810 + .max(10)
811 + .nullable()
812 + .optional()
813 + .describe('`null` removes the stored maximum so the default applies again'),
814 requireExplicitSelection: z.boolean().optional(),
815 })
816 .nullable()
695 - .optional(),
817 + .optional()
818 + .describe('`null` removes the session override; the mode then resolves to disabled'),
819 preload: z
820 .object({
821 tools: z.union([z.array(z.string()), z.literal('all')]).optional(),
822 })
823 .strict()
701 - .optional(),
824 + .nullable()
825 + .optional()
826 + .describe('Replaces the stored preload; `null` removes it'),
827 + search: z
828 + .object({ enable: z.boolean().optional() })
829 + .strict()
830 + .nullable()
831 + .optional()
832 + .describe('Replaces the search block; `null` removes it and restores the defaults'),
833 + execute: z
834 + .object({ enableMultiExecute: z.boolean().optional() })
835 + .strict()
836 + .nullable()
837 + .optional()
838 + .describe('Replaces the execute block; `null` removes it and restores the defaults'),
839 + experimental: ToolRouterUpdateExperimentalSchema.nullable()
840 + .optional()
841 + .describe('Experimental settings; `null` removes the stored block'),
842 + expectedConfigVersion: 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)'
847 + ),
848 })
849 .partial()
850 .superRefine((config, ctx) => {
ts/packages/core/src/utils/sdk.ts
+385 -22
@@ -1,12 +1,40 @@
1 -import { ComposioNoAPIKeyError } from '../errors/SDKErrors';
1 +import { z } from 'zod/v3';
2 +import {
3 + ComposioAPIKeyKindError,
4 + ComposioNoAPIKeyError,
5 + ComposioScopeConfigError,
6 +} from '../errors/SDKErrors';
7 import { COMPOSIO_DIR, DEFAULT_BASE_URL, USER_DATA_FILE_NAME } from './constants';
8 import { getEnvsWithPrefix, getEnvVariable } from './env';
9 import logger from './logger';
10 import { ComposioError } from '../errors/ComposioError';
11 import { ToolkitVersion, ToolkitVersionParam, ToolkitVersions } from '../types/tool.types';
12 +import type { ComposioRequestHeaders } from '../types/composio.types';
13 import { normalizeToolkitSlug } from './toolkitVersion';
14 import { platform } from '#platform';
15
16 +/**
17 + * Header that carries a Composio user API key (`uak_...`) instead of a project
18 + * API key. It is the only default header the credential resolver reads.
19 + */
20 +export const USER_API_KEY_HEADER = 'x-user-api-key';
21 +
22 +/** Prefix of Composio user API keys as issued by `composio login`. */
23 +const USER_API_KEY_PREFIX = 'uak_';
24 +
25 +/**
26 + * Header that carries the project API key. The SDK only ever sets it from the
27 + * resolved `apiKey`; a caller-placed entry in `defaultHeaders` is rejected
28 + * when project-key auth is disabled.
29 + */
30 +export const PROJECT_API_KEY_HEADER = 'x-api-key';
31 +
32 +/** Header carrying the organization nano ID that scopes user-key requests. */
33 +export const ORG_ID_HEADER = 'x-org-id';
34 +
35 +/** Header carrying the project nano ID that scopes user-key requests. */
36 +export const PROJECT_ID_HEADER = 'x-project-id';
37 +
38 // File path helpers
39 export const userDataPath = () => {
40 try {
@@ -22,38 +50,373 @@ export const userDataPath = () => {
50 };
51
52 /**
25 - * Reads and parses the user data JSON file from the Composio directory.
26 - *
27 - * @returns The parsed user data object containing user configuration (api_key, base_url, etc.), or empty object if file doesn't exist or can't be read
53 + * Shape of `~/.composio/user_data.json`. The file is written by the Composio
54 + * CLI; only the two fields the SDK consumes are validated, everything else is
55 + * carried through untouched.
56 + */
57 +const UserDataFileSchema = z
58 + .object({
59 + api_key: z.string().nullish(),
60 + base_url: z.string().nullish(),
61 + })
62 + .passthrough();
63 +
64 +export type UserDataFile = z.infer<typeof UserDataFileSchema>;
65 +
66 +export type UserDataFileRead =
67 + /** No file system, no home directory, or no file: nothing to fall back to. */
68 + | { status: 'missing' }
69 + /** The file exists but is not JSON or does not have the expected shape. */
70 + | { status: 'malformed'; path: string; reason: string }
71 + | { status: 'ok'; path: string; data: UserDataFile };
72 +
73 +/**
74 + * Reads and validates the user data JSON file from the Composio directory.
75 + * File contents never appear in the returned diagnostics.
76 */
29 -export const getUserDataJson = () => {
77 +export const readUserDataFile = (): UserDataFileRead => {
78 + if (!platform.supportsFileSystem) {
79 + return { status: 'missing' };
80 + }
81 + const dataPath = userDataPath();
82 + if (!dataPath) {
83 + return { status: 'missing' };
84 + }
85 +
86 + let raw: string | Uint8Array;
87 try {
31 - const dataPath = userDataPath();
32 - if (!dataPath || !platform.supportsFileSystem) {
33 - return {};
34 - }
35 - const data = platform.readFileSync(dataPath, 'utf8');
36 - return JSON.parse(data as string);
88 + raw = platform.readFileSync(dataPath, 'utf8');
89 } catch (_error) {
90 logger.debug('Environment', 'No user data file found');
39 - return {};
91 + return { status: 'missing' };
92 + }
93 +
94 + let json: unknown;
95 + try {
96 + json = JSON.parse(typeof raw === 'string' ? raw : new TextDecoder().decode(raw));
97 + } catch (_error) {
98 + logger.debug('Environment', `User data file at ${dataPath} could not be parsed as JSON`);
99 + return { status: 'malformed', path: dataPath, reason: 'could not be parsed as JSON' };
100 + }
101 +
102 + const parsed = UserDataFileSchema.safeParse(json);
103 + if (!parsed.success) {
104 + const fields = parsed.error.issues
105 + .map(issue => issue.path.join('.'))
106 + .filter(Boolean)
107 + .join(', ');
108 + const reason = fields
109 + ? `has an unexpected shape (invalid field${fields.includes(',') ? 's' : ''}: ${fields})`
110 + : 'has an unexpected shape (expected a JSON object)';
111 + logger.debug('Environment', `User data file at ${dataPath} ${reason}`);
112 + return { status: 'malformed', path: dataPath, reason };
113 + }
114 +
115 + return { status: 'ok', path: dataPath, data: parsed.data };
116 +};
117 +
118 +const findHeader = (
119 + headers: ComposioRequestHeaders | undefined,
120 + name: string
121 +): { name: string; value: string } | undefined => {
122 + if (!headers) {
123 + return undefined;
124 + }
125 + const wanted = name.toLowerCase();
126 + for (const [key, value] of Object.entries(headers)) {
127 + if (key.toLowerCase() === wanted) {
128 + return { name: key, value };
129 + }
130 }
131 + return undefined;
132 };
133
43 -// Client configuration functions
44 -export function getSDKConfig(baseUrl?: string | null, apiKey?: string | null) {
45 - const userData = getUserDataJson();
46 - const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
134 +/**
135 + * Returns the `x-user-api-key` entry from a header map, if it carries a
136 + * non-empty value. Matches the header name case-insensitively and ignores
137 + * every other header.
138 + */
139 +export const getUserApiKeyHeader = (
140 + headers: ComposioRequestHeaders | undefined
141 +): { name: string; value: string } | undefined => {
142 + const header = findHeader(headers, USER_API_KEY_HEADER);
143 + return header && typeof header.value === 'string' && header.value.length > 0 ? header : undefined;
144 +};
145
48 - const baseURLParsed =
49 - baseUrl || getEnvVariable('COMPOSIO_BASE_URL') || baseURLFromUserConfig || DEFAULT_BASE_URL;
50 - const apiKeyParsed = apiKey || getEnvVariable('COMPOSIO_API_KEY') || apiKeyFromUserConfig || '';
146 +export type CredentialHeaderInput = {
147 + /** The project API key the client resolved, or `null` when disabled. */
148 + apiKey: string | null | undefined;
149 + /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */
150 + userApiKey: string | null | undefined;
151 + /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */
152 + defaultHeaders: ComposioRequestHeaders | undefined;
153 +};
154 +
155 +/**
156 + * The single credential header that mirrors what the API client puts on the
157 + * wire for an SDK instance. A non-empty `x-user-api-key` entry in the default
158 + * headers wins: the client treats a caller-placed credential header as the
159 + * credential and suppresses the configured keys. Otherwise the project key
160 + * travels as `x-api-key`, otherwise the resolved user API key as
161 + * `x-user-api-key`. Empty when no credential is held. The environment is
162 + * never consulted here.
163 + */
164 +export const resolveCredentialHeaders = (input: CredentialHeaderInput): Record<string, string> => {
165 + const userApiKeyHeader = getUserApiKeyHeader(input.defaultHeaders);
166 + if (userApiKeyHeader) {
167 + return { [USER_API_KEY_HEADER]: userApiKeyHeader.value };
168 + }
169 + if (hasValue(input.apiKey)) {
170 + return { [PROJECT_API_KEY_HEADER]: input.apiKey };
171 + }
172 + if (hasValue(input.userApiKey)) {
173 + return { [USER_API_KEY_HEADER]: input.userApiKey };
174 + }
175 + return {};
176 +};
177 +
178 +export type SDKScopeOptions = {
179 + /** The `orgId` constructor option. */
180 + orgId?: string;
181 + /** The `projectId` constructor option. */
182 + projectId?: string;
183 + /** Default headers the SDK will attach to every request. */
184 + defaultHeaders?: ComposioRequestHeaders;
185 +};
186 +
187 +export type SDKScope = {
188 + orgId?: string;
189 + projectId?: string;
190 +};
191 +
192 +const resolveScopeValue = (
193 + option: string | undefined,
194 + headers: ComposioRequestHeaders | undefined,
195 + headerName: string,
196 + optionName: 'orgId' | 'projectId'
197 +): string | undefined => {
198 + const header = findHeader(headers, headerName);
199 + const headerValue = header && header.value.length > 0 ? header.value : undefined;
200 + const optionValue = hasValue(option) ? option : undefined;
201 + if (optionValue !== undefined && headerValue !== undefined && optionValue !== headerValue) {
202 + throw new ComposioScopeConfigError(
203 + `\`${optionName}\` and the \`${headerName}\` default header disagree`,
204 + {
205 + cause: `The ${optionName} option and the ${headerName} entry in defaultHeaders carry different values; the SDK keeps a single scope source`,
206 + meta: { option: optionName, header: headerName },
207 + }
208 + );
209 + }
210 + return optionValue ?? headerValue;
211 +};
212 +
213 +/**
214 + * Resolves the organization/project scope of an SDK instance.
215 + *
216 + * The scope comes from the `orgId` / `projectId` options, or from the
217 + * `x-org-id` / `x-project-id` default headers when the options are omitted.
218 + * A value present in both places must agree, and the two IDs must be supplied
219 + * together: a user API key without an explicit scope keeps the API default
220 + * (the developer project), so a half-configured scope is rejected instead of
221 + * silently selecting a project.
222 + */
223 +export function resolveSDKScope(options: SDKScopeOptions): SDKScope {
224 + const orgId = resolveScopeValue(options.orgId, options.defaultHeaders, ORG_ID_HEADER, 'orgId');
225 + const projectId = resolveScopeValue(
226 + options.projectId,
227 + options.defaultHeaders,
228 + PROJECT_ID_HEADER,
229 + 'projectId'
230 + );
231 + if ((orgId === undefined) !== (projectId === undefined)) {
232 + throw new ComposioScopeConfigError(
233 + orgId === undefined
234 + ? '`projectId` requires `orgId`: the organization and project nano IDs scope requests together'
235 + : '`orgId` requires `projectId`: the organization and project nano IDs scope requests together',
236 + {
237 + cause: 'Only one of the two scope identifiers was configured',
238 + meta: { orgId: orgId !== undefined, projectId: projectId !== undefined },
239 + }
240 + );
241 + }
242 + return orgId === undefined || projectId === undefined ? {} : { orgId, projectId };
243 +}
244 +
245 +/** The `x-org-id` / `x-project-id` headers for a resolved scope. */
246 +export const getScopeHeaders = (scope: SDKScope): ComposioRequestHeaders =>
247 + scope.orgId && scope.projectId
248 + ? { [ORG_ID_HEADER]: scope.orgId, [PROJECT_ID_HEADER]: scope.projectId }
249 + : {};
250 +
251 +export type SDKConfigOptions = {
252 + /** Default headers the SDK will attach to every request. */
253 + defaultHeaders?: ComposioRequestHeaders;
254 + /**
255 + * The `userApiKey` constructor option, exactly as the caller passed it:
256 + * `undefined` lets the API client read `COMPOSIO_USER_API_KEY`, `null`
257 + * disables that fallback.
258 + */
259 + userApiKey?: string | null;
260 + /**
261 + * The `orgApiKey` constructor option, exactly as the caller passed it:
262 + * `undefined` lets the API client read `COMPOSIO_ORG_API_KEY`, `null`
263 + * disables that fallback.
264 + */
265 + orgApiKey?: string | null;
266 +};
267 +
268 +export type SDKConfig = {
269 + baseURL: string;
270 + /** The project API key to send as `x-api-key`, or `null` when project-key auth is disabled. */
271 + apiKey: string | null;
272 +};
273 +
274 +const hasValue = (value: string | null | undefined): value is string =>
275 + typeof value === 'string' && value.length > 0;
276 +
277 +/**
278 + * Mirrors how the API client resolves `userApiKey` / `orgApiKey`: an explicit
279 + * value (including `null`) is final, `undefined` falls back to the environment.
280 + */
281 +const resolveAlternateCredential = (
282 + explicit: string | null | undefined,
283 + envName: string
284 +): string | undefined => {
285 + if (explicit !== undefined) {
286 + return hasValue(explicit) ? explicit : undefined;
287 + }
288 + const fromEnv = getEnvVariable(envName);
289 + return hasValue(fromEnv) ? fromEnv : undefined;
290 +};
291 +
292 +/**
293 + * The user API key the API client will hold: the `userApiKey` option when it
294 + * was passed (including `null`, which disables the fallback), otherwise
295 + * `COMPOSIO_USER_API_KEY`.
296 + */
297 +export const resolveUserApiKey = (userApiKey: string | null | undefined): string | undefined =>
298 + resolveAlternateCredential(userApiKey, 'COMPOSIO_USER_API_KEY');
299
52 - if (!apiKeyParsed) {
53 - ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
300 +/**
301 + * Whether the instance holds a credential other than the project key: a user
302 + * or organization API key (explicit or environment-resolved, as the API client
303 + * will see it), or a user API key placed in the default headers.
304 + */
305 +const hasAlternateCredential = (options: SDKConfigOptions): boolean =>
306 + resolveUserApiKey(options.userApiKey) !== undefined ||
307 + resolveAlternateCredential(options.orgApiKey, 'COMPOSIO_ORG_API_KEY') !== undefined ||
308 + getUserApiKeyHeader(options.defaultHeaders) !== undefined;
309 +
310 +/**
311 + * Resolves the base URL and project API key the SDK will use.
312 + *
313 + * Project key resolution distinguishes three caller intents:
314 + * - a non-empty string is used as-is and nothing else is consulted;
315 + * - `undefined` (or an empty string) falls back to `COMPOSIO_API_KEY`, then to
316 + * the `api_key` stored by the CLI in `~/.composio/user_data.json`;
317 + * - `null` disables project-key auth: neither `COMPOSIO_API_KEY` nor the stored
318 + * `api_key` is read, and the resolver only succeeds when the instance holds
319 + * another credential: a `userApiKey` or `orgApiKey` (explicit, or resolved
320 + * from `COMPOSIO_USER_API_KEY` / `COMPOSIO_ORG_API_KEY` the way the API
321 + * client does), or a non-empty `x-user-api-key` entry in `defaultHeaders`.
322 + * An `x-api-key` entry in `defaultHeaders` (any letter case) is rejected in
323 + * that mode: the project credential is only ever set from `apiKey`.
324 + *
325 + * A stored `uak_` user key is never used as a project key: when it is the only
326 + * candidate the resolver throws a {@link ComposioAPIKeyKindError} that names the
327 + * problem without echoing the key.
328 + */
329 +export function getSDKConfig(
330 + baseUrl?: string | null,
331 + apiKey?: string | null,
332 + options: SDKConfigOptions = {}
333 +): SDKConfig {
334 + let userData: UserDataFileRead | undefined;
335 + const readUserData = () => {
336 + userData ??= readUserDataFile();
337 + return userData;
338 + };
339 + const userDataValue = (field: 'api_key' | 'base_url'): string | undefined => {
340 + const read = readUserData();
341 + return read.status === 'ok' && hasValue(read.data[field]) ? read.data[field] : undefined;
342 + };
343 +
344 + const resolveApiKey = (): string | null => {
345 + if (apiKey === null) {
346 + const projectKeyHeader = findHeader(options.defaultHeaders, PROJECT_API_KEY_HEADER);
347 + if (projectKeyHeader) {
348 + throw new ComposioNoAPIKeyError(
349 + `Project API key resolution is disabled, but \`defaultHeaders\` carries a \`${projectKeyHeader.name}\` entry`,
350 + {
351 + cause:
352 + '`apiKey: null` sends no project key, so a raw x-api-key default header would bypass that choice; the SDK keeps a single source for the project credential',
353 + possibleFixes: [
354 + `Pass the project API key via \`apiKey\` instead of a raw \`${PROJECT_API_KEY_HEADER}\` default header`,
355 + `Remove the \`${projectKeyHeader.name}\` entry from \`defaultHeaders\` to authenticate with the user or organization API key alone`,
356 + ],
357 + }
358 + );
359 + }
360 + if (hasAlternateCredential(options)) {
361 + return null;
362 + }
363 + throw new ComposioNoAPIKeyError('Project API key resolution is disabled', {
364 + cause:
365 + '`apiKey: null` turns off the COMPOSIO_API_KEY and user config file fallbacks, and no user or organization API key was configured',
366 + possibleFixes: [
367 + 'Pass a project API key via `apiKey`, or omit it to fall back to COMPOSIO_API_KEY',
368 + 'To authenticate with a user API key instead, keep `apiKey: null` and pass `userApiKey` (or set COMPOSIO_USER_API_KEY)',
369 + `Alternatively, keep \`apiKey: null\` and set the \`${USER_API_KEY_HEADER}\` default header`,
370 + ],
371 + });
372 + }
373 +
374 + if (hasValue(apiKey)) {
375 + return apiKey;
376 + }
377 +
378 + const envApiKey = getEnvVariable('COMPOSIO_API_KEY');
379 + if (hasValue(envApiKey)) {
380 + return envApiKey;
381 + }
382 +
383 + const read = readUserData();
384 + const storedApiKey = userDataValue('api_key');
385 + if (read.status === 'ok' && hasValue(storedApiKey)) {
386 + if (storedApiKey.startsWith(USER_API_KEY_PREFIX)) {
387 + throw new ComposioAPIKeyKindError(undefined, {
388 + cause: `The user config file at ${read.path} holds a user API key written by the Composio CLI; it cannot authenticate SDK requests as a project`,
389 + meta: { userDataFilePath: read.path },
390 + });
391 + }
392 + return storedApiKey;
393 + }
394 +
395 + if (read.status === 'malformed') {
396 + throw new ComposioNoAPIKeyError('No Composio API key provided', {
397 + cause: `No API key was passed in the params or in COMPOSIO_API_KEY, and the user config file at ${read.path} ${read.reason}`,
398 + });
399 + }
400 + throw new ComposioNoAPIKeyError();
401 + };
402 +
403 + let apiKeyParsed: string | null;
404 + try {
405 + apiKeyParsed = resolveApiKey();
406 + } catch (error) {
407 + ComposioError.handleAndThrow(error);
408 }
409
56 - logger.debug('Environment', 'API Key: [REDACTED]');
410 + const baseURLParsed =
411 + (hasValue(baseUrl) ? baseUrl : undefined) ??
412 + getEnvVariable('COMPOSIO_BASE_URL') ??
413 + userDataValue('base_url') ??
414 + DEFAULT_BASE_URL;
415 +
416 + logger.debug(
417 + 'Environment',
418 + apiKeyParsed === null ? 'API Key: [DISABLED]' : 'API Key: [REDACTED]'
419 + );
420 logger.debug('Environment', `Base URL: ${baseURLParsed}`);
421
422 return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
ts/packages/core/test/core/credentials.test.ts
+35
@@ -1,6 +1,7 @@
1 import { describe, it, expect, afterEach, vi } from 'vitest';
2 import { Composio } from '../../src/composio';
3 import { MockProvider } from '../utils/mocks/provider.mock';
4 +import { ComposioNoAPIKeyError } from '../../src/errors/SDKErrors';
5
6 /**
7 * `userApiKey` / `orgApiKey` are forwarded to the API client, which selects the
@@ -72,4 +73,38 @@ describe('Composio user and organization API keys', () => {
73 expect(session.getClient().userApiKey).toBe('uak_env');
74 expect(session.getClient().orgApiKey).toBe('oak_env');
75 });
76 +
77 + it('accepts a disabled project key when a user API key is configured', () => {
78 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_env');
79 + const composio = new Composio({ ...baseConfig, apiKey: null, userApiKey: 'uak_test' });
80 + const client = composio.getClient();
81 + expect(client.apiKey).toBeNull();
82 + expect(client.userApiKey).toBe('uak_test');
83 + expect(composio.getConfig().apiKey).toBeNull();
84 + });
85 +
86 + it('accepts a disabled project key when an organization API key is configured', () => {
87 + const client = new Composio({ ...baseConfig, apiKey: null, orgApiKey: 'oak_test' }).getClient();
88 + expect(client.apiKey).toBeNull();
89 + expect(client.orgApiKey).toBe('oak_test');
90 + });
91 +
92 + it('rejects a raw x-api-key default header when the project key is disabled', () => {
93 + expect(
94 + () =>
95 + new Composio({
96 + ...baseConfig,
97 + apiKey: null,
98 + userApiKey: 'uak_test',
99 + defaultHeaders: { 'x-api-key': 'ak_raw' },
100 + })
101 + ).toThrow(ComposioNoAPIKeyError);
102 + });
103 +
104 + it('rejects a disabled project key when neither alternate key is configured', () => {
105 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_env');
106 + vi.stubEnv('COMPOSIO_USER_API_KEY', '');
107 + vi.stubEnv('COMPOSIO_ORG_API_KEY', '');
108 + expect(() => new Composio({ ...baseConfig, apiKey: null })).toThrow(ComposioNoAPIKeyError);
109 + });
110 });
ts/packages/core/test/core/session.test.ts
+482 -2
@@ -1,9 +1,19 @@
1 -import { describe, it, expect, vi } from 'vitest';
1 +import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
2 +import * as fs from 'node:fs';
3 +import * as os from 'node:os';
4 +import * as path from 'node:path';
5 import { Composio } from '../../src/composio';
6 import { MockProvider } from '../utils/mocks/provider.mock';
7 import { OpenAIProvider } from '../../src/provider/OpenAIProvider';
8 import { getDefaultHeaders, getSessionHeaders } from '../../src/utils/session';
9 import { version } from '../../package.json';
10 +import {
11 + ComposioAPIKeyKindError,
12 + ComposioNoAPIKeyError,
13 + ComposioScopeConfigError,
14 +} from '../../src/errors/SDKErrors';
15 +import { ComposioMCPDestinationError } from '../../src/errors/ToolRouterErrors';
16 +import logger from '../../src/utils/logger';
17
18 describe('Composio Session Management', () => {
19 const baseConfig = {
@@ -117,7 +127,7 @@ describe('Composio Session Management', () => {
127 session_id: 'session_123',
128 mcp: {
129 type: 'http',
120 - url: 'https://mcp.example.com/session_123',
130 + url: 'https://api.test.com/api/v3/tool_router/session/session_123/mcp',
131 },
132 config: {
133 preload: { tools: [] },
@@ -466,3 +476,473 @@ describe('Session Headers Configuration Integration', () => {
476 });
477 });
478 });
479 +
480 +describe('Credential resolution at the transport boundary', () => {
481 + let home: string;
482 + const userKey = 'uak_cliUserKeyValue';
483 + const projectKey = 'ak_explicitProjectKey';
484 +
485 + const writeUserData = (contents: Record<string, unknown>) => {
486 + const dir = path.join(home, '.composio');
487 + fs.mkdirSync(dir, { recursive: true });
488 + fs.writeFileSync(path.join(dir, 'user_data.json'), JSON.stringify(contents));
489 + };
490 +
491 + const captureFetch = () => {
492 + const fetchMock = vi.fn(async () =>
493 + Response.json({ slug: 'github', name: 'GitHub', meta: {}, is_local_toolkit: false })
494 + );
495 + vi.stubGlobal('fetch', fetchMock);
496 + return fetchMock;
497 + };
498 +
499 + const capturedHeaders = (fetchMock: ReturnType<typeof captureFetch>, callIndex = 0) => {
500 + const call = fetchMock.mock.calls[callIndex] as unknown as [string, { headers: HeadersInit }];
501 + return new Headers(call[1].headers);
502 + };
503 +
504 + const build = (config: ConstructorParameters<typeof Composio>[0]) =>
505 + new Composio({
506 + baseURL: 'https://api.test.com',
507 + provider: new MockProvider(),
508 + allowTracking: false,
509 + disableVersionCheck: true,
510 + ...config,
511 + });
512 +
513 + beforeEach(() => {
514 + home = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-credentials-'));
515 + vi.stubEnv('HOME', home);
516 + vi.stubEnv('COMPOSIO_API_KEY', undefined);
517 + vi.stubEnv('COMPOSIO_BASE_URL', undefined);
518 + vi.stubEnv('COMPOSIO_USER_API_KEY', undefined);
519 + vi.stubEnv('COMPOSIO_ORG_API_KEY', undefined);
520 + });
521 +
522 + afterEach(() => {
523 + vi.restoreAllMocks();
524 + vi.unstubAllGlobals();
525 + vi.unstubAllEnvs();
526 + fs.rmSync(home, { recursive: true, force: true });
527 + });
528 +
529 + it('sends the explicit project key even when a CLI user key is stored on disk', async () => {
530 + writeUserData({ api_key: userKey });
531 + const fetchMock = captureFetch();
532 +
533 + await build({ apiKey: projectKey }).getClient().toolkits.retrieve('github');
534 +
535 + const headers = capturedHeaders(fetchMock);
536 + expect(headers.get('x-api-key')).toBe(projectKey);
537 + expect(headers.get('x-user-api-key')).toBeNull();
538 + });
539 +
540 + it('never sends a stored CLI user key as the project key', () => {
541 + writeUserData({ api_key: userKey });
542 + const fetchMock = captureFetch();
543 +
544 + expect(() => build({})).toThrow(ComposioAPIKeyKindError);
545 + expect(fetchMock).not.toHaveBeenCalled();
546 + });
547 +
548 + it('sends only the user API key when the project key is disabled via the userApiKey option', async () => {
549 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignEnvKey');
550 + writeUserData({ api_key: 'ak_foreignDiskKey' });
551 + const fetchMock = captureFetch();
552 +
553 + const composio = build({ apiKey: null, userApiKey: userKey });
554 + await composio.getClient().toolkits.retrieve('github');
555 +
556 + const headers = capturedHeaders(fetchMock);
557 + expect(headers.get('x-api-key')).toBeNull();
558 + expect(headers.get('x-user-api-key')).toBe(userKey);
559 + expect(composio.getConfig().apiKey).toBeNull();
560 + expect(composio.getClient().apiKey).toBeNull();
561 + });
562 +
563 + it('sends only the user API key header when the project key is disabled via defaultHeaders', async () => {
564 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignEnvKey');
565 + writeUserData({ api_key: 'ak_foreignDiskKey' });
566 + const fetchMock = captureFetch();
567 +
568 + const composio = build({ apiKey: null, defaultHeaders: { 'x-user-api-key': userKey } });
569 + await composio.getClient().toolkits.retrieve('github');
570 +
571 + const headers = capturedHeaders(fetchMock);
572 + expect(headers.get('x-api-key')).toBeNull();
573 + expect(headers.get('x-user-api-key')).toBe(userKey);
574 + expect(composio.getConfig().apiKey).toBeNull();
575 + });
576 +
577 + it('rejects a disabled project key without any user credential', () => {
578 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignEnvKey');
579 +
580 + expect(() => build({ apiKey: null })).toThrow(ComposioNoAPIKeyError);
581 + });
582 +
583 + it('rejects a raw project key header when the project key is disabled', () => {
584 + const fetchMock = captureFetch();
585 +
586 + expect(() =>
587 + build({ apiKey: null, userApiKey: userKey, defaultHeaders: { 'X-Api-Key': projectKey } })
588 + ).toThrow(ComposioNoAPIKeyError);
589 + expect(fetchMock).not.toHaveBeenCalled();
590 + });
591 +
592 + it('does not let a clone reintroduce a raw project key header', async () => {
593 + const fetchMock = captureFetch();
594 + const composio = build({ apiKey: null, userApiKey: userKey });
595 +
596 + expect(() => composio.createSession({ headers: { 'x-api-key': projectKey } })).toThrow(
597 + ComposioNoAPIKeyError
598 + );
599 + await composio.getClient().toolkits.retrieve('github');
600 +
601 + expect(fetchMock).toHaveBeenCalledTimes(1);
602 + const headers = capturedHeaders(fetchMock);
603 + expect(headers.get('x-api-key')).toBeNull();
604 + expect(headers.get('x-user-api-key')).toBe(userKey);
605 + });
606 +
607 + it('keeps the resolved project key on clones when the environment changes later', async () => {
608 + const fetchMock = captureFetch();
609 + const composio = build({ apiKey: projectKey });
610 +
611 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_laterEnvKey');
612 + const clone = composio.createSession({ headers: { 'x-request-id': 'req-1' } });
613 + await clone.getClient().toolkits.retrieve('github');
614 +
615 + const headers = capturedHeaders(fetchMock);
616 + expect(headers.get('x-api-key')).toBe(projectKey);
617 + expect(headers.get('x-request-id')).toBe('req-1');
618 + });
619 +
620 + it('keeps the project key disabled on clones built from the userApiKey option', async () => {
621 + const fetchMock = captureFetch();
622 + const composio = build({ apiKey: null, userApiKey: userKey });
623 +
624 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_laterEnvKey');
625 + const clone = composio.createSession({ headers: { 'x-request-id': 'req-2' } });
626 + await clone.getClient().toolkits.retrieve('github');
627 +
628 + const headers = capturedHeaders(fetchMock);
629 + expect(headers.get('x-api-key')).toBeNull();
630 + expect(headers.get('x-user-api-key')).toBe(userKey);
631 + expect(headers.get('x-request-id')).toBe('req-2');
632 + expect(clone.getConfig().apiKey).toBeNull();
633 + });
634 +
635 + it('keeps the project key disabled on clones built from the user API key header', async () => {
636 + const fetchMock = captureFetch();
637 + const composio = build({ apiKey: null, defaultHeaders: { 'x-user-api-key': userKey } });
638 +
639 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_laterEnvKey');
640 + const clone = composio.createSession({ headers: { 'x-request-id': 'req-3' } });
641 + await clone.getClient().toolkits.retrieve('github');
642 +
643 + const headers = capturedHeaders(fetchMock);
644 + expect(headers.get('x-api-key')).toBeNull();
645 + expect(headers.get('x-user-api-key')).toBe(userKey);
646 + expect(headers.get('x-request-id')).toBe('req-3');
647 + expect(clone.getConfig().apiKey).toBeNull();
648 + });
649 +
650 + describe('MCP export follows the effective session auth context', () => {
651 + const orgId = 'org_nano_abc';
652 + const projectId = 'proj_nano_xyz';
653 + const sameOriginMcp = 'https://api.test.com/api/v3/tool_router/session/session_mcp/mcp';
654 +
655 + const sessionResponse = (mcpUrl: string) => ({
656 + session_id: 'session_mcp',
657 + mcp: { type: 'http', url: mcpUrl },
658 + config: { user_id: 'user_123', execute: {}, search: {}, preload: { tools: [] } },
659 + config_version: 1,
660 + warnings: [],
661 + });
662 +
663 + const captureSessionFetch = (mcpUrl: string = sameOriginMcp) => {
664 + const fetchMock = vi.fn(async () => Response.json(sessionResponse(mcpUrl)));
665 + vi.stubGlobal('fetch', fetchMock);
666 + return fetchMock;
667 + };
668 +
669 + it('exports only the user API key when the project key is disabled and a foreign key is ambient', async () => {
670 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignEnvKey');
671 + writeUserData({ api_key: 'ak_foreignDiskKey' });
672 + const fetchMock = captureSessionFetch();
673 +
674 + const composio = build({ apiKey: null, userApiKey: userKey });
675 + const session = await composio.sessions.create('user_123', { mcp: true });
676 +
677 + const requestHeaders = capturedHeaders(fetchMock);
678 + expect(requestHeaders.get('x-api-key')).toBeNull();
679 + expect(requestHeaders.get('x-user-api-key')).toBe(userKey);
680 + expect(requestHeaders.get('x-org-id')).toBeNull();
681 + expect(requestHeaders.get('x-project-id')).toBeNull();
682 + expect(session.mcp.url).toBe(sameOriginMcp);
683 + expect(session.mcp.headers).toEqual({ 'x-user-api-key': userKey });
684 + });
685 +
686 + it('exports the user API key placed in defaultHeaders when the project key is disabled', async () => {
687 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignEnvKey');
688 + const fetchMock = captureSessionFetch();
689 +
690 + const composio = build({ apiKey: null, defaultHeaders: { 'x-user-api-key': userKey } });
691 + const session = await composio.sessions.create('user_123', { mcp: true });
692 +
693 + expect(capturedHeaders(fetchMock).get('x-api-key')).toBeNull();
694 + expect(capturedHeaders(fetchMock).get('x-user-api-key')).toBe(userKey);
695 + expect(session.mcp.headers).toEqual({ 'x-user-api-key': userKey });
696 + });
697 +
698 + it('exports the user API key a clone was given over the key the parent resolved', async () => {
699 + const otherUserKey = 'uak_overridingUserKey';
700 + const fetchMock = captureSessionFetch();
701 +
702 + const composio = build({ apiKey: null, userApiKey: userKey });
703 + const clone = composio.createSession({ headers: { 'x-user-api-key': otherUserKey } });
704 + const session = await clone.sessions.create('user_123', { mcp: true });
705 +
706 + const requestHeaders = capturedHeaders(fetchMock);
707 + expect(requestHeaders.get('x-api-key')).toBeNull();
708 + expect(requestHeaders.get('x-user-api-key')).toBe(otherUserKey);
709 + expect(session.mcp.headers).toEqual({ 'x-user-api-key': otherUserKey });
710 + });
711 +
712 + it('exports the user API key placed in defaultHeaders over a configured project key', async () => {
713 + const fetchMock = captureSessionFetch();
714 +
715 + const composio = build({ apiKey: projectKey, defaultHeaders: { 'x-user-api-key': userKey } });
716 + const session = await composio.sessions.create('user_123', { mcp: true });
717 +
718 + const requestHeaders = capturedHeaders(fetchMock);
719 + expect(requestHeaders.get('x-api-key')).toBeNull();
720 + expect(requestHeaders.get('x-user-api-key')).toBe(userKey);
721 + expect(session.mcp.headers).toEqual({ 'x-user-api-key': userKey });
722 + });
723 +
724 + it('sends and exports the org/project scope headers together with the user key', async () => {
725 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignEnvKey');
726 + const fetchMock = captureSessionFetch();
727 +
728 + const composio = build({ apiKey: null, userApiKey: userKey, orgId, projectId });
729 + const session = await composio.sessions.create('user_123', { mcp: true });
730 +
731 + const requestHeaders = capturedHeaders(fetchMock);
732 + expect(requestHeaders.get('x-api-key')).toBeNull();
733 + expect(requestHeaders.get('x-user-api-key')).toBe(userKey);
734 + expect(requestHeaders.get('x-org-id')).toBe(orgId);
735 + expect(requestHeaders.get('x-project-id')).toBe(projectId);
736 + expect(session.mcp.headers).toEqual({
737 + 'x-user-api-key': userKey,
738 + 'x-org-id': orgId,
739 + 'x-project-id': projectId,
740 + });
741 + expect(composio.getConfig().orgId).toBe(orgId);
742 + expect(composio.getConfig().projectId).toBe(projectId);
743 + });
744 +
745 + it('rejects a half-configured scope', () => {
746 + expect(() => build({ apiKey: null, userApiKey: userKey, orgId })).toThrow(
747 + ComposioScopeConfigError
748 + );
749 + expect(() => build({ apiKey: null, userApiKey: userKey, projectId })).toThrow(
750 + ComposioScopeConfigError
751 + );
752 + });
753 +
754 + it('rejects a scope option that disagrees with the same header in defaultHeaders', () => {
755 + expect(() =>
756 + build({
757 + apiKey: null,
758 + userApiKey: userKey,
759 + orgId,
760 + projectId,
761 + defaultHeaders: { 'X-Org-Id': 'org_nano_other' },
762 + })
763 + ).toThrow(ComposioScopeConfigError);
764 + });
765 +
766 + it('adopts a scope supplied through defaultHeaders as the single header source', async () => {
767 + const fetchMock = captureSessionFetch();
768 +
769 + const composio = build({
770 + apiKey: null,
771 + userApiKey: userKey,
772 + defaultHeaders: { 'x-org-id': orgId, 'x-project-id': projectId },
773 + });
774 + const session = await composio.sessions.create('user_123', { mcp: true });
775 +
776 + const requestHeaders = capturedHeaders(fetchMock);
777 + expect(requestHeaders.get('x-org-id')).toBe(orgId);
778 + expect(requestHeaders.get('x-project-id')).toBe(projectId);
779 + expect(composio.getConfig().orgId).toBe(orgId);
780 + expect(composio.getConfig().projectId).toBe(projectId);
781 + expect(session.mcp.headers).toEqual({
782 + 'x-user-api-key': userKey,
783 + 'x-org-id': orgId,
784 + 'x-project-id': projectId,
785 + });
786 + });
787 +
788 + it('exports only the project key for project-key sessions', async () => {
789 + const fetchMock = captureSessionFetch();
790 +
791 + const composio = build({
792 + apiKey: projectKey,
793 + defaultHeaders: { 'x-request-id': 'req-9', 'x-tenant': 'acme' },
794 + });
795 + const session = await composio.sessions.create('user_123', { mcp: true });
796 +
797 + expect(capturedHeaders(fetchMock).get('x-api-key')).toBe(projectKey);
798 + expect(session.mcp.headers).toEqual({ 'x-api-key': projectKey });
799 + });
800 +
801 + it('never copies unrelated default headers into the MCP config', async () => {
802 + captureSessionFetch();
803 +
804 + const composio = build({
805 + apiKey: null,
806 + defaultHeaders: {
807 + 'x-user-api-key': userKey,
808 + 'x-request-id': 'req-9',
809 + authorization: 'Bearer other',
810 + },
811 + });
812 + const session = await composio.sessions.create('user_123', { mcp: true });
813 +
814 + expect(session.mcp.headers).toEqual({ 'x-user-api-key': userKey });
815 + });
816 +
817 + it('throws when the MCP URL is on a different origin and the caller asked for MCP', async () => {
818 + captureSessionFetch('https://mcp.example.com/session_mcp');
819 + const composio = build({ apiKey: projectKey });
820 +
821 + const failure = await composio.sessions.create('user_123', { mcp: true }).catch(e => e);
822 +
823 + expect(failure).toBeInstanceOf(ComposioMCPDestinationError);
824 + expect(failure.message).toBe(
825 + 'The session MCP endpoint origin https://mcp.example.com does not match the API origin https://api.test.com; the session credential was not attached'
826 + );
827 + expect(failure.meta).toEqual({
828 + mcpOrigin: 'https://mcp.example.com',
829 + apiOrigin: 'https://api.test.com',
830 + });
831 + expect(JSON.stringify(failure)).not.toContain(projectKey);
832 + });
833 +
834 + it('throws from use() as well when the caller asked for MCP on a different origin', async () => {
835 + captureSessionFetch('https://mcp.example.com/session_mcp');
836 + const composio = build({ apiKey: projectKey });
837 +
838 + const failure = await composio.sessions.use('session_mcp', { mcp: true }).catch(e => e);
839 +
840 + expect(failure).toBeInstanceOf(ComposioMCPDestinationError);
841 + expect(failure.message).toBe(
842 + 'The session MCP endpoint origin https://mcp.example.com does not match the API origin https://api.test.com; the session credential was not attached'
843 + );
844 + expect(JSON.stringify(failure)).not.toContain(projectKey);
845 + });
846 +
847 + it('does not warn for a same-origin MCP URL', async () => {
848 + captureSessionFetch(sameOriginMcp);
849 + const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});
850 + const composio = build({ apiKey: projectKey });
851 +
852 + const session = await composio.sessions.create('user_123');
853 +
854 + expect((session as unknown as { mcp: { headers: unknown } }).mcp.headers).toEqual({
855 + 'x-api-key': projectKey,
856 + });
857 + expect(warnSpy).not.toHaveBeenCalled();
858 + });
859 +
860 + it('returns the session with empty MCP headers and warns when the caller did not ask for MCP', async () => {
861 + const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});
862 + captureSessionFetch('https://mcp.example.com/session_mcp');
863 + const composio = build({ apiKey: projectKey });
864 +
865 + const created = await composio.sessions.create('user_123');
866 + const used = await composio.sessions.use('session_mcp');
867 +
868 + const createdMcp = (created as unknown as { mcp: { url: string; headers: unknown } }).mcp;
869 + const usedMcp = (used as unknown as { mcp: { url: string; headers: unknown } }).mcp;
870 + expect(createdMcp).toEqual({
871 + type: 'http',
872 + url: 'https://mcp.example.com/session_mcp',
873 + headers: {},
874 + });
875 + expect(usedMcp.headers).toEqual({});
876 + expect(warnSpy).toHaveBeenCalledTimes(2);
877 + const warning = String(warnSpy.mock.calls[0][0]);
878 + expect(warning).toBe(
879 + 'The session MCP endpoint origin https://mcp.example.com does not match the API origin https://api.test.com; the session credential was not attached. session.mcp.headers was left empty; pass `mcp: true` to make this an error'
880 + );
881 + expect(warning).not.toContain(projectKey);
882 + });
883 +
884 + it('rejects an MCP URL with an opaque origin before comparing origins', async () => {
885 + const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});
886 + captureSessionFetch('data:text/plain,session_mcp');
887 + const composio = build({ apiKey: projectKey });
888 +
889 + const failure = await composio.sessions.create('user_123', { mcp: true }).catch(e => e);
890 + expect(failure).toBeInstanceOf(ComposioMCPDestinationError);
891 + expect(failure.message).toBe('The MCP URL has an opaque origin');
892 + expect(failure.meta).toEqual({ role: 'MCP URL' });
893 + expect(JSON.stringify(failure)).not.toContain(projectKey);
894 +
895 + const session = await composio.sessions.create('user_123');
896 + const mcp = (session as unknown as { mcp: { headers: unknown } }).mcp;
897 + expect(mcp.headers).toEqual({});
898 + expect(warnSpy).toHaveBeenCalledTimes(1);
899 + expect(String(warnSpy.mock.calls[0][0])).toContain('opaque origin');
900 + });
901 +
902 + it('exports credentials to a same-origin https MCP URL as before', async () => {
903 + captureSessionFetch(sameOriginMcp);
904 + const composio = build({ apiKey: projectKey, baseURL: 'https://api.test.com' });
905 +
906 + const session = await composio.sessions.create('user_123', { mcp: true });
907 +
908 + expect(session.mcp).toEqual({
909 + type: 'http',
910 + url: sameOriginMcp,
911 + headers: { 'x-api-key': projectKey },
912 + });
913 + });
914 +
915 + it('exports credentials to a same-origin MCP URL on a plain-http custom base URL', async () => {
916 + const fetchMock = captureSessionFetch(
917 + 'http://localhost:3000/api/v3/tool_router/session/session_mcp/mcp'
918 + );
919 + const composio = build({ apiKey: projectKey, baseURL: 'http://localhost:3000' });
920 +
921 + const session = await composio.sessions.create('user_123', { mcp: true });
922 +
923 + expect(capturedHeaders(fetchMock).get('x-api-key')).toBe(projectKey);
924 + expect(session.mcp.headers).toEqual({ 'x-api-key': projectKey });
925 + });
926 +
927 + it('keeps the disabled project key and scope when a clone retrieves a session after the environment changes', async () => {
928 + const fetchMock = captureSessionFetch();
929 + const composio = build({ apiKey: null, userApiKey: userKey, orgId, projectId });
930 +
931 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_laterEnvKey');
932 + const clone = composio.createSession({ headers: { 'x-request-id': 'req-3' } });
933 + const session = await clone.sessions.use('session_mcp', { mcp: true });
934 +
935 + const requestHeaders = capturedHeaders(fetchMock);
936 + expect(requestHeaders.get('x-api-key')).toBeNull();
937 + expect(requestHeaders.get('x-user-api-key')).toBe(userKey);
938 + expect(requestHeaders.get('x-org-id')).toBe(orgId);
939 + expect(requestHeaders.get('x-project-id')).toBe(projectId);
940 + expect(requestHeaders.get('x-request-id')).toBe('req-3');
941 + expect(session.mcp.headers).toEqual({
942 + 'x-user-api-key': userKey,
943 + 'x-org-id': orgId,
944 + 'x-project-id': projectId,
945 + });
946 + });
947 + });
948 +});
ts/packages/core/test/lib/toolRouterParams.test.ts
+93
@@ -183,6 +183,99 @@ describe('transformToolRouterTagsParams', () => {
183 });
184
185 describe('transformToolRouterUpdateParams', () => {
186 + it('keeps an empty toolkit allowlist in the request', () => {
187 + expect(transformToolRouterUpdateParams({ toolkits: [] })).toEqual({
188 + toolkits: { enable: [] },
189 + });
190 + expect(transformToolRouterUpdateParams({ toolkits: { enable: [] } })).toEqual({
191 + toolkits: { enable: [] },
192 + });
193 + });
194 +
195 + it('sends null for every clearable block', () => {
196 + expect(
197 + transformToolRouterUpdateParams({
198 + toolkits: null,
199 + tools: null,
200 + tags: null,
201 + authConfigs: null,
202 + connectedAccounts: null,
203 + preload: null,
204 + search: null,
205 + execute: null,
206 + experimental: null,
207 + })
208 + ).toEqual({
209 + toolkits: null,
210 + tools: null,
211 + tags: null,
212 + auth_configs: null,
213 + connected_accounts: null,
214 + preload: null,
215 + search: null,
216 + execute: null,
217 + experimental: null,
218 + });
219 + });
220 +
221 + it('passes a null callback URL through manage_connections', () => {
222 + expect(transformToolRouterUpdateParams({ manageConnections: { callbackUrl: null } })).toEqual({
223 + manage_connections: { callback_url: null },
224 + });
225 + });
226 +
227 + it('maps enableConnectionRemoval through manage_connections, including null', () => {
228 + expect(
229 + transformToolRouterUpdateParams({ manageConnections: { enableConnectionRemoval: false } })
230 + ).toEqual({ manage_connections: { enable_connection_removal: false } });
231 + expect(
232 + transformToolRouterUpdateParams({ manageConnections: { enableConnectionRemoval: null } })
233 + ).toEqual({ manage_connections: { enable_connection_removal: null } });
234 + });
235 +
236 + it('passes a null maximum through multi_account', () => {
237 + expect(
238 + transformToolRouterUpdateParams({ multiAccount: { maxAccountsPerToolkit: null } })
239 + ).toEqual({ multi_account: { max_accounts_per_toolkit: null } });
240 + });
241 +
242 + it('maps search, execute and experimental leaves to their wire names', () => {
243 + expect(
244 + transformToolRouterUpdateParams({
245 + search: { enable: false },
246 + execute: { enableMultiExecute: false },
247 + experimental: {
248 + linkUrlOverwrite: null,
249 + fastMode: true,
250 + submitFeedback: { enable: true },
251 + permissions: {
252 + default: 'allow_all',
253 + overrides: { 'GMAIL_SEND:__none__': 'always_deny' },
254 + },
255 + sessionConfigId: 'cfg_1',
256 + },
257 + })
258 + ).toEqual({
259 + search: { enable: false },
260 + execute: { enable_multi_execute: false },
261 + experimental: {
262 + link_url_overwrite: null,
263 + fast_mode: true,
264 + submit_feedback: { enable: true },
265 + permissions: { default: 'allow_all', overrides: { 'GMAIL_SEND:__none__': 'always_deny' } },
266 + session_config_id: 'cfg_1',
267 + },
268 + });
269 + });
270 +
271 + it('never serializes the expectedConfigVersion option itself', () => {
272 + expect(
273 + transformToolRouterUpdateParams({ toolkits: ['github'], expectedConfigVersion: 4 })
274 + ).toEqual({
275 + toolkits: { enable: ['github'] },
276 + });
277 + });
278 +
279 it('should pass through toolkits correctly', () => {
280 const result = transformToolRouterUpdateParams({
281 toolkits: ['github', 'gmail'],
ts/packages/core/test/models/customToolRouting.test.ts
+14 -5
@@ -97,7 +97,7 @@ const createMockClient = () => ({
97 user_id: 'user_1',
98 },
99 config_version: 1,
100 - mcp: { type: 'http', url: 'https://mcp.example.com/sess_123' },
100 + mcp: { type: 'http', url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123' },
101 tool_router_tools: [],
102 }),
103 retrieve: vi.fn(),
@@ -158,7 +158,7 @@ const createSessionWithProvider = (
158 client as unknown as ComposioClient,
159 { apiKey: 'key', provider },
160 'sess_123',
161 - { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
161 + { type: 'http' as const, url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123' },
162 undefined,
163 buildCustomToolsMap(customTools),
164 'user_1'
@@ -298,7 +298,10 @@ describe('ToolRouterSession execution routing', () => {
298 client as unknown as ComposioClient,
299 { apiKey: 'key', provider: new MockProvider() },
300 'sess_123',
301 - { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
301 + {
302 + type: 'http' as const,
303 + url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123',
304 + },
305 undefined,
306 customToolsMap,
307 'user_1'
@@ -637,7 +640,10 @@ describe('ToolRouterSession execution routing', () => {
640 mockClient as unknown as ComposioClient,
641 { apiKey: 'key', provider: new MockProvider() },
642 'sess_123',
640 - { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
643 + {
644 + type: 'http' as const,
645 + url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123',
646 + }
647 );
648
649 const result = await session.tools();
@@ -1102,7 +1108,10 @@ describe('ToolRouterSession execution routing', () => {
1108 mockClient as unknown as ComposioClient,
1109 { apiKey: 'key' } as unknown as ComposioConfig<MockProvider>,
1110 'sess_123',
1105 - { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
1111 + {
1112 + type: 'http' as const,
1113 + url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123',
1114 + },
1115 undefined,
1116 customToolsMap,
1117 'user_1'
ts/packages/core/test/models/toolRouter.test.ts
+210 -12
@@ -1,7 +1,7 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { z } from 'zod/v3';
3 import { ToolRouter } from '../../src/models/ToolRouter';
4 -import ComposioClient from '@composio/client';
4 +import ComposioClient, { ConflictError } from '@composio/client';
5 import { telemetry } from '../../src/telemetry/Telemetry';
6 import { MockProvider } from '../utils/mocks/provider.mock';
7 import { Tools } from '../../src/models/Tools';
@@ -16,6 +16,7 @@ import type { ConnectionRequest } from '../../src/types/connectionRequest.types'
16 import { createCustomTool } from '../../src/models/CustomTool';
17 import { DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX } from '../../src/models/ToolRouterSession';
18 import { ValidationError } from '../../src/errors/ValidationErrors';
19 +import { ComposioSessionConfigConflictError } from '../../src/errors/ToolRouterErrors';
20
21 // Mock dependencies
22 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -69,7 +70,7 @@ const mockSessionCreateResponse = {
70 session_id: 'session_123',
71 mcp: {
72 type: 'http',
72 - url: 'https://mcp.example.com/session_123',
73 + url: 'https://api.composio.dev/api/v3/tool_router/session/session_123',
74 },
75 tool_router_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
76 config: {
@@ -87,7 +88,7 @@ const mockSessionRetrieveResponse = {
88 session_id: 'session_123',
89 mcp: {
90 type: 'http',
90 - url: 'https://mcp.example.com/session_123',
91 + url: 'https://api.composio.dev/api/v3/tool_router/session/session_123',
92 },
93 tool_router_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
94 config: {
@@ -223,7 +224,7 @@ describe('ToolRouter', () => {
224 expect(session).toHaveProperty('mcp');
225 expect(session.mcp).toEqual({
226 type: 'http',
226 - url: 'https://mcp.example.com/session_123',
227 + url: 'https://api.composio.dev/api/v3/tool_router/session/session_123',
228 headers: {
229 'x-api-key': 'test-api-key',
230 },
@@ -1847,7 +1848,7 @@ describe('ToolRouter', () => {
1848 ...mockSessionCreateResponse,
1849 mcp: {
1850 type: 'http',
1850 - url: 'https://mcp.example.com/session_123',
1851 + url: 'https://api.composio.dev/api/v3/tool_router/session/session_123',
1852 },
1853 };
1854
@@ -1863,7 +1864,7 @@ describe('ToolRouter', () => {
1864 ...mockSessionCreateResponse,
1865 mcp: {
1866 type: 'sse',
1866 - url: 'https://mcp.example.com/sse/session_123',
1867 + url: 'https://api.composio.dev/api/v3/tool_router/session/sse/session_123',
1868 },
1869 };
1870
@@ -1872,7 +1873,9 @@ describe('ToolRouter', () => {
1873 const session = await toolRouter.create(userId);
1874
1875 expect(session.mcp.type).toBe('sse');
1875 - expect(session.mcp.url).toBe('https://mcp.example.com/sse/session_123');
1876 + expect(session.mcp.url).toBe(
1877 + 'https://api.composio.dev/api/v3/tool_router/session/sse/session_123'
1878 + );
1879 });
1880
1881 it('should return session with all required properties', async () => {
@@ -3281,7 +3284,9 @@ describe('ToolRouter', () => {
3284 });
3285
3286 expect(session.sessionId).toBe('session_123');
3284 - expect(session.mcp.url).toBe('https://mcp.example.com/session_123');
3287 + expect(session.mcp.url).toBe(
3288 + 'https://api.composio.dev/api/v3/tool_router/session/session_123'
3289 + );
3290
3291 // Use authorize function
3292 const connection = await session.authorize('gmail');
@@ -3419,7 +3424,7 @@ describe('ToolRouter', () => {
3424 expect(session).toHaveProperty('mcp');
3425 expect(session.mcp).toEqual({
3426 type: 'http',
3422 - url: 'https://mcp.example.com/session_123',
3427 + url: 'https://api.composio.dev/api/v3/tool_router/session/session_123',
3428 headers: {
3429 'x-api-key': 'test-api-key',
3430 },
@@ -3723,7 +3728,9 @@ describe('ToolRouter', () => {
3728 const session = await toolRouter.use(sessionId);
3729
3730 expect(session.mcp.type).toBe('http');
3726 - expect(session.mcp.url).toBe('https://mcp.example.com/session_123');
3731 + expect(session.mcp.url).toBe(
3732 + 'https://api.composio.dev/api/v3/tool_router/session/session_123'
3733 + );
3734 });
3735
3736 it('should throw error if session retrieve fails', async () => {
@@ -3794,8 +3801,8 @@ describe('ToolRouter', () => {
3801
3802 expect(mockClient.toolRouter.session.patch).toHaveBeenCalledWith(
3803 sessionId,
3797 - expect.objectContaining({ toolkits: { enable: ['gmail'] } }),
3798 - undefined
3804 + expect.objectContaining({ toolkits: { enable: ['gmail'] }, expected_config_version: 7 }),
3805 + { maxRetries: 0 }
3806 );
3807 expect(config).toEqual(patchedConfig);
3808 expect(config.toolkits).toEqual({ enabled: ['gmail'] });
@@ -3904,5 +3911,196 @@ describe('ToolRouter', () => {
3911 ).rejects.toThrow(ValidationError);
3912 expect(mockClient.toolRouter.session.configHistory).not.toHaveBeenCalled();
3913 });
3914 +
3915 + describe('update contract', () => {
3916 + const patchResponse = (
3917 + configVersion: number,
3918 + preloadTools: string[] = ['SLACK_SEND_MESSAGE']
3919 + ) => ({
3920 + session_id: sessionId,
3921 + config: {
3922 + ...mockSessionRetrieveResponse.config,
3923 + preload: { tools: preloadTools },
3924 + },
3925 + config_version: configVersion,
3926 + warnings: [],
3927 + });
3928 +
3929 + const patchCall = (callIndex = 0) => {
3930 + const call = mockClient.toolRouter.session.patch.mock.calls[callIndex] as [
3931 + string,
3932 + Record<string, unknown>,
3933 + Record<string, unknown> | undefined,
3934 + ];
3935 + return { body: call[1], options: call[2] };
3936 + };
3937 +
3938 + const conflict = () =>
3939 + new ConflictError(409, { error: 'version conflict' }, 'Conflict', new Headers());
3940 +
3941 + beforeEach(() => {
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 () => {
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);
3953 + expect(body).not.toHaveProperty('expectedConfigVersion');
3954 + expect(body.toolkits).toEqual({ enable: ['gmail'] });
3955 + expect(options).toEqual({ maxRetries: 0 });
3956 + expect(session.configVersion).toBe(8);
3957 + expect(session.preload.tools).toEqual(['SLACK_SEND_MESSAGE']);
3958 + });
3959 +
3960 + it('forwards the caller request options next to the retry opt-out', async () => {
3961 + const session = await toolRouter.use(sessionId);
3962 + const signal = new AbortController().signal;
3963 +
3964 + await session.update({ toolkits: ['gmail'] }, { signal });
3965 +
3966 + expect(patchCall().options).toEqual({ signal, maxRetries: 0 });
3967 + });
3968 +
3969 + it('sends no precondition when the caller opts out with expectedConfigVersion: false', async () => {
3970 + const session = await toolRouter.use(sessionId);
3971 +
3972 + await session.update({ toolkits: ['gmail'], expectedConfigVersion: false });
3973 +
3974 + expect(patchCall().body).not.toHaveProperty('expected_config_version');
3975 + });
3976 +
3977 + it('sends an explicit expectedConfigVersion instead of the observed one', async () => {
3978 + const session = await toolRouter.use(sessionId);
3979 +
3980 + await session.update({ toolkits: ['gmail'], expectedConfigVersion: 9 });
3981 +
3982 + expect(patchCall().body.expected_config_version).toBe(9);
3983 + });
3984 +
3985 + it('rejects a non-positive expectedConfigVersion before calling the API', async () => {
3986 + const session = await toolRouter.use(sessionId);
3987 +
3988 + await expect(session.update({ expectedConfigVersion: 0 })).rejects.toThrow();
3989 + expect(mockClient.toolRouter.session.patch).not.toHaveBeenCalled();
3990 + });
3991 +
3992 + it('sends an explicit null callback URL so the stored callback is removed', async () => {
3993 + const session = await toolRouter.use(sessionId);
3994 +
3995 + await session.update({ manageConnections: { callbackUrl: null } });
3996 +
3997 + expect(patchCall().body.manage_connections).toEqual({ callback_url: null });
3998 + });
3999 +
4000 + it('preserves an empty toolkit allowlist instead of omitting it', async () => {
4001 + const session = await toolRouter.use(sessionId);
4002 +
4003 + await session.update({ toolkits: [] });
4004 + await session.update({ toolkits: { enable: [] } });
4005 +
4006 + expect(patchCall(0).body.toolkits).toEqual({ enable: [] });
4007 + expect(patchCall(1).body.toolkits).toEqual({ enable: [] });
4008 + });
4009 +
4010 + it('sends null for policy blocks the caller clears', async () => {
4011 + const session = await toolRouter.use(sessionId);
4012 +
4013 + await session.update({
4014 + toolkits: null,
4015 + tools: null,
4016 + tags: null,
4017 + authConfigs: null,
4018 + connectedAccounts: null,
4019 + preload: null,
4020 + multiAccount: null,
4021 + search: null,
4022 + execute: null,
4023 + experimental: null,
4024 + });
4025 +
4026 + expect(patchCall().body).toEqual({
4027 + toolkits: null,
4028 + tools: null,
4029 + tags: null,
4030 + auth_configs: null,
4031 + connected_accounts: null,
4032 + preload: null,
4033 + multi_account: null,
4034 + search: null,
4035 + execute: null,
4036 + experimental: null,
4037 + expected_config_version: 7,
4038 + });
4039 + });
4040 +
4041 + it('surfaces a 409 as a typed conflict error and leaves local state untouched', async () => {
4042 + const session = await toolRouter.use(sessionId);
4043 + const preloadBefore = session.preload;
4044 + mockClient.toolRouter.session.patch.mockRejectedValueOnce(conflict());
4045 +
4046 + const failure = await session.update({ toolkits: ['gmail'] }).catch(e => e);
4047 +
4048 + expect(failure).toBeInstanceOf(ComposioSessionConfigConflictError);
4049 + expect(failure.message).toMatch(/re-fetch/i);
4050 + expect(failure.message).toMatch(/retry/i);
4051 + expect(failure.statusCode).toBe(409);
4052 + expect(failure.meta).toMatchObject({ sessionId, expectedConfigVersion: 7 });
4053 + expect(session.configVersion).toBe(7);
4054 + expect(session.preload).toBe(preloadBefore);
4055 + expect(session.preload.tools).toEqual(['GMAIL_FETCH_EMAILS']);
4056 + });
4057 +
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 + });
4074 +
4075 + it('lets the first of two handles at version N win and the stale one conflict until re-read', async () => {
4076 + const first = await toolRouter.use(sessionId);
4077 + const second = await toolRouter.use(sessionId);
4078 + expect(first.configVersion).toBe(7);
4079 + expect(second.configVersion).toBe(7);
4080 +
4081 + await first.update({ toolkits: ['gmail'] });
4082 + expect(patchCall(0).body.expected_config_version).toBe(7);
4083 + expect(first.configVersion).toBe(8);
4084 +
4085 + mockClient.toolRouter.session.patch.mockRejectedValueOnce(conflict());
4086 + await expect(second.update({ toolkits: ['slack'] })).rejects.toBeInstanceOf(
4087 + ComposioSessionConfigConflictError
4088 + );
4089 + expect(patchCall(1).body.expected_config_version).toBe(7);
4090 + expect(second.configVersion).toBe(7);
4091 + expect(second.preload.tools).toEqual(['GMAIL_FETCH_EMAILS']);
4092 +
4093 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce({
4094 + ...mockSessionRetrieveResponse,
4095 + config_version: 8,
4096 + });
4097 + const reread = await toolRouter.use(sessionId);
4098 + expect(reread.configVersion).toBe(8);
4099 + mockClient.toolRouter.session.patch.mockResolvedValueOnce(patchResponse(9));
4100 + await reread.update({ toolkits: ['slack'] });
4101 + expect(patchCall(2).body.expected_config_version).toBe(8);
4102 + expect(reread.configVersion).toBe(9);
4103 + });
4104 + });
4105 });
4106 });
ts/packages/core/test/services/pusher.test.ts
+67 -1
@@ -1,4 +1,4 @@
1 -import { beforeEach, describe, expect, it, vi } from 'vitest';
1 +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2 import { PusherService } from '../../src/services/pusher/Pusher';
3
4 type EventHandler = (data: Record<string, unknown>) => void;
@@ -10,8 +10,10 @@ const {
10 mockGetCredentials,
11 mockLoggerError,
12 mockLoggerInfo,
13 + pusherConstructorOptions,
14 } = vi.hoisted(() => {
15 const eventBindings = new Map<string, EventHandler>();
16 + const constructorOptions: Array<Record<string, unknown>> = [];
17 const channel = {
18 bind: vi.fn((event: string, callback: EventHandler) => {
19 eventBindings.set(event, callback);
@@ -35,6 +37,7 @@ const {
37 }),
38 mockLoggerError: vi.fn(),
39 mockLoggerInfo: vi.fn(),
40 + pusherConstructorOptions: constructorOptions,
41 };
42 });
43
@@ -42,6 +45,9 @@ vi.mock('pusher-js', () => ({
45 default: class FakePusher {
46 subscribe = mockPusherClient.subscribe;
47 unsubscribe = mockPusherClient.unsubscribe;
48 + constructor(_key: string, options: Record<string, unknown>) {
49 + pusherConstructorOptions.push(options);
50 + }
51 },
52 }));
53
@@ -188,3 +194,63 @@ describe('PusherService subscription errors', () => {
194 );
195 });
196 });
197 +
198 +describe('PusherService channel authorization credentials', () => {
199 + const baseURL = 'https://backend.composio.dev';
200 + const channelAuthHeaders = () => {
201 + const options = pusherConstructorOptions.at(-1)!;
202 + const channelAuthorization = options.channelAuthorization as {
203 + headers: Record<string, string>;
204 + };
205 + return channelAuthorization.headers;
206 + };
207 +
208 + beforeEach(() => {
209 + bindings.clear();
210 + pusherConstructorOptions.length = 0;
211 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_foreignAmbientKey');
212 + });
213 +
214 + afterEach(() => {
215 + vi.unstubAllEnvs();
216 + });
217 +
218 + it('sends the project key of the client as x-api-key', async () => {
219 + const service = new PusherService({ baseURL, apiKey: 'ak_projectKey' } as never);
220 +
221 + await service.subscribe(vi.fn());
222 +
223 + expect(channelAuthHeaders()).toEqual({ 'x-api-key': 'ak_projectKey' });
224 + });
225 +
226 + it('sends no project key and never reads COMPOSIO_API_KEY when the client key is null', async () => {
227 + const service = new PusherService({ baseURL, apiKey: null, userApiKey: null } as never);
228 +
229 + await service.subscribe(vi.fn());
230 +
231 + expect(channelAuthHeaders()).toEqual({});
232 + expect(JSON.stringify(pusherConstructorOptions)).not.toContain('ak_foreignAmbientKey');
233 + });
234 +
235 + it('sends the resolved user API key of the client when the project key is null', async () => {
236 + const service = new PusherService({
237 + baseURL,
238 + apiKey: null,
239 + userApiKey: 'uak_userKey',
240 + } as never);
241 +
242 + await service.subscribe(vi.fn());
243 +
244 + expect(channelAuthHeaders()).toEqual({ 'x-user-api-key': 'uak_userKey' });
245 + });
246 +
247 + it('falls back to the x-user-api-key default header when the client holds no key', async () => {
248 + const service = new PusherService({ baseURL, apiKey: null, userApiKey: null } as never, {
249 + defaultHeaders: { 'X-User-Api-Key': 'uak_headerKey', 'x-request-id': 'req-1' },
250 + });
251 +
252 + await service.subscribe(vi.fn());
253 +
254 + expect(channelAuthHeaders()).toEqual({ 'x-user-api-key': 'uak_headerKey' });
255 + });
256 +});
ts/packages/core/test/tools/fileModifiers.test.ts
+1 -1
@@ -2349,7 +2349,7 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2349 dangerouslyAllowAutoUploadDownloadFiles: false,
2350 },
2351 'session-123',
2352 - { type: 'http', url: 'https://mcp.example.com/session-123' }
2352 + { type: 'http', url: 'https://api.composio.dev/api/v3/tool_router/session/session-123' }
2353 );
2354 mockClient.toolRouter.session.tools.mockResolvedValueOnce({
2355 items: [mockRawToolWithFileUpload],
ts/packages/core/test/utils/sdk.test.ts new
+364
@@ -0,0 +1,364 @@
1 +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2 +import * as fs from 'node:fs';
3 +import * as os from 'node:os';
4 +import * as path from 'node:path';
5 +import { getSDKConfig, getUserApiKeyHeader, resolveCredentialHeaders } from '../../src/utils/sdk';
6 +import {
7 + ComposioAPIKeyKindError,
8 + ComposioNoAPIKeyError,
9 + SDKErrorCodes,
10 +} from '../../src/errors/SDKErrors';
11 +import { DEFAULT_BASE_URL } from '../../src/utils/constants';
12 +
13 +const USER_KEY = 'uak_cliUserKeyValue';
14 +const ORG_KEY = 'oak_orgKeyValue';
15 +const PROJECT_KEY = 'ak_projectKeyValue';
16 +const ENV_KEY = 'ak_envKeyValue';
17 +const EXPLICIT_KEY = 'ak_explicitKeyValue';
18 +
19 +describe('getSDKConfig credential resolution', () => {
20 + let home: string;
21 +
22 + const userDataPath = () => path.join(home, '.composio', 'user_data.json');
23 +
24 + const writeUserData = (contents: string | Record<string, unknown>) => {
25 + fs.mkdirSync(path.dirname(userDataPath()), { recursive: true });
26 + fs.writeFileSync(
27 + userDataPath(),
28 + typeof contents === 'string' ? contents : JSON.stringify(contents)
29 + );
30 + };
31 +
32 + beforeEach(() => {
33 + home = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-sdk-config-'));
34 + vi.stubEnv('HOME', home);
35 + vi.stubEnv('COMPOSIO_API_KEY', undefined);
36 + vi.stubEnv('COMPOSIO_BASE_URL', undefined);
37 + vi.stubEnv('COMPOSIO_USER_API_KEY', undefined);
38 + vi.stubEnv('COMPOSIO_ORG_API_KEY', undefined);
39 + });
40 +
41 + afterEach(() => {
42 + vi.unstubAllEnvs();
43 + fs.rmSync(home, { recursive: true, force: true });
44 + });
45 +
46 + describe('explicit project key', () => {
47 + it('wins over the environment and the user config file', () => {
48 + vi.stubEnv('COMPOSIO_API_KEY', ENV_KEY);
49 + writeUserData({ api_key: PROJECT_KEY });
50 +
51 + expect(getSDKConfig(undefined, EXPLICIT_KEY).apiKey).toBe(EXPLICIT_KEY);
52 + });
53 +
54 + it('still works when the user config file holds a CLI user key', () => {
55 + writeUserData({ api_key: USER_KEY });
56 +
57 + expect(getSDKConfig(undefined, EXPLICIT_KEY).apiKey).toBe(EXPLICIT_KEY);
58 + });
59 + });
60 +
61 + describe('omitted project key', () => {
62 + it('reads COMPOSIO_API_KEY before the user config file', () => {
63 + vi.stubEnv('COMPOSIO_API_KEY', ENV_KEY);
64 + writeUserData({ api_key: PROJECT_KEY });
65 +
66 + expect(getSDKConfig().apiKey).toBe(ENV_KEY);
67 + });
68 +
69 + it('treats an empty string like an omitted key', () => {
70 + vi.stubEnv('COMPOSIO_API_KEY', ENV_KEY);
71 +
72 + expect(getSDKConfig(undefined, '').apiKey).toBe(ENV_KEY);
73 + });
74 +
75 + it('falls back to a legacy project key stored in the user config file', () => {
76 + writeUserData({ api_key: PROJECT_KEY, base_url: 'https://disk.example.com' });
77 +
78 + expect(getSDKConfig()).toEqual({
79 + baseURL: 'https://disk.example.com',
80 + apiKey: PROJECT_KEY,
81 + });
82 + });
83 +
84 + it('keeps accepting stored keys with unfamiliar prefixes', () => {
85 + writeUserData({ api_key: 'legacy-format-key' });
86 +
87 + expect(getSDKConfig().apiKey).toBe('legacy-format-key');
88 + });
89 +
90 + it('prefers the environment when the user config file only holds a CLI user key', () => {
91 + vi.stubEnv('COMPOSIO_API_KEY', ENV_KEY);
92 + writeUserData({ api_key: USER_KEY });
93 +
94 + expect(getSDKConfig().apiKey).toBe(ENV_KEY);
95 + });
96 +
97 + it('rejects a CLI user key as the only candidate with a redacted kind error', () => {
98 + writeUserData({ api_key: USER_KEY });
99 +
100 + let caught: unknown;
101 + try {
102 + getSDKConfig();
103 + } catch (error) {
104 + caught = error;
105 + }
106 +
107 + expect(caught).toBeInstanceOf(ComposioAPIKeyKindError);
108 + const error = caught as ComposioAPIKeyKindError;
109 + expect(error.code).toContain(SDKErrorCodes.API_KEY_KIND_MISMATCH);
110 + expect(error.possibleFixes.length).toBeGreaterThan(0);
111 + const serialized = JSON.stringify({
112 + message: error.message,
113 + cause: error.cause,
114 + possibleFixes: error.possibleFixes,
115 + meta: error.meta,
116 + });
117 + expect(serialized).not.toContain(USER_KEY);
118 + expect(serialized).toContain('user_data.json');
119 + expect(serialized).toContain('user API key');
120 + expect(serialized).toContain('userApiKey');
121 + });
122 +
123 + it('does not let a configured user API key rescue an omitted project key', () => {
124 + // Omitting the project key keeps its historical meaning: the project key
125 + // is required. Only an explicit `null` opts into user-key-only auth.
126 + expect(() => getSDKConfig(undefined, undefined, { userApiKey: USER_KEY })).toThrow(
127 + ComposioNoAPIKeyError
128 + );
129 + });
130 +
131 + it('throws the no-key error when nothing is configured', () => {
132 + expect(() => getSDKConfig()).toThrow(ComposioNoAPIKeyError);
133 + });
134 +
135 + it('reports a malformed user config file without leaking its contents', () => {
136 + writeUserData('{"api_key": "' + PROJECT_KEY + '"'); // truncated JSON
137 +
138 + let caught: unknown;
139 + try {
140 + getSDKConfig();
141 + } catch (error) {
142 + caught = error;
143 + }
144 +
145 + expect(caught).toBeInstanceOf(ComposioNoAPIKeyError);
146 + const error = caught as ComposioNoAPIKeyError;
147 + expect(String(error.cause)).toContain(userDataPath());
148 + expect(String(error.cause)).toMatch(/could not be parsed/i);
149 + expect(String(error.cause)).not.toContain(PROJECT_KEY);
150 + });
151 +
152 + it('reports an unexpected user config shape without leaking its contents', () => {
153 + writeUserData({ api_key: { nested: PROJECT_KEY } });
154 +
155 + let caught: unknown;
156 + try {
157 + getSDKConfig();
158 + } catch (error) {
159 + caught = error;
160 + }
161 +
162 + expect(caught).toBeInstanceOf(ComposioNoAPIKeyError);
163 + const error = caught as ComposioNoAPIKeyError;
164 + expect(String(error.cause)).toContain(userDataPath());
165 + expect(String(error.cause)).toMatch(/unexpected shape/i);
166 + expect(String(error.cause)).not.toContain(PROJECT_KEY);
167 + });
168 + });
169 +
170 + describe('explicit null project key', () => {
171 + it('reads neither the environment nor the user config file', () => {
172 + vi.stubEnv('COMPOSIO_API_KEY', ENV_KEY);
173 + writeUserData({ api_key: PROJECT_KEY });
174 +
175 + let caught: unknown;
176 + try {
177 + getSDKConfig(undefined, null);
178 + } catch (error) {
179 + caught = error;
180 + }
181 +
182 + expect(caught).toBeInstanceOf(ComposioNoAPIKeyError);
183 + const error = caught as ComposioNoAPIKeyError;
184 + expect(error.message).toMatch(/disabled/i);
185 + expect(JSON.stringify(error.possibleFixes)).toContain('userApiKey');
186 + expect(JSON.stringify(error.possibleFixes)).toContain('x-user-api-key');
187 + });
188 +
189 + it('resolves to a null project key when a user API key option is configured', () => {
190 + vi.stubEnv('COMPOSIO_API_KEY', ENV_KEY);
191 + writeUserData({ api_key: PROJECT_KEY });
192 +
193 + expect(getSDKConfig(undefined, null, { userApiKey: USER_KEY })).toEqual({
194 + baseURL: DEFAULT_BASE_URL,
195 + apiKey: null,
196 + });
197 + });
198 +
199 + it('resolves to a null project key when an organization API key option is configured', () => {
200 + expect(getSDKConfig(undefined, null, { orgApiKey: ORG_KEY }).apiKey).toBeNull();
201 + });
202 +
203 + it('accepts the user API key the client will read from COMPOSIO_USER_API_KEY', () => {
204 + vi.stubEnv('COMPOSIO_USER_API_KEY', USER_KEY);
205 +
206 + expect(getSDKConfig(undefined, null).apiKey).toBeNull();
207 + });
208 +
209 + it('accepts the organization API key the client will read from COMPOSIO_ORG_API_KEY', () => {
210 + vi.stubEnv('COMPOSIO_ORG_API_KEY', ORG_KEY);
211 +
212 + expect(getSDKConfig(undefined, null).apiKey).toBeNull();
213 + });
214 +
215 + it('does not read COMPOSIO_USER_API_KEY when the user API key option is null', () => {
216 + vi.stubEnv('COMPOSIO_USER_API_KEY', USER_KEY);
217 +
218 + expect(() => getSDKConfig(undefined, null, { userApiKey: null })).toThrow(
219 + ComposioNoAPIKeyError
220 + );
221 + });
222 +
223 + it('does not accept an empty user API key option', () => {
224 + expect(() => getSDKConfig(undefined, null, { userApiKey: '' })).toThrow(
225 + ComposioNoAPIKeyError
226 + );
227 + });
228 +
229 + it('resolves to a null project key when a user API key header is configured', () => {
230 + vi.stubEnv('COMPOSIO_API_KEY', ENV_KEY);
231 + writeUserData({ api_key: PROJECT_KEY });
232 +
233 + expect(
234 + getSDKConfig(undefined, null, { defaultHeaders: { 'x-user-api-key': USER_KEY } })
235 + ).toEqual({ baseURL: DEFAULT_BASE_URL, apiKey: null });
236 + });
237 +
238 + it('matches the user API key header name case-insensitively', () => {
239 + expect(
240 + getSDKConfig(undefined, null, { defaultHeaders: { 'X-User-Api-Key': USER_KEY } }).apiKey
241 + ).toBeNull();
242 + });
243 +
244 + it('does not accept an empty user API key header', () => {
245 + expect(() =>
246 + getSDKConfig(undefined, null, { defaultHeaders: { 'x-user-api-key': '' } })
247 + ).toThrow(ComposioNoAPIKeyError);
248 + });
249 +
250 + it('does not treat other default headers as a credential', () => {
251 + expect(() =>
252 + getSDKConfig(undefined, null, {
253 + defaultHeaders: { authorization: `Bearer ${PROJECT_KEY}` },
254 + })
255 + ).toThrow(ComposioNoAPIKeyError);
256 + });
257 +
258 + it('rejects a raw project key header even when a user API key is configured', () => {
259 + let caught: unknown;
260 + try {
261 + getSDKConfig(undefined, null, {
262 + userApiKey: USER_KEY,
263 + defaultHeaders: { 'x-api-key': PROJECT_KEY },
264 + });
265 + } catch (error) {
266 + caught = error;
267 + }
268 +
269 + expect(caught).toBeInstanceOf(ComposioNoAPIKeyError);
270 + const error = caught as ComposioNoAPIKeyError;
271 + expect(error.message).toBe(
272 + 'Project API key resolution is disabled, but `defaultHeaders` carries a `x-api-key` entry'
273 + );
274 + expect(error.possibleFixes[0]).toBe(
275 + 'Pass the project API key via `apiKey` instead of a raw `x-api-key` default header'
276 + );
277 + expect(JSON.stringify(error)).not.toContain(PROJECT_KEY);
278 + });
279 +
280 + it('matches a raw project key header name case-insensitively', () => {
281 + expect(() =>
282 + getSDKConfig(undefined, null, {
283 + defaultHeaders: { 'X-Api-Key': PROJECT_KEY, 'x-user-api-key': USER_KEY },
284 + })
285 + ).toThrow(
286 + 'Project API key resolution is disabled, but `defaultHeaders` carries a `X-Api-Key` entry'
287 + );
288 + });
289 + });
290 +
291 + describe('base URL', () => {
292 + it('prefers the explicit value, then the environment, then the user config file', () => {
293 + vi.stubEnv('COMPOSIO_BASE_URL', 'https://env.example.com');
294 + writeUserData({ api_key: PROJECT_KEY, base_url: 'https://disk.example.com' });
295 +
296 + expect(getSDKConfig('https://explicit.example.com', EXPLICIT_KEY).baseURL).toBe(
297 + 'https://explicit.example.com'
298 + );
299 + expect(getSDKConfig(undefined, EXPLICIT_KEY).baseURL).toBe('https://env.example.com');
300 +
301 + vi.stubEnv('COMPOSIO_BASE_URL', undefined);
302 + expect(getSDKConfig(undefined, EXPLICIT_KEY).baseURL).toBe('https://disk.example.com');
303 + });
304 +
305 + it('falls back to the default base URL', () => {
306 + expect(getSDKConfig(undefined, EXPLICIT_KEY).baseURL).toBe(DEFAULT_BASE_URL);
307 + });
308 + });
309 +});
310 +
311 +describe('getUserApiKeyHeader', () => {
312 + it('matches the header name case-insensitively and keeps the original key', () => {
313 + expect(getUserApiKeyHeader({ 'X-User-Api-Key': USER_KEY })).toEqual({
314 + name: 'X-User-Api-Key',
315 + value: USER_KEY,
316 + });
317 + });
318 +
319 + it('ignores a header whose value is not a non-empty string', () => {
320 + const untyped = (value: unknown) =>
321 + ({ 'x-user-api-key': value }) as unknown as Record<string, string>;
322 +
323 + expect(getUserApiKeyHeader(untyped(''))).toBeUndefined();
324 + expect(getUserApiKeyHeader(untyped(undefined))).toBeUndefined();
325 + expect(getUserApiKeyHeader(untyped(null))).toBeUndefined();
326 + expect(getUserApiKeyHeader(untyped(42))).toBeUndefined();
327 + expect(getUserApiKeyHeader(untyped([USER_KEY]))).toBeUndefined();
328 + expect(getUserApiKeyHeader(undefined)).toBeUndefined();
329 + });
330 +});
331 +
332 +describe('resolveCredentialHeaders', () => {
333 + it('prefers the x-user-api-key default header over the configured keys', () => {
334 + expect(
335 + resolveCredentialHeaders({
336 + apiKey: PROJECT_KEY,
337 + userApiKey: USER_KEY,
338 + defaultHeaders: { 'X-User-Api-Key': 'uak_headerKey' },
339 + })
340 + ).toEqual({ 'x-user-api-key': 'uak_headerKey' });
341 + });
342 +
343 + it('sends the project key when no credential header is placed', () => {
344 + expect(
345 + resolveCredentialHeaders({ apiKey: PROJECT_KEY, userApiKey: USER_KEY, defaultHeaders: {} })
346 + ).toEqual({ 'x-api-key': PROJECT_KEY });
347 + });
348 +
349 + it('sends the resolved user key when the project key is disabled', () => {
350 + expect(
351 + resolveCredentialHeaders({ apiKey: null, userApiKey: USER_KEY, defaultHeaders: undefined })
352 + ).toEqual({ 'x-user-api-key': USER_KEY });
353 + });
354 +
355 + it('ignores an empty credential header and returns nothing without a credential', () => {
356 + expect(
357 + resolveCredentialHeaders({
358 + apiKey: null,
359 + userApiKey: null,
360 + defaultHeaders: { 'x-user-api-key': '' },
361 + })
362 + ).toEqual({});
363 + });
364 +});
ts/packages/core/test/utils/sdk.workerd.test.ts new
+48
@@ -0,0 +1,48 @@
1 +import { afterEach, describe, expect, it, vi } from 'vitest';
2 +
3 +const platformMock = vi.hoisted(() => ({
4 + supportsFileSystem: false,
5 + homedir: vi.fn(() => null),
6 + joinPath: vi.fn((...segments: string[]) => segments.join('/')),
7 + readFileSync: vi.fn(() => {
8 + throw new Error('File system operations are not supported in this runtime environment');
9 + }),
10 +}));
11 +
12 +vi.mock('#platform', () => ({ platform: platformMock }));
13 +
14 +import { getSDKConfig } from '../../src/utils/sdk';
15 +import { ComposioNoAPIKeyError } from '../../src/errors/SDKErrors';
16 +
17 +describe('getSDKConfig on edge runtimes', () => {
18 + afterEach(() => {
19 + vi.unstubAllEnvs();
20 + vi.clearAllMocks();
21 + });
22 +
23 + it('never touches file system APIs when resolving an omitted key', () => {
24 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_envKeyValue');
25 +
26 + expect(getSDKConfig().apiKey).toBe('ak_envKeyValue');
27 + expect(platformMock.homedir).not.toHaveBeenCalled();
28 + expect(platformMock.readFileSync).not.toHaveBeenCalled();
29 + });
30 +
31 + it('throws the no-key error without touching file system APIs', () => {
32 + vi.stubEnv('COMPOSIO_API_KEY', undefined);
33 +
34 + expect(() => getSDKConfig()).toThrow(ComposioNoAPIKeyError);
35 + expect(platformMock.homedir).not.toHaveBeenCalled();
36 + expect(platformMock.readFileSync).not.toHaveBeenCalled();
37 + });
38 +
39 + it('never touches file system APIs when the project key is disabled', () => {
40 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_envKeyValue');
41 +
42 + expect(
43 + getSDKConfig('https://explicit.example.com', null, { userApiKey: 'uak_userKeyValue' })
44 + ).toEqual({ baseURL: 'https://explicit.example.com', apiKey: null });
45 + expect(platformMock.homedir).not.toHaveBeenCalled();
46 + expect(platformMock.readFileSync).not.toHaveBeenCalled();
47 + });
48 +});
ts/packages/core/type-tests/sessions-mcp.test-d.ts
+24
@@ -48,6 +48,30 @@ async function requestOptionsArg(): Promise<void> {
48 await composio.use('session_123', { mcp: true }, { signal: ctrl.signal });
49 }
50
51 +// `update()` accepts null for clearable blocks, an empty allowlist, a null
52 +// callback URL, and `expectedConfigVersion` as a positive integer (explicit
53 +// precondition) or `false` (opt out of the default precondition), never a
54 +// string.
55 +async function updateContract(): Promise<void> {
56 + const session = await composio.use('session_123');
57 + await session.update({
58 + toolkits: [],
59 + manageConnections: { callbackUrl: null },
60 + multiAccount: { maxAccountsPerToolkit: null },
61 + preload: null,
62 + search: null,
63 + execute: { enableMultiExecute: false },
64 + experimental: null,
65 + expectedConfigVersion: session.configVersion,
66 + });
67 + await session.update({ toolkits: null, expectedConfigVersion: false });
68 + // @ts-expect-error expectedConfigVersion is a positive integer or false
69 + await session.update({ expectedConfigVersion: '3' });
70 + // @ts-expect-error expectedConfigVersion: true has no meaning
71 + await session.update({ expectedConfigVersion: true });
72 +}
73 +
74 void createGating;
75 void useGating;
76 void requestOptionsArg;
77 +void updateContract;