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

chore: move owned clients to `2.0.0-rc.18` (#4914)

This PR: - no Linear issue - moves `@composio/client` (pnpm catalog and lockfile) and `composio-client` (`python/pyproject.toml`, `python/setup.py`, `uv.lock`) from `2.0.0-rc.17` to `2.0.0-rc.18` ([release](https://github.com/ComposioHQ/composio-client/releases/tag/client-v2.0.0-rc.18), https://github.com/ComposioHQ/composio-client/pull/92), covering the TypeScript SDK, Python SDK, and CLI - core: builds the client with `auth` and `scope` instead of `apiKey`/`userApiKey`/`orgApiKey` and scope default headers. Project key only is `Auth.project`; a project key with a user or org key is `Auth.auto` (rc.17's per-operation selection); `apiKey: null` with a user key is `Auth.user`; only an org key is `Auth.organization`. Credential and scope entries in `defaultHeaders` / `createSession({ headers })` are folded into core's own options rather than forwarded. Pusher and the MCP export read core's own resolved keys instead of `client.apiKey`/`userApiKey`. The one `client.request` is `client.get`, `RequestOptions` is imported from the client root, and the obsolete casts from the implementation plan go (two rows kept, see below). `COMPOSIO_ALLOW_INSECURE_HTTP=1` is forwarded, since the client no longer reads the environment - CLI: the Effect client authenticates with `Auth.user(key)` (`Auth.none()` before login) and carries `scope`; the project-key call (`getLatestToolVersion`) is a second `make` with `Auth.project` over the same `HttpClient` instead of a per-call `x-api-key` override. `Cache.makeWith` is gone (ticket 07): the session-id read is one `Effect.cached` per process, and the connected-account memo is keyed on auth mode, org, project and user id, never on a key - Python SDK: `ProjectAuth` / `AutoAuth` / `UserAuth` and `Scope` replace `api_key=`, `user_api_key=`, `org_api_key=` and the scope default headers. The `HttpClient` subclass keeps a minimal `_headers_for` that only adds `x-request-id` (rc.18 does not generate one, so deleting it would drop that header); its `disable_api_key` and environment-snapshot workarounds are gone. The SDK keeps its own copy of the auth for Pusher. `COMPOSIO_CUSTOM_HEADERS` is parsed by the SDK, since the client no longer reads it - breaking (core and slim, minor changeset `client-auth-scope`): with `apiKey: null` and only an org key, every request now carries `x-org-api-key` (before, only the org-owner operations did); more than one credential header throws; the client's `apiKey`/`userApiKey`/`orgApiKey` getters are read-only and deprecated; `COMPOSIO_CUSTOM_HEADERS` is no longer applied by core - adds a CLI `CHANGELOG.md` entry and updates the version quoted in `ts/packages/cli/AGENTS.md` ## Context rc.18 replaces the client's three credential fields with an explicit `auth` value and the `x-org-id` / `x-project-id` default headers with `scope`. While `auth` or `scope` is configured, generic headers cannot name the headers it owns, so all three consumers fail at construction on rc.18 without this PR. Generated methods that take `x-user-api-key` / `x-org-id` as parameters keep their signatures. Two rows of the plan's casts table did not hold against the rc.18 types and were kept: `ToolRouterSession.ts`'s `body as SessionPatchParams` (`expectedConfigVersion` is a documented, tested core option, so dropping it is a product call), and `toolRouterParams.ts`'s `WithNull<>` (rc.18 generates block-level `null` for six session blocks, not the seven core widens). Verified locally on the published `2.0.0-rc.18`: - `pnpm typecheck` (workspace): 14/14 tasks; `typecheck:examples` 33/33 and `lint:examples` pass - `pnpm turbo test` core: 73 files, 1876 passed, 2 expected fail; CLI: 153 files, 1819 passed, 1 skipped - `pnpm --filter @composio/cli run lint:effect`: 0 errors; `validate:changesets`: pass - `nox -s tst` (python/): 2408 passed, 4 skipped; providers 11 + 16 + 6 passed - `nox -s chk` (python/): ruff and mypy pass on `composio/`, `providers/`, `tests/`, `scripts/` The client's hosted release acceptance ran these commits against the candidate before publishing (composio-client runs 38814280524 and 38815346541): `downstream-compile`, `downstream-python` and `effect-subpath` pass.

Alberto Schiabel committed Oct 16, 2026 at 12:57 UTC e08c84f144b83cceaf98d1a582002bb34ac70001
58 files changed +1704 -710
.changeset/client-auth-scope.md new
+12
@@ -0,0 +1,12 @@
1 +---
2 +'@composio/core': minor
3 +'@composio/slim': minor
4 +---
5 +
6 +Requires `@composio/client` `2.0.0-rc.18`. The SDK now hands the API client its credential as the client's `auth` option and its organization and project as `scope`, instead of placing them in default headers. The `apiKey`, `userApiKey`, `orgApiKey`, `orgId` and `projectId` options, their environment fallbacks and the credentials sent on each request are unchanged, with one exception: with `apiKey: null` and only an organization API key, every request now carries `x-org-api-key`. Before, only the organization-owner operations did, and every other request went out without a credential.
7 +
8 +Credential and scope headers in `defaultHeaders` or `createSession({ headers })` keep working, but the SDK folds them into its own options instead of forwarding them: an `x-user-api-key` or `x-org-api-key` entry becomes the credential every request carries, an `x-api-key` entry becomes the project key, and `x-org-id` / `x-project-id` entries become `orgId` / `projectId`. `getConfig()` reports the folded values (for example `apiKey: null` and `userApiKey` for an `x-user-api-key` entry) and no longer lists those entries under `defaultHeaders`. Setting more than one of `x-api-key`, `x-user-api-key` and `x-org-api-key` now throws a `ComposioError`; the API rejected every such request.
9 +
10 +On the client returned by `getClient()`, `apiKey`, `userApiKey` and `orgApiKey` are read-only and deprecated (read the keys from `getConfig()`, or `authMode` and `scope` from the client), and a per-call `headers` option can no longer name a credential or scope header. The API client no longer reads the environment itself: the SDK still honours `COMPOSIO_ALLOW_INSECURE_HTTP=1`, and no longer applies `COMPOSIO_CUSTOM_HEADERS`; pass `defaultHeaders` instead.
11 +
12 +The deprecated `customConnectionData` now requires `val.access_token` for `S2S_OAUTH2`, as the API does.
pnpm-lock.yaml
+9 -9
@@ -28,8 +28,8 @@ catalogs:
28 specifier: ^5.20261012.1
29 version: 5.20261012.1
30 '@composio/client':
31 - specifier: 2.0.0-rc.17
32 - version: 2.0.0-rc.17
31 + specifier: 2.0.0-rc.18
32 + version: 2.0.0-rc.18
33 '@effect/language-service':
34 specifier: ^0.87.4
35 version: 0.87.4
@@ -968,7 +968,7 @@ importers:
968 dependencies:
969 '@composio/client':
970 specifier: 'catalog:'
971 - version: 2.0.0-rc.17(effect@4.0.3)
971 + version: 2.0.0-rc.18(effect@4.0.3)
972 '@composio/core':
973 specifier: workspace:*
974 version: link:../../packages/core
@@ -1216,7 +1216,7 @@ importers:
1216 version: link:../cli-keyring
1217 '@composio/client':
1218 specifier: 'catalog:'
1219 - version: 2.0.0-rc.17(effect@4.0.3)
1219 + version: 2.0.0-rc.18(effect@4.0.3)
1220 '@composio/core':
1221 specifier: workspace:*
1222 version: link:../core
@@ -1322,7 +1322,7 @@ importers:
1322 dependencies:
1323 '@composio/client':
1324 specifier: 'catalog:'
1325 - version: 2.0.0-rc.17(effect@4.0.3)
1325 + version: 2.0.0-rc.18(effect@4.0.3)
1326 '@composio/json-schema-to-zod':
1327 specifier: workspace:*
1328 version: link:../json-schema-to-zod
@@ -1727,7 +1727,7 @@ importers:
1727 dependencies:
1728 '@composio/client':
1729 specifier: 'catalog:'
1730 - version: 2.0.0-rc.17(effect@4.0.3)
1730 + version: 2.0.0-rc.18(effect@4.0.3)
1731 '@composio/json-schema-to-zod':
1732 specifier: workspace:*
1733 version: link:../json-schema-to-zod
@@ -2291,8 +2291,8 @@ packages:
2291 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
2292 engines: {node: '>=0.1.90'}
2293
2294 - '@composio/client@2.0.0-rc.17':
2295 - resolution: {integrity: sha512-j1fqyiAwAO6kOmbLwkLn4fb4//GNveV2yo0iMo4wTwOk9euRwQNK6lodVcRhJT6ZeRCSS2Xv8uUsJtmGsPTyiA==}
2294 + '@composio/client@2.0.0-rc.18':
2295 + resolution: {integrity: sha512-O7zIJfapLBVLkmSXf2Oqp/jsQ3st2XfOg8q7V/bliIg8akDmuflc6cwgGriFE3sV2HaaoAyqbtLqaF+ihXGMLg==}
2296 engines: {node: '>=22'}
2297 peerDependencies:
2298 effect: '*'
@@ -7581,7 +7581,7 @@ snapshots:
7581 '@colors/colors@1.5.0':
7582 optional: true
7583
7584 - '@composio/client@2.0.0-rc.17(effect@4.0.3)':
7584 + '@composio/client@2.0.0-rc.18(effect@4.0.3)':
7585 optionalDependencies:
7586 effect: 4.0.3
7587
pnpm-workspace.yaml
+1 -1
@@ -33,7 +33,7 @@ catalog:
33 '@clack/prompts': '^1.8.1'
34 '@cloudflare/vitest-pool-workers': 0.23.0
35 '@cloudflare/workers-types': ^5.20261012.1
36 - '@composio/client': 2.0.0-rc.17
36 + '@composio/client': 2.0.0-rc.18
37 '@effect/language-service': ^0.87.4
38 '@effect/platform-bun': 4.0.3
39 '@effect/vitest': 4.0.3
python/composio/client/__init__.py
+45 -105
@@ -18,18 +18,15 @@ from composio_client import (
18 NOT_GIVEN,
19 APIError,
20 APIStatusError,
21 + Auth,
22 ClientIdentity,
23 NotGiven,
24 + Scope,
25 )
26 from composio_client import Composio as BaseComposio
25 -from composio_client._base_client import HeaderParam, RequestOptions
27 from httpx import URL, Client, Response, Timeout
28
28 -from composio.core.models.tool_router_constants import (
29 - PROJECT_API_KEY_HEADER,
30 - USER_API_KEY_HEADER,
31 -)
32 -from composio.exceptions import ComposioError, InvalidParams
29 +from composio.exceptions import ComposioError
30 from composio.utils.logging import LogLevel, WithLogger, _VerbosityWrapper
31
32
@@ -351,94 +348,48 @@ class HttpClient(BaseComposio, WithLogger):
348 self,
349 *,
350 provider: str,
354 - api_key: t.Optional[str] = None,
355 - disable_api_key: bool = False,
356 - user_api_key: t.Optional[str] = None,
357 - org_api_key: t.Optional[str] = None,
351 + auth: Auth,
352 + scope: t.Optional[Scope] = None,
353 environment: te.Union[NotGiven, APIEnvironment] = "production",
354 base_url: t.Optional[t.Union[str, URL, NotGiven]] = NOT_GIVEN,
355 timeout: t.Optional[t.Union[float, Timeout, NotGiven]] = NOT_GIVEN,
356 max_retries: int = DEFAULT_MAX_RETRIES,
362 - default_headers: t.Optional[t.Mapping[str, str]] = None,
357 + default_headers: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
358 default_query: t.Optional[t.Mapping[str, object]] = None,
359 + identity: t.Optional[ClientIdentity] = None,
360 http_client: t.Optional[Client] = None,
361 logger: t.Optional[logging.Logger] = None,
362 logging_level: t.Optional[LogLevel] = None,
363 _strict_response_validation: bool = False,
368 - _environment_variables: t.Optional[t.Mapping[str, str]] = None,
364 ) -> None:
365 """
366 Initialize the client.
367
368 :param provider: The provider to use for the client.
369 + :param auth: How the client authenticates (``ProjectAuth``, ``UserAuth``,
370 + ``AutoAuth``, ...). The client reads no environment variable; the SDK
371 + resolves the keys before constructing it.
372 + :param scope: The organization and project requests are routed to, sent
373 + as ``x-org-id`` / ``x-project-id``.
374 :param logger: Logger that receives SDK and ``composio_client`` records.
375 :param logging_level: Level applied to the SDK and ``composio_client`` loggers.
376 - :param api_key: The API key to use for the client.
377 - :param disable_api_key: Turn project-key authentication off, including the
378 - ``COMPOSIO_API_KEY`` fallback; ``None`` alone keeps that fallback.
379 - :param _environment_variables: Environment snapshot the generated client
380 - resolves its fallbacks from instead of ``os.environ``; clones of a
381 - client built from a snapshot receive an empty one.
382 - :param user_api_key: User API key, sent only on operations that require it.
383 - :param org_api_key: Organization API key, sent only on operations that require it.
376 :param environment: The environment to use for the client.
377 :param base_url: The base URL to use for the client.
378 :param timeout: The timeout to use for the client.
379 :param max_retries: The maximum number of retries to use for the client.
388 - :param default_headers: The default headers to use for the client.
380 + :param default_headers: The default headers to use for the client. They
381 + may not name a credential header while ``auth`` holds a credential, nor
382 + a scope header while ``scope`` is set.
383 :param default_query: The default query parameters to use for the client.
384 + :param identity: How the client reports the SDK; derived from ``provider``
385 + when omitted. Clones pass the parent's.
386 :param http_client: The HTTP client to use for the client.
387 """
388 WithLogger.__init__(self, logger=logger, logging_level=logging_level)
393 - self._disable_api_key = disable_api_key
394 - if disable_api_key:
395 - # The project credential is only ever set from `api_key`: a raw
396 - # `x-api-key` default header would bypass the disabled project key.
397 - project_key_header = next(
398 - (
399 - name
400 - for name in (default_headers or {})
401 - if name.lower() == PROJECT_API_KEY_HEADER
402 - ),
403 - None,
404 - )
405 - if project_key_header is not None:
406 - raise InvalidParams(
407 - f"`disable_api_key=True` sends no project key, but "
408 - f"`default_headers` carries a `{project_key_header}` entry; "
409 - "pass the project API key as `api_key` instead of a raw "
410 - f"`{PROJECT_API_KEY_HEADER}` header, or remove the entry to "
411 - "authenticate with the user API key alone"
412 - )
413 - # The generated client reads COMPOSIO_API_KEY whenever `api_key` is
414 - # None, so hand it an environment without that variable. Clones
415 - # inherit the resolved values and an empty snapshot.
416 - api_key = None
417 - if _environment_variables is None:
418 - _environment_variables = {
419 - name: value
420 - for name, value in os.environ.items()
421 - if name != "COMPOSIO_API_KEY"
422 - }
423 - # The generated client sends its user key only on operations whose
424 - # security scheme names it, which excludes sessions. The resolved
425 - # user key is placed as the `x-user-api-key` default header instead,
426 - # so every request carries exactly that credential.
427 - resolved_user_api_key = user_api_key or _environment_variables.get(
428 - "COMPOSIO_USER_API_KEY"
429 - )
430 - if resolved_user_api_key and not any(
431 - name.lower() == USER_API_KEY_HEADER for name in (default_headers or {})
432 - ):
433 - default_headers = {
434 - **(default_headers or {}),
435 - USER_API_KEY_HEADER: resolved_user_api_key,
436 - }
389 BaseComposio.__init__(
390 self,
439 - api_key=api_key,
440 - user_api_key=user_api_key,
441 - org_api_key=org_api_key,
391 + auth=auth,
392 + scope=scope,
393 environment=environment,
394 base_url=base_url,
395 timeout=timeout,
@@ -446,10 +397,15 @@ class HttpClient(BaseComposio, WithLogger):
397 default_headers=default_headers,
398 default_query=default_query,
399 http_client=http_client,
449 - identity=_client_identity(provider),
400 + identity=identity if identity is not None else _client_identity(provider),
401 _strict_response_validation=_strict_response_validation,
451 - _environment_variables=_environment_variables,
402 )
403 + # The SDK's own reference to the credentials it authenticated with, for
404 + # the places that hand a key to something other than this client (the
405 + # session MCP config, the realtime channel auth). The client's
406 + # `api_key` / `user_api_key` read-back properties go in 2.0.0-rc.19,
407 + # and `auth` is the generated `/auth` resource.
408 + self.sdk_auth: Auth = auth
409 _install_client_log_forwarder(self._logger)
410 self.provider = provider
411 self.request_ctx = contextvars.ContextVar[RequestContext](
@@ -469,25 +425,17 @@ class HttpClient(BaseComposio, WithLogger):
425 **kwargs: t.Any,
426 ) -> te.Self:
427 """
472 - Clone the client, re-injecting the required ``provider`` keyword.
428 + Clone the client, re-injecting the SDK-only constructor keywords.
429
474 - The Stainless-generated ``copy`` rebuilds the client via
475 - ``self.__class__(...)`` without passing ``provider``, which this subclass
476 - requires — so the inherited ``copy``/``with_options`` raise ``TypeError``.
477 - Threading ``provider`` through ``_extra_kwargs`` makes them work again
478 - (e.g. ``with_options(max_retries=0)``).
430 + The generated ``copy`` rebuilds the client via ``type(self)(...)`` with
431 + the parent's ``auth``, ``scope``, ``identity`` and options, but cannot
432 + know ``provider``, which this subclass requires, or the SDK logger.
433 + Threading them through ``_extra_kwargs`` makes ``copy`` /
434 + ``with_options`` work (e.g. ``with_options(max_retries=0)``).
435 """
436 return super().copy( # type: ignore[misc]
437 _extra_kwargs={
438 "provider": self.provider,
483 - # Clones keep the project key disabled, so a default header
484 - # added through `with_options` goes through the same checks.
485 - "disable_api_key": self._disable_api_key,
486 - # The generated `copy` does not re-pass `_strict_response_validation`,
487 - # so without this the clone would silently fall back to the default
488 - # (False) even when the original had it enabled — keeping the sibling
489 - # a faithful copy that differs from the parent only in `max_retries`.
490 - "_strict_response_validation": self._strict_response_validation,
439 # Share the parent's logger; otherwise constructing the clone
440 # rebinds the process-wide client log forwarder to the default
441 # `composio` logger.
@@ -564,29 +512,21 @@ class HttpClient(BaseComposio, WithLogger):
512 super()._make_status_error(err_msg, body=body, response=response)
513 )
514
567 - def _headers_for(
568 - self,
569 - url: str,
570 - *,
571 - json_body: t.Optional[t.Dict[str, t.Any]],
572 - method_headers: t.Optional[HeaderParam],
573 - options: RequestOptions,
574 - withdrawn: bool,
575 - scheme: str,
576 - ) -> t.Dict[str, str]:
515 + def _headers_for(self, url: str, **kwargs: t.Any) -> t.Dict[str, str]:
516 """
578 - Add the request id at the active generated client's dispatch boundary.
579 -
580 - The identity headers come from the client's ``identity``.
517 + Add ``x-request-id`` to every dispatch to the API origin.
518 +
519 + The client builds every other header itself (credential from ``auth``,
520 + ``x-org-id`` / ``x-project-id`` from ``scope``, identity from
521 + ``identity``) and generates no request id, so this is all the override
522 + still does. The client calls it once per logical call (its retries
523 + reuse those headers) and again for each redirect hop, so a fresh id is
524 + minted per call and per same-origin hop unless the caller pinned one in
525 + ``default_headers`` or the request context. The keywords are forwarded
526 + untouched so the override does not depend on the client's private
527 + signature.
528 """
582 - headers = super()._headers_for(
583 - url,
584 - json_body=json_body,
585 - method_headers=method_headers,
586 - options=options,
587 - withdrawn=withdrawn,
588 - scheme=scheme,
589 - )
529 + headers = super()._headers_for(url, **kwargs)
530 target, base = URL(url), URL(self.base_url)
531 if (target.scheme, target.host, target.port) != (
532 base.scheme,
python/composio/core/models/base.py
+51 -17
@@ -10,8 +10,15 @@ import time
10 import traceback
11 import typing as t
12
13 +from composio_client import AutoAuth, NoAuth, ProjectAuth, Scope, UserAuth
14 +
15 from composio.__version__ import __version__
16 from composio.client import HttpClient
17 +from composio.core.models.tool_router_constants import (
18 + ORG_ID_HEADER,
19 + PROJECT_ID_HEADER,
20 + USER_API_KEY_HEADER,
21 +)
22 from composio.utils.redaction import redact_sensitive_text
23 from composio.utils.logging import WithLogger
24
@@ -106,22 +113,49 @@ def header_value(headers: t.Mapping[str, t.Any], name: str) -> t.Optional[str]:
113
114
115 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 + """The single credential header the client puts on its own requests.
117 +
118 + For the destinations the SDK hands a credential to outside the client (the
119 + session MCP config, the realtime channel auth). Read from the ``auth`` the
120 + SDK constructed the client with, never from the client's read-back
121 + properties: a project key (``ProjectAuth``, or ``AutoAuth`` holding one)
122 + travels as ``x-api-key``, otherwise a user key (``UserAuth``, or
123 + ``AutoAuth`` holding only a user key) as ``x-user-api-key``. Under
124 + ``NoAuth`` a caller-placed ``x-user-api-key`` default header is the
125 + credential. Empty when no such key is held as a string. The environment is
126 + never consulted here.
127 """
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}
128 + auth = client.sdk_auth
129 + project: object = None
130 + user: object = None
131 + if isinstance(auth, NoAuth):
132 + user = header_value(client.default_headers, USER_API_KEY_HEADER)
133 + elif isinstance(auth, ProjectAuth):
134 + project = auth.credential
135 + elif isinstance(auth, UserAuth):
136 + user = auth.credential
137 + elif isinstance(auth, AutoAuth):
138 + project, user = auth.project, auth.user
139 + if isinstance(project, str) and project:
140 + return {"x-api-key": project}
141 + if isinstance(user, str) and user:
142 + return {USER_API_KEY_HEADER: user}
143 return {}
144 +
145 +
146 +def scope_headers(client: HttpClient) -> t.Dict[str, str]:
147 + """The ``x-org-id`` / ``x-project-id`` the client sends to its API origin:
148 + its ``scope``, or without one the caller-placed default headers."""
149 + scope = client.scope
150 + if isinstance(scope, Scope):
151 + pairs = (
152 + (ORG_ID_HEADER, scope.organization_id),
153 + (PROJECT_ID_HEADER, scope.project_id),
154 + )
155 + else:
156 + default_headers: t.Mapping[str, t.Any] = client.default_headers
157 + pairs = (
158 + (ORG_ID_HEADER, header_value(default_headers, ORG_ID_HEADER)),
159 + (PROJECT_ID_HEADER, header_value(default_headers, PROJECT_ID_HEADER)),
160 + )
161 + return {name: value for name, value in pairs if value}
python/composio/core/models/tool_router.py
+12 -16
@@ -24,7 +24,7 @@ from composio_client.types.tool_router.session_retrieve_response import (
24 )
25
26 from composio.client import HttpClient
27 -from composio.core.models.base import Resource, credential_headers, header_value
27 +from composio.core.models.base import Resource, credential_headers, scope_headers
28 from composio.core.models.custom_tool import (
29 ExperimentalToolkit,
30 assert_no_custom_tool_slugs_in_preload,
@@ -43,9 +43,7 @@ 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,
46 PRELOAD_TOOLS_ALL,
48 - PROJECT_ID_HEADER,
47 SESSION_PRESET_DIRECT_TOOLS,
48 )
49 from composio.core.models.tool_router_session import (
@@ -674,13 +672,13 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
672 """
673 Create an MCP server config object with authentication headers.
674
677 - The headers mirror the effective auth of the underlying client: the
678 - ``x-user-api-key`` default header when one is placed (the client sends
679 - it and suppresses the configured keys), otherwise its project key as
680 - ``x-api-key``, otherwise the resolved ``user_api_key`` option as
681 - ``x-user-api-key``, plus ``x-org-id`` / ``x-project-id`` when the
682 - client carries an explicit scope. No other default header is copied
683 - and the environment is never re-read.
675 + The headers mirror the effective auth of the underlying client, read
676 + from the ``auth`` and ``scope`` the SDK built it with: its project key
677 + as ``x-api-key``, otherwise its user key as ``x-user-api-key`` (see
678 + :func:`~composio.core.models.base.credential_headers`), plus
679 + ``x-org-id`` / ``x-project-id`` when the client carries an explicit
680 + ``scope``. No other default header is copied and the environment is
681 + never re-read.
682
683 The headers are only attached when the MCP URL has the same origin as
684 the client's API base URL, whatever scheme is configured: that origin
@@ -712,12 +710,10 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
710 )
711 return ToolRouterMCPServerConfig(type=mcp_type, url=url, headers={})
712
715 - default_headers: t.Mapping[str, t.Any] = self._client.default_headers
716 - headers: t.Dict[str, t.Optional[str]] = dict(credential_headers(self._client))
717 - for scope_header in (ORG_ID_HEADER, PROJECT_ID_HEADER):
718 - scope_value = header_value(default_headers, scope_header)
719 - if scope_value:
720 - headers[scope_header] = scope_value
713 + headers: t.Dict[str, t.Optional[str]] = {
714 + **credential_headers(self._client),
715 + **scope_headers(self._client),
716 + }
717 return ToolRouterMCPServerConfig(type=mcp_type, url=url, headers=headers)
718
719 def _transform_tags_params(
python/composio/core/models/tool_router_constants.py
+4 -4
@@ -3,12 +3,12 @@ import typing as t
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.
6 +#: Header that carries the project API key. The client sets it from ``auth``
7 +#: and rejects a caller-placed default header while ``auth`` holds a key.
8 PROJECT_API_KEY_HEADER = "x-api-key"
9 #: 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.
10 +#: project API key. Under ``NoAuth`` it is the only credential default header
11 +#: 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"
python/composio/core/models/triggers.py
-1
@@ -1029,7 +1029,6 @@ class _SubcriptionBuilder(WithLogger):
1029 """Initialize pusher client."""
1030 super().__init__()
1031 self._client = client
1032 - self.api_key = self._client.api_key
1032 self.base_url = self._client.base_url
1033 self.internal = Internal(client=self._client)
1034 self.subscription = TriggerSubscription(client=self._client)
python/composio/sdk.py
+49 -20
@@ -7,6 +7,7 @@ import warnings
7
8 import httpx
9 import typing_extensions as te
10 +from composio_client import Auth, AutoAuth, ProjectAuth, Scope, UserAuth
11
12 from composio import exceptions
13 from composio.client import DEFAULT_MAX_RETRIES, APIEnvironment, HttpClient
@@ -23,7 +24,6 @@ from composio.core.models import (
24 )
25 from composio.core.models.base import allow_tracking
26 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,
@@ -64,14 +64,15 @@ class SDKConfig(te.TypedDict):
64 logging_level: te.NotRequired[LogLevel]
65
66
67 -def _scope_headers(
67 +def _scope(
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.
69 +) -> t.Optional[Scope]:
70 + """The client ``scope`` for an explicit ``org_id`` / ``project_id`` pair.
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 + The client sends them as ``x-org-id`` / ``x-project-id``.
76 """
77 org_id = org_id or None
78 project_id = project_id or None
@@ -81,8 +82,31 @@ def _scope_headers(
82 "(the organization and consumer project nano IDs) or neither"
83 )
84 if org_id is None or project_id is None:
84 - return {}
85 - return {ORG_ID_HEADER: org_id, PROJECT_ID_HEADER: project_id}
85 + return None
86 + return Scope(organization_id=org_id, project_id=project_id)
87 +
88 +
89 +def _env_key(name: str) -> t.Optional[str]:
90 + """``name`` from the environment, or ``None`` when unset or blank."""
91 + value = os.environ.get(name)
92 + return value if value and value.strip() else None
93 +
94 +
95 +def _custom_headers() -> t.Optional[t.Dict[str, str]]:
96 + """``COMPOSIO_CUSTOM_HEADERS`` (``name: value`` lines) as default headers.
97 +
98 + The generated client read this variable itself until 2.0.0-rc.18; it now
99 + reads no environment, so the SDK keeps sending what it always sent.
100 + """
101 + raw = os.environ.get("COMPOSIO_CUSTOM_HEADERS")
102 + if not raw:
103 + return None
104 + parsed: t.Dict[str, str] = {}
105 + for line in raw.split("\n"):
106 + colon = line.find(":")
107 + if colon >= 0:
108 + parsed[line[:colon].strip()] = line[colon + 1 :].strip()
109 + return parsed or None
110
111
112 class Composio(t.Generic[TTool, TToolCollection], WithLogger):
@@ -215,27 +239,34 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
239 logging_level = kwargs.get("logging_level")
240 WithLogger.__init__(self, logger=logger, logging_level=logging_level)
241 disable_api_key = kwargs.get("disable_api_key", False)
218 - api_key: t.Optional[str]
242 + user_api_key = kwargs.get("user_api_key") or _env_key("COMPOSIO_USER_API_KEY")
243 + org_api_key = kwargs.get("org_api_key") or _env_key("COMPOSIO_ORG_API_KEY")
244 + auth: Auth
245 if disable_api_key:
246 if kwargs.get("api_key") is not None:
247 raise exceptions.InvalidParams(
248 "`disable_api_key=True` cannot be combined with an explicit "
249 "`api_key`; pass one or the other"
250 )
225 - api_key = None
226 - user_api_key = kwargs.get("user_api_key") or os.environ.get(
227 - "COMPOSIO_USER_API_KEY"
228 - )
251 if not user_api_key:
252 raise exceptions.UserApiKeyNotProvidedError()
253 + # The user key alone, on every request. An organization key is
254 + # not sent in this mode, as before.
255 + auth = UserAuth(user_api_key)
256 else:
257 api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY"))
258 if not api_key:
259 raise exceptions.ApiKeyNotProvidedError()
235 -
236 - default_headers = _scope_headers(
237 - org_id=kwargs.get("org_id"), project_id=kwargs.get("project_id")
238 - )
260 + # With a user or organization key beside it, the client sends
261 + # exactly one credential per request: the project key wherever the
262 + # operation accepts it, otherwise the first declared scheme a key is
263 + # held for. With the project key alone, that key on every request.
264 + auth = (
265 + AutoAuth(project=api_key, user=user_api_key, organization=org_api_key)
266 + if user_api_key or org_api_key
267 + else ProjectAuth(api_key)
268 + )
269 + scope = _scope(org_id=kwargs.get("org_id"), project_id=kwargs.get("project_id"))
270
271 # Each instance gets its own provider so that the execute_tool_fn binding
272 # performed by Tools.__init__ cannot leak across SDK instances (issue #4369).
@@ -251,14 +282,12 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
282 self._client = HttpClient(
283 environment=kwargs.get("environment", "production"),
284 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"),
285 + auth=auth,
286 + scope=scope,
287 base_url=kwargs.get("base_url") or os.environ.get("COMPOSIO_BASE_URL"),
288 timeout=kwargs.get("timeout"),
289 max_retries=kwargs.get("max_retries", DEFAULT_MAX_RETRIES),
261 - default_headers=default_headers or None,
290 + default_headers=_custom_headers(),
291 http_client=kwargs.get("http_client"),
292 logger=logger,
293 logging_level=logging_level,
python/pyproject.toml
+1 -1
@@ -7,7 +7,7 @@ requires-python = ">=3.11,<3.16"
7 dependencies = [
8 "pysher>=1.0.8",
9 "pydantic>=2.11.9",
10 - "composio-client==2.0.0rc17",
10 + "composio-client==2.0.0rc18",
11 "typing-extensions>=4.16.0",
12 "openai>=2.48.0",
13 "json-schema-to-pydantic>=0.4.11",
python/setup.py
+1 -1
@@ -25,7 +25,7 @@ setup(
25 install_requires=[
26 "pysher>=1.0.8",
27 "pydantic>=2.11.9",
28 - "composio-client==2.0.0rc17",
28 + "composio-client==2.0.0rc18",
29 "typing-extensions>=4.16.0",
30 "openai>=2.48.0",
31 "json-schema-to-pydantic>=0.4.11",
python/tests/test_auth_configs.py
+2 -2
@@ -5,6 +5,7 @@ from unittest.mock import Mock
5
6 import httpx
7 import pytest
8 +from composio_client import ProjectAuth
9 from composio.client import HttpClient
10 from composio.client.types import (
11 auth_config_create_response,
@@ -436,8 +437,7 @@ def test_mutation_response_through_generated_client(
437
438 with HttpClient(
439 provider="test",
439 - api_key="test",
440 - _environment_variables={},
440 + auth=ProjectAuth("test"),
441 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
442 ) as client:
443 auth_configs = AuthConfigs(client)
python/tests/test_client_errors.py
+2 -1
@@ -16,6 +16,7 @@ from unittest.mock import Mock
16 import composio_client
17 import httpx
18 import pytest
19 +from composio_client import ProjectAuth
20
21 from composio import exceptions
22 from composio.client import HttpClient
@@ -50,7 +51,7 @@ def _client_returning(
51
52 return HttpClient(
53 provider="test",
53 - api_key="sk-test",
54 + auth=ProjectAuth("sk-test"),
55 base_url="https://backend.invalid",
56 max_retries=max_retries,
57 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
python/tests/test_client_provenance.py
+5 -4
@@ -6,6 +6,7 @@ from importlib.metadata import version
6 import httpx
7 import pytest
8 from composio_client import ComposioError as ClientComposioError
9 +from composio_client import ProjectAuth
10
11 from composio.client import HttpClient
12
@@ -20,7 +21,7 @@ def test_product_provenance_on_request(clone):
21
22 with HttpClient(
23 provider="test-provider",
23 - api_key="test-key",
24 + auth=ProjectAuth("test-key"),
25 base_url="https://backend.invalid",
26 http_client=httpx.Client(transport=httpx.MockTransport(respond)),
27 ) as client:
@@ -49,7 +50,7 @@ def test_product_provenance_is_not_added_to_another_origin():
50
51 with HttpClient(
52 provider="test-provider",
52 - api_key="test-key",
53 + auth=ProjectAuth("test-key"),
54 base_url="https://backend.invalid",
55 http_client=httpx.Client(transport=httpx.MockTransport(respond)),
56 ) as client:
@@ -68,7 +69,7 @@ def test_identity_headers_are_refused_in_default_headers(header):
69 ):
70 HttpClient(
71 provider="test-provider",
71 - api_key="test-key",
72 + auth=ProjectAuth("test-key"),
73 base_url="https://backend.invalid",
74 default_headers={header: "caller-value"},
75 )
@@ -84,7 +85,7 @@ def test_unsendable_provider_name_is_reported_as_unknown(provider):
85
86 with HttpClient(
87 provider=provider,
87 - api_key="test-key",
88 + auth=ProjectAuth("test-key"),
89 base_url="https://backend.invalid",
90 http_client=httpx.Client(transport=httpx.MockTransport(respond)),
91 ) as client:
python/tests/test_mcp.py
+4 -2
@@ -19,6 +19,7 @@ from unittest.mock import Mock
19
20 import httpx
21 import pytest
22 +from composio_client import ProjectAuth
23
24 from composio import ComposioDeprecationWarning
25 from composio.client import HttpClient
@@ -147,7 +148,7 @@ def _transport_mcp(requests: t.Optional[t.List[httpx.Request]] = None) -> MCP:
148
149 client = HttpClient(
150 provider="test",
150 - api_key="ak_test",
151 + auth=ProjectAuth("ak_test"),
152 base_url="https://backend.composio.dev",
153 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
154 )
@@ -204,6 +205,7 @@ _DEFAULT_FILTERS_SCRIPT = """
205 import warnings
206
207 import httpx
208 +from composio_client import ProjectAuth
209
210 from composio.client import HttpClient
211 from composio.core.models.mcp import MCP
@@ -222,7 +224,7 @@ def handler(request):
224 mcp = MCP(
225 HttpClient(
226 provider="test",
225 - api_key="ak_test",
227 + auth=ProjectAuth("ak_test"),
228 base_url="https://backend.composio.dev",
229 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
230 )
python/tests/test_no_retry_writes.py
+9 -9
@@ -17,7 +17,7 @@ from unittest.mock import Mock, patch
17
18 import httpx
19 import pytest
20 -from composio_client import DEFAULT_MAX_RETRIES, APIError
20 +from composio_client import DEFAULT_MAX_RETRIES, APIError, ProjectAuth
21 from composio_client import Composio as BaseComposio
22
23 from composio.client import HttpClient
@@ -53,7 +53,7 @@ def _client_with_transport(
53 """
54 return HttpClient(
55 provider="test",
56 - api_key="sk-test",
56 + auth=ProjectAuth("sk-test"),
57 base_url="https://backend.invalid",
58 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
59 )
@@ -65,7 +65,7 @@ class TestCopyOverride:
65 def test_with_options_does_not_raise_and_overrides_max_retries(self) -> None:
66 client = HttpClient(
67 provider="myprovider",
68 - api_key="sk-test",
68 + auth=ProjectAuth("sk-test"),
69 base_url="https://backend.invalid",
70 )
71
@@ -83,7 +83,7 @@ class TestCopyOverride:
83 def test_without_retries_is_a_cached_zero_retry_sibling(self) -> None:
84 client = HttpClient(
85 provider="test",
86 - api_key="sk-test",
86 + auth=ProjectAuth("sk-test"),
87 base_url="https://backend.invalid",
88 )
89
@@ -94,11 +94,11 @@ class TestCopyOverride:
94 assert client.max_retries == DEFAULT_MAX_RETRIES
95
96 def test_clone_preserves_strict_response_validation(self) -> None:
97 - # The generated `copy` drops `_strict_response_validation`; the override
98 - # re-injects it so the sibling differs from the parent only in retries.
97 + # The sibling must differ from the parent only in retries, including
98 + # `_strict_response_validation`, which the generated `copy` carries.
99 client = HttpClient(
100 provider="test",
101 - api_key="sk-test",
101 + auth=ProjectAuth("sk-test"),
102 base_url="https://backend.invalid",
103 _strict_response_validation=True,
104 )
@@ -115,8 +115,8 @@ class TestStainlessCopyContract:
115 """
116
117 def test_base_copy_accepts_extra_kwargs(self) -> None:
118 - # The override threads `provider` (and `_strict_response_validation`)
119 - # through `_extra_kwargs`; the base `copy` must still accept it.
118 + # The override threads `provider` (and the SDK logger) through
119 + # `_extra_kwargs`; the base `copy` must still accept it.
120 assert "_extra_kwargs" in inspect.signature(BaseComposio.copy).parameters
121
122 def test_with_options_is_aliased_to_our_copy_override(self) -> None:
python/tests/test_sdk.py
+218 -22
@@ -7,6 +7,8 @@ from unittest.mock import patch
7 import composio_client
8 import httpx
9 import pytest
10 +from composio_client import AutoAuth, ProjectAuth, Scope, UserAuth
11 +from composio_client import ComposioError as ClientComposioError
12
13 from composio import Composio, exceptions
14 from composio.client import HttpClient
@@ -33,12 +35,14 @@ class TestComposioSDK:
35 sdk = Composio(
36 api_key="ak_test", user_api_key="uak_test", org_api_key="oak_test"
37 )
36 - assert sdk.client.api_key == "ak_test"
37 - assert sdk.client.user_api_key == "uak_test"
38 - assert sdk.client.org_api_key == "oak_test"
38 + assert sdk.client.auth_mode == "auto"
39 + assert sdk.client.sdk_auth == AutoAuth(
40 + project="ak_test", user="uak_test", organization="oak_test"
41 + )
42
43 def test_sdk_reads_user_and_org_api_keys_from_env(self):
41 - """The client resolves COMPOSIO_USER_API_KEY / COMPOSIO_ORG_API_KEY itself."""
44 + """The SDK resolves COMPOSIO_USER_API_KEY / COMPOSIO_ORG_API_KEY; the
45 + client reads no environment."""
46 with patch.dict(
47 os.environ,
48 {
@@ -48,8 +52,9 @@ class TestComposioSDK:
52 },
53 ):
54 sdk = Composio()
51 - assert sdk.client.user_api_key == "uak_env"
52 - assert sdk.client.org_api_key == "oak_env"
55 + assert sdk.client.sdk_auth == AutoAuth(
56 + project="ak_env", user="uak_env", organization="oak_env"
57 + )
58
59 def test_sdk_config_types(self):
60 """Test SDK configuration types."""
@@ -255,7 +260,7 @@ class TestUserOnlyInitialization:
260 base_url="https://backend.composio.dev",
261 http_client=http_client,
262 )
258 - assert sdk.client.api_key is None
263 + assert sdk.client.auth_mode == "user"
264 session = sdk.sessions.create(user_id="user_123", mcp=True)
265
266 assert "x-api-key" not in requests[0].headers
@@ -297,8 +302,7 @@ class TestUserOnlyInitialization:
302 ):
303 sdk = Composio(disable_api_key=True)
304
300 - assert sdk.client.api_key is None
301 - assert sdk.client.user_api_key == "uak_env"
305 + assert sdk.client.sdk_auth == UserAuth("uak_env")
306
307 def test_disable_without_a_user_key_raises(self):
308 with patch.dict(
@@ -307,18 +311,18 @@ class TestUserOnlyInitialization:
311 with pytest.raises(exceptions.UserApiKeyNotProvidedError):
312 Composio(disable_api_key=True)
313
310 - def test_disable_beside_a_raw_project_key_header_raises(self):
314 + def test_user_auth_beside_a_raw_project_key_header_raises(self):
315 + """The client owns the credential headers while ``auth`` holds a key."""
316 http_client, requests = _session_transport()
312 - with pytest.raises(exceptions.InvalidParams) as excinfo:
317 + with pytest.raises(ClientComposioError) as excinfo:
318 HttpClient(
319 provider="test",
315 - disable_api_key=True,
316 - user_api_key="uak_user_key",
320 + auth=UserAuth("uak_user_key"),
321 default_headers={"X-Api-Key": "ak_raw_header"},
322 http_client=http_client,
323 )
324
321 - assert "`X-Api-Key`" in str(excinfo.value)
325 + assert "`x-api-key`" in str(excinfo.value)
326 assert "ak_raw_header" not in str(excinfo.value)
327 assert requests == []
328
@@ -331,7 +335,7 @@ class TestUserOnlyInitialization:
335 http_client=http_client,
336 )
337
334 - with pytest.raises(exceptions.InvalidParams):
338 + with pytest.raises(ClientComposioError):
339 sdk.client.with_options(default_headers={"x-api-key": "ak_raw_header"})
340 sdk.sessions.create(user_id="user_123")
341
@@ -356,26 +360,218 @@ class TestUserOnlyInitialization:
360 Composio(api_key="ak_test", org_id="", project_id="proj_nano_xyz")
361
362 sdk = Composio(api_key="ak_test", org_id="", project_id="")
363 + assert sdk.client.scope is None
364 assert "x-org-id" not in sdk.client.default_headers
365 assert "x-project-id" not in sdk.client.default_headers
366
367 def test_omitted_api_key_keeps_the_environment_fallback(self):
368 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_env"}):
369 sdk = Composio(user_api_key="uak")
365 - assert sdk.client.api_key == "ak_env"
370 + assert sdk.client.sdk_auth == AutoAuth(project="ak_env", user="uak")
371
372 def test_client_clones_stay_user_only_when_the_environment_changes(self):
373 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
374 sdk = Composio(disable_api_key=True, user_api_key="uak_user_key")
375 clone = sdk.client.with_options(max_retries=0)
376
372 - assert (sdk.client.api_key, sdk.client.user_api_key) == (None, "uak_user_key")
373 - assert (clone.api_key, clone.user_api_key) == (None, "uak_user_key")
377 + assert sdk.client.sdk_auth == UserAuth("uak_user_key")
378 + assert clone.sdk_auth == UserAuth("uak_user_key")
379 + assert clone.auth_mode == "user"
380 assert clone.max_retries == 0
381
376 - def test_generated_client_keeps_its_environment_fallback_for_a_bare_none(self):
377 - """The SDK, not the generated client, turns the project key off."""
382 + def test_generated_client_reads_no_environment(self):
383 + """The SDK, not the generated client, resolves keys from the environment."""
384 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_env"}):
379 - client = composio_client.Composio(api_key=None, user_api_key="uak")
385 + client = composio_client.Composio(auth=UserAuth("uak"))
386 +
387 + assert client.auth_mode == "user"
388 +
389 +
390 +def _recording_transport() -> t.Tuple[httpx.Client, t.List[httpx.Request]]:
391 + requests: t.List[httpx.Request] = []
392 +
393 + def handler(request: httpx.Request) -> httpx.Response:
394 + requests.append(request)
395 + return httpx.Response(200, json={})
396 +
397 + return httpx.Client(transport=httpx.MockTransport(handler)), requests
398 +
399 +
400 +#: An operation that accepts the project key, one that accepts only a user key
401 +#: and one that accepts only an organization key.
402 +PROJECT_OP = "/api/v3.1/tools"
403 +USER_OP = "/api/v3.1/org/list"
404 +ORG_OP = "/api/v3.1/org/owner/project/list"
405 +
406 +CREDENTIAL_HEADERS = ("x-api-key", "x-user-api-key", "x-org-api-key")
407 +
408 +
409 +def _credentials_sent(sdk: Composio, path: str, requests: t.List[httpx.Request]):
410 + sdk.client.get(path, cast_to=dict)
411 + return {
412 + name: requests[-1].headers[name]
413 + for name in CREDENTIAL_HEADERS
414 + if name in requests[-1].headers
415 + }
416 +
417 +
418 +class TestAuthAndScopeMapping:
419 + """What the SDK resolves becomes the client's ``auth`` and ``scope``."""
420 +
421 + @pytest.fixture(autouse=True)
422 + def _isolated_environment(self):
423 + with patch.dict(os.environ, {}, clear=True):
424 + yield
425 +
426 + @pytest.mark.parametrize(
427 + ("config", "expected"),
428 + [
429 + ({"api_key": "ak"}, ProjectAuth("ak")),
430 + (
431 + {"api_key": "ak", "user_api_key": "uak"},
432 + AutoAuth(project="ak", user="uak"),
433 + ),
434 + (
435 + {"api_key": "ak", "org_api_key": "oak"},
436 + AutoAuth(project="ak", organization="oak"),
437 + ),
438 + (
439 + {"api_key": "ak", "user_api_key": "uak", "org_api_key": "oak"},
440 + AutoAuth(project="ak", user="uak", organization="oak"),
441 + ),
442 + ({"disable_api_key": True, "user_api_key": "uak"}, UserAuth("uak")),
443 + (
444 + {"disable_api_key": True, "user_api_key": "uak", "org_api_key": "oak"},
445 + UserAuth("uak"),
446 + ),
447 + # Empty keys count as unset, as the environment fallback always has.
448 + (
449 + {"api_key": "ak", "user_api_key": "", "org_api_key": ""},
450 + ProjectAuth("ak"),
451 + ),
452 + ],
453 + )
454 + def test_keys_map_to_auth(self, config, expected):
455 + sdk = Composio(**config)
456 +
457 + assert sdk.client.sdk_auth == expected
458 + assert sdk.client.auth_mode == expected.mode
459 +
460 + def test_environment_keys_map_to_auth(self):
461 + with patch.dict(
462 + os.environ,
463 + {"COMPOSIO_API_KEY": "ak_env", "COMPOSIO_ORG_API_KEY": "oak_env"},
464 + ):
465 + sdk = Composio()
466 +
467 + assert sdk.client.sdk_auth == AutoAuth(project="ak_env", organization="oak_env")
468 +
469 + def test_blank_environment_keys_count_as_unset(self):
470 + with patch.dict(
471 + os.environ,
472 + {
473 + "COMPOSIO_API_KEY": "ak_env",
474 + "COMPOSIO_USER_API_KEY": " ",
475 + "COMPOSIO_ORG_API_KEY": "",
476 + },
477 + ):
478 + sdk = Composio()
479 +
480 + assert sdk.client.sdk_auth == ProjectAuth("ak_env")
481 +
482 + def test_explicit_keys_win_over_the_environment(self):
483 + with patch.dict(
484 + os.environ,
485 + {"COMPOSIO_USER_API_KEY": "uak_env", "COMPOSIO_ORG_API_KEY": "oak_env"},
486 + ):
487 + sdk = Composio(api_key="ak", user_api_key="uak", org_api_key="oak")
488 +
489 + assert sdk.client.sdk_auth == AutoAuth(
490 + project="ak", user="uak", organization="oak"
491 + )
492 +
493 + def test_project_key_alone_is_sent_on_every_operation(self):
494 + http_client, requests = _recording_transport()
495 + sdk = Composio(api_key="ak", http_client=http_client)
496 +
497 + for path in (PROJECT_OP, USER_OP, ORG_OP):
498 + assert _credentials_sent(sdk, path, requests) == {"x-api-key": "ak"}
499 +
500 + def test_auto_auth_sends_exactly_one_credential_per_operation(self):
501 + http_client, requests = _recording_transport()
502 + sdk = Composio(
503 + api_key="ak", user_api_key="uak", org_api_key="oak", http_client=http_client
504 + )
505 +
506 + assert _credentials_sent(sdk, PROJECT_OP, requests) == {"x-api-key": "ak"}
507 + assert _credentials_sent(sdk, USER_OP, requests) == {"x-user-api-key": "uak"}
508 + assert _credentials_sent(sdk, ORG_OP, requests) == {"x-org-api-key": "oak"}
509 +
510 + def test_user_only_sends_the_user_key_on_every_operation(self):
511 + http_client, requests = _recording_transport()
512 + sdk = Composio(
513 + disable_api_key=True,
514 + user_api_key="uak",
515 + org_api_key="oak",
516 + http_client=http_client,
517 + )
518 +
519 + for path in (PROJECT_OP, USER_OP, ORG_OP):
520 + assert _credentials_sent(sdk, path, requests) == {"x-user-api-key": "uak"}
521 +
522 + def test_scope_ids_become_the_client_scope(self):
523 + http_client, requests = _recording_transport()
524 + sdk = Composio(
525 + api_key="ak",
526 + org_id="org_nano_abc",
527 + project_id="proj_nano_xyz",
528 + http_client=http_client,
529 + )
530 +
531 + assert sdk.client.scope == Scope(
532 + organization_id="org_nano_abc", project_id="proj_nano_xyz"
533 + )
534 + assert sdk.client.default_headers == {}
535 + sdk.client.get(PROJECT_OP, cast_to=dict)
536 + assert requests[0].headers["x-org-id"] == "org_nano_abc"
537 + assert requests[0].headers["x-project-id"] == "proj_nano_xyz"
538 +
539 + def test_scope_survives_a_clone(self):
540 + sdk = Composio(api_key="ak", org_id="org_nano_abc", project_id="proj_nano_xyz")
541 +
542 + clone = sdk.client.with_options(max_retries=0)
543 +
544 + assert clone.scope == sdk.client.scope
545 + assert clone.sdk_auth == ProjectAuth("ak")
546 +
547 + def test_no_scope_leaves_the_client_unscoped(self):
548 + http_client, requests = _recording_transport()
549 + sdk = Composio(api_key="ak", http_client=http_client)
550 +
551 + assert sdk.client.scope is None
552 + sdk.client.get(PROJECT_OP, cast_to=dict)
553 + assert "x-org-id" not in requests[0].headers
554 + assert "x-project-id" not in requests[0].headers
555 +
556 + def test_custom_headers_from_the_environment_are_still_sent(self):
557 + http_client, requests = _recording_transport()
558 + with patch.dict(
559 + os.environ, {"COMPOSIO_CUSTOM_HEADERS": "x-trace: abc\nx-team: core "}
560 + ):
561 + sdk = Composio(api_key="ak", http_client=http_client)
562 +
563 + sdk.client.get(PROJECT_OP, cast_to=dict)
564 + assert requests[0].headers["x-trace"] == "abc"
565 + assert requests[0].headers["x-team"] == "core"
566 +
567 + def test_every_api_request_carries_a_request_id(self):
568 + http_client, requests = _recording_transport()
569 + sdk = Composio(api_key="ak", http_client=http_client)
570 +
571 + sdk.client.get(PROJECT_OP, cast_to=dict)
572 + sdk.client.get(PROJECT_OP, cast_to=dict)
573 + sdk.client.get("https://storage.invalid/file", cast_to=dict)
574
381 - assert (client.api_key, client.user_api_key) == ("ak_env", "uak")
575 + first, second, foreign = (r.headers.get("x-request-id") for r in requests)
576 + assert first and second and first != second
577 + assert foreign is None
python/tests/test_tool_execution.py
+2 -3
@@ -6,7 +6,7 @@ from unittest.mock import Mock, patch
6
7 import httpx
8 import pytest
9 -from composio_client import omit
9 +from composio_client import ProjectAuth, omit
10 from pydantic import BaseModel, Field, RootModel
11
12 from composio.client import HttpClient
@@ -1477,10 +1477,9 @@ class TestSerializeArguments:
1477 with httpx.Client(transport=httpx.MockTransport(respond)) as transport:
1478 client = HttpClient(
1479 provider="openai",
1480 - api_key="test-key",
1480 + auth=ProjectAuth("test-key"),
1481 base_url="https://composio.invalid",
1482 http_client=transport,
1483 - _environment_variables={},
1483 )
1484 tools = Tools(client=client, provider=OpenAIProvider())
1485 result = tools.execute(
python/tests/test_tool_router.py
+68 -42
@@ -9,7 +9,17 @@ from unittest.mock import MagicMock, patch
9
10 import httpx
11 import pytest
12 -from composio_client import ConflictError, omit
12 +from composio_client import (
13 + Auth,
14 + AutoAuth,
15 + ConflictError,
16 + NoAuth,
17 + ProjectAuth,
18 + Scope,
19 + UserAuth,
20 + omit,
21 +)
22 +from composio_client import ComposioError as ClientComposioError
23 from composio_client.types.tool_router.session_search_response import (
24 SessionSearchResponse,
25 )
@@ -58,8 +68,8 @@ class GrepInput(BaseModel):
68 def mock_client():
69 """Create a mock HTTP client."""
70 client = mock_http_client(MagicMock)
61 - client.api_key = "test-api-key"
62 - client.user_api_key = None
71 + client.sdk_auth = ProjectAuth("test-api-key")
72 + client.scope = None
73 client.base_url = httpx.URL("https://backend.composio.dev")
74 client.default_headers = {}
75
@@ -311,7 +321,7 @@ class TestToolRouter:
321
322 client = HttpClient(
323 provider="test",
314 - api_key="sk-test",
324 + auth=ProjectAuth("sk-test"),
325 base_url="https://backend.invalid",
326 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
327 )
@@ -2366,7 +2376,7 @@ class TestInstantContractTransport:
2376 )
2377 def test_create_and_patch_send_new_policy(self, policy):
2378 client, requests = _transport_client(
2369 - api_key="ak_test", base_url="https://backend.composio.dev"
2379 + auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev"
2380 )
2381 router = ToolRouter(client=client, provider=MagicMock())
2382 session = router.create(user_id="user_123", instant=policy)
@@ -2420,7 +2430,7 @@ class TestInstantContractTransport:
2430
2431 client = HttpClient(
2432 provider="test",
2423 - api_key="ak_test",
2433 + auth=ProjectAuth("ak_test"),
2434 base_url="https://backend.composio.dev",
2435 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2436 )
@@ -2453,7 +2463,7 @@ class TestInstantContractTransport:
2463
2464 client = HttpClient(
2465 provider="test",
2456 - api_key="ak_test",
2466 + auth=ProjectAuth("ak_test"),
2467 base_url="https://backend.composio.dev",
2468 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2469 )
@@ -2509,7 +2519,7 @@ def _answering_client(
2519
2520 client = HttpClient(
2521 provider="test",
2512 - api_key="ak_test",
2522 + auth=ProjectAuth("ak_test"),
2523 base_url="https://backend.composio.dev",
2524 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2525 )
@@ -2584,7 +2594,7 @@ class TestApprovalRules:
2594
2595 def test_create_sends_approval_lists_and_fallback(self):
2596 client, requests = _transport_client(
2587 - api_key="ak_test", base_url="https://backend.composio.dev"
2597 + auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev"
2598 )
2599
2600 ToolRouter(client=client, provider=MagicMock()).create(
@@ -2626,7 +2636,7 @@ class TestApprovalRules:
2636
2637 def test_update_sends_approval_lists_and_fallback(self):
2638 client, requests = _transport_client(
2629 - api_key="ak_test", base_url="https://backend.composio.dev"
2639 + auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev"
2640 )
2641 session = ToolRouter(client=client, provider=MagicMock()).create(
2642 user_id="user_123"
@@ -3065,10 +3075,9 @@ def _session_tool_execute_fn(client: HttpClient) -> t.Callable[..., t.Any]:
3075
3076 def _transport_client(
3077 *,
3068 - api_key: t.Optional[str],
3078 + auth: Auth,
3079 base_url: str,
3070 - disable_api_key: bool = False,
3071 - user_api_key: t.Optional[str] = None,
3080 + scope: t.Optional[Scope] = None,
3081 default_headers: t.Optional[t.Dict[str, str]] = None,
3082 mcp_url: str = MCP_SAME_ORIGIN_URL,
3083 ) -> t.Tuple[HttpClient, t.List[httpx.Request]]:
@@ -3080,9 +3089,8 @@ def _transport_client(
3089
3090 client = HttpClient(
3091 provider="test",
3083 - api_key=api_key,
3084 - disable_api_key=disable_api_key,
3085 - user_api_key=user_api_key,
3092 + auth=auth,
3093 + scope=scope,
3094 base_url=base_url,
3095 default_headers=default_headers,
3096 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
@@ -3096,7 +3104,7 @@ class TestMcpAuthContext:
3104 def test_project_key_session_exports_only_the_project_key(self):
3105 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
3106 client, requests = _transport_client(
3099 - api_key="ak_project_key",
3107 + auth=ProjectAuth("ak_project_key"),
3108 base_url="https://backend.composio.dev",
3109 default_headers={"x-request-id": "req-1"},
3110 )
@@ -3110,9 +3118,7 @@ class TestMcpAuthContext:
3118 def test_user_key_option_session_exports_only_the_user_key(self):
3119 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
3120 client, requests = _transport_client(
3113 - api_key=None,
3114 - disable_api_key=True,
3115 - user_api_key="uak_user_key",
3121 + auth=UserAuth("uak_user_key"),
3122 base_url="https://backend.composio.dev",
3123 default_headers={"x-request-id": "r"},
3124 )
@@ -3125,10 +3131,10 @@ class TestMcpAuthContext:
3131 assert session.mcp.headers == {"x-user-api-key": "uak_user_key"}
3132
3133 def test_user_key_header_session_exports_only_the_user_key(self):
3134 + """Under ``NoAuth`` a caller-placed user key header is the credential."""
3135 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}):
3136 client, requests = _transport_client(
3130 - api_key=None,
3131 - disable_api_key=True,
3137 + auth=NoAuth(),
3138 base_url="https://backend.composio.dev",
3139 default_headers={"x-user-api-key": "uak_user_key", "x-request-id": "r"},
3140 )
@@ -3142,15 +3148,10 @@ class TestMcpAuthContext:
3148
3149 def test_scope_headers_are_exported_with_the_user_key(self):
3150 client, requests = _transport_client(
3145 - api_key=None,
3146 - disable_api_key=True,
3147 - user_api_key="uak_user_key",
3151 + auth=UserAuth("uak_user_key"),
3152 + scope=Scope(organization_id="org_nano_abc", project_id="proj_nano_xyz"),
3153 base_url="https://backend.composio.dev",
3149 - default_headers={
3150 - "x-org-id": "org_nano_abc",
3151 - "x-project-id": "proj_nano_xyz",
3152 - "x-request-id": "r",
3153 - },
3154 + default_headers={"x-request-id": "r"},
3155 )
3156 session = ToolRouter(client=client, provider=MagicMock()).use(
3157 "session_123", mcp=True
@@ -3167,8 +3168,7 @@ class TestMcpAuthContext:
3168 def test_retrieve_preserves_the_user_key_after_environment_changes(self):
3169 with patch.dict(os.environ, {}, clear=True):
3170 client, requests = _transport_client(
3170 - api_key=None,
3171 - disable_api_key=True,
3171 + auth=NoAuth(),
3172 base_url="https://backend.composio.dev",
3173 default_headers={"X-User-Api-Key": "uak_user_key"},
3174 )
@@ -3183,7 +3183,7 @@ class TestMcpAuthContext:
3183 def test_no_credential_exports_no_headers_without_reading_the_environment(
3184 self, tool_router, mock_client
3185 ):
3186 - mock_client.api_key = None
3186 + mock_client.sdk_auth = NoAuth()
3187 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_ambient"}):
3188 session = tool_router.create(user_id="user_123", mcp=True)
3189
@@ -3263,23 +3263,49 @@ class TestMcpAuthContext:
3263 assert "The MCP URL has an opaque origin" in caplog.text
3264 assert "test-api-key" not in caplog.text
3265
3266 - def test_user_key_default_header_wins_over_the_configured_project_key(self):
3266 + def test_user_key_default_header_beside_a_project_key_is_refused(self):
3267 + """A second credential next to ``auth`` cannot be configured at all, so
3268 + the request and the MCP export can never disagree about it."""
3269 + with pytest.raises(ClientComposioError, match="`x-user-api-key`"):
3270 + _transport_client(
3271 + auth=ProjectAuth("ak_project_key"),
3272 + base_url="https://backend.composio.dev",
3273 + default_headers={"x-user-api-key": "uak_header_key"},
3274 + )
3275 +
3276 + def test_project_key_beside_a_user_key_exports_the_project_key(self):
3277 client, requests = _transport_client(
3268 - api_key="ak_project_key",
3278 + auth=AutoAuth(project="ak_project_key", user="uak_user_key"),
3279 base_url="https://backend.composio.dev",
3270 - default_headers={"x-user-api-key": "uak_header_key"},
3280 )
3281 session = ToolRouter(client=client, provider=MagicMock()).create(
3282 user_id="user_123", mcp=True
3283 )
3284
3276 - assert "x-api-key" not in requests[0].headers
3277 - assert requests[0].headers["x-user-api-key"] == "uak_header_key"
3278 - assert session.mcp.headers == {"x-user-api-key": "uak_header_key"}
3285 + assert requests[0].headers["x-api-key"] == "ak_project_key"
3286 + assert "x-user-api-key" not in requests[0].headers
3287 + assert session.mcp.headers == {"x-api-key": "ak_project_key"}
3288 +
3289 + def test_scope_without_an_organization_exports_only_the_project_id(self):
3290 + client, requests = _transport_client(
3291 + auth=UserAuth("uak_user_key"),
3292 + scope=Scope(project_id="proj_nano_xyz"),
3293 + base_url="https://backend.composio.dev",
3294 + )
3295 + session = ToolRouter(client=client, provider=MagicMock()).create(
3296 + user_id="user_123", mcp=True
3297 + )
3298 +
3299 + assert "x-org-id" not in requests[0].headers
3300 + assert requests[0].headers["x-project-id"] == "proj_nano_xyz"
3301 + assert session.mcp.headers == {
3302 + "x-user-api-key": "uak_user_key",
3303 + "x-project-id": "proj_nano_xyz",
3304 + }
3305
3306 def test_invalid_port_in_mcp_url_raises_the_typed_error(self):
3307 client, _ = _transport_client(
3282 - api_key="ak_project_key",
3308 + auth=ProjectAuth("ak_project_key"),
3309 base_url="https://backend.composio.dev",
3310 mcp_url="https://backend.composio.dev:bad/mcp",
3311 )
@@ -3292,7 +3318,7 @@ class TestMcpAuthContext:
3318
3319 def test_malformed_mcp_url_is_not_echoed_in_the_error(self):
3320 client, _ = _transport_client(
3295 - api_key="ak_project_key",
3321 + auth=ProjectAuth("ak_project_key"),
3322 base_url="https://backend.composio.dev",
3323 mcp_url="not-a-url?token=secret_value",
3324 )
@@ -3313,7 +3339,7 @@ class TestMcpAuthContext:
3339
3340 def test_same_origin_plain_http_base_url_exports_credentials(self):
3341 client, requests = _transport_client(
3316 - api_key="ak_project_key",
3342 + auth=ProjectAuth("ak_project_key"),
3343 base_url="http://localhost:3000",
3344 mcp_url="http://localhost:3000/api/v3/tool_router/session/session_123/mcp",
3345 )
python/tests/test_tool_router_session_files.py
+2 -1
@@ -5,6 +5,7 @@ from unittest.mock import MagicMock, patch
5
6 import pytest
7 import requests
8 +from composio_client import ProjectAuth
9
10 from composio.core.models.tool_router_session_files import (
11 RemoteFile,
@@ -44,7 +45,7 @@ def mock_stream_response(
45 def mock_client():
46 """Create a mock HTTP client with files API."""
47 client = MagicMock()
47 - client.api_key = "test-api-key"
48 + client.sdk_auth = ProjectAuth("test-api-key")
49
50 # Mock files.list
51 mock_list_response = MagicMock()
python/tests/test_tools_proxy.py
+2 -1
@@ -6,6 +6,7 @@ from unittest.mock import Mock
6
7 import httpx
8 import pytest
9 +from composio_client import ProjectAuth
10
11 from composio.client import HttpClient
12 from composio.core.models.base import allow_tracking
@@ -28,7 +29,7 @@ def _proxy_body(**kwargs: t.Any) -> t.Dict[str, t.Any]:
29
30 client = HttpClient(
31 provider="test",
31 - api_key="sk-test",
32 + auth=ProjectAuth("sk-test"),
33 base_url="https://backend.invalid",
34 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
35 )
python/tests/test_triggers.py
+6 -9
@@ -14,7 +14,7 @@ from unittest.mock import Mock, patch
14 import httpx
15 import pytest
16 import requests
17 -from composio_client import NotFoundError, omit
17 +from composio_client import NoAuth, NotFoundError, ProjectAuth, UserAuth, omit
18
19 from composio import exceptions
20 from composio.core.models import triggers as triggers_module
@@ -2183,7 +2183,7 @@ class TestPusherClusterValidation:
2183 def _builder() -> _SubcriptionBuilder:
2184 client = Mock()
2185 client.base_url = "https://api.example.com"
2186 - client.api_key = "sk-secret-value"
2186 + client.sdk_auth = ProjectAuth("sk-secret-value")
2187 return _SubcriptionBuilder(client=client)
2188
2189 @pytest.mark.parametrize("cluster", ["mt1", "eu", "ap-southeast-1", "us3"])
@@ -2197,8 +2197,7 @@ class TestPusherClusterValidation:
2197 def test_user_only_client_authorizes_the_channel_with_the_user_key(self):
2198 client = Mock()
2199 client.base_url = "https://api.example.com"
2200 - client.api_key = None
2201 - client.user_api_key = "uak_user_key"
2200 + client.sdk_auth = UserAuth("uak_user_key")
2201 client.default_headers = {}
2202
2203 pusher = _SubcriptionBuilder(client=client)._get_pusher_instance(
@@ -2208,13 +2207,11 @@ class TestPusherClusterValidation:
2207 assert "x-api-key" not in pusher.auth_endpoint_headers
2208 assert pusher.auth_endpoint_headers["x-user-api-key"] == "uak_user_key"
2209
2211 - def test_user_key_default_header_authorizes_the_channel_over_the_project_key(
2212 - self,
2213 - ):
2210 + def test_user_key_default_header_authorizes_the_channel_without_auth(self):
2211 + """Under ``NoAuth`` a caller-placed user key header is the credential."""
2212 client = Mock()
2213 client.base_url = "https://api.example.com"
2216 - client.api_key = "sk-secret-value"
2217 - client.user_api_key = None
2214 + client.sdk_auth = NoAuth()
2215 client.default_headers = {"X-User-Api-Key": "uak_header_key"}
2216
2217 pusher = _SubcriptionBuilder(client=client)._get_pusher_instance(
ts/packages/cli/AGENTS.md
+13 -13
@@ -106,18 +106,18 @@ test/src/commands/<group>/<shared-module>.test.ts group helper
106
107 ### Services — `src/services/`
108
109 -| Service | Purpose |
110 -| ---------------------------------- | ---------------------------------------------------------------------------------------------- |
111 -| `ComposioUserContext` | Auth state — reads/writes `~/.composio/user-config.json`, merges env vars |
112 -| `ComposioClientSingleton` | Builds and caches `@composio/client/effect` clients per key, org, and project; counts requests |
113 -| `ComposioSessionRepository` | Creates OAuth2 sessions, polls until `linked` state |
114 -| `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
115 -| `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
116 -| `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |
117 -| `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
118 -| `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
119 -
120 -Every Composio API request goes through an Effect client from `@composio/client/effect`, obtained from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `make`, which never reads the ambient environment: the user key and base URL come from the CLI's own configuration. Each client is built with `deprecationNotices: 'off'`, the CLI's `identity` (`cliClientIdentity()` in `client-provenance.ts`, from which the client sends the provenance headers and which makes it refuse them in `defaultHeaders` and per-call `headers`), the CLI's own `defaultHeaders` (`x-user-api-key`, plus `x-org-id`/`x-project-id` when both are known), and a counting `fetch` (`composio-client-metrics.ts`) provided as the transport's `FetchHttpClient.Fetch`. Explicitly configured HTTP base URLs remain supported without an additional environment flag. `composio-clients.ts` holds client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `validated` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure and continue with a fallback share one handler, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; the tag list lives in `src/services/composio-errors.ts`. Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. The CLI's clients send every request once. A call that is safe to repeat — a read, or a call whose repeat changes nothing on the server — passes the `idempotent` request option (`src/services/composio-request.ts`) and is retried by the client after a connection failure, a timeout, or a 408, 409, 429 or 5xx response; combine it with `validated` as `{ ...idempotent, ...validated }`. Creates, updates, deletes, links, sessions, tool executions and proxied calls never pass it, because a request that failed in flight may already have acted. It also rejects importing `make` or the client layers from `@composio/client/effect` anywhere but `composio-clients.ts`, and `getFor` takes an org and a project together or neither, because the two headers are only sent as a pair. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
109 +| Service | Purpose |
110 +| ---------------------------------- | -------------------------------------------------------------------------------------------------- |
111 +| `ComposioUserContext` | Auth state — reads/writes `~/.composio/user-config.json`, merges env vars |
112 +| `ComposioClientSingleton` | Builds an `@composio/client/effect` client per lookup for a key, org, and project; counts requests |
113 +| `ComposioSessionRepository` | Creates OAuth2 sessions, polls until `linked` state |
114 +| `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
115 +| `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
116 +| `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |
117 +| `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
118 +| `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
119 +
120 +Every Composio API request goes through an Effect client from `@composio/client/effect`, obtained from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `make`, which never reads the ambient environment: the user key and base URL come from the CLI's own configuration. Each client is built with `deprecationNotices: 'off'`, the CLI's `identity` (`cliClientIdentity()` in `client-provenance.ts`, from which the client sends the provenance headers and which makes it refuse them in `defaultHeaders` and per-call `headers`), `auth` (`Auth.user` with the user key, `Auth.project` when a caller passes `projectApiKey`, `Auth.none()` before login), `scope` (the org and project, when both are known), `x-cli-session-id` as the one default header (read once per process), and a counting `fetch` (`composio-client-metrics.ts`) provided as the transport's `FetchHttpClient.Fetch`. Explicitly configured HTTP base URLs remain supported without an additional environment flag. `composio-clients.ts` holds client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `validated` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure and continue with a fallback share one handler, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; the tag list lives in `src/services/composio-errors.ts`. Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. The CLI's clients send every request once. A call that is safe to repeat — a read, or a call whose repeat changes nothing on the server — passes the `idempotent` request option (`src/services/composio-request.ts`) and is retried by the client after a connection failure, a timeout, or a 408, 409, 429 or 5xx response; combine it with `validated` as `{ ...idempotent, ...validated }`. Creates, updates, deletes, links, sessions, tool executions and proxied calls never pass it, because a request that failed in flight may already have acted. It also rejects importing `make` or the client layers from `@composio/client/effect` anywhere but `composio-clients.ts`, and `getFor` takes an org and a project together or neither, because the two headers are only sent as a pair. Every `getFor` builds a new client, so never key a memo on a client instance: `clientScopeKey(client)` gives its auth mode, org, and project (`listActiveConnectedAccounts` keys on it and the user id). While a client has `auth` and `scope`, a per-call `x-api-key`, `x-user-api-key`, `x-org-api-key`, `x-org-id` or `x-project-id` header fails the call before it is sent; an org or project known alone goes on an unscoped client's request, as `orgScopedOptions` and `getLatestToolVersion` do. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
121
122 Services are `Context.Service` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
123
@@ -153,7 +153,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
153
154 ### Key Dependencies
155
156 -`effect` (pinned `4.0.3`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.17` via the workspace catalog; the CLI calls it through the `@composio/client/effect` entry point and imports only types from the rest of the package), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
156 +`effect` (pinned `4.0.3`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.18` via the workspace catalog; the CLI calls it through the `@composio/client/effect` entry point and imports only types from the rest of the package), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
157
158 ## Output Conventions: Composable CLI Output
159
ts/packages/cli/CHANGELOG.md
+9
@@ -11,6 +11,15 @@
11 developer project, an incomplete link response, a toolkit whose auth
12 Composio does not manage, and the waiting and timeout lines shown while a
13 link is pending. Exit codes and the JSON printed on stdout are unchanged.
14 +- The CLI now uses `@composio/client@2.0.0-rc.18` (up from `2.0.0-rc.17`). No
15 + command changes.
16 +- API requests now authenticate through the API client's `auth` option (the
17 + logged-in user's API key, or no credential before login) and name the org and
18 + project through its `scope`, instead of the CLI placing `x-user-api-key`,
19 + `x-org-id` and `x-project-id` in default headers. The headers sent are
20 + unchanged. The CLI no longer keeps a client per API key and project for the
21 + life of the process, so the user API key is held only by the client making
22 + the request.
23
24 ## 0.4.5
25
ts/packages/cli/src/services/composio-account.ts
+16 -12
@@ -291,8 +291,8 @@ export const resolveConsumerProject = (params: {
291
292 /**
293 * Resolves the latest version of a tool. When `projectApiKey` is given the
294 - * request carries `x-api-key` instead of the user key, so exactly one
295 - * credential is sent.
294 + * request is sent by a client that authenticates with it instead of the user
295 + * key, so exactly one credential is sent.
296 */
297 export const getLatestToolVersion = (params: {
298 apiKey: string;
@@ -303,19 +303,23 @@ export const getLatestToolVersion = (params: {
303 }): Effect.Effect<LatestToolVersionResponse, ClientError, ComposioClientSingleton> =>
304 Effect.gen(function* () {
305 const clientSingleton = yield* ComposioClientSingleton;
306 - const headers = {
307 - ...(params.projectApiKey
308 - ? { 'x-api-key': params.projectApiKey, 'x-user-api-key': null }
309 - : {}),
310 - ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
311 - ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
312 - };
313 - // The headers above carry whichever of the org and project is known.
306 + const credential = params.projectApiKey
307 + ? { projectApiKey: params.projectApiKey }
308 + : { userApiKey: params.apiKey };
309 + // A client's scope names the org and the project together; when only one
310 + // of them is known it goes on the request, which an unscoped client allows.
311 const client = yield* clientSingleton.getFor(
312 params.orgId && params.projectId
316 - ? { userApiKey: params.apiKey, orgId: params.orgId, projectId: params.projectId }
317 - : { userApiKey: params.apiKey }
313 + ? { ...credential, orgId: params.orgId, projectId: params.projectId }
314 + : credential
315 );
316 + const headers =
317 + params.orgId && params.projectId
318 + ? undefined
319 + : {
320 + ...(params.orgId ? { 'x-org-id': params.orgId } : {}),
321 + ...(params.projectId ? { 'x-project-id': params.projectId } : {}),
322 + };
323 const payload = yield* client.get(
324 `/api/v3/tools/${encodeURIComponent(params.toolSlug)}/get_latest_version`,
325 { headers, ...idempotent }
ts/packages/cli/src/services/composio-clients.ts
+76 -87
@@ -1,21 +1,11 @@
1 -import {
2 - Cache,
3 - Context,
4 - Duration,
5 - Effect,
6 - Exit,
7 - Layer,
8 - Option,
9 - Stream,
10 - Array,
11 - Order,
12 -} from 'effect';
1 +import { Context, Effect, Layer, Option, Stream, Array, Order } from 'effect';
2 import * as Str from 'effect/String';
3 import type { Cause } from 'effect';
4 import { FetchHttpClient, HttpClient } from 'effect/http';
5 import {
6 // eslint-disable-next-line no-restricted-imports -- this module is the one place the client is built
7 make as makeComposioClient,
8 + Auth,
9 type ComposioClientShape,
10 type ConfigurationError,
11 } from '@composio/client/effect';
@@ -87,39 +77,23 @@ const sortBySlug = <T extends { readonly slug: string }>(
77 const normalizeApiKey = (rawApiKey?: string): string | undefined =>
78 typeof rawApiKey === 'string' && rawApiKey.trim().length > 0 ? rawApiKey : undefined;
79
90 -const buildDefaultHeaders = (params: {
91 - userApiKey?: string;
92 - orgId?: string;
93 - projectId?: string;
94 - cliSessionId?: string;
95 -}): Record<string, string> | undefined => {
96 - // The identity headers come from the client's `identity`, which refuses them here.
97 - const defaultHeaders = {
98 - ...(params.userApiKey
99 - ? ({ 'x-user-api-key': params.userApiKey } satisfies Record<string, string>)
100 - : {}),
101 - ...(params.orgId && params.projectId
102 - ? ({
103 - 'x-org-id': params.orgId,
104 - 'x-project-id': params.projectId,
105 - } satisfies Record<string, string>)
106 - : {}),
107 - ...(params.cliSessionId
108 - ? ({ 'x-cli-session-id': params.cliSessionId } satisfies Record<string, string>)
109 - : {}),
110 - };
111 -
112 - return defaultHeaders;
113 -};
80 +/**
81 + * Which key a client sends: the user's (`userApiKey`, defaulting to the
82 + * logged-in user's), or a project key in its place.
83 + */
84 +type ClientCredential =
85 + | { readonly userApiKey?: string; readonly projectApiKey?: undefined }
86 + | { readonly projectApiKey: string; readonly userApiKey?: undefined };
87
88 /**
89 * Whose requests a client sends. The org and project headers are only sent
90 * together, so a scope names both or neither.
91 */
119 -export type ClientScope = { readonly userApiKey?: string } & (
120 - | { readonly orgId: string; readonly projectId: string }
121 - | { readonly orgId?: undefined; readonly projectId?: undefined }
122 -);
92 +export type ClientScope = ClientCredential &
93 + (
94 + | { readonly orgId: string; readonly projectId: string }
95 + | { readonly orgId?: undefined; readonly projectId?: undefined }
96 + );
97
98 /**
99 * Shape exposed by {@link ComposioClientSingleton}.
@@ -131,7 +105,8 @@ export interface ComposioClientSingletonShape {
105 */
106 readonly get: () => Effect.Effect<ComposioClientShape, ClientBuildError | NoSuchElementError>;
107 /**
134 - * The client for an explicit scope. `userApiKey` defaults to the user's key.
108 + * The client for an explicit scope. `userApiKey` defaults to the user's key;
109 + * a `projectApiKey` is sent instead of any user key.
110 */
111 readonly getFor: (
112 params: ClientScope
@@ -152,16 +127,25 @@ export interface ComposioClientSingletonShape {
127 */
128 export type ClientBuildError = ConfigurationError | ComposioClientConfigurationError;
129
130 +// What each client built here addresses: its auth mode, org, and project, never
131 +// its key. `getFor` builds a new client on every call, so a memo over a
132 +// client's reads keys on this rather than on the instance.
133 +const clientScopeKeys = new WeakMap<ComposioClientShape, string>();
134 +let nextUnscopedClient = 0;
135 +
136 /**
156 - * The scope a client is built for, with the user key resolved. A plain record
157 - * is compared and hashed structurally by `Equal` and `Hash`, so two lookups
158 - * with the same fields resolve to the same cache entry.
137 + * A memo key for what `client` addresses. Two clients from
138 + * {@link ComposioClientSingleton} with the same auth mode, org, and project
139 + * share it; a client built anywhere else (a test double) gets one of its own.
140 */
160 -interface ResolvedClientScope {
161 - readonly userApiKey: string | undefined;
162 - readonly orgId: string | undefined;
163 - readonly projectId: string | undefined;
164 -}
141 +export const clientScopeKey = (client: ComposioClientShape): string => {
142 + let key = clientScopeKeys.get(client);
143 + if (key === undefined) {
144 + key = `instance:${nextUnscopedClient++}`;
145 + clientScopeKeys.set(client, key);
146 + }
147 + return key;
148 +};
149
150 /**
151 * Singleton service that lazily accesses `Config` only when needed, which is used to build and provide
@@ -169,10 +153,15 @@ interface ResolvedClientScope {
153 *
154 * Clients are built with `make`, which never consults the ambient process
155 * environment: every credential and the base URL come from the CLI's own
172 - * configuration. Custom HTTP base URLs remain supported. The user key is
173 - * placed in `defaultHeaders` as `x-user-api-key`, which keeps today's wire
174 - * bytes on every operation; it is also passed as `userApiKey`, while the
175 - * caller-placed header still wins at dispatch.
156 + * configuration. Custom HTTP base URLs remain supported. A client
157 + * authenticates with `Auth.user` and the user key, with `Auth.project` when a
158 + * caller names a project key, and with `Auth.none()` before anyone has logged
159 + * in; the org and project go in its `scope`. No credential or scope header is
160 + * placed in `defaultHeaders`, which the client refuses while `auth` and
161 + * `scope` own them.
162 + *
163 + * Every lookup builds a new client (`make` costs a few microseconds), so no
164 + * credential is held anywhere but in the client a caller is using.
165 */
166 const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
167 Effect.gen(function* () {
@@ -180,30 +169,49 @@ const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
169 const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
170 const httpClient = yield* HttpClient.HttpClient;
171
183 - const buildClient = (scope: ResolvedClientScope) =>
184 - Effect.gen(function* () {
185 - const cliSessionId = yield* getCurrentCwdSessionId();
172 + // Read from disk once per process, with the services captured here.
173 + const sessionIdServices =
174 + yield* Effect.context<Effect.Services<ReturnType<typeof getCurrentCwdSessionId>>>();
175 + const currentCwdSessionId = yield* Effect.cached(
176 + getCurrentCwdSessionId().pipe(Effect.provideContext(sessionIdServices))
177 + );
178
187 - return yield* Effect.try({
179 + // `ctx.data` is read per call: a login or logout changes the user key.
180 + const getFor = (params?: ClientScope) =>
181 + Effect.gen(function* () {
182 + const cliSessionId = yield* currentCwdSessionId;
183 + const userApiKey = normalizeApiKey(
184 + params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)
185 + );
186 + const auth =
187 + params?.projectApiKey !== undefined
188 + ? Auth.project(params.projectApiKey)
189 + : userApiKey !== undefined
190 + ? Auth.user(userApiKey)
191 + : Auth.none();
192 + const orgId = params?.orgId;
193 + const projectId = params?.projectId;
194 +
195 + const client = yield* Effect.try({
196 try: () =>
197 // A call that passes `decode: true` has its response validated
198 // against the client's schema for that operation.
199 makeComposioClient(
200 {
193 - apiKey: null,
194 - userApiKey: scope.userApiKey ?? null,
195 - orgApiKey: null,
201 + auth,
202 + scope:
203 + orgId !== undefined && projectId !== undefined
204 + ? { organizationId: orgId, projectId }
205 + : undefined,
206 baseURL: ctx.data.baseURL,
207 // Preserve support for explicitly configured HTTP backends.
208 allowInsecureHTTP: true,
209 deprecationNotices: 'off',
210 + // The identity headers come from here; the client refuses them
211 + // in `defaultHeaders`.
212 identity: cliClientIdentity(),
201 - defaultHeaders: buildDefaultHeaders({
202 - userApiKey: scope.userApiKey,
203 - orgId: scope.orgId,
204 - projectId: scope.projectId,
205 - cliSessionId,
206 - }),
213 + defaultHeaders:
214 + cliSessionId !== undefined ? { 'x-cli-session-id': cliSessionId } : undefined,
215 // Only a call that passes `idempotent` is retried.
216 maxRetries: 0,
217 schemas: schemaLoaders,
@@ -220,29 +228,10 @@ const makeComposioClientSingleton = (metrics: ClientMetricsCollector) =>
228 cause,
229 }),
230 });
231 + clientScopeKeys.set(client, `${auth.mode}\u0000${orgId ?? ''}\u0000${projectId ?? ''}`);
232 + return client;
233 });
234
225 - // One client per scope, built once: concurrent first callers share the
226 - // in-flight build. The lookup reads the session id from disk with the
227 - // services captured here. A failed build is not kept (its entry's time to
228 - // live is zero), so the next caller builds again instead of replaying a
229 - // configuration error that a later login may have fixed.
230 - const clients = yield* Cache.makeWith(buildClient, {
231 - capacity: 64,
232 - timeToLive: exit => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
233 - });
234 -
235 - // `ctx.data` is read per call: a login or logout changes the user key,
236 - // and with it the scope.
237 - const getFor = (params?: ClientScope) =>
238 - Effect.suspend(() =>
239 - Cache.get(clients, {
240 - userApiKey: normalizeApiKey(params?.userApiKey ?? Option.getOrUndefined(ctx.data.apiKey)),
241 - orgId: params?.orgId,
242 - projectId: params?.projectId,
243 - })
244 - );
245 -
235 return {
236 get: Effect.fn(function* () {
237 const resolvedProjectContext = yield* Option.match(projectContextOpt, {
ts/packages/cli/src/services/connected-account-selection.ts
+6 -17
@@ -5,6 +5,7 @@ import { decodeConnectedAccountItems } from 'src/effects/decode-connected-accoun
5 import type { TerminalUI } from 'src/services/terminal-ui';
6 import { memoizeInProcess } from 'src/utils/memoize-in-process';
7 import { idempotent } from 'src/services/composio-request';
8 +import { clientScopeKey } from 'src/services/composio-clients';
9
10 // `status` is an open enum, so this is shape-identical to
11 // `ConnectedAccountItem`; tool-router rows normalize statuses outside the
@@ -139,23 +140,11 @@ export const formatConnectedAccountChoices = (
140 ): ReadonlyArray<string> =>
141 items.filter(isUsableConnectedAccount).sort(compareNewestFirst).map(formatConnectedAccountChoice);
142
142 -// Clients come from `ComposioClientSingleton`, one instance per
143 -// org/project, so identity is a sound cache key. Ids instead of the object
144 -// itself keep the memo key a string.
145 -const clientIds = new WeakMap<ComposioClientShape, number>();
146 -let nextClientId = 0;
147 -const clientId = (client: ComposioClientShape): number => {
148 - let id = clientIds.get(client);
149 - if (id === undefined) {
150 - id = nextClientId++;
151 - clientIds.set(client, id);
152 - }
153 - return id;
154 -};
155 -
143 /**
157 - * Every active connected account of `userId`, fetched once per client and
158 - * user for the lifetime of the process.
144 + * Every active connected account of `userId`, fetched once per org, project,
145 + * and user for the lifetime of the process. The client's org and project come
146 + * from `clientScopeKey`: each `getFor` builds a new client, so two callers
147 + * holding different instances for the same project still share one fetch.
148 *
149 * `composio execute` needs this list twice on every call, from two code paths
150 * that cannot see each other: `resolveConnectedAccountForToolkit` picks the
@@ -172,7 +161,7 @@ const ACTIVE_ACCOUNTS_PAGE_SIZE = 1000;
161
162 export const listActiveConnectedAccounts = memoizeInProcess({
163 keyOf: (input: { readonly client: ComposioClientShape; readonly userId: string }) =>
175 - `${clientId(input.client)}\u0000${input.userId}`,
164 + `${clientScopeKey(input.client)}\u0000${input.userId}`,
165 make: ({ client, userId }) =>
166 client.connectedAccounts.list(
167 {
ts/packages/cli/src/services/consumer-short-term-cache.ts
+3 -3
@@ -435,9 +435,9 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
435 orgId: scope.orgId,
436 });
437 // The nano id, as `resolveCommandProject` hands it to `composio execute`:
438 - // `getFor` keys its clients on these params, and the memoized
439 - // connected-account list is keyed on the client, so a different project
440 - // id here would mean a second `GET /connected_accounts` per execute.
438 + // the memoized connected-account list is keyed on the client's org and
439 + // project, so a different project id here would mean a second
440 + // `GET /connected_accounts` per execute.
441 const client = yield* clientSingleton.getFor({
442 orgId: scope.orgId,
443 projectId: consumerProject.project_nano_id,
ts/packages/cli/test/__utils__/layers/accounts.ts
+7 -4
@@ -6,10 +6,12 @@ import { TIMESTAMP } from '../models/account';
6
7 /**
8 * The credentials and scope one mock-client request carries: the parameters
9 - * the client was obtained with, overridden by per-request headers.
9 + * the client was obtained with, and the org or project an unscoped client
10 + * names on the request itself.
11 */
12 export interface MockRequestScope {
13 readonly userApiKey?: string;
14 + /** The project key the client authenticates with, in place of a user key. */
15 readonly apiKey?: string;
16 readonly orgId?: string;
17 readonly projectId?: string;
@@ -71,13 +73,14 @@ const withTestData = <A>(value: A | undefined, operation: MockAccountRequest['op
73 const LATEST_TOOL_VERSION_PATH = /^\/api\/v3\/tools\/[^/]+\/get_latest_version$/;
74 const CREATE_PROJECT_API_KEY_PATH = /^\/api\/v3\/org\/project\/[^/]+\/api_keys\/create$/;
75
76 +// The credential is the client's own; an unscoped client may still name the
77 +// org or project on one request.
78 const scopeOf = (base: MockRequestScope, options?: RequestOptions): MockRequestScope => {
79 // The CLI only ever passes plain header records.
80 const headers = (options?.headers ?? {}) as Record<string, string | null | undefined>;
77 - const userApiKey = headers['x-user-api-key'];
81 return {
79 - userApiKey: userApiKey === null ? undefined : (userApiKey ?? base.userApiKey),
80 - apiKey: headers['x-api-key'] ?? undefined,
82 + userApiKey: base.userApiKey,
83 + apiKey: base.apiKey,
84 orgId: headers['x-org-id'] ?? base.orgId,
85 projectId: headers['x-project-id'] ?? base.projectId,
86 };
ts/packages/cli/test/__utils__/services/stub-composio-client.ts
+2 -4
@@ -1,4 +1,4 @@
1 -import { make, type ComposioClientShape } from '@composio/client/effect';
1 +import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2 import { Effect, Layer, Result } from 'effect';
3 import { HttpClient, HttpClientRequest, HttpClientResponse } from 'effect/http';
4 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -41,9 +41,7 @@ export const stubComposioClient = (
41 );
42 const client = make(
43 {
44 - apiKey: 'test',
45 - userApiKey: null,
46 - orgApiKey: null,
44 + auth: Auth.project('test'),
45 baseURL: 'https://stub.invalid',
46 deprecationNotices: 'off',
47 maxRetries: 0,
ts/packages/cli/test/__utils__/services/test-layer.ts
+11 -6
@@ -1,6 +1,7 @@
1 import path from 'node:path';
2 import * as tempy from 'tempy';
3 import {
4 + Auth,
5 make as makeComposioClient,
6 type ComposioError,
7 type RequestOptions,
@@ -38,6 +39,7 @@ import {
39 ComposioClientSingleton,
40 ComposioSessionRepository,
41 ComposioToolkitsRepository,
42 + type ClientScope,
43 } from 'src/services/composio-clients';
44 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
45 import type { TriggerInstanceItem } from 'src/models/triggers';
@@ -771,9 +773,7 @@ export const TestLayer = (input?: TestLiveInput) =>
773 const mockComposioClient = withShadows(
774 makeComposioClient(
775 {
774 - apiKey: 'test',
775 - userApiKey: null,
776 - orgApiKey: null,
776 + auth: Auth.project('test'),
777 baseURL: 'https://mock.invalid',
778 deprecationNotices: 'off',
779 },
@@ -788,7 +788,7 @@ export const TestLayer = (input?: TestLiveInput) =>
788
789 const scopedClients = new Map<string, typeof mockComposioClient>();
790 const mockClientFor = (scope: MockRequestScope) => {
791 - const key = JSON.stringify([scope.userApiKey, scope.orgId, scope.projectId]);
791 + const key = JSON.stringify([scope.userApiKey, scope.apiKey, scope.orgId, scope.projectId]);
792 const cached = scopedClients.get(key);
793 if (cached) return cached;
794 const scoped = withShadows(mockComposioClient, mockAccountResources(accountData, scope));
@@ -802,8 +802,13 @@ export const TestLayer = (input?: TestLiveInput) =>
802 get: Effect.fn(function* () {
803 return mockClientFor({});
804 }),
805 - getFor: Effect.fn(function* (params: MockRequestScope) {
806 - return mockClientFor(params);
805 + getFor: Effect.fn(function* (params: ClientScope) {
806 + return mockClientFor({
807 + userApiKey: params.userApiKey,
808 + apiKey: params.projectApiKey,
809 + orgId: params.orgId,
810 + projectId: params.projectId,
811 + });
812 }),
813 getMetrics: () => Effect.succeed({ byteSize: 0, requests: 0 }),
814 })
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+2 -4
@@ -1,4 +1,4 @@
1 -import { make, type ComposioClientShape } from '@composio/client/effect';
1 +import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3 import * as BunPath from '@effect/platform-bun/BunPath';
4 import { describe, expect, it } from '@effect/vitest';
@@ -126,9 +126,7 @@ interface LinkRequest {
126 // A resource neither layer below shadows reaches this transport and dies with its URL.
127 const baseClient = make(
128 {
129 - apiKey: 'test',
130 - userApiKey: null,
131 - orgApiKey: null,
129 + auth: Auth.project('test'),
130 baseURL: 'https://mock.invalid',
131 deprecationNotices: 'off',
132 },
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+138 -22
@@ -8,7 +8,9 @@ import { ConfigProvider, Effect, Exit, Layer, Logger } from 'effect';
8 import { FetchHttpClient } from 'effect/http';
9 import * as tempy from 'tempy';
10 import { VERSION as clientLibraryVersion, type ComposioClientShape } from '@composio/client/effect';
11 -import { ComposioClientSingleton } from 'src/services/composio-clients';
11 +import { ComposioClientSingleton, clientScopeKey } from 'src/services/composio-clients';
12 +import { listActiveConnectedAccounts } from 'src/services/connected-account-selection';
13 +import { stubComposioClient } from 'test/__utils__/services/stub-composio-client';
14 import { idempotent, validated } from 'src/services/composio-request';
15 import { APP_VERSION } from 'src/constants';
16 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
@@ -161,6 +163,45 @@ describe('ComposioClientSingleton headers', () => {
163 );
164 });
165
166 + it.effect('reads the cwd CLI session ID once for every client it builds', () => {
167 + const fetchSpy = vi
168 + .spyOn(globalThis, 'fetch')
169 + .mockImplementation(() => Promise.resolve(okResponse()));
170 + const homedir = tempy.temporaryDirectory();
171 + const configMap = new Map([
172 + ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
173 + ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
174 + ]);
175 +
176 + return Effect.gen(function* () {
177 + const path = yield* Path.Path;
178 + vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
179 + yield* writeCliSessionCache(homedir, {
180 + id: 'cli_s_first',
181 + expiresAt: '1970-01-01T00:01:00.000Z',
182 + });
183 + const clientSingleton = yield* ComposioClientSingleton;
184 + yield* listTools(yield* clientSingleton.get());
185 +
186 + yield* writeCliSessionCache(homedir, {
187 + id: 'cli_s_second',
188 + expiresAt: '1970-01-01T00:01:00.000Z',
189 + });
190 + yield* listTools(
191 + yield* clientSingleton.getFor({ userApiKey: 'uak_other', orgId: 'o', projectId: 'p' })
192 + );
193 +
194 + const sessionIds = fetchSpy.mock.calls.map(call =>
195 + new Headers((call[1] as RequestInit).headers).get('x-cli-session-id')
196 + );
197 + expect(sessionIds).toEqual(['cli_s_first', 'cli_s_first']);
198 + }).pipe(
199 + Effect.provide(
200 + Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
201 + )
202 + );
203 + });
204 +
205 it.effect('omits an expired cwd CLI session ID', () => {
206 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
207 const homedir = tempy.temporaryDirectory();
@@ -258,8 +299,8 @@ describe('ComposioClientSingleton headers', () => {
299 return Effect.gen(function* () {
300 const clientSingleton = yield* ComposioClientSingleton;
301 const client = yield* clientSingleton.get();
261 - // `auth.session.retrieveInfo` is an operation where the client would
262 - // attach its own `userApiKey` credential; the caller-placed header wins.
302 + // The client authenticates with `Auth.user`, so the user key is its one
303 + // credential on every operation.
304 yield* client.auth.session.retrieveInfo();
305
306 const [input, init] = fetchSpy.mock.calls[0]!;
@@ -413,38 +454,113 @@ describe('ComposioClientSingleton client', () => {
454 }).pipe(Effect.provide(singletonLayer(baseConfig())));
455 });
456
416 - it.effect('caches one client per key, org, and project', () =>
457 + it.effect('sends a project key in place of the user key, with the scope', () => {
458 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
459 +
460 + return Effect.gen(function* () {
461 + const clientSingleton = yield* ComposioClientSingleton;
462 + const client = yield* clientSingleton.getFor({
463 + projectApiKey: 'ak_project',
464 + orgId: 'org_a',
465 + projectId: 'proj_a',
466 + });
467 + yield* listTools(client);
468 +
469 + const headers = sentHeaders(fetchSpy.mock.calls[0]!);
470 + expect(headers.get('x-api-key')).toBe('ak_project');
471 + expect(headers.has('x-user-api-key')).toBe(false);
472 + expect(headers.get('x-org-id')).toBe('org_a');
473 + expect(headers.get('x-project-id')).toBe('proj_a');
474 + }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_user']]))));
475 + });
476 +
477 + it.effect('refuses a request that names another org than its scope, before sending', () => {
478 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
479 +
480 + return Effect.gen(function* () {
481 + const clientSingleton = yield* ComposioClientSingleton;
482 + const client = yield* clientSingleton.getFor({
483 + userApiKey: 'uak_scope',
484 + orgId: 'org_a',
485 + projectId: 'proj_a',
486 + });
487 + const error = yield* Effect.flip(
488 + client.get('/api/v3/tools/X/get_latest_version', { headers: { 'x-org-id': 'org_b' } })
489 + );
490 +
491 + expect(error._tag).toBe('@composio/client/ConfigurationError');
492 + expect(fetchSpy).not.toHaveBeenCalled();
493 + }).pipe(Effect.provide(singletonLayer(baseConfig())));
494 + });
495 +
496 + it.effect('keys clients for a memo by auth mode, org, and project, never by instance', () =>
497 Effect.gen(function* () {
498 const clientSingleton = yield* ComposioClientSingleton;
499 const scope = { userApiKey: 'uak_a', orgId: 'org_a', projectId: 'proj_a' };
500
501 const first = yield* clientSingleton.getFor(scope);
422 - const second = yield* clientSingleton.getFor(scope);
502 + const second = yield* clientSingleton.getFor({ ...scope, userApiKey: 'uak_b' });
503 const otherProject = yield* clientSingleton.getFor({ ...scope, projectId: 'proj_b' });
504 + const projectKey = yield* clientSingleton.getFor({
505 + projectApiKey: 'ak_a',
506 + orgId: 'org_a',
507 + projectId: 'proj_a',
508 + });
509 + const { client: elsewhere } = stubComposioClient(okResponse);
510
425 - expect(second).toBe(first);
426 - expect(otherProject).not.toBe(first);
511 + expect(second).not.toBe(first);
512 + expect(clientScopeKey(second)).toBe(clientScopeKey(first));
513 + expect(clientScopeKey(otherProject)).not.toBe(clientScopeKey(first));
514 + expect(clientScopeKey(projectKey)).not.toBe(clientScopeKey(first));
515 + expect(clientScopeKey(first)).not.toContain('uak_a');
516 + // A client built outside the singleton is keyed on its own.
517 + expect(clientScopeKey(elsewhere)).toBe(clientScopeKey(elsewhere));
518 + expect(clientScopeKey(elsewhere)).not.toBe(clientScopeKey(first));
519 }).pipe(Effect.provide(singletonLayer(baseConfig())))
520 );
521
430 - it.effect('hands concurrent first callers of a scope the same client', () =>
431 - Effect.gen(function* () {
522 + it.effect('lists active connected accounts once per org, project, and user', () => {
523 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(() =>
524 + Promise.resolve(
525 + new Response(
526 + JSON.stringify({
527 + items: [],
528 + total_items: 0,
529 + total_pages: 1,
530 + current_page: 1,
531 + next_cursor: null,
532 + }),
533 + { status: 200, headers: { 'Content-Type': 'application/json' } }
534 + )
535 + )
536 + );
537 +
538 + return Effect.gen(function* () {
539 const clientSingleton = yield* ComposioClientSingleton;
433 - const scope = { userApiKey: 'uak_a', orgId: 'org_a', projectId: 'proj_a' };
540 + const scope = { orgId: 'org_a', projectId: 'proj_a' };
541
435 - const [first, second, third] = yield* Effect.all(
436 - [
437 - clientSingleton.getFor(scope),
438 - clientSingleton.getFor({ ...scope }),
439 - clientSingleton.getFor(scope),
440 - ],
441 - { concurrency: 'unbounded' }
442 - );
542 + // Two lookups of one scope hand back two instances; they share one fetch.
543 + yield* listActiveConnectedAccounts({
544 + client: yield* clientSingleton.getFor(scope),
545 + userId: 'user_1',
546 + });
547 + yield* listActiveConnectedAccounts({
548 + client: yield* clientSingleton.getFor(scope),
549 + userId: 'user_1',
550 + });
551 + expect(fetchSpy).toHaveBeenCalledTimes(1);
552
444 - expect(second).toBe(first);
445 - expect(third).toBe(first);
446 - }).pipe(Effect.provide(singletonLayer(baseConfig())))
447 - );
553 + yield* listActiveConnectedAccounts({
554 + client: yield* clientSingleton.getFor({ ...scope, projectId: 'proj_b' }),
555 + userId: 'user_1',
556 + });
557 + yield* listActiveConnectedAccounts({
558 + client: yield* clientSingleton.getFor(scope),
559 + userId: 'user_2',
560 + });
561 + expect(fetchSpy).toHaveBeenCalledTimes(3);
562 + }).pipe(Effect.provide(singletonLayer(baseConfig([['COMPOSIO_USER_API_KEY', 'uak_memo']]))));
563 + });
564
565 it.effect('counts requests on its own transport beside an application FetchHttpClient', () => {
566 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
ts/packages/cli/test/src/services/composio-clients.test.ts
+53
@@ -355,6 +355,59 @@ describe('composio-clients', () => {
355 expect(headers.has('x-user-api-key')).toBe(false);
356 }).pipe(Effect.provide(withSingleton))
357 );
358 +
359 + it.effect.each([
360 + {
361 + known: 'the org and the project',
362 + orgId: 'org_1',
363 + projectId: 'proj_1',
364 + projectApiKey: undefined,
365 + credentials: { user: 'uak_test', project: null },
366 + },
367 + {
368 + known: 'the org only',
369 + orgId: 'org_1',
370 + projectId: undefined,
371 + projectApiKey: undefined,
372 + credentials: { user: 'uak_test', project: null },
373 + },
374 + {
375 + known: 'the project only',
376 + orgId: undefined,
377 + projectId: 'proj_1',
378 + projectApiKey: undefined,
379 + credentials: { user: 'uak_test', project: null },
380 + },
381 + {
382 + known: 'the org and the project, with a project key',
383 + orgId: 'org_1',
384 + projectId: 'proj_1',
385 + projectApiKey: 'ak_project',
386 + credentials: { user: null, project: 'ak_project' },
387 + },
388 + ])('getLatestToolVersion sends whichever of $known is known', params =>
389 + Effect.gen(function* () {
390 + const fetchSpy = vi
391 + .spyOn(globalThis, 'fetch')
392 + .mockResolvedValue(jsonResponse({ tool_slug: 'GMAIL_SEND_EMAIL', version: '1' }));
393 +
394 + yield* getLatestToolVersion({
395 + apiKey: 'uak_test',
396 + toolSlug: 'GMAIL_SEND_EMAIL',
397 + orgId: params.orgId,
398 + projectId: params.projectId,
399 + projectApiKey: params.projectApiKey,
400 + });
401 +
402 + const { headers } = requestOf(fetchSpy.mock.calls[0]);
403 + expect(headers.get('x-org-id')).toBe(params.orgId ?? null);
404 + expect(headers.get('x-project-id')).toBe(params.projectId ?? null);
405 + expect({
406 + user: headers.get('x-user-api-key'),
407 + project: headers.get('x-api-key'),
408 + }).toEqual(params.credentials);
409 + }).pipe(Effect.provide(withSingleton))
410 + );
411 });
412
413 describe('repository request core', () => {
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+2 -4
@@ -8,7 +8,7 @@ import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
8 import * as BunPath from '@effect/platform-bun/BunPath';
9 import { Effect, Fiber, Layer } from 'effect';
10 import { HttpClient } from 'effect/http';
11 -import { BadRequestError, make } from '@composio/client/effect';
11 +import { Auth, BadRequestError, make } from '@composio/client/effect';
12 import {
13 ComposioBlockedInternalUrlError,
14 ComposioSensitiveFilePathBlockedError,
@@ -229,9 +229,7 @@ describe('uploadToolInputFiles — presigned-URL request', () => {
229 let interrupted = false;
230 const client = make(
231 {
232 - apiKey: 'test',
233 - userApiKey: null,
234 - orgApiKey: null,
232 + auth: Auth.project('test'),
233 baseURL: 'https://stub.invalid',
234 deprecationNotices: 'off',
235 },
ts/packages/core/src/composio.ts
+54 -48
@@ -1,3 +1,4 @@
1 +import { getEnvVariable } from './utils/env';
2 import type { BaseComposioProvider } from './provider/BaseProvider';
3 import ComposioClient from '@composio/client';
4 import type { Logger as ClientLogger, LogLevel as ClientLogLevel } from '@composio/client';
@@ -14,13 +15,13 @@ import { SessionConfigs } from './models/SessionConfigs';
15 import { Keyring } from './models/Keyring';
16 import { telemetry } from './telemetry/Telemetry';
17 import {
17 - getScopeHeaders,
18 getSDKConfig,
19 getToolkitVersionsFromEnv,
20 - getUserApiKeyHeader,
20 + resolveSDKCredentials,
21 resolveSDKScope,
22 - resolveUserApiKey,
23 - USER_API_KEY_HEADER,
22 + toClientAuth,
23 + toClientScope,
24 + withoutSDKOwnedHeaders,
25 } from './utils/sdk';
26 import logger from './utils/logger';
27 import type { ComposioLogger, LogLevel } from './utils/logger';
@@ -50,7 +51,9 @@ export type ComposioConfig<
51 * - `null`: disables project-key authentication entirely, including both fallbacks. The SDK
52 * then requires another credential (`userApiKey`, `orgApiKey`, or an `x-user-api-key`
53 * entry in `defaultHeaders`) and sends no `x-api-key`; an `x-api-key` entry in
53 - * `defaultHeaders` is rejected, also on `createSession()` clones.
54 + * `defaultHeaders` is rejected, also on `createSession()` clones. The user API key
55 + * then authenticates every request; the organization API key does when it is the
56 + * only credential held.
57 *
58 * @example 'ak_1234567890'
59 */
@@ -71,7 +74,8 @@ export type ComposioConfig<
74 * Sent as `x-org-api-key` only on operations whose security scheme accepts
75 * it, never alongside the project key. Falls back to
76 * `process.env['COMPOSIO_ORG_API_KEY']`; `null` disables that fallback.
74 - * Combine with `apiKey: null` to authenticate with the organization key alone.
77 + * Combine with `apiKey: null` (and no user API key) to authenticate every
78 + * request with the organization key alone.
79 * @example 'oak_1234567890'
80 */
81 orgApiKey?: string | null;
@@ -168,10 +172,14 @@ export type ComposioConfig<
172 /**
173 * Default headers attached to every request made through this instance.
174 *
171 - * `x-user-api-key` is the one header the SDK treats as a credential: together
172 - * with `apiKey: null` it authenticates requests with a Composio user API key
173 - * instead of a project key. The project key is only ever set from `apiKey`:
174 - * an `x-api-key` entry is rejected when `apiKey` is `null`.
175 + * Credential and scope headers are not forwarded as headers: the SDK folds
176 + * them into its own options, which `getConfig()` then reports.
177 + * A non-empty `x-user-api-key` (or `x-org-api-key`) entry becomes the
178 + * credential every request carries, in place of the configured keys; together
179 + * with `apiKey: null` it authenticates with that key instead of a project key.
180 + * An `x-api-key` entry replaces the project key, and is rejected when `apiKey`
181 + * is `null`. At most one of the three may be set. `x-org-id` / `x-project-id`
182 + * entries supply `orgId` / `projectId`.
183 *
184 * The SDK reports itself through the API client's identity headers
185 * (`x-client-provenance`, `x-client-version`, `x-client-library`,
@@ -472,16 +480,20 @@ export class Composio<
480 }
481 );
482
475 - // The API client sends its user key only on operations whose security
476 - // scheme names it, which excludes sessions. With the project key disabled
477 - // the resolved user key is placed as the `x-user-api-key` default header
478 - // instead, so every request carries exactly that credential and clones,
479 - // the MCP export, and trigger subscriptions read the same header.
480 - const userApiKey = apiKeyParsed === null ? resolveUserApiKey(config?.userApiKey) : undefined;
481 - const defaultHeadersInput =
482 - userApiKey !== undefined && !getUserApiKeyHeader(config?.defaultHeaders)
483 - ? { ...config?.defaultHeaders, [USER_API_KEY_HEADER]: userApiKey }
484 - : config?.defaultHeaders;
483 + // The SDK owns the credential: it resolves the keys (with their
484 + // environment fallbacks) and folds a credential default header into them,
485 + // so the API client receives one `auth` and never a credential header.
486 + // The resolved keys are stored on the config, so clones, the MCP export
487 + // and trigger subscriptions read the same values.
488 + const credentials = resolveSDKCredentials({
489 + apiKey: apiKeyParsed,
490 + userApiKey: config?.userApiKey,
491 + orgApiKey: config?.orgApiKey,
492 + defaultHeaders: config?.defaultHeaders,
493 + });
494 + // Credential and scope entries travel as `auth` and `scope`; the client
495 + // refuses them in `defaultHeaders`.
496 + const defaultHeaders = withoutSDKOwnedHeaders(config?.defaultHeaders);
497
498 if (config?.logger !== undefined || config?.logLevel !== undefined) {
499 logger.configure({ level: config.logLevel, sink: config.logger });
@@ -503,8 +515,10 @@ export class Composio<
515 this.config = {
516 ...config,
517 baseURL: baseURLParsed,
506 - apiKey: apiKeyParsed,
507 - defaultHeaders: defaultHeadersInput,
518 + apiKey: credentials.apiKey,
519 + userApiKey: credentials.userApiKey,
520 + orgApiKey: credentials.orgApiKey,
521 + defaultHeaders,
522 toolkitVersions: getToolkitVersionsFromEnv(config?.toolkitVersions),
523 allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking,
524 dangerouslyAllowAutoUploadDownloadFiles:
@@ -519,32 +533,29 @@ export class Composio<
533 projectId: scope.projectId,
534 };
535
522 - // The resolved scope is the single source of the x-org-id / x-project-id
523 - // headers: it travels via `this.config` to clones and to the MCP export.
524 - const defaultHeaders = { ...this.config.defaultHeaders, ...getScopeHeaders(scope) };
525 -
536 /**
537 * Initialize the Composio SDK client.
538 * The client is used to make API calls to the Composio API. It sends the
529 - * SDK's identity headers from `identity`, and refuses them in `defaultHeaders`.
539 + * credential from `auth`, the resolved org/project scope from `scope`, and
540 + * the SDK's identity headers from `identity`, and refuses all three in
541 + * `defaultHeaders`.
542 */
543 this.client = new ComposioClient({
532 - apiKey: apiKeyParsed,
533 - userApiKey: config?.userApiKey,
534 - orgApiKey: config?.orgApiKey,
544 + auth: toClientAuth(credentials),
545 + scope: toClientScope(scope),
546 baseURL: baseURLParsed,
536 - defaultHeaders: defaultHeaders,
547 + // The client stopped reading the process environment in rc.18; this
548 + // opt-in for a plain-HTTP development origin is the one setting of its
549 + // own that core forwards.
550 + ...(getEnvVariable('COMPOSIO_ALLOW_INSECURE_HTTP') === '1'
551 + ? { allowInsecureHTTP: true }
552 + : {}),
553 + defaultHeaders,
554 identity: getClientIdentity(this.provider),
555 logger: clientLoggerAdapter,
556 logLevel: toClientLogLevel(logger.getLevel()),
557 });
558
542 - // Store the resolved values, as with `apiKey`, so `getConfig()` and the
543 - // `createSession()` clone carry whatever the client resolved from env
544 - // rather than re-reading the environment later.
545 - this.config.userApiKey = this.client.userApiKey;
546 - this.config.orgApiKey = this.client.orgApiKey;
547 -
559 this.tools = new Tools(this.client, this.config);
560 this.mcp = new MCP(this.client);
561 this.toolkits = new Toolkits(this.client);
@@ -579,7 +590,7 @@ export class Composio<
590 */
591 if (this.config.allowTracking) {
592 telemetry.setup({
582 - apiKey: apiKeyParsed ?? '',
593 + apiKey: credentials.apiKey ?? '',
594 baseUrl: baseURLParsed ?? '',
595 isAgentic: this.provider?._isAgentic || false,
596 version: version,
@@ -669,18 +680,13 @@ export class Composio<
680 * ```
681 */
682 createSession(options?: { headers?: ComposioRequestHeaders }): Composio<TProvider> {
672 - // The clone inherits the resolved credentials: the project, user, and
673 - // organization keys travel via `this.config`; a user API key placed in the
674 - // default headers travels via its header unless the caller overrides it.
675 - const userApiKeyHeader = getUserApiKeyHeader(options?.headers)
676 - ? undefined
677 - : getUserApiKeyHeader(this.config.defaultHeaders);
678 - const sessionHeaders = userApiKeyHeader
679 - ? { [userApiKeyHeader.name]: userApiKeyHeader.value, ...options?.headers }
680 - : options?.headers;
683 + // The clone inherits the resolved credentials and scope through
684 + // `this.config`, where a credential or scope default header has already
685 + // been folded in; `headers` replaces the default headers, and a
686 + // credential or scope header in it is folded in the same way.
687 return new Composio({
688 ...this.config,
683 - defaultHeaders: sessionHeaders,
689 + defaultHeaders: options?.headers,
690 });
691 }
692
ts/packages/core/src/models/ConnectedAccounts.ts
+7 -16
@@ -6,6 +6,7 @@
6 * @module ConnectedAccounts
7 */
8 import ComposioClient, { BadRequestError, ConflictError } from '@composio/client';
9 +import type { APIPromise } from '@composio/client';
10 import {
11 ConnectedAccountCreateResponse,
12 ConnectedAccountDeleteResponse,
@@ -126,11 +127,7 @@ export class ConnectedAccounts {
127 cursor: parsedQuery.data.cursor?.toString(),
128 limit: parsedQuery.data.limit,
129 order_by: parsedQuery.data.orderBy,
129 - // Cast widens to match the Stainless-generated client params, which
130 - // lag behind the live API enum. Apollo accepts the union value at
131 - // runtime (`z.nativeEnum(ConnectionStatusEnum)` on the query param);
132 - // remove the cast once `@composio/client` is regenerated.
133 - statuses: parsedQuery.data.statuses as ConnectedAccountListParamsRaw['statuses'],
130 + statuses: parsedQuery.data.statuses,
131 toolkit_slugs: parsedQuery.data.toolkitSlugs,
132 user_ids: parsedQuery.data.userIds,
133 ...(parsedQuery.data.accountType !== undefined && {
@@ -271,18 +268,12 @@ export class ConnectedAccounts {
268 // caller needs to migrate. Custom auth configs and non-OAuth schemes
269 // never see the header, eliminating the false-positive warning that
270 // an `auth_scheme`-only check produced for `link()`-unaffected callers.
274 - const apiCall = this.client.connectedAccounts.create(createParams, requestOptions);
275 - if (typeof (apiCall as { withResponse?: unknown }).withResponse === 'function') {
271 + const apiCall: APIPromise<ConnectedAccountCreateResponse> =
272 + this.client.connectedAccounts.create(createParams, requestOptions);
273 + // Checked at runtime: test mocks may return a plain Promise.
274 + if (typeof apiCall.withResponse === 'function') {
275 const resolved = await withCancellation(
277 - () =>
278 - (
279 - apiCall as unknown as {
280 - withResponse: () => Promise<{
281 - data: ConnectedAccountCreateResponse;
282 - response: Response;
283 - }>;
284 - }
285 - ).withResponse(),
276 + () => apiCall.withResponse(),
277 requestOptions?.signal
278 );
279 response = resolved.data;
ts/packages/core/src/models/Tools.ts
+1 -4
@@ -992,8 +992,7 @@ export class Tools<
992 * @deprecated The `customConnectionData` execute param is deprecated and will be
993 * removed in a future release. Use `customAuthParams` instead.
994 */
995 - custom_connection_data:
996 - body.customConnectionData as ComposioToolExecuteParams['custom_connection_data'],
995 + custom_connection_data: body.customConnectionData,
996 arguments: body.arguments,
997 user_id: body.userId,
998 version: toolkitVersion,
@@ -1390,8 +1389,6 @@ export class Tools<
1389 * @deprecated The `customConnectionData` proxy param is deprecated and will be
1390 * removed in a future release. Use `customAuthParams` instead.
1391 */
1393 - // oxlint-disable-next-line typescript/ban-ts-comment -- generated client versions disagree about this deprecated field
1394 - // @ts-ignore
1392 custom_connection_data: toolProxyParams.data.customConnectionData,
1393 } as ComposioToolProxyParams;
1394 return withCancellation(
ts/packages/core/src/models/Triggers.ts
+5 -1
@@ -158,7 +158,11 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
158
159 constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
160 this.client = client;
161 - this.pusherService = new PusherService(client, { defaultHeaders: config?.defaultHeaders });
161 + this.pusherService = new PusherService(client, {
162 + apiKey: config?.apiKey,
163 + userApiKey: config?.userApiKey,
164 + defaultHeaders: config?.defaultHeaders,
165 + });
166 this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
167 telemetry.instrument(this, 'Triggers');
168 }
ts/packages/core/src/services/internal/InternalService.ts
+3 -4
@@ -24,10 +24,9 @@ export class InternalService {
24 * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
25 */
26 async getSDKRealtimeCredentials(): Promise<SDKRealtimeCredentialsResponse> {
27 - const response = await this.client.request<ComposioSDKRealtimeCredentialsResponse>({
28 - method: 'get',
29 - path: SDK_REALTIME_CREDENTIALS_ENDPOINT,
30 - });
27 + const response = await this.client.get<ComposioSDKRealtimeCredentialsResponse>(
28 + SDK_REALTIME_CREDENTIALS_ENDPOINT
29 + );
30
31 const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
32 pusherKey: response.pusher_key,
ts/packages/core/src/services/pusher/Pusher.ts
+8 -4
@@ -14,6 +14,10 @@ import { resolveCredentialHeaders } from '../../utils/sdk';
14 import type { ComposioRequestHeaders } from '../../types/composio.types';
15
16 export type PusherServiceOptions = {
17 + /** The project API key the owning SDK instance resolved, or `null` when disabled. */
18 + apiKey?: string | null;
19 + /** The user API key the owning SDK instance resolved, or `null`. */
20 + userApiKey?: string | null;
21 /** Default headers of the owning SDK instance; only `x-user-api-key` is consulted. */
22 defaultHeaders?: ComposioRequestHeaders;
23 };
@@ -57,11 +61,11 @@ export class PusherService {
61 constructor(client: ComposioClient, options: PusherServiceOptions = {}) {
62 this.composioClient = client;
63 this.pusherBaseURL = client.baseURL;
60 - // Channel authorization mirrors the client's effective auth; the
61 - // environment is never consulted here.
64 + // Channel authorization mirrors the SDK instance's effective auth, from the
65 + // keys the SDK resolved; the environment is never consulted here.
66 this.authHeaders = resolveCredentialHeaders({
63 - apiKey: client.apiKey,
64 - userApiKey: client.userApiKey,
67 + apiKey: options.apiKey,
68 + userApiKey: options.userApiKey,
69 defaultHeaders: options.defaultHeaders,
70 });
71 telemetry.instrument(this, 'PusherService');
ts/packages/core/src/types/connectedAccountAuthStates.types.ts
+2 -1
@@ -222,7 +222,8 @@ const S2SOauth2ConnectionDataSchema = z.discriminatedUnion('status', [
222 }).catchall(z.unknown()),
223 ]);
224 const CustomS2SOauth2ConnectionDataSchema = BaseSchemeRaw.extend({
225 - access_token: z.string().optional(),
225 + // Required by the API: custom connection data supplies the token itself.
226 + access_token: z.string(),
227 id_token: z.string().optional(),
228 token_type: z.string().optional(),
229 refresh_token: z.string().nullish().optional(),
ts/packages/core/src/types/requestOptions.types.ts
+1 -10
@@ -1,4 +1,4 @@
1 -import type ComposioClient from '@composio/client';
1 +import type { RequestOptions as ClientRequestOptions } from '@composio/client';
2
3 /**
4 * Per-request transport options for cancelling an SDK call.
@@ -38,15 +38,6 @@ export type ComposioRequestOptions = {
38 signal?: AbortSignal;
39 };
40
41 -/**
42 - * The `@composio/client` per-request transport options, reached via a public
43 - * method whose only parameter is that type (`tools.retrieveEnum`). The
44 - * `internal/*` subpath that declares `RequestOptions` is not in the package's
45 - * `exports`, so we derive it structurally instead of deep-importing it.
46 - * @internal
47 - */
48 -type ClientRequestOptions = NonNullable<Parameters<ComposioClient['tools']['retrieveEnum']>[0]>;
49 -
41 /**
42 * Compile-time guards: {@link ComposioRequestOptions} is forwarded verbatim to
43 * every `@composio/client` call, so it MUST stay a structural subset of the
ts/packages/core/src/utils/sdk.ts
+152 -5
@@ -1,4 +1,6 @@
1 import { z } from 'zod/v3';
2 +import { Auth } from '@composio/client';
3 +import type { Scope } from '@composio/client';
4 import {
5 ComposioAPIKeyKindError,
6 ComposioNoAPIKeyError,
@@ -29,12 +31,29 @@ const USER_API_KEY_PREFIX = 'uak_';
31 */
32 export const PROJECT_API_KEY_HEADER = 'x-api-key';
33
34 +/** Header that carries the organization API key (`oak_...`). */
35 +export const ORG_API_KEY_HEADER = 'x-org-api-key';
36 +
37 /** Header carrying the organization nano ID that scopes user-key requests. */
38 export const ORG_ID_HEADER = 'x-org-id';
39
40 /** Header carrying the project nano ID that scopes user-key requests. */
41 export const PROJECT_ID_HEADER = 'x-project-id';
42
43 +/**
44 + * Header names the SDK owns: the API client sends a credential from its
45 + * `auth` and the scope from its `scope`, and refuses these names in its
46 + * `defaultHeaders`. The SDK folds caller-supplied entries into its own
47 + * credential and scope options instead of forwarding them.
48 + */
49 +const SDK_OWNED_HEADERS = [
50 + PROJECT_API_KEY_HEADER,
51 + USER_API_KEY_HEADER,
52 + ORG_API_KEY_HEADER,
53 + ORG_ID_HEADER,
54 + PROJECT_ID_HEADER,
55 +];
56 +
57 // File path helpers
58 export const userDataPath = () => {
59 try {
@@ -242,11 +261,29 @@ export function resolveSDKScope(options: SDKScopeOptions): SDKScope {
261 return orgId === undefined || projectId === undefined ? {} : { orgId, projectId };
262 }
263
245 -/** The `x-org-id` / `x-project-id` headers for a resolved scope. */
246 -export const getScopeHeaders = (scope: SDKScope): ComposioRequestHeaders =>
264 +/**
265 + * The API client `scope` for a resolved SDK scope: the organization and
266 + * project nano IDs the client sends as `x-org-id` / `x-project-id`, or
267 + * `undefined` when the instance is unscoped.
268 + */
269 +export const toClientScope = (scope: SDKScope): Scope | undefined =>
270 scope.orgId && scope.projectId
248 - ? { [ORG_ID_HEADER]: scope.orgId, [PROJECT_ID_HEADER]: scope.projectId }
249 - : {};
271 + ? { organizationId: scope.orgId, projectId: scope.projectId }
272 + : undefined;
273 +
274 +/**
275 + * `headers` without the credential and scope entries the SDK owns (matched
276 + * case-insensitively). Those travel through the API client's `auth` and
277 + * `scope`, which refuse the same names in `defaultHeaders`.
278 + */
279 +export const withoutSDKOwnedHeaders = (
280 + headers: ComposioRequestHeaders | undefined
281 +): ComposioRequestHeaders | undefined =>
282 + headers === undefined
283 + ? undefined
284 + : Object.fromEntries(
285 + Object.entries(headers).filter(([name]) => !SDK_OWNED_HEADERS.includes(name.toLowerCase()))
286 + );
287
288 export type SDKConfigOptions = {
289 /** Default headers the SDK will attach to every request. */
@@ -297,6 +334,14 @@ const resolveAlternateCredential = (
334 export const resolveUserApiKey = (userApiKey: string | null | undefined): string | undefined =>
335 resolveAlternateCredential(userApiKey, 'COMPOSIO_USER_API_KEY');
336
337 +/**
338 + * The organization API key the instance holds: the `orgApiKey` option when it
339 + * was passed (including `null`, which disables the fallback), otherwise
340 + * `COMPOSIO_ORG_API_KEY`.
341 + */
342 +export const resolveOrgApiKey = (orgApiKey: string | null | undefined): string | undefined =>
343 + resolveAlternateCredential(orgApiKey, 'COMPOSIO_ORG_API_KEY');
344 +
345 /**
346 * Whether the instance holds a credential other than the project key: a user
347 * or organization API key (explicit or environment-resolved, as the API client
@@ -304,9 +349,111 @@ export const resolveUserApiKey = (userApiKey: string | null | undefined): string
349 */
350 const hasAlternateCredential = (options: SDKConfigOptions): boolean =>
351 resolveUserApiKey(options.userApiKey) !== undefined ||
307 - resolveAlternateCredential(options.orgApiKey, 'COMPOSIO_ORG_API_KEY') !== undefined ||
352 + resolveOrgApiKey(options.orgApiKey) !== undefined ||
353 getUserApiKeyHeader(options.defaultHeaders) !== undefined;
354
355 +/**
356 + * The credentials an SDK instance authenticates with, after the environment
357 + * fallbacks and the credential default headers are applied. `null` is a
358 + * credential the instance does not hold.
359 + */
360 +export type SDKCredentials = {
361 + /** The project API key, or `null` when project-key auth is disabled. */
362 + apiKey: string | null;
363 + /** The user API key (`uak_...`), or `null`. */
364 + userApiKey: string | null;
365 + /** The organization API key (`oak_...`), or `null`. */
366 + orgApiKey: string | null;
367 +};
368 +
369 +export type SDKCredentialsInput = {
370 + /** The project API key {@link getSDKConfig} resolved. */
371 + apiKey: string | null;
372 + /** The `userApiKey` option as passed: `undefined` falls back to `COMPOSIO_USER_API_KEY`. */
373 + userApiKey?: string | null;
374 + /** The `orgApiKey` option as passed: `undefined` falls back to `COMPOSIO_ORG_API_KEY`. */
375 + orgApiKey?: string | null;
376 + /** Default headers the caller configured; only the credential headers are read. */
377 + defaultHeaders?: ComposioRequestHeaders;
378 +};
379 +
380 +const CREDENTIAL_HEADERS = [PROJECT_API_KEY_HEADER, USER_API_KEY_HEADER, ORG_API_KEY_HEADER];
381 +
382 +/**
383 + * Resolves the credentials of an SDK instance.
384 + *
385 + * The user and organization keys fall back to `COMPOSIO_USER_API_KEY` and
386 + * `COMPOSIO_ORG_API_KEY` when their option is omitted. A non-empty credential
387 + * header in `defaultHeaders` (any letter case) is folded in as the credential
388 + * it names, and it is the credential the instance sends, as it was when the
389 + * header itself went on the wire: an `x-user-api-key` or `x-org-api-key` entry
390 + * disables the project key and takes the place of the configured user or
391 + * organization key, and an `x-api-key` entry takes the place of the project
392 + * key. At most one credential header may be set: the API rejects a request
393 + * that carries two.
394 + */
395 +export function resolveSDKCredentials(input: SDKCredentialsInput): SDKCredentials {
396 + const headers = CREDENTIAL_HEADERS.flatMap(name => {
397 + const header = findHeader(input.defaultHeaders, name);
398 + return header && hasValue(header.value) ? [{ ...header, canonical: name }] : [];
399 + });
400 + if (headers.length > 1) {
401 + throw new ComposioError('`defaultHeaders` carries more than one credential header', {
402 + cause: `The API accepts exactly one credential per request, and \`defaultHeaders\` sets ${headers
403 + .map(header => `\`${header.name}\``)
404 + .join(' and ')}`,
405 + possibleFixes: [
406 + 'Pass credentials through `apiKey`, `userApiKey` and `orgApiKey` instead of default headers',
407 + 'Keep at most one of `x-api-key`, `x-user-api-key` and `x-org-api-key` in `defaultHeaders`',
408 + ],
409 + });
410 + }
411 + const userApiKey = resolveUserApiKey(input.userApiKey) ?? null;
412 + const orgApiKey = resolveOrgApiKey(input.orgApiKey) ?? null;
413 + const [header] = headers;
414 + switch (header?.canonical) {
415 + case USER_API_KEY_HEADER:
416 + return { apiKey: null, userApiKey: header.value, orgApiKey };
417 + case ORG_API_KEY_HEADER:
418 + return { apiKey: null, userApiKey: null, orgApiKey: header.value };
419 + case PROJECT_API_KEY_HEADER:
420 + return { apiKey: header.value, userApiKey, orgApiKey };
421 + default:
422 + return { apiKey: input.apiKey, userApiKey, orgApiKey };
423 + }
424 +}
425 +
426 +/**
427 + * The API client `auth` for the credentials of an SDK instance.
428 + *
429 + * - A project key alone authenticates every request with it.
430 + * - A project key with a user and/or organization key selects one per
431 + * operation: the project key wherever the operation accepts it, otherwise
432 + * the first declared scheme a key is held for.
433 + * - Without a project key, the user key authenticates every request (sessions
434 + * included, whose operations declare no scheme), and the organization key
435 + * does when it is the only one held.
436 + */
437 +export const toClientAuth = (credentials: SDKCredentials): Auth => {
438 + const { apiKey, userApiKey, orgApiKey } = credentials;
439 + if (apiKey !== null) {
440 + return userApiKey === null && orgApiKey === null
441 + ? Auth.project(apiKey)
442 + : Auth.auto({
443 + project: apiKey,
444 + user: userApiKey ?? undefined,
445 + organization: orgApiKey ?? undefined,
446 + });
447 + }
448 + if (userApiKey !== null) {
449 + return Auth.user(userApiKey);
450 + }
451 + if (orgApiKey !== null) {
452 + return Auth.organization(orgApiKey);
453 + }
454 + throw new ComposioNoAPIKeyError();
455 +};
456 +
457 /**
458 * Resolves the base URL and project API key the SDK will use.
459 *
ts/packages/core/src/utils/transformers/connectedAccounts.ts
+9 -20
@@ -23,13 +23,6 @@ import { ConnectionDataSchema } from '../../types/connectedAccountAuthStates.typ
23 import logger from '../logger';
24 import { transform } from '../transform';
25
26 -type RawConnectedAccountResponseWithLabels = (
27 - RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]
28 -) & {
29 - word_id?: string | null;
30 - alias?: string | null;
31 -};
32 -
26 /**
27 * Transforms the raw connected account response from the Composio API to the SDK format.
28 *
@@ -45,8 +38,6 @@ type RawConnectedAccountResponseWithLabels = (
38 export function transformConnectedAccountResponse(
39 response: RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]
40 ): ConnectedAccountRetrieveResponse {
48 - const responseWithLabels = response as RawConnectedAccountResponseWithLabels;
49 -
41 // Safely parse the state field, filtering out unsupported auth schemes
42 const parseState = (state: unknown) => {
43 try {
@@ -70,9 +61,9 @@ export function transformConnectedAccountResponse(
61 isComposioManaged: response.auth_config.is_composio_managed,
62 isDisabled: response.auth_config.is_disabled,
63 },
73 - wordId: responseWithLabels.word_id ?? null,
74 - alias: responseWithLabels.alias ?? null,
75 - data: (response as unknown as ConnectedAccountRetrieveResponse).data ?? undefined,
64 + wordId: response.word_id ?? null,
65 + alias: response.alias ?? null,
66 + data: response.data ?? undefined,
67 state: parseState(response.state),
68 status: response.status,
69 statusReason: response.status_reason,
@@ -86,17 +77,15 @@ export function transformConnectedAccountResponse(
77 // caller isn't authorised to see the ACL), so distinguish "I can't
78 // see the ACL" from "ACL is the default deny-by-default state" by
79 // checking field presence.
89 - experimental: responseWithLabels.experimental
80 + experimental: response.experimental
81 ? {
91 - accountType: responseWithLabels.experimental.account_type,
92 - aclConfigForShared: responseWithLabels.experimental.acl_config_for_shared
82 + accountType: response.experimental.account_type,
83 + aclConfigForShared: response.experimental.acl_config_for_shared
84 ? {
94 - allowAllUsers:
95 - responseWithLabels.experimental.acl_config_for_shared.allow_all_users,
96 - allowedUserIds:
97 - responseWithLabels.experimental.acl_config_for_shared.allowed_user_ids,
85 + allowAllUsers: response.experimental.acl_config_for_shared.allow_all_users,
86 + allowedUserIds: response.experimental.acl_config_for_shared.allowed_user_ids,
87 notAllowedUserIds:
99 - responseWithLabels.experimental.acl_config_for_shared.not_allowed_user_ids,
88 + response.experimental.acl_config_for_shared.not_allowed_user_ids,
89 }
90 : undefined,
91 }
ts/packages/core/src/utils/transformers/mcp.ts
+3 -10
@@ -32,9 +32,6 @@ export function transformMcpCreateResponse(
32 const result = CustomCreateResponseSchema.safeParse({
33 id: response.id,
34 name: response.name,
35 - createdAt: (response as unknown as Record<string, unknown>).created_at,
36 - updatedAt: (response as unknown as Record<string, unknown>).updated_at,
37 - status: (response as unknown as Record<string, unknown>).status,
35 });
36
37 if (!result.success) {
@@ -55,7 +52,6 @@ export function transformMcpListResponse(response: McpListResponseRaw): McpListR
52 name: item.name,
53 createdAt: item.created_at,
54 updatedAt: item.updated_at,
58 - status: (item as unknown as Record<string, unknown>).status,
55 }));
56
57 const result = McpListResponseSchema.safeParse({
@@ -82,7 +78,6 @@ export function transformMcpRetrieveResponse(
78 name: response.name,
79 createdAt: response.created_at,
80 updatedAt: response.updated_at,
85 - status: (response as unknown as Record<string, unknown>).status,
81 toolkits: response.toolkits,
82 tools: response.allowed_tools,
83 managedAuthViaComposio: response.managed_auth_via_composio,
@@ -105,9 +100,8 @@ export function transformMcpRetrieveResponse(
100 */
101 export function transformMcpDeleteResponse(response: McpDeleteResponseRaw): McpDeleteResponse {
102 const result = McpDeleteResponseSchema.safeParse({
108 - id: (response as unknown as Record<string, unknown>).id,
109 - deleted: (response as unknown as Record<string, unknown>).deleted,
110 - message: (response as unknown as Record<string, unknown>).message,
103 + id: response.id,
104 + deleted: response.deleted,
105 });
106
107 if (!result.success) {
@@ -128,9 +122,8 @@ export function transformMcpUpdateResponse(response: McpUpdateResponseRaw): McpU
122 name: response.name,
123 createdAt: response.created_at,
124 updatedAt: response.updated_at,
131 - status: (response as unknown as Record<string, unknown>).status,
125 toolkits: response.toolkits,
133 - tools: (response as unknown as Record<string, unknown>).tools,
126 + tools: response.allowed_tools,
127 });
128
129 if (!result.success) {
ts/packages/core/test/core/credentials.test.ts
+359 -79
@@ -1,13 +1,17 @@
1 -import { describe, it, expect, afterEach, vi } from 'vitest';
1 +import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
2 +import { ComposioError as ClientComposioError } from '@composio/client';
3 import { Composio } from '../../src/composio';
4 import { MockProvider } from '../utils/mocks/provider.mock';
4 -import { ComposioNoAPIKeyError } from '../../src/errors/SDKErrors';
5 +import { ComposioError } from '../../src/errors/ComposioError';
6 +import { ComposioNoAPIKeyError, ComposioScopeConfigError } from '../../src/errors/SDKErrors';
7
8 /**
7 - * `userApiKey` / `orgApiKey` are forwarded to the API client, which selects the
8 - * credential per operation and resolves the env fallbacks itself.
9 + * The SDK resolves its credentials (options, environment fallbacks, and a
10 + * credential default header) and hands the API client a single `auth`, plus
11 + * the resolved org/project scope as `scope`. Neither travels through the
12 + * client's `defaultHeaders`, which refuses those names.
13 */
10 -describe('Composio user and organization API keys', () => {
14 +describe('Composio credentials and scope', () => {
15 const baseConfig = {
16 apiKey: 'ak_test',
17 baseURL: 'https://api.test.com',
@@ -16,95 +20,371 @@ describe('Composio user and organization API keys', () => {
20 disableVersionCheck: true,
21 };
22
23 + const captureFetch = () => {
24 + const fetchMock = vi.fn(async () => Response.json({}));
25 + vi.stubGlobal('fetch', fetchMock);
26 + return fetchMock;
27 + };
28 +
29 + const sentHeaders = (fetchMock: ReturnType<typeof captureFetch>, callIndex = 0) => {
30 + const call = fetchMock.mock.calls[callIndex] as unknown as [string, { headers: HeadersInit }];
31 + return new Headers(call[1].headers);
32 + };
33 +
34 + const credentialHeaders = (headers: Headers) => ({
35 + 'x-api-key': headers.get('x-api-key'),
36 + 'x-user-api-key': headers.get('x-user-api-key'),
37 + 'x-org-api-key': headers.get('x-org-api-key'),
38 + });
39 +
40 + beforeEach(() => {
41 + vi.stubEnv('COMPOSIO_API_KEY', undefined);
42 + vi.stubEnv('COMPOSIO_USER_API_KEY', undefined);
43 + vi.stubEnv('COMPOSIO_ORG_API_KEY', undefined);
44 + });
45 +
46 afterEach(() => {
47 vi.unstubAllEnvs();
48 + vi.unstubAllGlobals();
49 });
50
23 - it('forwards both keys to the API client', () => {
24 - const composio = new Composio({
25 - ...baseConfig,
26 - userApiKey: 'uak_test',
27 - orgApiKey: 'oak_test',
51 + describe('auth mapping', () => {
52 + it('authenticates every request with the project key when it is the only key', async () => {
53 + const fetchMock = captureFetch();
54 + const composio = new Composio(baseConfig);
55 +
56 + expect(composio.getClient().authMode).toBe('project');
57 + await composio.getClient().toolRouter.session.retrieve('trs_1');
58 + await composio.getClient().org.list();
59 +
60 + expect(credentialHeaders(sentHeaders(fetchMock, 0))).toEqual({
61 + 'x-api-key': 'ak_test',
62 + 'x-user-api-key': null,
63 + 'x-org-api-key': null,
64 + });
65 + expect(credentialHeaders(sentHeaders(fetchMock, 1))).toEqual({
66 + 'x-api-key': 'ak_test',
67 + 'x-user-api-key': null,
68 + 'x-org-api-key': null,
69 + });
70 });
29 - const client = composio.getClient();
30 - expect(client.apiKey).toBe('ak_test');
31 - expect(client.userApiKey).toBe('uak_test');
32 - expect(client.orgApiKey).toBe('oak_test');
33 - });
71
35 - it('leaves both keys unset on the client when not configured', () => {
36 - vi.stubEnv('COMPOSIO_USER_API_KEY', '');
37 - vi.stubEnv('COMPOSIO_ORG_API_KEY', '');
38 - const client = new Composio(baseConfig).getClient();
39 - expect(client.userApiKey).toBeNull();
40 - expect(client.orgApiKey).toBeNull();
41 - });
72 + it('selects per operation when the project key comes with a user key', async () => {
73 + const fetchMock = captureFetch();
74 + const composio = new Composio({ ...baseConfig, userApiKey: 'uak_test' });
75
43 - it('lets the client resolve the env fallbacks', () => {
44 - vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
45 - vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');
46 - const client = new Composio(baseConfig).getClient();
47 - expect(client.userApiKey).toBe('uak_env');
48 - expect(client.orgApiKey).toBe('oak_env');
49 - });
76 + expect(composio.getClient().authMode).toBe('auto');
77 + await composio.getClient().toolRouter.session.retrieve('trs_1');
78 + await composio.getClient().org.list();
79
51 - it('exposes both keys on getConfig() and carries them into createSession()', () => {
52 - const composio = new Composio({
53 - ...baseConfig,
54 - userApiKey: 'uak_test',
55 - orgApiKey: 'oak_test',
56 - });
57 - expect(composio.getConfig()).toMatchObject({ userApiKey: 'uak_test', orgApiKey: 'oak_test' });
58 - const session = composio.createSession({ headers: { 'x-request-id': '1' } });
59 - expect(session.getConfig()).toMatchObject({ userApiKey: 'uak_test', orgApiKey: 'oak_test' });
60 - expect(session.getClient().userApiKey).toBe('uak_test');
61 - expect(session.getClient().orgApiKey).toBe('oak_test');
62 - });
80 + expect(credentialHeaders(sentHeaders(fetchMock, 0))).toEqual({
81 + 'x-api-key': 'ak_test',
82 + 'x-user-api-key': null,
83 + 'x-org-api-key': null,
84 + });
85 + expect(credentialHeaders(sentHeaders(fetchMock, 1))).toEqual({
86 + 'x-api-key': null,
87 + 'x-user-api-key': 'uak_test',
88 + 'x-org-api-key': null,
89 + });
90 + });
91
64 - it('stores env-resolved keys on the config so createSession() keeps them after env changes', () => {
65 - vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
66 - vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');
67 - const composio = new Composio(baseConfig);
68 - expect(composio.getConfig()).toMatchObject({ userApiKey: 'uak_env', orgApiKey: 'oak_env' });
69 -
70 - vi.stubEnv('COMPOSIO_USER_API_KEY', '');
71 - vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_other');
72 - const session = composio.createSession({ headers: { 'x-request-id': '1' } });
73 - expect(session.getClient().userApiKey).toBe('uak_env');
74 - expect(session.getClient().orgApiKey).toBe('oak_env');
75 - });
92 + it('selects per operation when the project key comes with an organization key', async () => {
93 + const fetchMock = captureFetch();
94 + const composio = new Composio({ ...baseConfig, orgApiKey: 'oak_test' });
95 +
96 + expect(composio.getClient().authMode).toBe('auto');
97 + await composio.getClient().toolkits.retrieve('github');
98 + await composio.getClient().org.owner.project.list();
99
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();
100 + expect(sentHeaders(fetchMock, 0).get('x-api-key')).toBe('ak_test');
101 + expect(credentialHeaders(sentHeaders(fetchMock, 1))).toEqual({
102 + 'x-api-key': null,
103 + 'x-user-api-key': null,
104 + 'x-org-api-key': 'oak_test',
105 + });
106 + });
107 +
108 + it('selects per operation with all three keys, resolving the alternates from the environment', async () => {
109 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
110 + vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');
111 + const fetchMock = captureFetch();
112 + const composio = new Composio(baseConfig);
113 +
114 + expect(composio.getClient().authMode).toBe('auto');
115 + await composio.getClient().org.list();
116 + await composio.getClient().org.owner.project.list();
117 +
118 + expect(sentHeaders(fetchMock, 0).get('x-user-api-key')).toBe('uak_env');
119 + expect(sentHeaders(fetchMock, 1).get('x-org-api-key')).toBe('oak_env');
120 + });
121 +
122 + it('authenticates every request, sessions included, with the user key when the project key is disabled', async () => {
123 + const fetchMock = captureFetch();
124 + const composio = new Composio({ ...baseConfig, apiKey: null, userApiKey: 'uak_test' });
125 +
126 + expect(composio.getClient().authMode).toBe('user');
127 + await composio.getClient().toolRouter.session.retrieve('trs_1');
128 +
129 + expect(credentialHeaders(sentHeaders(fetchMock))).toEqual({
130 + 'x-api-key': null,
131 + 'x-user-api-key': 'uak_test',
132 + 'x-org-api-key': null,
133 + });
134 + });
135 +
136 + it('reads COMPOSIO_USER_API_KEY when the project key is disabled and the option is omitted', () => {
137 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
138 +
139 + const composio = new Composio({ ...baseConfig, apiKey: null });
140 +
141 + expect(composio.getClient().authMode).toBe('user');
142 + expect(composio.getConfig()).toMatchObject({ apiKey: null, userApiKey: 'uak_env' });
143 + });
144 +
145 + it('keeps the user key on every request when an organization key is also configured', async () => {
146 + const fetchMock = captureFetch();
147 + const composio = new Composio({
148 + ...baseConfig,
149 + apiKey: null,
150 + userApiKey: 'uak_test',
151 + orgApiKey: 'oak_test',
152 + });
153 +
154 + expect(composio.getClient().authMode).toBe('user');
155 + await composio.getClient().toolRouter.session.retrieve('trs_1');
156 + await composio.getClient().org.owner.project.list();
157 +
158 + expect(credentialHeaders(sentHeaders(fetchMock, 0))).toEqual({
159 + 'x-api-key': null,
160 + 'x-user-api-key': 'uak_test',
161 + 'x-org-api-key': null,
162 + });
163 + expect(credentialHeaders(sentHeaders(fetchMock, 1))).toEqual({
164 + 'x-api-key': null,
165 + 'x-user-api-key': 'uak_test',
166 + 'x-org-api-key': null,
167 + });
168 + });
169 +
170 + it('authenticates every request with the organization key when it is the only key', async () => {
171 + const fetchMock = captureFetch();
172 + const composio = new Composio({ ...baseConfig, apiKey: null, orgApiKey: 'oak_test' });
173 +
174 + expect(composio.getClient().authMode).toBe('organization');
175 + await composio.getClient().org.owner.project.list();
176 +
177 + expect(credentialHeaders(sentHeaders(fetchMock))).toEqual({
178 + 'x-api-key': null,
179 + 'x-user-api-key': null,
180 + 'x-org-api-key': 'oak_test',
181 + });
182 + });
183 +
184 + it('rejects a disabled project key when neither alternate key is configured', () => {
185 + vi.stubEnv('COMPOSIO_API_KEY', 'ak_env');
186 + expect(() => new Composio({ ...baseConfig, apiKey: null })).toThrow(ComposioNoAPIKeyError);
187 + });
188 });
189
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');
190 + describe('credential default headers', () => {
191 + it('authenticates with an x-user-api-key header alone and does not forward it as a header', async () => {
192 + const fetchMock = captureFetch();
193 + const composio = new Composio({
194 + ...baseConfig,
195 + apiKey: null,
196 + defaultHeaders: { 'X-User-Api-Key': 'uak_header', 'x-request-id': 'req-1' },
197 + });
198 +
199 + expect(composio.getClient().authMode).toBe('user');
200 + expect(composio.getConfig()).toMatchObject({
201 + apiKey: null,
202 + userApiKey: 'uak_header',
203 + defaultHeaders: { 'x-request-id': 'req-1' },
204 + });
205 + await composio.getClient().toolRouter.session.retrieve('trs_1');
206 +
207 + const headers = sentHeaders(fetchMock);
208 + expect(credentialHeaders(headers)).toEqual({
209 + 'x-api-key': null,
210 + 'x-user-api-key': 'uak_header',
211 + 'x-org-api-key': null,
212 + });
213 + expect(headers.get('x-request-id')).toBe('req-1');
214 + });
215 +
216 + it('lets an x-user-api-key header replace a configured project key', async () => {
217 + const fetchMock = captureFetch();
218 + const composio = new Composio({
219 + ...baseConfig,
220 + defaultHeaders: { 'x-user-api-key': 'uak_header' },
221 + });
222 +
223 + expect(composio.getClient().authMode).toBe('user');
224 + await composio.getClient().toolkits.retrieve('github');
225 +
226 + expect(credentialHeaders(sentHeaders(fetchMock))).toEqual({
227 + 'x-api-key': null,
228 + 'x-user-api-key': 'uak_header',
229 + 'x-org-api-key': null,
230 + });
231 + });
232 +
233 + it('lets an x-org-api-key header replace the configured keys', () => {
234 + const composio = new Composio({
235 + ...baseConfig,
236 + userApiKey: 'uak_test',
237 + defaultHeaders: { 'x-org-api-key': 'oak_header' },
238 + });
239 +
240 + expect(composio.getClient().authMode).toBe('organization');
241 + expect(composio.getConfig()).toMatchObject({
242 + apiKey: null,
243 + userApiKey: null,
244 + orgApiKey: 'oak_header',
245 + });
246 + });
247 +
248 + it('takes the project key from an x-api-key header', async () => {
249 + const fetchMock = captureFetch();
250 + const composio = new Composio({
251 + ...baseConfig,
252 + defaultHeaders: { 'x-api-key': 'ak_header' },
253 + });
254 +
255 + expect(composio.getClient().authMode).toBe('project');
256 + await composio.getClient().toolkits.retrieve('github');
257 +
258 + expect(sentHeaders(fetchMock).get('x-api-key')).toBe('ak_header');
259 + });
260 +
261 + it('rejects more than one credential header', () => {
262 + expect(
263 + () =>
264 + new Composio({
265 + ...baseConfig,
266 + defaultHeaders: { 'x-api-key': 'ak_header', 'x-user-api-key': 'uak_header' },
267 + })
268 + ).toThrow(ComposioError);
269 + });
270 +
271 + it('rejects a raw x-api-key default header when the project key is disabled', () => {
272 + expect(
273 + () =>
274 + new Composio({
275 + ...baseConfig,
276 + apiKey: null,
277 + userApiKey: 'uak_test',
278 + defaultHeaders: { 'x-api-key': 'ak_raw' },
279 + })
280 + ).toThrow(ComposioNoAPIKeyError);
281 + });
282 +
283 + it('still lets the API client reject identity headers', () => {
284 + expect(
285 + () => new Composio({ ...baseConfig, defaultHeaders: { 'x-source': 'custom' } })
286 + ).toThrow(ClientComposioError);
287 + });
288 });
289
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);
290 + describe('createSession()', () => {
291 + it('carries the resolved keys on the config, not the API client, into clones', () => {
292 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
293 + vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');
294 + const composio = new Composio(baseConfig);
295 + expect(composio.getConfig()).toMatchObject({ userApiKey: 'uak_env', orgApiKey: 'oak_env' });
296 +
297 + vi.stubEnv('COMPOSIO_USER_API_KEY', '');
298 + vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_other');
299 + const session = composio.createSession({ headers: { 'x-request-id': '1' } });
300 +
301 + expect(session.getConfig()).toMatchObject({
302 + apiKey: 'ak_test',
303 + userApiKey: 'uak_env',
304 + orgApiKey: 'oak_env',
305 + });
306 + expect(session.getClient().authMode).toBe('auto');
307 + });
308 +
309 + it('routes a user key from the parent default headers through auth', async () => {
310 + const fetchMock = captureFetch();
311 + const composio = new Composio({
312 + ...baseConfig,
313 + defaultHeaders: { 'x-user-api-key': 'uak_header' },
314 + });
315 +
316 + const session = composio.createSession({ headers: { 'x-request-id': 'req-2' } });
317 + await session.getClient().toolRouter.session.retrieve('trs_1');
318 +
319 + expect(session.getConfig().defaultHeaders).toEqual({ 'x-request-id': 'req-2' });
320 + expect(session.getClient().authMode).toBe('user');
321 + expect(credentialHeaders(sentHeaders(fetchMock))).toEqual({
322 + 'x-api-key': null,
323 + 'x-user-api-key': 'uak_header',
324 + 'x-org-api-key': null,
325 + });
326 + });
327 +
328 + it('lets a clone header replace the parent user key', () => {
329 + const composio = new Composio({ ...baseConfig, apiKey: null, userApiKey: 'uak_parent' });
330 +
331 + const session = composio.createSession({ headers: { 'x-user-api-key': 'uak_clone' } });
332 +
333 + expect(session.getConfig()).toMatchObject({ apiKey: null, userApiKey: 'uak_clone' });
334 + expect(session.getClient().authMode).toBe('user');
335 + });
336 });
337
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);
338 + describe('scope', () => {
339 + const orgId = 'org_nano_abc';
340 + const projectId = 'proj_nano_xyz';
341 +
342 + it('passes orgId and projectId to the API client as its scope', async () => {
343 + const fetchMock = captureFetch();
344 + const composio = new Composio({ ...baseConfig, orgId, projectId });
345 +
346 + expect(composio.getClient().scope).toEqual({ organizationId: orgId, projectId });
347 + await composio.getClient().toolkits.retrieve('github');
348 +
349 + const headers = sentHeaders(fetchMock);
350 + expect(headers.get('x-org-id')).toBe(orgId);
351 + expect(headers.get('x-project-id')).toBe(projectId);
352 + });
353 +
354 + it('moves a scope supplied through default headers into the client scope', () => {
355 + const composio = new Composio({
356 + ...baseConfig,
357 + defaultHeaders: { 'X-Org-Id': orgId, 'x-project-id': projectId, 'x-request-id': 'r' },
358 + });
359 +
360 + expect(composio.getClient().scope).toEqual({ organizationId: orgId, projectId });
361 + expect(composio.getConfig()).toMatchObject({
362 + orgId,
363 + projectId,
364 + defaultHeaders: { 'x-request-id': 'r' },
365 + });
366 + });
367 +
368 + it('leaves the client unscoped without a scope', () => {
369 + expect(new Composio(baseConfig).getClient().scope).toBeUndefined();
370 + });
371 +
372 + it('keeps the scope on clones', () => {
373 + const session = new Composio({ ...baseConfig, orgId, projectId }).createSession();
374 +
375 + expect(session.getClient().scope).toEqual({ organizationId: orgId, projectId });
376 + });
377 +
378 + it('rejects a scope option that disagrees with its default header', () => {
379 + expect(
380 + () =>
381 + new Composio({
382 + ...baseConfig,
383 + orgId,
384 + projectId,
385 + defaultHeaders: { 'x-org-id': 'org_other' },
386 + })
387 + ).toThrow(ComposioScopeConfigError);
388 + });
389 });
390 });
ts/packages/core/test/core/session.test.ts
+1 -1
@@ -495,7 +495,7 @@ describe('Credential resolution at the transport boundary', () => {
495 expect(headers.get('x-api-key')).toBeNull();
496 expect(headers.get('x-user-api-key')).toBe(userKey);
497 expect(composio.getConfig().apiKey).toBeNull();
498 - expect(composio.getClient().apiKey).toBeNull();
498 + expect(composio.getClient().authMode).toBe('user');
499 });
500
501 it('sends only the user API key header when the project key is disabled via defaultHeaders', async () => {
ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 -import ComposioClient from '@composio/client';
2 +import ComposioClient, { Auth } from '@composio/client';
3 import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';
4 import { ComposioBlockedInternalUrlError, ValidationError } from '../../src/errors';
5 import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';
@@ -16,7 +16,7 @@ const mockLookup = vi.mocked(lookup);
16 const sessionId = 'trs_session_123';
17
18 const createMockClient = () => {
19 - const client = new ComposioClient({ apiKey: 'test-api-key' });
19 + const client = new ComposioClient({ auth: Auth.project('test-api-key') });
20 const files = Object.assign(client.toolRouter.session.files, {
21 list: vi.fn<typeof client.toolRouter.session.files.list>(),
22 createUploadURL: vi.fn<typeof client.toolRouter.session.files.createUploadURL>(),
ts/packages/core/test/models/customTool.test.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 -import ComposioClient from '@composio/client';
2 +import ComposioClient, { Auth } from '@composio/client';
3 import { z as z4 } from 'zod';
4 import { z } from 'zod/v3';
5 import {
@@ -779,7 +779,7 @@ describe('serializeCustomToolkits', () => {
779 // ────────────────────────────────────────────────────────────────
780
781 describe('SessionContextImpl', () => {
782 - const client = new ComposioClient({ apiKey: 'test-api-key' });
782 + const client = new ComposioClient({ auth: Auth.project('test-api-key') });
783 const session = Object.assign(client.toolRouter.session, {
784 execute: vi.fn<typeof client.toolRouter.session.execute>(),
785 proxyExecute: vi.fn<typeof client.toolRouter.session.proxyExecute>(),
ts/packages/core/test/models/inputRequiredExecution.test.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { describe, it, expect, vi, assert } from 'vitest';
2 -import ComposioClient, { createFetchTransport } from '@composio/client';
2 +import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
3 import { z } from 'zod/v3';
4 import { Tools } from '../../src/models/Tools';
5 import { ToolRouterSession } from '../../src/models/ToolRouterSession';
@@ -52,7 +52,7 @@ const createClient = (body: unknown) => {
52 })
53 );
54 const client = new ComposioClient({
55 - apiKey: 'test-api-key',
55 + auth: Auth.project('test-api-key'),
56 baseURL: 'https://backend.invalid',
57 transport: createFetchTransport({ fetch }),
58 });
ts/packages/core/test/models/mcp.deprecation.test.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { describe, it, expect, vi } from 'vitest';
2 -import ComposioClient, { createFetchTransport } from '@composio/client';
2 +import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
3 import { MCP } from '../../src/models/MCP';
4 import logger from '../../src/utils/logger';
5
@@ -14,7 +14,7 @@ describe('MCP.generate managed auth deprecation', () => {
14 it('replaces the API client notice with one SDK notice per process', async () => {
15 const clientLogger = { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() };
16 const client = new ComposioClient({
17 - apiKey: 'test-api-key',
17 + auth: Auth.project('test-api-key'),
18 baseURL: 'https://backend.composio.test',
19 logger: clientLogger,
20 logLevel: 'warn',
ts/packages/core/test/models/noRetryExecution.test.ts
+2 -2
@@ -1,5 +1,5 @@
1 import { describe, it, expect, vi } from 'vitest';
2 -import ComposioClient, { createFetchTransport } from '@composio/client';
2 +import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
3 import { Tools } from '../../src/models/Tools';
4 import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5 import { SessionContextImpl } from '../../src/models/SessionContext';
@@ -33,7 +33,7 @@ const createFailingClient = () => {
33 })
34 );
35 const client = new ComposioClient({
36 - apiKey: 'test-api-key',
36 + auth: Auth.project('test-api-key'),
37 baseURL: 'https://backend.invalid',
38 transport: createFetchTransport({ fetch }),
39 });
ts/packages/core/test/services/pusher.test.ts
+29 -11
@@ -83,7 +83,7 @@ vi.mock('../../src/utils/logger', () => ({
83 const credentials = { projectId: 'project-id', pusherKey: 'pusher-key', pusherCluster: 'mt1' };
84
85 const createService = () =>
86 - new PusherService({ baseURL: 'https://backend.composio.dev', apiKey: 'api-key' } as never);
86 + new PusherService({ baseURL: 'https://backend.composio.dev' } as never, { apiKey: 'api-key' });
87
88 const flushMacrotask = () =>
89 new Promise<void>(resolve => {
@@ -442,16 +442,16 @@ describe('PusherService channel authorization credentials', () => {
442 vi.unstubAllEnvs();
443 });
444
445 - it('sends the project key of the client as x-api-key', async () => {
446 - const service = new PusherService({ baseURL, apiKey: 'ak_projectKey' } as never);
445 + it('sends the project key the SDK resolved as x-api-key', async () => {
446 + const service = new PusherService({ baseURL } as never, { apiKey: 'ak_projectKey' });
447
448 await service.subscribe(vi.fn());
449
450 expect(channelAuthHeaders()).toEqual({ 'x-api-key': 'ak_projectKey' });
451 });
452
453 - it('sends no project key and never reads COMPOSIO_API_KEY when the client key is null', async () => {
454 - const service = new PusherService({ baseURL, apiKey: null, userApiKey: null } as never);
453 + it('sends no project key and never reads COMPOSIO_API_KEY when the SDK key is null', async () => {
454 + const service = new PusherService({ baseURL } as never, { apiKey: null, userApiKey: null });
455
456 await service.subscribe(vi.fn());
457
@@ -459,20 +459,38 @@ describe('PusherService channel authorization credentials', () => {
459 expect(JSON.stringify(pusherConstructorOptions)).not.toContain('ak_foreignAmbientKey');
460 });
461
462 - it('sends the resolved user API key of the client when the project key is null', async () => {
463 - const service = new PusherService({
464 - baseURL,
462 + it('sends the user API key the SDK resolved when the project key is null', async () => {
463 + const service = new PusherService({ baseURL } as never, {
464 apiKey: null,
465 userApiKey: 'uak_userKey',
467 - } as never);
466 + });
467
468 await service.subscribe(vi.fn());
469
470 expect(channelAuthHeaders()).toEqual({ 'x-user-api-key': 'uak_userKey' });
471 });
472
474 - it('falls back to the x-user-api-key default header when the client holds no key', async () => {
475 - const service = new PusherService({ baseURL, apiKey: null, userApiKey: null } as never, {
473 + it('never reads a key back from the API client', async () => {
474 + const client = {
475 + baseURL,
476 + get apiKey(): string {
477 + throw new Error('client.apiKey must not be read');
478 + },
479 + get userApiKey(): string {
480 + throw new Error('client.userApiKey must not be read');
481 + },
482 + };
483 + const service = new PusherService(client as never, { apiKey: 'ak_sdkKey' });
484 +
485 + await service.subscribe(vi.fn());
486 +
487 + expect(channelAuthHeaders()).toEqual({ 'x-api-key': 'ak_sdkKey' });
488 + });
489 +
490 + it('falls back to the x-user-api-key default header when the SDK holds no key', async () => {
491 + const service = new PusherService({ baseURL } as never, {
492 + apiKey: null,
493 + userApiKey: null,
494 defaultHeaders: { 'X-User-Api-Key': 'uak_headerKey', 'x-request-id': 'req-1' },
495 });
496
ts/packages/core/test/utils/mocks/client.mock.ts
+2 -2
@@ -1,7 +1,7 @@
1 import { vi } from 'vitest';
2 -import ComposioClient from '@composio/client';
2 +import ComposioClient, { Auth } from '@composio/client';
3
4 -const client = new ComposioClient({ apiKey: 'test-api-key' });
4 +const client = new ComposioClient({ auth: Auth.project('test-api-key') });
5
6 const tools = Object.assign(client.tools, {
7 list: vi.fn<typeof client.tools.list>(),
ts/packages/core/test/utils/sdk.test.ts
+183 -1
@@ -2,7 +2,17 @@ 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';
5 +import { Auth } from '@composio/client';
6 +import {
7 + getSDKConfig,
8 + getUserApiKeyHeader,
9 + resolveCredentialHeaders,
10 + resolveSDKCredentials,
11 + toClientAuth,
12 + toClientScope,
13 + withoutSDKOwnedHeaders,
14 +} from '../../src/utils/sdk';
15 +import { ComposioError } from '../../src/errors/ComposioError';
16 import {
17 ComposioAPIKeyKindError,
18 ComposioNoAPIKeyError,
@@ -362,3 +372,175 @@ describe('resolveCredentialHeaders', () => {
372 ).toEqual({});
373 });
374 });
375 +
376 +describe('resolveSDKCredentials', () => {
377 + beforeEach(() => {
378 + vi.stubEnv('COMPOSIO_USER_API_KEY', undefined);
379 + vi.stubEnv('COMPOSIO_ORG_API_KEY', undefined);
380 + });
381 +
382 + afterEach(() => {
383 + vi.unstubAllEnvs();
384 + });
385 +
386 + it('keeps the resolved project key and the explicit alternate keys', () => {
387 + expect(
388 + resolveSDKCredentials({ apiKey: PROJECT_KEY, userApiKey: USER_KEY, orgApiKey: ORG_KEY })
389 + ).toEqual({ apiKey: PROJECT_KEY, userApiKey: USER_KEY, orgApiKey: ORG_KEY });
390 + });
391 +
392 + it('falls back to the environment for omitted alternate keys, and not for null ones', () => {
393 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
394 + vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');
395 +
396 + expect(resolveSDKCredentials({ apiKey: PROJECT_KEY })).toEqual({
397 + apiKey: PROJECT_KEY,
398 + userApiKey: 'uak_env',
399 + orgApiKey: 'oak_env',
400 + });
401 + expect(
402 + resolveSDKCredentials({ apiKey: PROJECT_KEY, userApiKey: null, orgApiKey: null })
403 + ).toEqual({ apiKey: PROJECT_KEY, userApiKey: null, orgApiKey: null });
404 + });
405 +
406 + it('folds an x-user-api-key header in as the only user credential', () => {
407 + expect(
408 + resolveSDKCredentials({
409 + apiKey: PROJECT_KEY,
410 + userApiKey: 'uak_option',
411 + orgApiKey: ORG_KEY,
412 + defaultHeaders: { 'X-User-Api-Key': USER_KEY },
413 + })
414 + ).toEqual({ apiKey: null, userApiKey: USER_KEY, orgApiKey: ORG_KEY });
415 + });
416 +
417 + it('folds an x-org-api-key header in as the only credential', () => {
418 + expect(
419 + resolveSDKCredentials({
420 + apiKey: PROJECT_KEY,
421 + userApiKey: USER_KEY,
422 + defaultHeaders: { 'x-org-api-key': ORG_KEY },
423 + })
424 + ).toEqual({ apiKey: null, userApiKey: null, orgApiKey: ORG_KEY });
425 + });
426 +
427 + it('folds an x-api-key header in as the project key', () => {
428 + expect(
429 + resolveSDKCredentials({
430 + apiKey: EXPLICIT_KEY,
431 + userApiKey: USER_KEY,
432 + defaultHeaders: { 'x-api-key': PROJECT_KEY },
433 + })
434 + ).toEqual({ apiKey: PROJECT_KEY, userApiKey: USER_KEY, orgApiKey: null });
435 + });
436 +
437 + it('ignores empty credential headers', () => {
438 + expect(
439 + resolveSDKCredentials({
440 + apiKey: PROJECT_KEY,
441 + defaultHeaders: { 'x-user-api-key': '', 'x-org-api-key': '' },
442 + })
443 + ).toEqual({ apiKey: PROJECT_KEY, userApiKey: null, orgApiKey: null });
444 + });
445 +
446 + it('rejects two credential headers without echoing either value', () => {
447 + const resolve = () =>
448 + resolveSDKCredentials({
449 + apiKey: PROJECT_KEY,
450 + defaultHeaders: { 'x-user-api-key': USER_KEY, 'X-Org-Api-Key': ORG_KEY },
451 + });
452 +
453 + expect(resolve).toThrow(ComposioError);
454 + expect(resolve).toThrow('`defaultHeaders` carries more than one credential header');
455 + const error = (() => {
456 + try {
457 + resolve();
458 + } catch (caught) {
459 + return caught as ComposioError;
460 + }
461 + })();
462 + expect(JSON.stringify({ message: error?.message, cause: error?.cause })).not.toMatch(
463 + /uak_|oak_/
464 + );
465 + });
466 +});
467 +
468 +describe('toClientAuth', () => {
469 + it.each([
470 + [
471 + 'a project key alone',
472 + { apiKey: PROJECT_KEY, userApiKey: null, orgApiKey: null },
473 + Auth.project(PROJECT_KEY),
474 + ],
475 + [
476 + 'a project key and a user key',
477 + { apiKey: PROJECT_KEY, userApiKey: USER_KEY, orgApiKey: null },
478 + Auth.auto({ project: PROJECT_KEY, user: USER_KEY }),
479 + ],
480 + [
481 + 'a project key and an organization key',
482 + { apiKey: PROJECT_KEY, userApiKey: null, orgApiKey: ORG_KEY },
483 + Auth.auto({ project: PROJECT_KEY, organization: ORG_KEY }),
484 + ],
485 + [
486 + 'all three keys',
487 + { apiKey: PROJECT_KEY, userApiKey: USER_KEY, orgApiKey: ORG_KEY },
488 + Auth.auto({ project: PROJECT_KEY, user: USER_KEY, organization: ORG_KEY }),
489 + ],
490 + [
491 + 'a user key without a project key',
492 + { apiKey: null, userApiKey: USER_KEY, orgApiKey: null },
493 + Auth.user(USER_KEY),
494 + ],
495 + [
496 + 'a user and an organization key without a project key',
497 + { apiKey: null, userApiKey: USER_KEY, orgApiKey: ORG_KEY },
498 + Auth.user(USER_KEY),
499 + ],
500 + [
501 + 'an organization key alone',
502 + { apiKey: null, userApiKey: null, orgApiKey: ORG_KEY },
503 + Auth.organization(ORG_KEY),
504 + ],
505 + ])('maps %s', (_name, credentials, expected) => {
506 + expect(toClientAuth(credentials)).toEqual(expected);
507 + });
508 +
509 + it('refuses to build auth without any credential', () => {
510 + expect(() => toClientAuth({ apiKey: null, userApiKey: null, orgApiKey: null })).toThrow(
511 + ComposioNoAPIKeyError
512 + );
513 + });
514 +});
515 +
516 +describe('toClientScope', () => {
517 + it('maps a resolved scope to the client scope', () => {
518 + expect(toClientScope({ orgId: 'org_1', projectId: 'proj_1' })).toEqual({
519 + organizationId: 'org_1',
520 + projectId: 'proj_1',
521 + });
522 + });
523 +
524 + it('leaves an unscoped instance unscoped', () => {
525 + expect(toClientScope({})).toBeUndefined();
526 + });
527 +});
528 +
529 +describe('withoutSDKOwnedHeaders', () => {
530 + it('drops credential and scope headers in any letter case and keeps the rest', () => {
531 + expect(
532 + withoutSDKOwnedHeaders({
533 + 'X-Api-Key': PROJECT_KEY,
534 + 'x-user-api-key': USER_KEY,
535 + 'X-ORG-API-KEY': ORG_KEY,
536 + 'x-org-id': 'org_1',
537 + 'X-Project-Id': 'proj_1',
538 + 'x-request-id': 'req-1',
539 + })
540 + ).toEqual({ 'x-request-id': 'req-1' });
541 + });
542 +
543 + it('keeps undefined as undefined', () => {
544 + expect(withoutSDKOwnedHeaders(undefined)).toBeUndefined();
545 + });
546 +});
ts/packages/core/test/utils/transformers/mcp.test.ts
+23 -27
@@ -15,22 +15,31 @@ describe('MCP Transformers', () => {
15 const snakeCaseResponse = {
16 id: 'mcp_123',
17 name: 'test-server',
18 - created_at: '2024-01-01T00:00:00Z',
19 - updated_at: '2024-01-02T00:00:00Z',
20 - status: 'active',
18 + auth_config_ids: ['ac_1'],
19 + allowed_tools: ['GMAIL_SEND_EMAIL'],
20 + mcp_url: 'https://mcp.example.com/server',
21 + commands: { claude: 'claude', cursor: 'cursor', windsurf: 'windsurf' },
22 } as unknown;
23
24 const result = transformMcpCreateResponse(snakeCaseResponse);
25
25 - expect(result).toEqual({
26 + expect(result).toStrictEqual({
27 id: 'mcp_123',
28 name: 'test-server',
28 - createdAt: '2024-01-01T00:00:00Z',
29 - updatedAt: '2024-01-02T00:00:00Z',
30 - status: 'active',
29 });
30 });
31
32 + it('does not read timestamps or a status the create response never carries', () => {
33 + const result = transformMcpCreateResponse({
34 + id: 'mcp_123',
35 + name: 'test-server',
36 + created_at: '2024-01-01T00:00:00Z',
37 + status: 'active',
38 + } as unknown);
39 +
40 + expect(result).toStrictEqual({ id: 'mcp_123', name: 'test-server' });
41 + });
42 +
43 it('should handle missing optional fields', () => {
44 const minimalResponse = {
45 id: 'mcp_123',
@@ -67,14 +76,12 @@ describe('MCP Transformers', () => {
76 name: 'server-1',
77 created_at: '2024-01-01T00:00:00Z',
78 updated_at: '2024-01-01T00:00:00Z',
70 - status: 'active',
79 },
80 {
81 id: 'mcp_456',
82 name: 'server-2',
83 created_at: '2024-01-02T00:00:00Z',
84 updated_at: '2024-01-02T00:00:00Z',
77 - status: 'inactive',
85 },
86 ],
87 } as unknown;
@@ -88,14 +95,12 @@ describe('MCP Transformers', () => {
95 name: 'server-1',
96 createdAt: '2024-01-01T00:00:00Z',
97 updatedAt: '2024-01-01T00:00:00Z',
91 - status: 'active',
98 },
99 {
100 id: 'mcp_456',
101 name: 'server-2',
102 createdAt: '2024-01-02T00:00:00Z',
103 updatedAt: '2024-01-02T00:00:00Z',
98 - status: 'inactive',
104 },
105 ],
106 });
@@ -131,9 +136,8 @@ describe('MCP Transformers', () => {
136 name: 'test-server',
137 created_at: '2024-01-01T00:00:00Z',
138 updated_at: '2024-01-02T00:00:00Z',
134 - status: 'active',
139 toolkits: ['gmail', 'github'],
136 - tools: undefined,
140 + allowed_tools: ['GMAIL_SEND_EMAIL'],
141 managed_auth_via_composio: true,
142 mcp_url: 'https://mcp.example.com/server',
143 commands: {
@@ -150,9 +154,8 @@ describe('MCP Transformers', () => {
154 name: 'test-server',
155 createdAt: '2024-01-01T00:00:00Z',
156 updatedAt: '2024-01-02T00:00:00Z',
153 - status: 'active',
157 toolkits: ['gmail', 'github'],
155 - tools: undefined,
158 + tools: ['GMAIL_SEND_EMAIL'],
159 managedAuthViaComposio: true,
160 mcpUrl: 'https://mcp.example.com/server',
161 commands: {
@@ -204,15 +207,13 @@ describe('MCP Transformers', () => {
207 const snakeCaseResponse = {
208 id: 'mcp_123',
209 deleted: true,
207 - message: 'Server deleted successfully',
210 } as unknown;
211
212 const result = transformMcpDeleteResponse(snakeCaseResponse);
213
212 - expect(result).toEqual({
214 + expect(result).toStrictEqual({
215 id: 'mcp_123',
216 deleted: true,
215 - message: 'Server deleted successfully',
217 });
218 });
219
@@ -236,9 +237,8 @@ describe('MCP Transformers', () => {
237 name: 'updated-server',
238 created_at: '2024-01-01T00:00:00Z',
239 updated_at: '2024-01-03T00:00:00Z',
239 - status: 'active',
240 toolkits: ['gmail', 'slack'],
241 - tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE'],
241 + allowed_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE'],
242 } as unknown;
243
244 const result = transformMcpUpdateResponse(snakeCaseResponse);
@@ -248,7 +248,6 @@ describe('MCP Transformers', () => {
248 name: 'updated-server',
249 createdAt: '2024-01-01T00:00:00Z',
250 updatedAt: '2024-01-03T00:00:00Z',
251 - status: 'active',
251 toolkits: ['gmail', 'slack'],
252 tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE'],
253 });
@@ -366,12 +365,10 @@ describe('MCP Transformers', () => {
365
366 const result = transformMcpCreateResponse(responseWithNulls);
367
369 - expect(result).toEqual({
368 + // The create response carries no timestamps or status; they are not read.
369 + expect(result).toStrictEqual({
370 id: 'mcp_123',
371 name: 'test-server',
372 - createdAt: null,
373 - updatedAt: null,
374 - status: null,
372 });
373 });
374
@@ -404,10 +401,9 @@ describe('MCP Transformers', () => {
401 const result = transformMcpCreateResponse(responseWithExtraFields);
402
403 // Should only include known fields
407 - expect(result).toEqual({
404 + expect(result).toStrictEqual({
405 id: 'mcp_123',
406 name: 'test-server',
410 - createdAt: '2024-01-01T00:00:00Z',
407 });
408 expect(result).not.toHaveProperty('some_unknown_field');
409 expect(result).not.toHaveProperty('nested_object');
uv.lock
+9 -9
@@ -757,7 +757,7 @@ dev = [
757
758 [package.metadata]
759 requires-dist = [
760 - { name = "composio-client", specifier = "==2.0.0rc17" },
760 + { name = "composio-client", specifier = "==2.0.0rc18" },
761 { name = "json-schema-to-pydantic", specifier = ">=0.4.11" },
762 { name = "jsonschema", specifier = ">=4.23.0" },
763 { name = "openai", specifier = ">=2.48.0" },
@@ -803,16 +803,16 @@ requires-dist = [
803
804 [[package]]
805 name = "composio-client"
806 -version = "2.0.0rc17"
806 +version = "2.0.0rc18"
807 source = { registry = "https://pypi.org/simple" }
808 dependencies = [
809 { name = "httpx" },
810 { name = "pydantic" },
811 { name = "typing-extensions" },
812 ]
813 -sdist = { url = "https://files.pythonhosted.org/packages/4f/5b/46db80356fd2fe5c4b47256bf2f8f8d0821609eafb6f9016a36c4aceb90f/composio_client-2.0.0rc17.tar.gz", hash = "sha256:9e6f3df1910518f4cd7c65c9a573986e11f0dbe02be0ec72175616fc3d7a45b1", size = 620910, upload-time = "2026-10-15T19:45:14.864Z" }
813 +sdist = { url = "https://files.pythonhosted.org/packages/62/cf/dbcfc9ca2f22117a5713c9bda594e94ccc7c0982a4496949bbb5ab19dad9/composio_client-2.0.0rc18.tar.gz", hash = "sha256:b0ee06db35c724fdafc7de2a60600f6cffa845bef83f7989c1f4fb9e628db185", size = 633932, upload-time = "2026-10-15T22:21:53.89Z" }
814 wheels = [
815 - { url = "https://files.pythonhosted.org/packages/05/38/078d855a7c0f7edd24786e184a032a14333042367f0434b9beab5ecfa16e/composio_client-2.0.0rc17-py3-none-any.whl", hash = "sha256:cf12b509818fe077d58def2e5ca9c6931c5e7646e43506283204e3b823207f3a", size = 448281, upload-time = "2026-10-15T19:45:12.857Z" },
815 + { url = "https://files.pythonhosted.org/packages/e1/e5/c17922253b80831c2aa4872ee2dd1161b624db67f937a7228345e3bd73e8/composio_client-2.0.0rc18-py3-none-any.whl", hash = "sha256:3852b2311c35229ef2109d36525bfbc3d696bbd88dd347b731b7d9233d22b199", size = 455413, upload-time = "2026-10-15T22:21:52.271Z" },
816 ]
817
818 [[package]]
@@ -1749,8 +1749,8 @@ name = "httpcore2"
1749 version = "2.13.0"
1750 source = { registry = "https://pypi.org/simple" }
1751 dependencies = [
1752 - { name = "h11", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
1753 - { name = "truststore", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
1752 + { name = "h11" },
1753 + { name = "truststore" },
1754 ]
1755 sdist = { url = "https://files.pythonhosted.org/packages/15/8c/e925b1c92018abb3a1863ce1549d76d2381e334d21d65d4ac8f65dabd78a/httpcore2-2.13.0.tar.gz", hash = "sha256:2adc8be4fb285fbcd6d894298db3b52c177e74b6674eda3a76bd36be3292a3db", size = 67740, upload-time = "2026-09-14T14:18:04.717Z" }
1756 wheels = [
@@ -1989,7 +1989,7 @@ name = "importlib-metadata"
1989 version = "9.0.1"
1990 source = { registry = "https://pypi.org/simple" }
1991 dependencies = [
1992 - { name = "zipp", marker = "python_full_version < '3.12'" },
1992 + { name = "zipp" },
1993 ]
1994 sdist = { url = "https://files.pythonhosted.org/packages/6f/7e/1e7e8dc30634b93ebb3d58a3dea569ad146e656218d3960ab04f62047b29/importlib_metadata-9.0.1.tar.gz", hash = "sha256:ab830580bc0ef3db61ce8fae716389e5462b67e033018bab6d8f80ef17172f99", size = 59124, upload-time = "2026-08-28T15:30:34.646Z" }
1995 wheels = [
@@ -4865,8 +4865,8 @@ name = "secretstorage"
4865 version = "3.5.0"
4866 source = { registry = "https://pypi.org/simple" }
4867 dependencies = [
4868 - { name = "cryptography", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
4869 - { name = "jeepney", marker = "python_full_version != '3.12.*' or sys_platform != 'emscripten'" },
4868 + { name = "cryptography" },
4869 + { name = "jeepney" },
4870 ]
4871 sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" }
4872 wheels = [