Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(core): add userApiKey and orgApiKey to ComposioConfig (#4532)
Alberto Schiabel17a20be89208
diff --git a/.changeset/core-user-org-api-keys.md b/.changeset/core-user-org-api-keys.mdnew file mode 100644index 000000000..54b2c1129--- /dev/null+++ b/.changeset/core-user-org-api-keys.md@@ -0,0 +1,5 @@+---+'@composio/core': minor+---++Add `userApiKey` and `orgApiKey` to `ComposioConfig`. Both are forwarded to the underlying API client, which sends each one only on operations whose security scheme requires it (organization, consumer, and user-scoped endpoints reached through `getClient()`), never alongside the project key. They fall back to `COMPOSIO_USER_API_KEY` and `COMPOSIO_ORG_API_KEY`. A project `apiKey` is still required.diff --git a/python/composio/client/__init__.py b/python/composio/client/__init__.pyindex b7aa15875..027613534 100644--- a/python/composio/client/__init__.py+++ b/python/composio/client/__init__.py@@ -196,6 +196,8 @@ class HttpClient(BaseComposio, WithLogger):*,provider: str,api_key: t.Optional[str] = None,+ user_api_key: t.Optional[str] = None,+ org_api_key: t.Optional[str] = None,environment: te.Union[NotGiven, APIEnvironment] = "production",base_url: t.Optional[t.Union[str, URL, NotGiven]] = NOT_GIVEN,timeout: t.Optional[t.Union[float, Timeout, NotGiven]] = NOT_GIVEN,@@ -214,6 +216,8 @@ class HttpClient(BaseComposio, WithLogger)::param logger: Logger that receives SDK and ``composio_client`` records.:param logging_level: Level applied to the SDK and ``composio_client`` loggers.:param api_key: The API key to use for the client.+ :param user_api_key: User API key, sent only on operations that require it.+ :param org_api_key: Organization API key, sent only on operations that require it.:param environment: The environment to use for the client.:param base_url: The base URL to use for the client.:param timeout: The timeout to use for the client.@@ -226,6 +230,8 @@ class HttpClient(BaseComposio, WithLogger):BaseComposio.__init__(self,api_key=api_key,+ user_api_key=user_api_key,+ org_api_key=org_api_key,environment=environment,base_url=base_url,timeout=timeout,diff --git a/python/composio/sdk.py b/python/composio/sdk.pyindex b1ad08a35..78c145e09 100644--- a/python/composio/sdk.py+++ b/python/composio/sdk.py@@ -43,6 +43,8 @@ _TOOL_ROUTER_DEPRECATION = (class SDKConfig(te.TypedDict):environment: te.NotRequired[APIEnvironment]api_key: te.NotRequired[str]+ user_api_key: te.NotRequired[str]+ org_api_key: te.NotRequired[str]base_url: te.NotRequired[str]timeout: te.NotRequired[int]max_retries: te.NotRequired[int]@@ -110,6 +112,16 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger)::param provider: The provider to use for the SDK. Defaults to OpenAIProvider.:param environment: The environment to use for the SDK.:param api_key: The API key to use for the SDK.+ :param user_api_key: User API key (``uak_*``) for the organization, consumer,+ and user-scoped endpoints reached through ``composio.client``. Sent as+ ``x-user-api-key`` only on operations whose security scheme requires it,+ never alongside the project key. Falls back to ``COMPOSIO_USER_API_KEY``.+ A project ``api_key`` is still required.+ :param org_api_key: Organization API key (``oak_*``) for the organization-owner+ endpoints reached through ``composio.client``. Sent as ``x-org-api-key`` only+ on operations whose security scheme requires it, never alongside the+ project key. Falls back to ``COMPOSIO_ORG_API_KEY``. A project ``api_key``+ is still required.:param base_url: The base URL to use for the SDK.:param timeout: The timeout to use for the SDK.:param max_retries: The maximum number of retries to use for the SDK.@@ -173,6 +185,8 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):environment=kwargs.get("environment", "production"),provider=actual_provider.name,api_key=api_key,+ user_api_key=kwargs.get("user_api_key"),+ org_api_key=kwargs.get("org_api_key"),base_url=kwargs.get("base_url") or os.environ.get("COMPOSIO_BASE_URL"),timeout=kwargs.get("timeout"),max_retries=kwargs.get("max_retries", DEFAULT_MAX_RETRIES),diff --git a/python/tests/test_sdk.py b/python/tests/test_sdk.pyindex 3eeef1096..92e2d7c80 100644--- a/python/tests/test_sdk.py+++ b/python/tests/test_sdk.py@@ -40,6 +40,29 @@ class TestComposioSDK:sdk = Composio(api_key="test-key")assert sdk is not None+ def test_sdk_forwards_user_and_org_api_keys_to_client(self):+ """User and org keys reach the API client, which selects them per operation."""+ sdk = Composio(+ api_key="ak_test", user_api_key="uak_test", org_api_key="oak_test"+ )+ assert sdk.client.api_key == "ak_test"+ assert sdk.client.user_api_key == "uak_test"+ assert sdk.client.org_api_key == "oak_test"++ def test_sdk_reads_user_and_org_api_keys_from_env(self):+ """The client resolves COMPOSIO_USER_API_KEY / COMPOSIO_ORG_API_KEY itself."""+ with patch.dict(+ os.environ,+ {+ "COMPOSIO_API_KEY": "ak_env",+ "COMPOSIO_USER_API_KEY": "uak_env",+ "COMPOSIO_ORG_API_KEY": "oak_env",+ },+ ):+ sdk = Composio()+ assert sdk.client.user_api_key == "uak_env"+ assert sdk.client.org_api_key == "oak_env"+def test_sdk_config_types(self):"""Test SDK configuration types."""from composio.sdk import SDKConfig@@ -51,6 +74,8 @@ class TestComposioSDK:expected_fields = {"environment","api_key",+ "user_api_key",+ "org_api_key","base_url","timeout","max_retries",diff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.tsindex 1e7947685..c296c5f33 100644--- a/ts/packages/core/src/composio.ts+++ b/ts/packages/core/src/composio.ts@@ -36,6 +36,24 @@ export type ComposioConfig<* @example 'sk-1234567890'*/apiKey?: string | null;+ /**+ * User API key (`uak_*`) for the organization, consumer, and user-scoped+ * endpoints reached through `getClient()` (for example `client.org.list()`).+ * Sent as `x-user-api-key` only on operations whose security scheme requires+ * it, never alongside the project key. Falls back to+ * `process.env['COMPOSIO_USER_API_KEY']`. A project `apiKey` is still required.+ * @example 'uak_1234567890'+ */+ userApiKey?: string | null;+ /**+ * Organization API key (`oak_*`) for the organization-owner endpoints reached+ * through `getClient()` (for example `client.org.owner.project.list()`).+ * Sent as `x-org-api-key` only on operations whose security scheme requires+ * it, never alongside the project key. Falls back to+ * `process.env['COMPOSIO_ORG_API_KEY']`. A project `apiKey` is still required.+ * @example 'oak_1234567890'+ */+ orgApiKey?: string | null;/*** The base URL of the Composio API.* @example 'https://backend.composio.dev'@@ -424,12 +442,20 @@ export class Composio<*/this.client = new ComposioClient({apiKey: apiKeyParsed,+ userApiKey: config?.userApiKey,+ orgApiKey: config?.orgApiKey,baseURL: baseURLParsed,defaultHeaders: defaultHeaders,logger: clientLoggerAdapter,logLevel: toClientLogLevel(logger.getLevel()),});+ // Store the resolved values, as with `apiKey`, so `getConfig()` and the+ // `createSession()` clone carry whatever the client resolved from env+ // rather than re-reading the environment later.+ this.config.userApiKey = this.client.userApiKey;+ this.config.orgApiKey = this.client.orgApiKey;+this.tools = new Tools(this.client, this.config);this.mcp = new MCP(this.client);this.toolkits = new Toolkits(this.client);diff --git a/ts/packages/core/test/core/credentials.test.ts b/ts/packages/core/test/core/credentials.test.tsnew file mode 100644index 000000000..6650693e0--- /dev/null+++ b/ts/packages/core/test/core/credentials.test.ts@@ -0,0 +1,75 @@+import { describe, it, expect, afterEach, vi } from 'vitest';+import { Composio } from '../../src/composio';+import { MockProvider } from '../utils/mocks/provider.mock';++/**+ * `userApiKey` / `orgApiKey` are forwarded to the API client, which selects the+ * credential per operation and resolves the env fallbacks itself.+ */+describe('Composio user and organization API keys', () => {+ const baseConfig = {+ apiKey: 'ak_test',+ baseURL: 'https://api.test.com',+ provider: new MockProvider(),+ allowTracking: false,+ disableVersionCheck: true,+ };++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('forwards both keys to the API client', () => {+ const composio = new Composio({+ ...baseConfig,+ userApiKey: 'uak_test',+ orgApiKey: 'oak_test',+ });+ const client = composio.getClient();+ expect(client.apiKey).toBe('ak_test');+ expect(client.userApiKey).toBe('uak_test');+ expect(client.orgApiKey).toBe('oak_test');+ });++ it('leaves both keys unset on the client when not configured', () => {+ vi.stubEnv('COMPOSIO_USER_API_KEY', '');+ vi.stubEnv('COMPOSIO_ORG_API_KEY', '');+ const client = new Composio(baseConfig).getClient();+ expect(client.userApiKey).toBeNull();+ expect(client.orgApiKey).toBeNull();+ });++ it('lets the client resolve the env fallbacks', () => {+ vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');+ vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');+ const client = new Composio(baseConfig).getClient();+ expect(client.userApiKey).toBe('uak_env');+ expect(client.orgApiKey).toBe('oak_env');+ });++ it('exposes both keys on getConfig() and carries them into createSession()', () => {+ const composio = new Composio({+ ...baseConfig,+ userApiKey: 'uak_test',+ orgApiKey: 'oak_test',+ });+ expect(composio.getConfig()).toMatchObject({ userApiKey: 'uak_test', orgApiKey: 'oak_test' });+ const session = composio.createSession({ headers: { 'x-request-id': '1' } });+ expect(session.getConfig()).toMatchObject({ userApiKey: 'uak_test', orgApiKey: 'oak_test' });+ expect(session.getClient().userApiKey).toBe('uak_test');+ expect(session.getClient().orgApiKey).toBe('oak_test');+ });++ it('stores env-resolved keys on the config so createSession() keeps them after env changes', () => {+ vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');+ vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');+ const composio = new Composio(baseConfig);+ expect(composio.getConfig()).toMatchObject({ userApiKey: 'uak_env', orgApiKey: 'oak_env' });++ vi.stubEnv('COMPOSIO_USER_API_KEY', '');+ vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_other');+ const session = composio.createSession({ headers: { 'x-request-id': '1' } });+ expect(session.getClient().userApiKey).toBe('uak_env');+ expect(session.getClient().orgApiKey).toBe('oak_env');+ });+});