@devries-cameron20 / composio-1 / commits / 6c56b7359
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(sdk): port main into next with owned client `2.0.0-rc.8` (#4568)

This PR: - merges `main` (the owned-client beta line) into `next` for a stable minor release: `@composio/core`/`@composio/slim` `0.20.0`, Python `composio` `0.23.0` - bumps `@composio/client` to `2.0.0-rc.8` and `composio-client` to `2.0.0rc8` (`@composio/client` is already in `minimumReleaseAgeExclude`, so the <72h release installs) - keeps beta-only release state on `main`: no `.changeset/pre.json`, beta versions/CHANGELOGs, or provider `1.0.0-beta` peer-range assertions in `test/release-workflow.test.ts` - turns the owned-client changesets into `minor` bumps and folds `session.configHistory()` → `session.listConfigHistory()` into them, since the old name only shipped in the beta - adapts to rc.8: sets `premium_usage: false` on the fallback session config (TS + Python) and maps the new `user_visible`/`required_scopes` keys to `ToolkitAuthField.userVisible`/`ToolkitAuthConfigDetails.requiredScopes` - adds `docs/content/changelog/09-22-26-sdk-releases.mdx` for the release ## Context Beyond the client swap, `main` brings webhooks, logs, keyring, usage, custom toolkits, connected-account `revoke()`/`completeAuth()`, toolkit scope APIs, session config history, `userApiKey`/`orgApiKey`, and configurable SDK logging to both SDKs. These have been exercised on the beta for a few weeks. On add/add conflicts, `docs/agent/lib/safety.ts` keeps `next`'s later hardening, and the Python client wrapper takes `main`'s client-2.0 version. Verified locally: TS build (20/20), typecheck (16/16 plus examples), unit tests (28/28 tasks), release-workflow, provider-compatibility, examples validation, `oxlint`, docs static tests (590 pass), Python tests on 3.12 (1982 passed), and `nox -s chk` (ruff + mypy). --------- Co-authored-by: sdkrelease[bot] <294075132+sdkrelease[bot]@users.noreply.github.com> Co-authored-by: Srujan <srujan@composio.dev> Co-authored-by: Brendan O'Leary <brendan@olearycrew.com> Co-authored-by: Shelley <shelley@exe.dev>

Alberto Schiabel committed Sep 22, 2026 at 16:12 UTC 6c56b735922cd0c7995e100a8b5a7878f384a4ae
144 files changed +8430 -508
.changeset/core-user-org-api-keys.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Add `userApiKey` and `orgApiKey` to `ComposioConfig`. Both are forwarded to the underlying API client, which sends each one only on operations whose security scheme requires it (organization, consumer, and user-scoped endpoints reached through `getClient()`), never alongside the project key. They fall back to `COMPOSIO_USER_API_KEY` and `COMPOSIO_ORG_API_KEY`. A project `apiKey` is still required.
.changeset/owned-client-surface.md new
+21
@@ -0,0 +1,21 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Expose the rest of the owned client surface on the `Composio` class:
6 +
7 +- `composio.webhooks.subscriptions` (`list`, `get`, `set`, `update`, `delete`, `rotateSecret`, `listEventTypes`) and `composio.webhooks.endpoints` (`list`, `get`, `create`, `replace`, `update`). `composio.triggers.setWebhookSubscription()` now delegates to the same upsert as `webhooks.subscriptions.set()`. Its behaviour for well-formed API responses is unchanged; malformed responses are now rejected with a `ValidationError` instead of being read leniently.
8 +- `composio.logs.search()` and `composio.logs.get()` for tool-execution logs.
9 +- `composio.connectedAccounts.revoke()`, which surfaces the API's 400/409 as `ComposioConnectedAccountRevocationNotSupportedError` / `ComposioConnectedAccountNotRevokableError`. `connectedAccounts.refresh()` is marked `@deprecated` (the endpoint is deprecated upstream).
10 +- `composio.toolkits.getMany(slugs)` and `composio.toolkits.changelog()`.
11 +- `session.listConfigHistory()` on sessions.
12 +- `composio.experimental.usage.summary()` and `composio.experimental.usage.breakdown()` (experimental, shape may change).
13 +- `composio.toolkits.recommendScopes(toolkitSlug, { tools, ... })` and `composio.toolkits.listGrantContexts(toolkitSlug)` for OAuth scope recommendations (the API marks both beta).
14 +- `composio.connectedAccounts.completeAuth({ userId, sessionUri })`, which completes a deferred OAuth connection after your OAuth callback verifier has confirmed the user's identity.
15 +- `composio.keyring.listTransferKeys()`, which returns the public JWKs of the organization's customer-managed keyring.
16 +- `composio.experimental.customToolkits` (`upsert`, `sync`, `delete`) for project-owned custom toolkits (in pilot, shape may change).
17 +- `CIMD_OAUTH` joins `AuthSchemeTypes`.
18 +- `triggers.listActive()` returns `{}` for `state` and `triggerConfig` when the API sends `null`.
19 +- `ToolkitAuthField` gains `userVisible` (from `user_visible`) and `ToolkitAuthConfigDetails` gains `requiredScopes` (from `required_scopes`), both omitted when the API does not send them.
20 +- `@composio/client` moves to `2.0.0-rc.8`. The API removed `validate_credentials` from the connected-account refresh, so `connectedAccounts.refresh()` now ignores `validateCredentials` and logs a warning when it is set.
21 +- `logger` and `logLevel` options on `new Composio({...})`. `logger` accepts any `{ error, warn, info, debug }` sink (`console`, pino, winston, ...) and receives the SDK's formatted, credential-redacted output; `logLevel` (`'silent' | 'error' | 'warn' | 'info' | 'debug'`) overrides `COMPOSIO_LOG_LEVEL`. The owned client's runtime deprecation warnings (response `Deprecation`/`Sunset` headers and deprecated request inputs) are now routed through that SDK logger instead of `console`. The client's per-request lifecycle logs are emitted only at `'debug'`. `tools.get`/`getRawComposioTools` send the API's `query` parameter in place of the deprecated `search` wire parameter; the SDK's public `search` option is unchanged.
.changeset/use-owned-composio-client.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Replace the frozen Stainless `@composio/client` with the owned `2.0.0-rc.8` client.
.github/workflows/dead-code.yml
+2 -2
@@ -11,7 +11,7 @@ name: Dead Code
11
12 on:
13 push:
14 - branches: [master, next]
14 + branches: [master, next, main]
15 paths:
16 - 'ts/**'
17 - 'python/**'
@@ -25,7 +25,7 @@ on:
25 - 'mise.toml'
26 - 'mise.lock'
27 pull_request:
28 - branches: [master, next]
28 + branches: [master, next, main]
29 paths:
30 - 'ts/**'
31 - 'python/**'
.github/workflows/examples-live.yml
+23 -3
@@ -24,6 +24,10 @@ on:
24 description: 'Comma-separated entry ids (empty = full manifest)'
25 type: string
26 default: ''
27 + exclude_toolkits:
28 + description: 'Comma-separated toolkits to exclude, including dependent entries'
29 + type: string
30 + default: googledrive
31 client_tarball_url:
32 description: 'Candidate TypeScript client tarball URL (required for TS candidate entries)'
33 type: string
@@ -54,6 +58,9 @@ env:
58 COMPOSIO_API_KEY: ${{ secrets.COMPOSIO_API_KEY }}
59 OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
60 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
61 + # Keep unavailable coverage explicit. The harness records excluded entry ids
62 + # in its summary artifact; remove this default when staging has Drive auth.
63 + EXCLUDE_TOOLKITS: ${{ inputs.exclude_toolkits || 'googledrive' }}
64 # mock unless explicitly dispatched live; the nightly adds a small live canary.
65 LLM_MODE: ${{ inputs.llm || 'mock' }}
66 # Entries mocks cannot cover (llmMock:false) plus one representative
@@ -62,7 +69,7 @@ env:
69
70 jobs:
71 examples-live:
65 - name: ${{ inputs.client || 'baseline' }} sweep (${{ inputs.lang || 'all' }})
72 + name: ${{ inputs.client || 'baseline' }} sweep (${{ inputs.lang || 'all' }}, excluding ${{ inputs.exclude_toolkits || 'googledrive' }})
73 environment: staging
74 runs-on: ubuntu-latest
75 timeout-minutes: 60
@@ -130,7 +137,19 @@ jobs:
137 run: node harness/run.mjs selftest
138
139 - name: Verify provisioned project state
133 - run: node scripts/examples-provision.mjs --gc > /tmp/examples-provision.env
140 + env:
141 + IDS_INPUT: ${{ inputs.ids }}
142 + LANG_INPUT: ${{ inputs.lang || 'all' }}
143 + run: |
144 + set -euo pipefail
145 + ARGS=(--gc --exclude-toolkits "$EXCLUDE_TOOLKITS")
146 + if [ "$LANG_INPUT" != "all" ]; then
147 + ARGS+=(--lang "$LANG_INPUT")
148 + fi
149 + if [ -n "$IDS_INPUT" ]; then
150 + ARGS+=(--ids "$IDS_INPUT")
151 + fi
152 + node scripts/examples-provision.mjs "${ARGS[@]}" > /tmp/examples-provision.env
153
154 - name: Sweep
155 env:
@@ -148,6 +167,7 @@ jobs:
167 if [ -n "$IDS_INPUT" ]; then
168 ARGS+=(--ids "$IDS_INPUT")
169 fi
170 + ARGS+=(--exclude-toolkits "$EXCLUDE_TOOLKITS")
171 node harness/run.mjs sweep "${ARGS[@]}"
172
173 - name: Live LLM canary
@@ -155,7 +175,7 @@ jobs:
175 run: |
176 set -euo pipefail
177 source /tmp/examples-provision.env
158 - node harness/run.mjs sweep --client baseline --llm live --ids "$CANARY_IDS"
178 + node harness/run.mjs sweep --client baseline --llm live --ids "$CANARY_IDS" --exclude-toolkits "$EXCLUDE_TOOLKITS"
179
180 - name: Upload sweep results and traces
181 if: ${{ always() }}
.github/workflows/py.check.yaml
+1
@@ -3,6 +3,7 @@ on:
3 push:
4 branches:
5 - next
6 + - main
7 paths:
8 - 'python/**/*.py'
9 - 'python/pyproject.toml'
.github/workflows/py.release.yml
+21 -1
@@ -39,10 +39,30 @@ jobs:
39 - name: Setup Python with UV
40 uses: ./.github/actions/setup-python-uv
41
42 + - name: Resolve release package set
43 + id: release_mode
44 + run: |
45 + python - <<'PY' >> "$GITHUB_OUTPUT"
46 + import re
47 + import tomllib
48 +
49 + with open("pyproject.toml", "rb") as pyproject:
50 + version = tomllib.load(pyproject)["project"]["version"]
51 +
52 + # PEP 440 compact form (0.23.1rc1) and the separator form emitted by
53 + # python/scripts/bump.py --pre (0.23.1-rc.1) are both prereleases.
54 + is_prerelease = re.search(r"(?:a|b|rc|dev)[-_.]?\d", version, re.IGNORECASE) is not None
55 + print(f"core_only={'true' if is_prerelease else 'false'}")
56 + PY
57 +
58 - name: Build Artifacts
59 run: |
60 make env
45 - make build
61 + if [[ "${{ steps.release_mode.outputs.core_only }}" == "true" ]]; then
62 + make build-core
63 + else
64 + make build
65 + fi
66
67 - name: Publish Artifacts
68 if: github.event_name == 'push'
.github/workflows/py.test.yml
+2 -2
@@ -2,7 +2,7 @@ name: Test Python SDK
2
3 on:
4 push:
5 - branches: [master, next]
5 + branches: [master, next, main]
6 paths:
7 - 'python/**/*.py'
8 - 'python/**/*.json'
@@ -17,7 +17,7 @@ on:
17 # The TypeSafe provider tests read the question corpus of the TypeScript provider.
18 - 'ts/packages/providers/typesafe/test/fixtures/question-corpus.json'
19 pull_request:
20 - branches: [master, next]
20 + branches: [master, next, main]
21 paths:
22 - 'python/**/*.py'
23 - 'python/**/*.json'
.github/workflows/security.secrets-detection.yml
+1
@@ -6,6 +6,7 @@ on:
6 branches:
7 - master
8 - next
9 + - main
10
11 permissions:
12 contents: read
.github/workflows/ts.audit.yml
+2 -2
@@ -2,7 +2,7 @@ name: Audit Typescript SDK
2
3 on:
4 push:
5 - branches: [master, next]
5 + branches: [master, next, main]
6 paths:
7 - 'ts/**'
8 - '.github/actions/setup-node-pnpm-bun/action.yml'
@@ -13,7 +13,7 @@ on:
13 - 'pnpm-lock.yaml'
14 - 'pnpm-workspace.yaml'
15 pull_request:
16 - branches: [master, next]
16 + branches: [master, next, main]
17 paths:
18 - 'ts/**'
19 - '.github/actions/setup-node-pnpm-bun/action.yml'
.github/workflows/ts.build.yml
+1 -1
@@ -2,7 +2,7 @@ name: Build Typescript SDK
2
3 on:
4 push:
5 - branches: [next]
5 + branches: [next, main]
6 paths:
7 - 'ts/**'
8 - '.oxlintrc.json'
.github/workflows/ts.examples.yml
+2 -2
@@ -2,7 +2,7 @@ name: Examples TypeScript SDK
2
3 on:
4 push:
5 - branches: [master, next]
5 + branches: [master, next, main]
6 paths:
7 - 'ts/examples/**'
8 - 'ts/packages/core/**'
@@ -17,7 +17,7 @@ on:
17 - 'pnpm-lock.yaml'
18 - 'turbo.jsonc'
19 pull_request:
20 - branches: [master, next]
20 + branches: [master, next, main]
21 paths:
22 - 'ts/examples/**'
23 - 'ts/packages/core/**'
.github/workflows/ts.release.yml
+1 -1
@@ -3,7 +3,7 @@ name: TS SDK Release
3 on:
4 workflow_dispatch:
5 push:
6 - branches: [next]
6 + branches: [next, main]
7
8 permissions:
9 contents: read
.github/workflows/ts.test-e2e.yml
+1 -1
@@ -2,7 +2,7 @@ name: E2E Test Typescript SDK
2
3 on:
4 push:
5 - branches: [master, next]
5 + branches: [master, next, main]
6 paths:
7 - 'ts/**'
8 # A catalog pin or lockfile change swaps what every ts/** package
.github/workflows/ts.test.yml
+2 -2
@@ -2,7 +2,7 @@ name: Test Typescript SDK
2
3 on:
4 push:
5 - branches: [master, next]
5 + branches: [master, next, main]
6 paths:
7 - '.changeset/**'
8 - 'ts/**'
@@ -18,7 +18,7 @@ on:
18 - 'test/provider-compatibility.test.ts'
19 - 'turbo.jsonc'
20 pull_request:
21 - branches: [master, next]
21 + branches: [master, next, main]
22 paths:
23 - '.changeset/**'
24 - 'ts/**'
.github/workflows/ts.typecheck.yml
+2 -2
@@ -2,7 +2,7 @@ name: Typecheck Typescript SDK
2
3 on:
4 push:
5 - branches: [master, next]
5 + branches: [master, next, main]
6 paths:
7 - 'ts/**'
8 - '.github/actions/setup-node-pnpm-bun/action.yml'
@@ -13,7 +13,7 @@ on:
13 - 'pnpm-lock.yaml'
14 - 'turbo.jsonc'
15 pull_request:
16 - branches: [master, next]
16 + branches: [master, next, main]
17 paths:
18 - 'ts/**'
19 - '.github/actions/setup-node-pnpm-bun/action.yml'
docs/app/(home)/reference/(v31)/changelog/page.tsx
+10 -1
@@ -62,7 +62,16 @@ export default function ChangelogPage() {
62 <PageActions path="/reference/changelog" />
63 <DocsBody>
64 <p className="text-fd-muted-foreground">
65 - Latest updates and announcements for Composio.
65 + Latest updates and announcements for Composio. Follow{' '}
66 + <a
67 + href="https://x.com/composiodevs"
68 + target="_blank"
69 + rel="noreferrer"
70 + className="font-medium text-foreground underline underline-offset-4 hover:text-primary"
71 + >
72 + @composiodevs on X
73 + </a>{' '}
74 + for product news and announcements.
75 </p>
76 <h2 id="latest">Latest</h2>
77 <div className="relative">
docs/app/global.css
+7 -4
@@ -601,8 +601,9 @@ textarea:focus-visible {
601 gap: 0.5rem;
602 }
603
604 -/* GitHub icon link */
605 -#nd-nav a[href*="github.com"] {
604 +/* Social icon links */
605 +#nd-nav a[href*="github.com"],
606 +#nd-nav a[href*="x.com"] {
607 display: inline-flex;
608 align-items: center;
609 justify-content: center;
@@ -613,12 +614,14 @@ textarea:focus-visible {
614 transition: color var(--header-transition), background var(--header-transition);
615 }
616
616 -#nd-nav a[href*="github.com"]:hover {
617 +#nd-nav a[href*="github.com"]:hover,
618 +#nd-nav a[href*="x.com"]:hover {
619 color: var(--color-fd-foreground);
620 background: var(--color-fd-accent);
621 }
622
621 -#nd-nav a[href*="github.com"]:focus-visible {
623 +#nd-nav a[href*="github.com"]:focus-visible,
624 +#nd-nav a[href*="x.com"]:focus-visible {
625 outline: 2px solid var(--composio-orange);
626 outline-offset: 2px;
627 }
docs/app/layout.tsx
+1 -1
@@ -118,7 +118,7 @@ export default async function Layout({ children }: LayoutProps<'/'>) {
118 },
119 sameAs: [
120 'https://github.com/composiohq',
121 - 'https://twitter.com/composiohq',
121 + 'https://x.com/composiodevs',
122 'https://discord.gg/composio',
123 ],
124 },
docs/content/changelog/09-22-26-sdk-releases.mdx new
+34
@@ -0,0 +1,34 @@
1 +---
2 +title: 'Python SDK 0.23.0 and TypeScript SDK 0.20.0 move to the Composio-owned client'
3 +description: 'Both SDKs now use the Composio-owned 2.0.0-rc.8 client and add webhook, logs, keyring, usage, custom toolkit, connected account, toolkit, and session APIs.'
4 +date: '2026-09-22'
5 +---
6 +
7 +Python SDK `0.23.0` and TypeScript SDK `0.20.0` replace the frozen generated client with the Composio-owned client (`composio-client` `2.0.0rc8` and `@composio/client` `2.0.0-rc.8`). The TypeScript APIs shipped first in the `1.0.0` betas. The Python `2.0.0b0` beta only swapped the client, so `0.23.0` is the first Python release with these APIs. Both are now part of the stable release line.
8 +
9 +### Release versions
10 +
11 +| SDK | Version |
12 +| --------------------------- | -------- |
13 +| Python `composio` | `0.23.0` |
14 +| TypeScript `@composio/core` | `0.20.0` |
15 +| TypeScript `@composio/slim` | `0.20.0` |
16 +
17 +### Owned client
18 +
19 +The owned client covers the released v3.1 operations while preserving the SDK's existing imports, types, retries, timeouts, error classes, raw responses, streaming responses, and `AbortSignal` support.
20 +
21 +### What's new
22 +
23 +- Project webhooks (`webhooks.subscriptions` and `webhooks.endpoints`), tool execution logs, customer-managed keyring transfer keys, experimental usage metering, and experimental project-owned custom toolkits.
24 +- Connected account revocation and deferred OAuth completion.
25 +- Toolkit bulk retrieval, changelogs, OAuth scope recommendations, and grant contexts. Toolkit auth details now include each field's end-user visibility and the scopes an auth method always requests.
26 +- Tool Router session configuration history through `session.listConfigHistory()` in TypeScript and `session.list_config_history()` in Python.
27 +- `userApiKey` and `orgApiKey` in TypeScript, and `user_api_key` and `org_api_key` in Python, for user- and organization-scoped operations. A project API key is still required.
28 +- Configurable SDK logging with redacted output. TypeScript routes owned-client deprecation warnings through the SDK logger, and Python raises them as `ComposioDeprecationWarning`.
29 +
30 +<Callout>
31 + `connectedAccounts.refresh()` is deprecated because the API deprecated its endpoint. The API also
32 + removed credential validation from refresh, so TypeScript now ignores `validateCredentials` and
33 + logs a warning when you set it.
34 +</Callout>
docs/lib/layout.shared.tsx
+13
@@ -57,6 +57,19 @@ export function baseOptions(): BaseLayoutProps {
57 external: true,
58 secondary: true,
59 },
60 + {
61 + type: 'icon',
62 + label: 'X (formerly Twitter)',
63 + icon: (
64 + <svg fill="currentColor" viewBox="0 0 24 24" className="size-4">
65 + <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
66 + </svg>
67 + ),
68 + text: 'X',
69 + url: 'https://x.com/composiodevs',
70 + external: true,
71 + secondary: true,
72 + },
73 {
74 type: 'button',
75 text: (
harness/errors.mjs new
+6
@@ -0,0 +1,6 @@
1 +export class HarnessError extends Error {
2 + constructor(message, exitCode = 2) {
3 + super(message);
4 + this.exitCode = exitCode;
5 + }
6 +}
harness/manifest.mjs new
+99
@@ -0,0 +1,99 @@
1 +import { readFileSync } from 'node:fs';
2 +import { dirname, join, resolve } from 'node:path';
3 +import { fileURLToPath } from 'node:url';
4 +import { HarnessError } from './errors.mjs';
5 +
6 +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
7 +
8 +export const BROWSER_GRANT_TOOLKITS = [
9 + { exportPrefix: 'GMAIL', slug: 'gmail' },
10 + { slug: 'googledrive' },
11 + { exportPrefix: 'GITHUB', slug: 'github' },
12 + { exportPrefix: 'SLACK', slug: 'slack' },
13 +];
14 +
15 +export const DEMO_TOOLKIT = {
16 + exportPrefix: 'APIKEY',
17 + slug: 'serpapi',
18 + demoValue: 'examples-demo-key',
19 +};
20 +
21 +const parseCsv = value =>
22 + value
23 + ? value
24 + .split(',')
25 + .map(part => part.trim())
26 + .filter(Boolean)
27 + : [];
28 +
29 +const toolkitForId = id => {
30 + for (const toolkit of [...BROWSER_GRANT_TOOLKITS, DEMO_TOOLKIT]) {
31 + if (toolkit.exportPrefix && id.startsWith(`COMPOSIO_EXAMPLES_${toolkit.exportPrefix}_`)) {
32 + return toolkit.slug;
33 + }
34 + }
35 + return undefined;
36 +};
37 +
38 +export const entryToolkits = entry => {
39 + const toolkits = new Set(entry.toolkits ?? []);
40 + for (const id of entry.ids ?? []) {
41 + const toolkit = toolkitForId(id);
42 + if (toolkit) toolkits.add(toolkit);
43 + }
44 + return [...toolkits];
45 +};
46 +
47 +export const validateManifestEntries = entries => {
48 + for (const entry of entries) {
49 + if (!entry.id || !entry.lang || !entry.file || !entry.tier) {
50 + throw new HarnessError(`manifest entry missing required fields: ${JSON.stringify(entry)}`);
51 + }
52 + if (entry.lang === 'ts' && entry.tier !== 'X' && !entry.pkg) {
53 + throw new HarnessError(`ts entry ${entry.id} missing pkg`);
54 + }
55 + if (entry.tier === '3' && !entry.readiness) {
56 + throw new HarnessError(`tier-3 entry ${entry.id} missing readiness regex`);
57 + }
58 + }
59 + return entries;
60 +};
61 +
62 +export const loadManifest = () =>
63 + validateManifestEntries(
64 + JSON.parse(readFileSync(join(ROOT, 'examples-manifest.json'), 'utf8')).entries
65 + );
66 +
67 +export const selectManifestEntries = (
68 + entries,
69 + { lang, ids, tiers = '1,2,3', excludeToolkits } = {}
70 +) => {
71 + const selectedIds = new Set(parseCsv(ids));
72 + const selectedTiers = new Set(parseCsv(tiers));
73 + const excludedToolkitSet = new Set(parseCsv(excludeToolkits));
74 + const eligibleEntries = entries.filter(
75 + entry =>
76 + entry.tier !== 'X' &&
77 + selectedTiers.has(entry.tier) &&
78 + (!lang || entry.lang === lang) &&
79 + (selectedIds.size === 0 || selectedIds.has(entry.id))
80 + );
81 + const excludedEntries = eligibleEntries.filter(entry =>
82 + entryToolkits(entry).some(toolkit => excludedToolkitSet.has(toolkit))
83 + );
84 + const excludedIds = new Set(excludedEntries.map(entry => entry.id));
85 +
86 + return {
87 + entries: eligibleEntries.filter(entry => !excludedIds.has(entry.id)),
88 + excludedEntries,
89 + excludedToolkits: [...excludedToolkitSet],
90 + };
91 +};
92 +
93 +export const requiredBrowserGrantToolkits = entries =>
94 + BROWSER_GRANT_TOOLKITS.filter(toolkit =>
95 + entries.some(entry => entryToolkits(entry).includes(toolkit.slug))
96 + );
97 +
98 +export const requiresDemoToolkit = entries =>
99 + entries.some(entry => entryToolkits(entry).includes(DEMO_TOOLKIT.slug));
harness/run.mjs
+178 -46
@@ -2,8 +2,8 @@
2 // Examples runner: sweeps the entrypoints in examples-manifest.json against
3 // the live backend, recording per-entry results and Composio traces.
4 //
5 -// node harness/run.mjs sweep --client baseline|candidate [--lang ts|py] [--ids a,b] [--tiers 1,2,3] [--llm live|mock]
6 -// node harness/run.mjs neg [--lang ts|py] [--ids a,b] [--sample N] [--seed S]
5 +// node harness/run.mjs sweep --client baseline|candidate [--lang ts|py] [--ids a,b] [--tiers 1,2,3] [--exclude-toolkits a,b] [--llm live|mock]
6 +// node harness/run.mjs neg [--lang ts|py] [--ids a,b] [--exclude-toolkits a,b] [--sample N] [--seed S]
7 // node harness/run.mjs selftest
8 //
9 // Exit codes: 0 ok · 1 findings (red entries / failed expectations) · 2 usage/env error.
@@ -12,11 +12,19 @@ import { spawn } from 'node:child_process';
12 import { mkdirSync, readFileSync, writeFileSync, appendFileSync, existsSync, rmSync } from 'node:fs';
13 import { dirname, join, relative, resolve } from 'node:path';
14 import { fileURLToPath } from 'node:url';
15 +import {
16 + entryToolkits,
17 + loadManifest,
18 + requiredBrowserGrantToolkits,
19 + requiresDemoToolkit,
20 + selectManifestEntries,
21 + validateManifestEntries,
22 +} from './manifest.mjs';
23 import { resolveBackendBaseUrl, STAGING_BASE_URL } from './backend-url.mjs';
24 +import { HarnessError } from './errors.mjs';
25
26 const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
27 const ARTIFACTS = join(ROOT, '.artifacts', 'examples-parity');
19 -const STAINLESS_TS_VERSION = '0.1.0-alpha.76';
28 const AIMOCK_VERSION = '1.38.0';
29 const AIMOCK_PORT = Number(process.env.AIMOCK_PORT ?? 4010);
30
@@ -31,38 +39,25 @@ const opt = (name, fallback) => {
39 return i >= 0 && args[i + 1] !== undefined ? args[i + 1] : fallback;
40 };
41
34 -class HarnessError extends Error {
35 - constructor(message, exitCode = 2) {
36 - super(message);
37 - this.exitCode = exitCode;
38 - }
39 -}
40 -
42 const fail = (msg, code = 2) => {
43 throw new HarnessError(msg, code);
44 };
45
45 -const loadManifest = () => {
46 - const manifest = JSON.parse(readFileSync(join(ROOT, 'examples-manifest.json'), 'utf8'));
47 - for (const e of manifest.entries) {
48 - if (!e.id || !e.lang || !e.file || !e.tier) fail(`manifest entry missing required fields: ${JSON.stringify(e)}`);
49 - if (e.lang === 'ts' && e.tier !== 'X' && !e.pkg) fail(`ts entry ${e.id} missing pkg`);
50 - if (e.tier === '3' && !e.readiness) fail(`tier-3 entry ${e.id} missing readiness regex`);
51 - }
52 - return manifest.entries;
53 -};
46 +const selectionOptions = () => ({
47 + lang: opt('lang'),
48 + ids: opt('ids'),
49 + tiers: opt('tiers', '1,2,3'),
50 + excludeToolkits: opt('exclude-toolkits'),
51 +});
52 +
53 +const selectEntries = () => selectManifestEntries(loadManifest(), selectionOptions());
54
55 -const selectEntries = () => {
56 - const lang = opt('lang');
57 - const ids = opt('ids') ? opt('ids').split(',') : null;
58 - const tiers = (opt('tiers', '1,2,3')).split(',');
59 - return loadManifest().filter(
60 - (e) =>
61 - e.tier !== 'X' &&
62 - tiers.includes(e.tier) &&
63 - (!lang || e.lang === lang) &&
64 - (!ids || ids.includes(e.id))
55 +const reportExclusions = selection => {
56 + if (selection.excludedEntries.length === 0) return;
57 + console.log(
58 + `excluding ${selection.excludedEntries.length} entries requiring ${selection.excludedToolkits.join(', ')}:`
59 );
60 + for (const entry of selection.excludedEntries) console.log(` - ${entry.id}`);
61 };
62
63 const baseUrl = () => {
@@ -268,13 +263,28 @@ const sh = (cmdline, opts = {}) =>
263 child.on('exit', (code) => (code === 0 ? resolveSh(out) : rejectSh(new Error(`${cmdline.join(' ')} → exit ${code}\n${out.slice(-2000)}`))));
264 });
265
271 -const resolvedTsClientVersion = async () => {
272 - const out = await sh(['node', '-e', "console.log(JSON.parse(require('fs').readFileSync(require.resolve('@composio/client/package.json', {paths:[require('path').join(process.cwd(),'ts/packages/core')]}), 'utf8')).version)"]);
273 - return out.trim().split('\n').pop();
266 +/**
267 + * Resolve @composio/client as @composio/core sees it. The realpath identifies
268 + * the installed copy: a `file:` override lands in its own store directory even
269 + * when the tarball reports the same version as the catalog pin, so comparing
270 + * paths (not versions) is what tells a real swap from a no-op.
271 + */
272 +const resolvedTsClient = async () => {
273 + const out = await sh(['node', '-e', "const path=require('path');const fs=require('fs');const manifest=require.resolve('@composio/client/package.json', {paths:[path.join(process.cwd(),'ts/packages/core')]});console.log(JSON.stringify({path:fs.realpathSync(manifest),version:JSON.parse(fs.readFileSync(manifest,'utf8')).version}))"]);
274 + return JSON.parse(out.trim().split('\n').pop());
275 +};
276 +
277 +const assertTsCandidateApplied = (baseline, candidate) => {
278 + if (candidate.path === baseline.path) {
279 + fail(
280 + `override did not take effect: @composio/client still resolves to the installed baseline at ${candidate.path} (${candidate.version})`
281 + );
282 + }
283 };
284
285 const applyTsCandidate = async (tarball) => {
286 if (!existsSync(tarball)) fail(`COMPOSIO_CLIENT_TARBALL not found: ${tarball}`);
287 + const baseline = await resolvedTsClient();
288 const yaml = readFileSync(WORKSPACE_YAML, 'utf8');
289 if (/^overrides:$/m.test(yaml)) {
290 // Merge into the repo's existing overrides block (e.g. security pins);
@@ -284,11 +294,9 @@ const applyTsCandidate = async (tarball) => {
294 writeFileSync(WORKSPACE_YAML, `${yaml}\noverrides:\n '@composio/client': file:${tarball}\n`);
295 }
296 await sh(['pnpm', 'install', '--no-frozen-lockfile']);
287 - const version = await resolvedTsClientVersion();
288 - if (version === STAINLESS_TS_VERSION) {
289 - fail(`override did not take effect: @composio/client still resolves to ${version}`);
290 - }
291 - console.log(`candidate @composio/client resolved: ${version}`);
297 + const candidate = await resolvedTsClient();
298 + assertTsCandidateApplied(baseline, candidate);
299 + console.log(`candidate @composio/client resolved: ${candidate.version} (${candidate.path})`);
300 await sh(['pnpm', 'run', 'build:packages']);
301 };
302
@@ -305,14 +313,30 @@ const restoreTsBaseline = async (snapshot) => {
313 await sh(['pnpm', 'install', '--frozen-lockfile']);
314 };
315
316 +/**
317 + * Resolve composio-client as the python project sees it. `uv run --with <wheel>`
318 + * layers an ephemeral overlay on the project environment, so the realpath tells
319 + * a real swap from a no-op even when the wheel matches the pinned version.
320 + */
321 +const resolvedPyClient = async (extraArgs = []) => {
322 + const out = await sh(['uv', 'run', '--project', 'python', ...extraArgs, 'python', '-c', 'import composio_client, importlib.metadata, json, os; print(json.dumps({"path": os.path.realpath(composio_client.__file__), "version": importlib.metadata.version("composio-client")}))']);
323 + return JSON.parse(out.trim().split('\n').pop());
324 +};
325 +
326 +const assertPyCandidateApplied = (baseline, candidate) => {
327 + if (candidate.path === baseline.path) {
328 + fail(
329 + `python candidate did not take effect: composio-client still resolves to the installed baseline at ${candidate.path} (${candidate.version})`
330 + );
331 + }
332 +};
333 +
334 const verifyPyCandidate = async (wheel) => {
335 if (!existsSync(wheel)) fail(`COMPOSIO_CLIENT_WHEEL not found: ${wheel}`);
310 - const out = await sh(['uv', 'run', '--project', 'python', '--with', wheel, 'python', '-c', 'import composio_client, importlib.metadata; print(importlib.metadata.version("composio-client"))']);
311 - const version = out.trim().split('\n').pop();
312 - if (!version.startsWith('2.')) {
313 - fail(`python candidate did not take effect (resolved ${version}); Stage B (SDK migration) must land first`);
314 - }
315 - return version;
336 + const baseline = await resolvedPyClient();
337 + const candidate = await resolvedPyClient(['--with', wheel]);
338 + assertPyCandidateApplied(baseline, candidate);
339 + return candidate.version;
340 };
341
342 const PY_PROJECT = join(ROOT, 'python', 'pyproject.toml');
@@ -385,9 +409,11 @@ const cmdSweep = async () => {
409 const llm = opt('llm', 'live');
410 if (!['live', 'mock'].includes(llm)) fail(`--llm must be live|mock`);
411 LLM_MOCK = llm === 'mock';
388 - const entries = selectEntries();
412 + const selection = selectEntries();
413 + const entries = selection.entries;
414 if (entries.length === 0) fail('no entries selected');
415 if (!process.env.COMPOSIO_API_KEY) fail('COMPOSIO_API_KEY is required for a sweep (disposable examples-project key)', 2);
416 + reportExclusions(selection);
417
418 const id = `${runId()}-${client}${LLM_MOCK ? '-mock' : ''}`;
419 const runDir = join(ARTIFACTS, id);
@@ -427,7 +453,22 @@ const cmdSweep = async () => {
453 };
454 writeFileSync(
455 join(runDir, 'summary.json'),
430 - JSON.stringify({ runId: id, client, llm, baseUrl: baseUrl(), counts, startedAt: new Date().toISOString() }, null, 2)
456 + JSON.stringify(
457 + {
458 + runId: id,
459 + client,
460 + llm,
461 + baseUrl: baseUrl(),
462 + counts,
463 + selection: {
464 + excludedToolkits: selection.excludedToolkits,
465 + excludedEntries: selection.excludedEntries.map(entry => entry.id),
466 + },
467 + startedAt: new Date().toISOString(),
468 + },
469 + null,
470 + 2
471 + )
472 );
473 console.log(`sweep ${id}: ${counts.green} green / ${counts.red} red / ${counts.skipped} skipped`);
474 process.exitCode = counts.red > 0 ? 1 : 0;
@@ -439,7 +480,9 @@ const cmdSweep = async () => {
480 };
481
482 const cmdNeg = async () => {
442 - let entries = selectEntries().filter((e) => e.backend !== false);
483 + const selection = selectEntries();
484 + reportExclusions(selection);
485 + let entries = selection.entries.filter((e) => e.backend !== false);
486 const sample = opt('sample');
487 if (sample) {
488 const rand = mulberry32(Number(opt('seed', '42')));
@@ -511,6 +554,95 @@ const cmdSelftest = async () => {
554 cleanupRan && cleanupError instanceof HarnessError
555 );
556
557 + const installedBaseline = {
558 + path: '/repo/node_modules/.pnpm/@composio+client@2.0.0-rc.3/node_modules/@composio/client',
559 + version: '2.0.0-rc.3',
560 + };
561 + let noOpCandidateRejected = false;
562 + try {
563 + assertTsCandidateApplied(installedBaseline, { ...installedBaseline });
564 + } catch {
565 + noOpCandidateRejected = true;
566 + }
567 + check('candidate swap rejects the installed baseline copy', noOpCandidateRejected);
568 +
569 + let sameVersionCandidateAccepted = true;
570 + try {
571 + assertTsCandidateApplied(installedBaseline, {
572 + path: '/repo/node_modules/.pnpm/file+client.tgz/node_modules/@composio/client',
573 + version: installedBaseline.version,
574 + });
575 + } catch {
576 + sameVersionCandidateAccepted = false;
577 + }
578 + check('candidate swap accepts a tarball reporting the pinned version', sameVersionCandidateAccepted);
579 +
580 + const installedPyBaseline = {
581 + path: '/repo/.venv/lib/python3.12/site-packages/composio_client/__init__.py',
582 + version: '2.0.0rc5',
583 + };
584 + let noOpPyCandidateRejected = false;
585 + try {
586 + assertPyCandidateApplied(installedPyBaseline, { ...installedPyBaseline });
587 + } catch {
588 + noOpPyCandidateRejected = true;
589 + }
590 + check('python candidate swap rejects the installed baseline copy', noOpPyCandidateRejected);
591 +
592 + let sameVersionPyCandidateAccepted = true;
593 + try {
594 + assertPyCandidateApplied(installedPyBaseline, {
595 + path: '/cache/uv/archive-v0/abc123/lib/python3.12/site-packages/composio_client/__init__.py',
596 + version: installedPyBaseline.version,
597 + });
598 + } catch {
599 + sameVersionPyCandidateAccepted = false;
600 + }
601 + check('python candidate swap accepts a wheel reporting the pinned version', sameVersionPyCandidateAccepted);
602 +
603 + let invalidManifestIsUsageError = false;
604 + try {
605 + validateManifestEntries([{ id: 'missing-required-fields' }]);
606 + } catch (error) {
607 + invalidManifestIsUsageError = error instanceof HarnessError && error.exitCode === 2;
608 + }
609 + check('invalid manifest entries are usage errors', invalidManifestIsUsageError);
610 +
611 + const manifest = loadManifest();
612 + const withoutGoogleDrive = selectManifestEntries(manifest, {
613 + excludeToolkits: 'googledrive',
614 + });
615 + check(
616 + 'Google Drive exclusion removes every dependent entry and preserves the rest',
617 + withoutGoogleDrive.excludedEntries.length > 0 &&
618 + withoutGoogleDrive.excludedEntries.every(entry =>
619 + entryToolkits(entry).includes('googledrive')
620 + ) &&
621 + withoutGoogleDrive.entries.every(entry => !entryToolkits(entry).includes('googledrive')) &&
622 + withoutGoogleDrive.entries.length + withoutGoogleDrive.excludedEntries.length ===
623 + selectManifestEntries(manifest).entries.length
624 + );
625 + check(
626 + 'Google Drive exclusion removes it from provisioning',
627 + !requiredBrowserGrantToolkits(withoutGoogleDrive.entries).some(
628 + toolkit => toolkit.slug === 'googledrive'
629 + )
630 + );
631 + const apiKeyOnly = selectManifestEntries(manifest, {
632 + ids: 'ts/connected-accounts/api-key',
633 + }).entries;
634 + check(
635 + 'selected API-key example provisions only its demo toolkit',
636 + requiredBrowserGrantToolkits(apiKeyOnly).length === 0 && requiresDemoToolkit(apiKeyOnly)
637 + );
638 + const implicitGmail = selectManifestEntries(manifest, {
639 + ids: 'py/fastapi_app',
640 + }).entries;
641 + check(
642 + 'resource identifiers contribute implicit toolkit requirements',
643 + requiredBrowserGrantToolkits(implicitGmail).some(toolkit => toolkit.slug === 'gmail')
644 + );
645 +
646 const cleanupFixture = join(runDir, 'cleanup-fixture.txt');
647 writeFileSync(cleanupFixture, 'user contents');
648 const cleanupSnapshot = snapshotFiles([cleanupFixture]);
pnpm-lock.yaml
+9 -8
@@ -28,8 +28,8 @@ catalogs:
28 specifier: ^5.20260915.1
29 version: 5.20260915.1
30 '@composio/client':
31 - specifier: 0.1.0-alpha.76
32 - version: 0.1.0-alpha.76
31 + specifier: 2.0.0-rc.8
32 + version: 2.0.0-rc.8
33 '@effect/language-service':
34 specifier: ^0.87.2
35 version: 0.87.2
@@ -1219,7 +1219,7 @@ importers:
1219 version: link:../cli-local-tools
1220 '@composio/client':
1221 specifier: 'catalog:'
1222 - version: 0.1.0-alpha.76
1222 + version: 2.0.0-rc.8
1223 '@composio/core':
1224 specifier: workspace:*
1225 version: link:../core
@@ -1368,7 +1368,7 @@ importers:
1368 dependencies:
1369 '@composio/client':
1370 specifier: 'catalog:'
1371 - version: 0.1.0-alpha.76
1371 + version: 2.0.0-rc.8
1372 '@composio/json-schema-to-zod':
1373 specifier: workspace:*
1374 version: link:../json-schema-to-zod
@@ -1758,7 +1758,7 @@ importers:
1758 dependencies:
1759 '@composio/client':
1760 specifier: 'catalog:'
1761 - version: 0.1.0-alpha.76
1761 + version: 2.0.0-rc.8
1762 '@composio/json-schema-to-zod':
1763 specifier: workspace:*
1764 version: link:../json-schema-to-zod
@@ -2310,8 +2310,9 @@ packages:
2310 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
2311 engines: {node: '>=0.1.90'}
2312
2313 - '@composio/client@0.1.0-alpha.76':
2314 - resolution: {integrity: sha512-MXC5JGRVdiQ4EgLricy9o/mqBa1+1T7wHFZ6Q4ZJkrjzZqOMvxTgy21Zlb5J/1oGkB2bg9UDzpH8PkXCp/D4zA==}
2313 + '@composio/client@2.0.0-rc.8':
2314 + resolution: {integrity: sha512-0C0Flmblx0Y3i6iGUY/MvST4aNXn3xEmPEA4wqZd3acm9x6u61/0i1LXCgBzFTTZEveK8YBFRu8Lpo/SMZwAFQ==}
2315 + engines: {node: '>=22'}
2316
2317 '@cspotcode/source-map-support@0.8.1':
2318 resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
@@ -7314,7 +7315,7 @@ snapshots:
7315 '@colors/colors@1.5.0':
7316 optional: true
7317
7317 - '@composio/client@0.1.0-alpha.76': {}
7318 + '@composio/client@2.0.0-rc.8': {}
7319
7320 '@cspotcode/source-map-support@0.8.1':
7321 dependencies:
pnpm-workspace.yaml
+1 -1
@@ -35,7 +35,7 @@ catalog:
35 '@clack/prompts': '^1.8.1'
36 '@cloudflare/vitest-pool-workers': 0.22.0
37 '@cloudflare/workers-types': ^5.20260915.1
38 - '@composio/client': 0.1.0-alpha.76
38 + '@composio/client': 2.0.0-rc.8
39 '@effect/language-service': ^0.87.2
40 '@effect/platform-bun': 4.0.0-rc.115
41 '@effect/vitest': 4.0.0-rc.115
python/Makefile
+4 -2
@@ -1,4 +1,4 @@
1 -.PHONY: clean-build sync provider create-provider env fmt chk snt tst type_inference dead-code bump build format check sanity test
1 +.PHONY: clean-build sync provider create-provider env fmt chk snt tst type_inference dead-code bump build build-core format check sanity test
2
3 PROVIDER_DIRS := $(patsubst %/,%,$(sort $(dir $(wildcard providers/*/pyproject.toml))))
4
@@ -76,8 +76,10 @@ test: tst
76 bump: clean-build
77 @uv run python scripts/bump.py
78
79 -build: clean-build
79 +build-core: clean-build
80 @./.venv/bin/python -m build
81 +
82 +build: build-core
83 @set -e; for provider in $(PROVIDER_DIRS); do\
84 ./.venv/bin/python -m build $$provider;\
85 cp $$provider/dist/* dist/;\
python/composio/__init__.py
+2
@@ -22,6 +22,7 @@ from .core.models.webhook_events import (
22 WebhookEventType,
23 is_connection_expired_event,
24 )
25 +from .exceptions import ComposioDeprecationWarning
26 from .core.types import (
27 ToolkitLatestVersion,
28 ToolkitVersion,
@@ -32,6 +33,7 @@ from .sdk import Composio
33
34 __all__ = (
35 "Composio",
36 + "ComposioDeprecationWarning",
37 "CustomTool",
38 "ExperimentalToolkit",
39 "RemoteFile",
python/composio/__version__.py
+1 -1
@@ -1 +1 @@
1 -__version__ = "0.22.0"
1 +__version__ = "0.23.0"
python/composio/client/__init__.py
+167 -14
@@ -3,9 +3,11 @@ This module is a light wrapper around the auto-generated composio client.
3 """
4
5 import contextvars
6 +import logging
7 import os
8 import platform
9 import typing as t
10 +import weakref
11 from importlib.metadata import version
12 from uuid import uuid4
13
@@ -16,13 +18,12 @@ from composio_client import (
18 APIError,
19 APIStatusError,
20 NotGiven,
19 - _base_client,
21 )
22 from composio_client import Composio as BaseComposio
23 from httpx import URL, Client, Request, Response, Timeout
24
25 from composio.exceptions import ComposioError
25 -from composio.utils.logging import WithLogger
26 +from composio.utils.logging import LogLevel, WithLogger, _VerbosityWrapper
27
28 ComposioAPIError = APIError
29 APIEnvironment = te.Literal["production", "staging", "local"]
@@ -87,6 +88,119 @@ def _rebuild_sdk_error(
88 return _with_sdk_error_base(error_class)(message, response=response, body=body)
89
90
91 +def _as_sdk_error(error: APIStatusError) -> APIStatusError:
92 + if isinstance(error, ComposioError):
93 + return error
94 + sdk_error = _with_sdk_error_base(type(error))(
95 + error.message, response=error.response, body=error.body
96 + )
97 + return sdk_error.with_traceback(error.__traceback__)
98 +
99 +
100 +CLIENT_LOGGER_NAME = "composio_client"
101 +"""Name of the logger the generated ``composio_client`` package writes to."""
102 +
103 +
104 +_active_log_wrapper: contextvars.ContextVar[t.Optional[_VerbosityWrapper]] = (
105 + contextvars.ContextVar("composio_client_log_wrapper", default=None)
106 +)
107 +"""The SDK logger of the :class:`HttpClient` currently performing a request.
108 +
109 +The generated client writes every lifecycle record to one process-wide
110 +``composio_client`` logger, so the record itself does not say which SDK
111 +instance made the request. :meth:`HttpClient.request` binds this variable
112 +for the duration of each call so the forwarder can deliver the record to
113 +that instance's logger instead of whichever instance was constructed last.
114 +"""
115 +
116 +
117 +class _ClientLogForwarder(logging.Handler):
118 + """Forward ``composio_client`` records into the SDK logger.
119 +
120 + The generated client logs request/response lifecycle through
121 + ``logging.getLogger("composio_client")``. Routing those records through
122 + the SDK's :class:`_VerbosityWrapper` keeps one destination for SDK users
123 + and applies the same credential redaction and line truncation the SDK's
124 + own records get. The client's INFO records (per-request lifecycle) are
125 + forwarded as DEBUG.
126 +
127 + One forwarder is installed per process. A record emitted while an
128 + :class:`HttpClient` request is in flight goes to that client's logger
129 + (see :data:`_active_log_wrapper`); a record emitted outside any request
130 + goes to the logger of the most recently constructed client.
131 + """
132 +
133 + def __init__(self, wrapper: _VerbosityWrapper) -> None:
134 + super().__init__()
135 + self.wrapper = wrapper
136 +
137 + def emit(self, record: logging.LogRecord) -> None:
138 + wrapper = _active_log_wrapper.get() or self.wrapper
139 + try:
140 + message = record.getMessage()
141 + if record.levelno >= logging.ERROR:
142 + wrapper.error(message, exc_info=record.exc_info)
143 + elif record.levelno >= logging.WARNING:
144 + wrapper.warning(message, exc_info=record.exc_info)
145 + else:
146 + wrapper.debug(message, exc_info=record.exc_info)
147 + except Exception: # noqa: BLE001 - logging must never fail the call
148 + self.handleError(record)
149 +
150 +
151 +_forwarding_wrappers: "weakref.WeakSet[_VerbosityWrapper]" = weakref.WeakSet()
152 +"""The SDK loggers of the :class:`HttpClient` instances still alive.
153 +
154 +The ``composio_client`` logger has one process-wide level, so it is kept at
155 +the most permissive level any live instance needs; each instance's wrapper
156 +then filters what it actually emits. Weak references let an instance that
157 +was garbage collected stop holding the level down.
158 +"""
159 +
160 +
161 +def _client_level_for(wrapper: _VerbosityWrapper) -> int:
162 + """The ``composio_client`` level that lets ``wrapper`` see what it wants.
163 +
164 + The client's INFO records are forwarded as DEBUG, so the client only
165 + needs to produce them when the SDK logger is at DEBUG; otherwise only
166 + its WARNING and above records are worth producing.
167 + """
168 + level = wrapper.logger.getEffectiveLevel()
169 + return level if level <= logging.DEBUG else max(level, logging.WARNING)
170 +
171 +
172 +def _install_client_log_forwarder(wrapper: _VerbosityWrapper) -> logging.Logger:
173 + """Attach the process-wide forwarder to the client logger.
174 +
175 + Idempotent: the single forwarder is created on first use and kept
176 + afterwards. Each call rebinds its fallback logger to ``wrapper`` (the
177 + most recently constructed SDK instance); records emitted during a
178 + request are routed to the requesting instance regardless of that
179 + fallback, so earlier instances keep receiving their own request logs.
180 +
181 + The client logger's level is the most permissive one any live instance
182 + needs, so constructing a quieter instance never silences the lifecycle
183 + records of an earlier, more verbose one.
184 + """
185 + client_logger = logging.getLogger(CLIENT_LOGGER_NAME)
186 + forwarder: t.Optional[_ClientLogForwarder] = None
187 + for handler in list(client_logger.handlers):
188 + if not isinstance(handler, _ClientLogForwarder):
189 + continue
190 + if forwarder is None:
191 + forwarder = handler
192 + continue
193 + client_logger.removeHandler(handler)
194 + if forwarder is None:
195 + client_logger.addHandler(_ClientLogForwarder(wrapper))
196 + else:
197 + forwarder.wrapper = wrapper
198 + _forwarding_wrappers.add(wrapper)
199 + client_logger.setLevel(min(_client_level_for(w) for w in _forwarding_wrappers))
200 + client_logger.propagate = False
201 + return client_logger
202 +
203 +
204 def _get_python_implementation() -> str:
205 """
206 Get the Python implementation name.
@@ -198,6 +312,8 @@ class HttpClient(BaseComposio, WithLogger):
312 *,
313 provider: str,
314 api_key: t.Optional[str] = None,
315 + user_api_key: t.Optional[str] = None,
316 + org_api_key: t.Optional[str] = None,
317 environment: te.Union[NotGiven, APIEnvironment] = "production",
318 base_url: t.Optional[t.Union[str, URL, NotGiven]] = NOT_GIVEN,
319 timeout: t.Optional[t.Union[float, Timeout, NotGiven]] = NOT_GIVEN,
@@ -205,13 +321,19 @@ class HttpClient(BaseComposio, WithLogger):
321 default_headers: t.Optional[t.Mapping[str, str]] = None,
322 default_query: t.Optional[t.Mapping[str, object]] = None,
323 http_client: t.Optional[Client] = None,
324 + logger: t.Optional[logging.Logger] = None,
325 + logging_level: t.Optional[LogLevel] = None,
326 _strict_response_validation: bool = False,
327 ) -> None:
328 """
329 Initialize the client.
330
331 :param provider: The provider to use for the client.
332 + :param logger: Logger that receives SDK and ``composio_client`` records.
333 + :param logging_level: Level applied to the SDK and ``composio_client`` loggers.
334 :param api_key: The API key to use for the client.
335 + :param user_api_key: User API key, sent only on operations that require it.
336 + :param org_api_key: Organization API key, sent only on operations that require it.
337 :param environment: The environment to use for the client.
338 :param base_url: The base URL to use for the client.
339 :param timeout: The timeout to use for the client.
@@ -220,10 +342,12 @@ class HttpClient(BaseComposio, WithLogger):
342 :param default_query: The default query parameters to use for the client.
343 :param http_client: The HTTP client to use for the client.
344 """
223 - WithLogger.__init__(self)
345 + WithLogger.__init__(self, logger=logger, logging_level=logging_level)
346 BaseComposio.__init__(
347 self,
348 api_key=api_key,
349 + user_api_key=user_api_key,
350 + org_api_key=org_api_key,
351 environment=environment,
352 base_url=base_url,
353 timeout=timeout,
@@ -233,8 +357,7 @@ class HttpClient(BaseComposio, WithLogger):
357 http_client=http_client,
358 _strict_response_validation=_strict_response_validation,
359 )
236 - # TOFIX: Verbosity wrapper impl
237 - _base_client.log = self._logger # type: ignore
360 + _install_client_log_forwarder(self._logger)
361 self.provider = provider
362 self.request_ctx = contextvars.ContextVar[RequestContext](
363 "request_ctx",
@@ -269,6 +392,10 @@ class HttpClient(BaseComposio, WithLogger):
392 # (False) even when the original had it enabled — keeping the sibling
393 # a faithful copy that differs from the parent only in `max_retries`.
394 "_strict_response_validation": self._strict_response_validation,
395 + # Share the parent's logger; otherwise constructing the clone
396 + # rebinds the process-wide client log forwarder to the default
397 + # `composio` logger.
398 + "logger": self._logger.logger,
399 **_extra_kwargs,
400 },
401 **kwargs,
@@ -303,19 +430,45 @@ class HttpClient(BaseComposio, WithLogger):
430 self._without_retries = self.with_options(max_retries=0)
431 return self._without_retries
432
306 - def _make_status_error(
433 + def request( # type: ignore[override]
434 self,
308 - err_msg: str,
435 + cast_to: t.Any,
436 + options: t.Mapping[str, t.Any],
437 *,
310 - body: object,
311 - response: Response,
312 - ) -> APIStatusError:
438 + stream: bool = False,
439 + stream_cls: t.Optional[t.Type[t.Any]] = None,
440 + ) -> t.Any:
441 + # Bind this instance's logger for the request so the client's
442 + # lifecycle records reach it (see `_active_log_wrapper`).
443 + token = _active_log_wrapper.set(self._logger)
444 + try:
445 + return super().request(
446 + cast_to, options, stream=stream, stream_cls=stream_cls
447 + )
448 + finally:
449 + _active_log_wrapper.reset(token)
450 +
451 + def _decode(self, response: Response) -> t.Any:
452 + """
453 + Raise status errors that are also ``ComposioError``s; see
454 + ``_with_sdk_error_base``.
455 """
314 - Build the generated client's status error so it is also a
315 - ``ComposioError``; see ``_with_sdk_error_base``.
456 + try:
457 + return super()._decode(response)
458 + except APIStatusError as error:
459 + raise _as_sdk_error(error) from None
460 +
461 + def _process_response(
462 + self, response: Response, cast_to: t.Optional[t.Type[t.Any]]
463 + ) -> t.Any:
464 """
317 - error = super()._make_status_error(err_msg, body=body, response=response)
318 - return _with_sdk_error_base(type(error))(err_msg, response=response, body=body)
465 + Raise status errors that are also ``ComposioError``s; see
466 + ``_with_sdk_error_base``.
467 + """
468 + try:
469 + return super()._process_response(response, cast_to)
470 + except APIStatusError as error:
471 + raise _as_sdk_error(error) from None
472
473 def _prepare_request(self, request: Request) -> None:
474 """
python/composio/client/types.py
+92
@@ -13,14 +13,26 @@ from composio_client.types import (
13 auth_config_retrieve_response,
14 auth_config_update_params,
15 connected_account_create_params,
16 + connected_account_complete_auth_response,
17 connected_account_create_response,
18 connected_account_list_params,
19 connected_account_list_response,
20 connected_account_patch_params,
21 connected_account_patch_response,
22 + connected_account_refresh_params,
23 + connected_account_refresh_response,
24 connected_account_retrieve_response,
25 + connected_account_revoke_response,
26 connected_account_update_status_response,
27 + custom_delete_toolkit_response,
28 + custom_sync_response,
29 + custom_upsert_params,
30 + custom_upsert_response,
31 + keyring_list_transfer_keys_response,
32 link_create_params,
33 + log_create_tool_execution_params,
34 + log_create_tool_execution_response,
35 + log_retrieve_tool_execution_response,
36 tool_execute_params,
37 tool_execute_response,
38 tool_list_response,
@@ -28,8 +40,44 @@ from composio_client.types import (
40 tool_proxy_response,
41 toolkit_list_params,
42 toolkit_list_response,
43 + toolkit_recommend_scopes_params,
44 + toolkit_recommend_scopes_response,
45 + toolkit_retrieve_changelog_response,
46 + toolkit_retrieve_multi_params,
47 + toolkit_retrieve_multi_response,
48 toolkit_retrieve_response,
49 + toolkit_retrieve_scopes_grant_context_params,
50 + toolkit_retrieve_scopes_grant_context_response,
51 trigger_instance_upsert_response,
52 + webhook_endpoint_create_params,
53 + webhook_endpoint_create_response,
54 + webhook_endpoint_list_params,
55 + webhook_endpoint_list_response,
56 + webhook_endpoint_replace_params,
57 + webhook_endpoint_replace_response,
58 + webhook_endpoint_retrieve_response,
59 + webhook_endpoint_update_params,
60 + webhook_endpoint_update_response,
61 + webhook_subscription_create_params,
62 + webhook_subscription_create_response,
63 + webhook_subscription_delete_response,
64 + webhook_subscription_list_event_types_response,
65 + webhook_subscription_list_params,
66 + webhook_subscription_list_response,
67 + webhook_subscription_retrieve_response,
68 + webhook_subscription_rotate_secret_response,
69 + webhook_subscription_update_params,
70 + webhook_subscription_update_response,
71 +)
72 +from composio_client.types.project import (
73 + usage_retrieve_params,
74 + usage_retrieve_response,
75 + usage_retrieve_summary_params,
76 + usage_retrieve_summary_response,
77 +)
78 +from composio_client.types.tool_router import (
79 + session_config_history_params,
80 + session_config_history_response,
81 )
82
83 Tool: t.TypeAlias = tool_list_response.Item
@@ -71,15 +119,29 @@ __all__ = (
119 "auth_config_list_response",
120 "auth_config_retrieve_response",
121 "auth_config_update_params",
122 + "connected_account_complete_auth_response",
123 "connected_account_create_params",
124 "connected_account_create_response",
125 "connected_account_list_params",
126 "connected_account_list_response",
127 "connected_account_patch_params",
128 "connected_account_patch_response",
129 + "connected_account_refresh_params",
130 + "connected_account_refresh_response",
131 "connected_account_retrieve_response",
132 + "connected_account_revoke_response",
133 "connected_account_update_status_response",
134 + "custom_delete_toolkit_response",
135 + "custom_sync_response",
136 + "custom_upsert_params",
137 + "custom_upsert_response",
138 + "keyring_list_transfer_keys_response",
139 "link_create_params",
140 + "log_create_tool_execution_params",
141 + "log_create_tool_execution_response",
142 + "log_retrieve_tool_execution_response",
143 + "session_config_history_params",
144 + "session_config_history_response",
145 "trigger_instance_upsert_response",
146 "tool_execute_params",
147 "tool_execute_response",
@@ -88,7 +150,37 @@ __all__ = (
150 "tool_proxy_response",
151 "toolkit_list_params",
152 "toolkit_list_response",
153 + "toolkit_recommend_scopes_params",
154 + "toolkit_recommend_scopes_response",
155 + "toolkit_retrieve_changelog_response",
156 + "toolkit_retrieve_multi_params",
157 + "toolkit_retrieve_multi_response",
158 "toolkit_retrieve_response",
159 + "toolkit_retrieve_scopes_grant_context_params",
160 + "toolkit_retrieve_scopes_grant_context_response",
161 + "usage_retrieve_params",
162 + "usage_retrieve_response",
163 + "usage_retrieve_summary_params",
164 + "usage_retrieve_summary_response",
165 + "webhook_endpoint_create_params",
166 + "webhook_endpoint_create_response",
167 + "webhook_endpoint_list_params",
168 + "webhook_endpoint_list_response",
169 + "webhook_endpoint_replace_params",
170 + "webhook_endpoint_replace_response",
171 + "webhook_endpoint_retrieve_response",
172 + "webhook_endpoint_update_params",
173 + "webhook_endpoint_update_response",
174 + "webhook_subscription_create_params",
175 + "webhook_subscription_create_response",
176 + "webhook_subscription_delete_response",
177 + "webhook_subscription_list_event_types_response",
178 + "webhook_subscription_list_params",
179 + "webhook_subscription_list_response",
180 + "webhook_subscription_retrieve_response",
181 + "webhook_subscription_rotate_secret_response",
182 + "webhook_subscription_update_params",
183 + "webhook_subscription_update_response",
184 "Tool",
185 "ToolkitMinimal",
186 "AuthConfig",
python/composio/core/models/__init__.py
+23 -1
@@ -9,7 +9,13 @@ from .custom_tool_types import (
9 SessionContext,
10 ToolRouterSessionProxyExecuteResponse,
11 )
12 -from .experimental import ExperimentalAPI
12 +from .experimental import (
13 + ExperimentalAPI,
14 + ExperimentalCustomToolkits,
15 + ExperimentalUsage,
16 +)
17 +from .keyring import Keyring
18 +from .logs import Logs
19 from .mcp import MCP
20 from .tool_router import ToolRouter
21 from .tool_router_constants import SESSION_PRESET_DIRECT_TOOLS
@@ -29,6 +35,13 @@ from .webhook_events import (
35 WebhookEventType,
36 is_connection_expired_event,
37 )
38 +from .webhooks import (
39 + WebhookEndpoints,
40 + Webhooks,
41 + WebhookSubscription,
42 + WebhookSubscriptions,
43 + WebhookVersion,
44 +)
45
46 __all__ = [
47 "AuthConfigs",
@@ -38,7 +51,11 @@ __all__ = [
51 "ConnectionStatusEnum",
52 "CustomTool",
53 "ExperimentalAPI",
54 + "ExperimentalCustomToolkits",
55 "ExperimentalToolkit",
56 + "ExperimentalUsage",
57 + "Keyring",
58 + "Logs",
59 "MCP",
60 "ProxyExecuteBinaryData",
61 "RegisteredCustomTool",
@@ -56,7 +73,12 @@ __all__ = [
73 "Tools",
74 "Triggers",
75 "WebhookConnectionMetadata",
76 + "WebhookEndpoints",
77 "WebhookEvent",
78 "WebhookEventType",
79 + "WebhookSubscription",
80 + "WebhookSubscriptions",
81 + "WebhookVersion",
82 + "Webhooks",
83 "is_connection_expired_event",
84 ]
python/composio/core/models/connected_accounts.py
+114 -3
@@ -7,15 +7,19 @@ import typing as t
7 import warnings
8
9 import typing_extensions as te
10 -from composio_client import BadRequestError, omit
10 +from composio_client import BadRequestError, ConflictError, omit
11
12 from composio import exceptions
13 from composio.client import HttpClient
14 from composio.client.types import (
15 + connected_account_complete_auth_response,
16 connected_account_create_params,
17 connected_account_patch_params,
18 connected_account_patch_response,
19 + connected_account_refresh_params,
20 + connected_account_refresh_response,
21 connected_account_retrieve_response,
22 + connected_account_revoke_response,
23 connected_account_update_status_response,
24 link_create_params,
25 )
@@ -35,6 +39,17 @@ _TERMINAL_CONNECTION_STATES: t.FrozenSet[str] = frozenset(
39 # warning on every initiate() call.
40 _legacy_initiate_warning_emitted = False
41
42 +_REFRESH_DEPRECATION = (
43 + "connected_accounts.refresh() is deprecated: the API marks "
44 + "POST /connected_accounts/{id}/refresh as deprecated. Re-initiate "
45 + "auth with connected_accounts.link() or toolkits.authorize() instead."
46 +)
47 +
48 +_REFRESH_VALIDATE_CREDENTIALS_IGNORED = (
49 + "connected_accounts.refresh(): the API no longer accepts "
50 + "validate_credentials; the argument is ignored."
51 +)
52 +
53
54 class ConnectionRequest(Resource):
55 """
@@ -368,7 +383,6 @@ class ConnectedAccounts:
383 self.list = self._client.connected_accounts.list
384 self.delete = self._client.connected_accounts.delete
385 self.update_status = self._client.connected_accounts.update_status
371 - self.refresh = self._client.connected_accounts.refresh
386 self.enable = functools.partial(
387 self._client.connected_accounts.update_status,
388 enabled=True,
@@ -378,6 +392,103 @@ class ConnectedAccounts:
392 enabled=False,
393 )
394
395 + @te.deprecated(_REFRESH_DEPRECATION, category=None)
396 + def refresh(
397 + self,
398 + nanoid: str,
399 + **params: te.Unpack[
400 + connected_account_refresh_params.ConnectedAccountRefreshParams
401 + ],
402 + ) -> connected_account_refresh_response.ConnectedAccountRefreshResponse:
403 + """
404 + Refresh the credentials of a connected account.
405 +
406 + .. deprecated::
407 + The API marks ``POST /connected_accounts/{id}/refresh`` as
408 + deprecated. Re-initiate authentication with
409 + :meth:`link` or ``composio.toolkits.authorize()`` instead.
410 +
411 + :param nanoid: The connected account ID (``ca_xxx``).
412 + :return: The refresh response.
413 +
414 + Example:
415 + composio.connected_accounts.refresh("ca_abc123")
416 + """
417 + warnings.warn(
418 + _REFRESH_DEPRECATION, exceptions.ComposioDeprecationWarning, stacklevel=2
419 + )
420 + # The API no longer accepts validate_credentials; forward every other
421 + # kwarg (timeout, extra_headers, ...) unchanged.
422 + forwarded: t.Dict[str, t.Any] = dict(params)
423 + if forwarded.pop("validate_credentials", None) is not None:
424 + warnings.warn(
425 + _REFRESH_VALIDATE_CREDENTIALS_IGNORED,
426 + exceptions.ComposioDeprecationWarning,
427 + stacklevel=2,
428 + )
429 + return self._client.connected_accounts.refresh(nanoid, **forwarded)
430 +
431 + def revoke(
432 + self, nanoid: str
433 + ) -> connected_account_revoke_response.ConnectedAccountRevokeResponse:
434 + """
435 + Revoke a connected account's upstream tokens (best effort) and mark
436 + the connection ``REVOKED``.
437 +
438 + Raises :class:`composio.exceptions.ComposioConnectedAccountRevocationNotSupportedError`
439 + when the toolkit does not support programmatic revocation (API 400)
440 + and :class:`composio.exceptions.ComposioConnectedAccountNotRevokableError`
441 + when the connection is not in a revokable state (API 409).
442 +
443 + :param nanoid: The connected account ID (``ca_xxx``).
444 + :return: The revoked tokens and the updated connected account.
445 +
446 + Example:
447 + result = composio.connected_accounts.revoke("ca_abc123")
448 + print(result.connected_account.status) # "REVOKED"
449 + """
450 + try:
451 + return self._client.connected_accounts.revoke(nanoid)
452 + except BadRequestError as error:
453 + raise exceptions.ComposioConnectedAccountRevocationNotSupportedError(
454 + f"Connected account {nanoid!r} cannot be revoked programmatically: "
455 + f"the toolkit does not support token revocation ({error})"
456 + ) from error
457 + except ConflictError as error:
458 + raise exceptions.ComposioConnectedAccountNotRevokableError(
459 + f"Connected account {nanoid!r} is not in a revokable state ({error})"
460 + ) from error
461 +
462 + def complete_auth(
463 + self, *, user_id: str, session_uri: str
464 + ) -> connected_account_complete_auth_response.ConnectedAccountCompleteAuthResponse:
465 + """
466 + Complete a deferred OAuth connection once you have verified the
467 + user's identity.
468 +
469 + When your project has an OAuth callback verifier configured, Composio
470 + does not activate a new OAuth connection by itself: it redirects to
471 + your verifier with a single-use session URI. After confirming who the
472 + user is, redeem it here; Composio checks that your project owns the
473 + pending connection and that ``user_id`` is its owner, completes the
474 + token exchange, and the connection becomes ``ACTIVE``. Redeeming a
475 + session twice, or after it expires, fails with a 404 from the API.
476 +
477 + :param user_id: The user the connection was initiated for.
478 + :param session_uri: The session URI from the verifier redirect.
479 + :return: The completed ``connected_account_id`` and its ``toolkit_slug``.
480 +
481 + Example:
482 + result = composio.connected_accounts.complete_auth(
483 + user_id="user_123",
484 + session_uri=session_uri, # from the verifier redirect
485 + )
486 + print(result.connected_account_id)
487 + """
488 + return self._client.connected_accounts.complete_auth(
489 + user_id=user_id, session_uri=session_uri
490 + )
491 +
492 def update(
493 self,
494 nanoid: str,
@@ -609,7 +720,7 @@ class ConnectedAccounts:
720 "composio.connected_accounts.link() — same return shape, "
721 "same allow_multiple semantics. "
722 "https://docs.composio.dev/docs/changelog/2026/04/24",
612 - DeprecationWarning,
723 + exceptions.ComposioDeprecationWarning,
724 stacklevel=2,
725 )
726
python/composio/core/models/experimental.py
+191 -1
@@ -18,10 +18,22 @@ from __future__ import annotations
18
19 import typing as t
20
21 +import typing_extensions as te
22 from pydantic import BaseModel
23
24 from composio.client import HttpClient
24 -from composio.client.types import connected_account_patch_response
25 +from composio.utils.pydantic import none_to_omit
26 +from composio.client.types import (
27 + connected_account_patch_response,
28 + custom_delete_toolkit_response,
29 + custom_sync_response,
30 + custom_upsert_params,
31 + custom_upsert_response,
32 + usage_retrieve_params,
33 + usage_retrieve_response,
34 + usage_retrieve_summary_params,
35 + usage_retrieve_summary_response,
36 +)
37
38 from .custom_tool import (
39 CustomTool,
@@ -37,6 +49,176 @@ from .custom_tool import (
49 ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT = "acl_config_for_shared is only valid on SHARED"
50
51
52 +class ExperimentalUsage:
53 + """Project usage metering, accessed via ``composio.experimental.usage``.
54 +
55 + Experimental — the response shape may change in future releases. Scoped
56 + to the project the API key belongs to.
57 + """
58 +
59 + def __init__(self, client: t.Optional[HttpClient] = None) -> None:
60 + self._client = client
61 +
62 + def _require_client(self) -> HttpClient:
63 + from composio import exceptions
64 +
65 + if self._client is None:
66 + raise exceptions.ValidationError(
67 + "experimental.usage requires a Composio client. Access it via "
68 + "composio.experimental.usage.summary(...)."
69 + )
70 + return self._client
71 +
72 + def summary(
73 + self,
74 + **params: te.Unpack[usage_retrieve_summary_params.UsageRetrieveSummaryParams],
75 + ) -> usage_retrieve_summary_response.UsageRetrieveSummaryResponse:
76 + """
77 + Fetch a usage summary for the project. Experimental — shape may change.
78 +
79 + :param from_: Start of the window (Unix epoch milliseconds).
80 + :param to: End of the window (Unix epoch milliseconds).
81 + :param entity_types: Restrict the summary to these entity types.
82 + :param filters: Additional server-side filters.
83 + :return: Usage totals keyed by entity type under ``.entities``.
84 +
85 + Example:
86 + summary = composio.experimental.usage.summary(
87 + entity_types=["tool_calls"],
88 + )
89 + """
90 + return self._require_client().project.usage.retrieve_summary(**params)
91 +
92 + def breakdown(
93 + self,
94 + entity_type: str,
95 + **params: te.Unpack[usage_retrieve_params.UsageRetrieveParams],
96 + ) -> usage_retrieve_response.UsageRetrieveResponse:
97 + """
98 + Fetch a grouped usage breakdown for one entity type. Experimental —
99 + shape may change.
100 +
101 + :param entity_type: The metered entity type, e.g. ``tool_calls`` or ``sessions``.
102 + :param from_: Start of the window (Unix epoch milliseconds).
103 + :param to: End of the window (Unix epoch milliseconds).
104 + :param group_by: Field to group the breakdown by (API default: ``tool_slug``
105 + for ``tool_calls``, ``user_id`` for ``sessions``).
106 + :param order_by: Sort key (``key``, ``total_quantity`` or ``event_count``).
107 + :param order_direction: ``asc`` or ``desc``.
108 + :param limit: Maximum number of groups to return.
109 + :param filters: Additional server-side filters.
110 + :return: The usage totals and per-group breakdown.
111 +
112 + Example:
113 + breakdown = composio.experimental.usage.breakdown(
114 + "tool_calls",
115 + group_by="tool_slug",
116 + )
117 + """
118 + return self._require_client().project.usage.retrieve(entity_type, **params)
119 +
120 +
121 +class ExperimentalCustomToolkits:
122 + """Project-owned custom toolkits, accessed via
123 + ``composio.experimental.custom_toolkits``.
124 +
125 + Experimental — custom toolkits are in pilot and the shape may change.
126 + These toolkits are registered in your Composio project from your own app
127 + or MCP server, with their own auth configs and connected accounts. They
128 + are unrelated to the in-process toolkits built with
129 + ``composio.experimental.Toolkit``.
130 + """
131 +
132 + def __init__(self, client: t.Optional[HttpClient] = None) -> None:
133 + self._client = client
134 +
135 + def _require_client(self) -> HttpClient:
136 + from composio import exceptions
137 +
138 + if self._client is None:
139 + raise exceptions.ValidationError(
140 + "experimental.custom_toolkits requires a Composio client. Access "
141 + "it via composio.experimental.custom_toolkits.upsert(...)."
142 + )
143 + return self._client
144 +
145 + def upsert(
146 + self,
147 + **params: te.Unpack[custom_upsert_params.CustomUpsertParams],
148 + ) -> custom_upsert_response.CustomUpsertResponse:
149 + """
150 + Create a custom toolkit, or update its display metadata (name, API key
151 + field copy) when the project already owns one with this slug.
152 + Experimental — shape may change.
153 +
154 + ``app_url`` and ``auth_schemes`` cannot change on an existing
155 + toolkit: re-sending them unchanged is a no-op, and changing them fails
156 + with a 409. Delete and re-register the toolkit instead, which revokes
157 + its connections.
158 +
159 + :param slug: Letters, digits, underscores or spaces (max 30). The API
160 + prefixes it with ``CUSTOM_`` and turns spaces into underscores.
161 + :param toolkit_config: ``name``, ``app_url`` (the MCP URL for MCP
162 + apps), ``auth_schemes`` and an optional base64 ``logo_file``.
163 + :return: The toolkit's ``slug``.
164 +
165 + Example:
166 + composio.experimental.custom_toolkits.upsert(
167 + slug="INTERNAL_API",
168 + toolkit_config={
169 + "name": "Internal API",
170 + "app_url": "https://mcp.internal.example.com/mcp",
171 + "auth_schemes": [
172 + {
173 + "mode": "API_KEY",
174 + "headers": {"Authorization": "Bearer {{generic_api_key}}"},
175 + }
176 + ],
177 + },
178 + )
179 + """
180 + return self._require_client().custom.upsert(**params)
181 +
182 + def sync(
183 + self, slug: str, *, connected_account_id: t.Optional[str] = None
184 + ) -> custom_sync_response.CustomSyncResponse:
185 + """
186 + Re-fetch a custom toolkit's tool definitions from its remote MCP
187 + server. Call it when automatic sync fails or the remote tools change.
188 + Experimental — shape may change.
189 +
190 + :param slug: The custom toolkit slug (``CUSTOM_...``).
191 + :param connected_account_id: Connected account to use when fetching
192 + the remote tool definitions.
193 + :return: The toolkit ``version`` and ``synced_count``.
194 +
195 + Example:
196 + result = composio.experimental.custom_toolkits.sync("CUSTOM_MY_TOOLKIT")
197 + print(result.synced_count)
198 + """
199 + return self._require_client().custom.sync(
200 + slug=slug, connected_account_id=none_to_omit(connected_account_id)
201 + )
202 +
203 + def delete(
204 + self, slug: str
205 + ) -> custom_delete_toolkit_response.CustomDeleteToolkitResponse:
206 + """
207 + Delete a custom toolkit owned by the project, with its tools, auth
208 + configs and connected accounts. The credentials behind those
209 + connected accounts are revoked in background jobs
210 + (``revoke_job_ids``). Composio-managed toolkits cannot be deleted
211 + (API 403). Experimental — shape may change.
212 +
213 + :param slug: The custom toolkit slug (``CUSTOM_...``).
214 + :return: What was deleted.
215 +
216 + Example:
217 + composio.experimental.custom_toolkits.delete("CUSTOM_MY_TOOLKIT")
218 + """
219 + return self._require_client().custom.delete_toolkit(slug)
220 +
221 +
222 class ExperimentalAPI:
223 """Experimental APIs accessed via ``composio.experimental``.
224
@@ -47,8 +229,16 @@ class ExperimentalAPI:
229
230 Toolkit = ExperimentalToolkit
231
232 + usage: ExperimentalUsage
233 + """Project usage metering. Experimental — shape may change."""
234 +
235 + custom_toolkits: ExperimentalCustomToolkits
236 + """Project-owned custom toolkits. Experimental — shape may change."""
237 +
238 def __init__(self, client: t.Optional[HttpClient] = None) -> None:
239 self._client = client
240 + self.usage = ExperimentalUsage(client=client)
241 + self.custom_toolkits = ExperimentalCustomToolkits(client=client)
242
243 def update_acl(
244 self,
python/composio/core/models/keyring.py new
+39
@@ -0,0 +1,39 @@
1 +"""
2 +Keyring module for the Composio SDK.
3 +
4 +Exposes ``composio.keyring`` for the organization's customer-managed keyring.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +from composio.client.types import keyring_list_transfer_keys_response
10 +from composio.core.models.base import Resource
11 +
12 +
13 +class Keyring(Resource):
14 + """The organization's customer-managed keyring."""
15 +
16 + def list_transfer_keys(
17 + self,
18 + ) -> keyring_list_transfer_keys_response.KeyringListTransferKeysResponse:
19 + """
20 + List the public transfer keys of the organization's active customer
21 + keyring, the keys a secret is sealed to before it is sent to Composio.
22 +
23 + Seal new secrets to the key whose ``kid`` is ``active_kid``: a JWE
24 + with ``RSA-OAEP-256`` key management, ``A256GCM`` content
25 + encryption, and the ``kid`` in the protected header. Older keys stay
26 + listed so values sealed to them remain openable. The API answers 404
27 + when the organization has no ACTIVE keyring instance.
28 +
29 + :return: ``active_kid`` and every accepted public JWK under ``keys``,
30 + newest first.
31 +
32 + Example:
33 + transfer_keys = composio.keyring.list_transfer_keys()
34 + jwk = next(
35 + key for key in transfer_keys.keys
36 + if key.kid == transfer_keys.active_kid
37 + )
38 + """
39 + return self._client.keyring.list_transfer_keys()
python/composio/core/models/logs.py new
+63
@@ -0,0 +1,63 @@
1 +"""
2 +Logs module for the Composio SDK.
3 +
4 +Exposes ``composio.logs`` for searching and retrieving tool execution logs.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +import typing_extensions as te
10 +
11 +from composio.client.types import (
12 + log_create_tool_execution_params,
13 + log_create_tool_execution_response,
14 + log_retrieve_tool_execution_response,
15 +)
16 +from composio.core.models.base import Resource
17 +
18 +
19 +class Logs(Resource):
20 + """Search and retrieve tool execution logs."""
21 +
22 + def search(
23 + self,
24 + **params: te.Unpack[
25 + log_create_tool_execution_params.LogCreateToolExecutionParams
26 + ],
27 + ) -> log_create_tool_execution_response.LogCreateToolExecutionResponse:
28 + """
29 + Search tool execution logs with filters, pagination, and a time range.
30 +
31 + Despite the underlying ``POST`` verb this is a read-only search.
32 +
33 + :param limit: Maximum number of logs to return.
34 + :param cursor: Pagination cursor from a previous response.
35 + :param filters: Filter clauses to narrow the search.
36 + :param time_range: Time window to search within.
37 + :return: Matching logs plus a ``next_cursor`` for pagination.
38 +
39 + Example:
40 + page = composio.logs.search(
41 + limit=20,
42 + filters=[
43 + {"field": "toolkit_slug", "operator": "==", "value": "github"}
44 + ],
45 + )
46 + for log in page.logs:
47 + print(log.id)
48 + """
49 + return self._client.logs.create_tool_execution(**params)
50 +
51 + def get(
52 + self, id: str
53 + ) -> log_retrieve_tool_execution_response.LogRetrieveToolExecutionResponse:
54 + """
55 + Retrieve a single tool execution log by id.
56 +
57 + :param id: The log id.
58 + :return: The full log entry.
59 +
60 + Example:
61 + log = composio.logs.get("log_123")
62 + """
63 + return self._client.logs.retrieve_tool_execution(id)
python/composio/core/models/tool_router_session.py
+31 -1
@@ -12,6 +12,7 @@ import typing as t
12 from concurrent.futures import ThreadPoolExecutor
13 from dataclasses import dataclass
14
15 +import typing_extensions as te
16 from composio_client import BadRequestError, Omit, omit
17 from composio_client._types import SequenceNotStr
18 from composio_client.types.tool_list_response import (
@@ -36,7 +37,11 @@ from composio_client.types.tool_router.session_search_response import (
37
38 from composio import exceptions
39 from composio.client import HttpClient
39 -from composio.client.types import Tool
40 +from composio.client.types import (
41 + Tool,
42 + session_config_history_params,
43 + session_config_history_response,
44 +)
45 from composio.core.models._modifiers import Modifiers, apply_modifier_by_type
46 from composio.core.models.connected_accounts import ConnectionRequest
47 from composio.core.models.custom_tool import (
@@ -172,6 +177,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
177 execute=session_create_response.ConfigExecute(),
178 search=session_create_response.ConfigSearch(),
179 preload=session_create_response.ConfigPreload(tools=self.preload.tools),
180 + premium_usage=False,
181 )
182 # The MCP endpoint exists on every session at runtime (kept for
183 # backwards compatibility), but is only typed via
@@ -985,6 +991,30 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
991 self.preload = _session_preload_config(response.config.preload)
992 return self.config
993
994 + def list_config_history(
995 + self,
996 + **query: te.Unpack[session_config_history_params.SessionConfigHistoryParams],
997 + ) -> session_config_history_response.SessionConfigHistoryResponse:
998 + """
999 + List the configuration history of this session, newest first.
1000 +
1001 + Every ``update()`` records a new config version; this returns those
1002 + versions with cursor-based pagination.
1003 +
1004 + :param cursor: Pagination cursor from a previous response.
1005 + :param limit: Number of items per page (max 100).
1006 + :return: The config versions under ``.items`` plus pagination fields.
1007 +
1008 + Example:
1009 + history = session.list_config_history(limit=10)
1010 + for entry in history.items:
1011 + print(entry.version, entry.is_current)
1012 + """
1013 + return self._client.tool_router.session.config_history(
1014 + session_id=self.session_id,
1015 + **query,
1016 + )
1017 +
1018 def delete(self) -> ToolRouterSessionDeleteResponse:
1019 """
1020 Delete this session.
python/composio/core/models/toolkits.py
+116
@@ -2,13 +2,20 @@ from __future__ import annotations
2
3 import typing as t
4
5 +import typing_extensions as te
6 +
7 from composio import exceptions
8 from composio.client import HttpClient
9 from composio.client.types import (
10 AuthSchemeL,
11 toolkit_list_params,
12 toolkit_list_response,
13 + toolkit_recommend_scopes_params,
14 + toolkit_recommend_scopes_response,
15 + toolkit_retrieve_changelog_response,
16 toolkit_retrieve_response,
17 + toolkit_retrieve_scopes_grant_context_params,
18 + toolkit_retrieve_scopes_grant_context_response,
19 )
20 from composio.core.models.connected_accounts import ConnectedAccounts
21 from composio.utils.pydantic import none_to_omit
@@ -84,6 +91,115 @@ class Toolkits(Resource):
91 return self._client.toolkits.retrieve(slug=slug)
92 return self._client.toolkits.list(**(query or {})).items
93
94 + def get_many(
95 + self,
96 + slugs: t.Sequence[str],
97 + *,
98 + category: t.Optional[str] = None,
99 + managed_by: t.Optional[t.Literal["composio", "all", "project"]] = None,
100 + sort_by: t.Optional[t.Literal["usage", "alphabetically"]] = None,
101 + limit: t.Optional[float] = None,
102 + cursor: t.Optional[str] = None,
103 + ) -> t.List[t.Any]:
104 + """
105 + Fetch several toolkits by slug in one request.
106 +
107 + :param slugs: The toolkit slugs to fetch.
108 + :param category: Only return toolkits in this category.
109 + :param managed_by: Filter by who manages the toolkit.
110 + :param sort_by: Sort order of the returned toolkits.
111 + :param limit: Maximum number of toolkits to return.
112 + :param cursor: Pagination cursor from a previous response.
113 + :return: The matching toolkits.
114 +
115 + Example:
116 + toolkits = composio.toolkits.get_many(["github", "slack"])
117 + for toolkit in toolkits:
118 + print(toolkit.slug, toolkit.name)
119 + """
120 + return self._client.toolkits.retrieve_multi(
121 + toolkits=list(slugs),
122 + category=none_to_omit(category),
123 + managed_by=none_to_omit(managed_by),
124 + sort_by=none_to_omit(sort_by),
125 + limit=none_to_omit(limit),
126 + cursor=none_to_omit(cursor),
127 + ).items
128 +
129 + def changelog(
130 + self,
131 + ) -> toolkit_retrieve_changelog_response.ToolkitRetrieveChangelogResponse:
132 + """
133 + Retrieve the toolkit changelog (the last 10 versions per toolkit).
134 +
135 + :return: The changelog entries under ``.items``.
136 +
137 + Example:
138 + changelog = composio.toolkits.changelog()
139 + for entry in changelog.items:
140 + print(entry.slug, [v.version for v in entry.versions])
141 + """
142 + return self._client.toolkits.retrieve_changelog()
143 +
144 + def recommend_scopes(
145 + self,
146 + toolkit_slug: str,
147 + **params: te.Unpack[
148 + toolkit_recommend_scopes_params.ToolkitRecommendScopesParams
149 + ],
150 + ) -> toolkit_recommend_scopes_response.ToolkitRecommendScopesResponse:
151 + """
152 + Recommend the OAuth scopes to request so a connection can run the
153 + given tools. Experimental — the API marks this endpoint beta.
154 +
155 + :param toolkit_slug: The toolkit to recommend scopes for.
156 + :param tools: Tool slugs to cover; ``[]`` covers every tool in the toolkit.
157 + :param auth_scheme: Auth scheme the connection will use (API default ``OAUTH2``).
158 + :param toolkit_version: Toolkit version to compute from (API default: latest).
159 + :param grant_context: Dimension to selected value, e.g.
160 + ``{"account_type": "Google Workspace"}``. See :meth:`list_grant_contexts`.
161 + :param include: Scopes the recommendation must include.
162 + :param exclude: Scopes the recommendation must not include.
163 + :param available_scopes: Scopes your OAuth app can request; the
164 + recommendation never goes outside this list.
165 + :return: The ``least_privilege`` and ``fewest`` scope sets plus the
166 + ``conditional`` scopes, under ``.scopes``.
167 +
168 + Example:
169 + recommendation = composio.toolkits.recommend_scopes(
170 + "gmail",
171 + tools=["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"],
172 + )
173 + print(recommendation.scopes.least_privilege)
174 + """
175 + return self._client.toolkits.recommend_scopes(toolkit_slug, **params)
176 +
177 + def list_grant_contexts(
178 + self,
179 + toolkit_slug: str,
180 + **params: te.Unpack[
181 + toolkit_retrieve_scopes_grant_context_params.ToolkitRetrieveScopesGrantContextParams
182 + ],
183 + ) -> toolkit_retrieve_scopes_grant_context_response.ToolkitRetrieveScopesGrantContextResponse:
184 + """
185 + List the grant-context dimensions a toolkit's scope recommendation
186 + depends on, with their allowed values and the default the API
187 + assumes. Experimental — the API marks this endpoint beta.
188 +
189 + :param toolkit_slug: The toolkit to list grant contexts for.
190 + :param auth_scheme: Auth scheme the connection will use (API default ``OAUTH2``).
191 + :param toolkit_version: Toolkit version to read from (API default: latest).
192 + :return: ``grant_context_dimensions`` and ``default_grant_context``.
193 +
194 + Example:
195 + contexts = composio.toolkits.list_grant_contexts("gmail")
196 + for dimension in contexts.grant_context_dimensions:
197 + print(dimension.dimension, dimension.values)
198 + """
199 + return self._client.toolkits.retrieve_scopes_grant_context(
200 + toolkit_slug, **params
201 + )
202 +
203 def list_categories(self):
204 """List all categories of toolkits."""
205 return self._client.toolkits.retrieve_categories().items
python/composio/core/models/tools.py
+1 -1
@@ -250,7 +250,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
250 tools_list.extend(
251 self._client.tools.list(
252 toolkit_slug=none_to_omit(",".join(toolkits) if toolkits else None),
253 - search=none_to_omit(search),
253 + query=none_to_omit(search),
254 scopes=scopes,
255 limit=limit,
256 toolkit_versions=none_to_omit(self._toolkit_versions),
python/composio/core/models/triggers.py
+18 -125
@@ -13,7 +13,6 @@ import traceback
13 import typing as t
14 import uuid
15 from concurrent.futures import ThreadPoolExecutor
16 -from enum import Enum
16
17 import requests
18 import typing_extensions as te
@@ -28,6 +27,12 @@ from composio.client import HttpClient
27 from composio.client.types import trigger_instance_upsert_response
28 from composio.core.models.base import Resource
29 from composio.core.models.internal import Internal
30 +from composio.core.models.webhooks import (
31 + DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS,
32 + WebhookSubscription,
33 + WebhookSubscriptions,
34 + WebhookVersion,
35 +)
36 from composio.core.types import ToolkitVersionParam
37 from composio.exceptions import ComposioSDKTimeoutError
38 from composio.utils.logging import WithLogger
@@ -102,14 +107,6 @@ class _TriggerData(te.TypedDict):
107 originalPayload: t.Dict
108
109
105 -class WebhookVersion(str, Enum):
106 - """Webhook payload version."""
107 -
108 - V1 = "V1"
109 - V2 = "V2"
110 - V3 = "V3"
111 -
112 -
110 class WebhookPayloadV1(te.TypedDict):
111 """V1 webhook payload structure."""
112
@@ -206,20 +203,14 @@ class VerifyWebhookResult(t.TypedDict):
203 raw_payload: WebhookPayload # The original parsed payload
204
205
209 -class WebhookSubscription(t.TypedDict, total=False):
210 - """Webhook subscription returned by the Composio API."""
211 -
212 - id: str
213 - webhook_url: str
214 - version: str
215 - enabled_events: t.List[str]
216 - secret: str
217 - created_at: str
218 - updated_at: str
219 -
220 -
221 -DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS = ("composio.trigger.message",)
222 -WEBHOOK_SUBSCRIPTIONS_PATH = "/api/v3.1/webhook_subscriptions"
206 +# Re-exported for backwards compatibility; the definitions live in
207 +# :mod:`composio.core.models.webhooks`.
208 +__all__ = [
209 + "DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS",
210 + "Triggers",
211 + "WebhookSubscription",
212 + "WebhookVersion",
213 +]
214
215
216 _ = {
@@ -1187,110 +1178,12 @@ class Triggers(Resource):
1178 webhook_url=f"{APP_URL}/webhooks/composio",
1179 )
1180 """
1190 - if not webhook_url:
1191 - raise exceptions.ValidationError("please provide a valid `webhook_url`")
1192 -
1193 - events = list(
1194 - DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS
1195 - if enabled_events is None
1196 - else enabled_events
1197 - )
1198 - if len(events) == 0:
1199 - raise exceptions.ValidationError(
1200 - "please provide at least one enabled event"
1201 - )
1202 -
1203 - version_value = (
1204 - version.value if isinstance(version, WebhookVersion) else version
1205 - )
1206 - body = {
1207 - "webhook_url": webhook_url,
1208 - "enabled_events": events,
1209 - "version": version_value,
1210 - }
1211 -
1212 - existing = self._client.get(
1213 - WEBHOOK_SUBSCRIPTIONS_PATH,
1214 - cast_to=object,
1215 - options={"params": {"limit": 1}},
1216 - )
1217 - subscription_id = self._first_webhook_subscription_id(existing)
1218 -
1219 - if subscription_id:
1220 - return self._normalize_webhook_subscription(
1221 - self._client.patch(
1222 - f"{WEBHOOK_SUBSCRIPTIONS_PATH}/{subscription_id}",
1223 - cast_to=object,
1224 - body=body,
1225 - )
1226 - )
1227 -
1228 - return self._normalize_webhook_subscription(
1229 - self._client.post(
1230 - WEBHOOK_SUBSCRIPTIONS_PATH,
1231 - cast_to=object,
1232 - body=body,
1233 - ),
1181 + return WebhookSubscriptions(client=self._client).set(
1182 + webhook_url=webhook_url,
1183 + enabled_events=enabled_events,
1184 + version=version,
1185 )
1186
1236 - @staticmethod
1237 - def _normalize_webhook_subscription(raw: object) -> WebhookSubscription:
1238 - """Build a typed :class:`WebhookSubscription` from the raw API response.
1239 -
1240 - Maps explicitly (accepting either snake_case or camelCase wire keys)
1241 - instead of ``cast``-ing the raw object, so the returned dict always
1242 - matches the declared shape and a shift in the wire format surfaces as a
1243 - normalized field rather than a ``KeyError`` at the call site.
1244 - """
1245 - data = raw if isinstance(raw, dict) else {}
1246 -
1247 - def _first_str(*keys: str) -> t.Optional[str]:
1248 - for key in keys:
1249 - value = data.get(key)
1250 - if isinstance(value, str) and value:
1251 - return value
1252 - return None
1253 -
1254 - def _str_list(*keys: str) -> t.List[str]:
1255 - for key in keys:
1256 - value = data.get(key)
1257 - if isinstance(value, list):
1258 - return [item for item in value if isinstance(item, str)]
1259 - return []
1260 -
1261 - result: WebhookSubscription = {
1262 - "id": _first_str("id") or "",
1263 - "webhook_url": _first_str("webhook_url", "webhookUrl") or "",
1264 - "version": _first_str("version") or WebhookVersion.V3.value,
1265 - "enabled_events": _str_list("enabled_events", "enabledEvents"),
1266 - }
1267 - secret = _first_str("secret")
1268 - if secret is not None:
1269 - result["secret"] = secret
1270 - created_at = _first_str("created_at", "createdAt")
1271 - if created_at is not None:
1272 - result["created_at"] = created_at
1273 - updated_at = _first_str("updated_at", "updatedAt")
1274 - if updated_at is not None:
1275 - result["updated_at"] = updated_at
1276 - return result
1277 -
1278 - @staticmethod
1279 - def _first_webhook_subscription_id(response: object) -> t.Optional[str]:
1280 - if not isinstance(response, dict):
1281 - return None
1282 -
1283 - items = response.get("items")
1284 - if not isinstance(items, list) or len(items) == 0:
1285 - return None
1286 -
1287 - first = items[0]
1288 - if not isinstance(first, dict):
1289 - return None
1290 -
1291 - subscription_id = first.get("id")
1292 - return subscription_id if isinstance(subscription_id, str) else None
1293 -
1187 def get_type(self, slug: str) -> TriggersTypeRetrieveResponse:
1188 """
1189 Get a trigger type by its slug
python/composio/core/models/webhooks.py new
+472
@@ -0,0 +1,472 @@
1 +"""
2 +Webhooks module for the Composio SDK.
3 +
4 +Exposes ``composio.webhooks.subscriptions`` (the project-level webhook
5 +subscription used for event delivery) and ``composio.webhooks.endpoints``
6 +(per toolkit + OAuth app inbound ingress URLs).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +import typing as t
12 +from enum import Enum
13 +
14 +import pydantic
15 +
16 +from composio import exceptions
17 +from composio.client import HttpClient
18 +from composio.client.types import (
19 + webhook_endpoint_create_response,
20 + webhook_endpoint_list_response,
21 + webhook_endpoint_replace_response,
22 + webhook_endpoint_retrieve_response,
23 + webhook_endpoint_update_response,
24 + webhook_subscription_delete_response,
25 + webhook_subscription_list_event_types_response,
26 + webhook_subscription_list_response,
27 + webhook_subscription_retrieve_response,
28 + webhook_subscription_rotate_secret_response,
29 + webhook_subscription_update_response,
30 +)
31 +from composio.core.models.base import Resource
32 +from composio.utils.pydantic import none_to_omit
33 +
34 +
35 +class WebhookVersion(str, Enum):
36 + """Webhook payload version."""
37 +
38 + V1 = "V1"
39 + V2 = "V2"
40 + V3 = "V3"
41 +
42 +
43 +WebhookVersionL = t.Literal["V1", "V2", "V3"]
44 +
45 +_WEBHOOK_VERSIONS: t.Dict[str, WebhookVersionL] = {"V1": "V1", "V2": "V2", "V3": "V3"}
46 +
47 +
48 +def _webhook_version(version: t.Union[WebhookVersion, str]) -> WebhookVersionL:
49 + """Narrow a caller-supplied version to the literal the client accepts."""
50 + value = version.value if isinstance(version, WebhookVersion) else version
51 + literal = _WEBHOOK_VERSIONS.get(value)
52 + if literal is None:
53 + raise exceptions.ValidationError(
54 + f"unsupported webhook version {value!r}; expected one of V1, V2, V3"
55 + )
56 + return literal
57 +
58 +
59 +class WebhookSubscription(t.TypedDict, total=False):
60 + """Webhook subscription returned by the Composio API."""
61 +
62 + id: str
63 + webhook_url: str
64 + version: str
65 + enabled_events: t.List[str]
66 + secret: str
67 + created_at: str
68 + updated_at: str
69 +
70 +
71 +DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS = ("composio.trigger.message",)
72 +
73 +
74 +class _WebhookSubscriptionWire(pydantic.BaseModel):
75 + """Boundary schema for a subscription response.
76 +
77 + Accepts snake_case or camelCase wire keys and rejects a payload that
78 + lacks the fields :class:`WebhookSubscription` promises, so a malformed
79 + 2xx surfaces as a :class:`~composio.exceptions.ValidationError` instead
80 + of a typed subscription with empty or defaulted values.
81 + """
82 +
83 + model_config = pydantic.ConfigDict(extra="ignore", populate_by_name=True)
84 +
85 + id: str = pydantic.Field(min_length=1)
86 + webhook_url: str = pydantic.Field(
87 + min_length=1,
88 + validation_alias=pydantic.AliasChoices("webhook_url", "webhookUrl"),
89 + )
90 + version: str = pydantic.Field(min_length=1)
91 + enabled_events: t.List[str] = pydantic.Field(
92 + validation_alias=pydantic.AliasChoices("enabled_events", "enabledEvents"),
93 + )
94 + secret: t.Optional[str] = None
95 + created_at: t.Optional[str] = pydantic.Field(
96 + default=None,
97 + validation_alias=pydantic.AliasChoices("created_at", "createdAt"),
98 + )
99 + updated_at: t.Optional[str] = pydantic.Field(
100 + default=None,
101 + validation_alias=pydantic.AliasChoices("updated_at", "updatedAt"),
102 + )
103 +
104 +
105 +def normalize_webhook_subscription(raw: object) -> WebhookSubscription:
106 + """Build a typed :class:`WebhookSubscription` from an API response.
107 +
108 + Accepts either the client's pydantic response models or a plain dict and
109 + validates it against :class:`_WebhookSubscriptionWire`, so the returned
110 + dict always matches the declared shape and a malformed response raises
111 + :class:`~composio.exceptions.ValidationError` at the boundary.
112 + """
113 + if isinstance(raw, pydantic.BaseModel):
114 + # The client builds response models without validation, so enum
115 + # fields hold plain strings; silence pydantic's serializer warnings.
116 + data: t.Any = raw.model_dump(mode="json", warnings=False)
117 + elif isinstance(raw, dict):
118 + data = raw
119 + else:
120 + raise exceptions.ValidationError(
121 + "malformed webhook subscription response: expected an object, "
122 + f"got {type(raw).__name__}"
123 + )
124 +
125 + try:
126 + parsed = _WebhookSubscriptionWire.model_validate(data)
127 + except pydantic.ValidationError as error:
128 + raise exceptions.ValidationError(
129 + f"malformed webhook subscription response: {error}"
130 + ) from error
131 +
132 + result: WebhookSubscription = {
133 + "id": parsed.id,
134 + "webhook_url": parsed.webhook_url,
135 + "version": parsed.version,
136 + "enabled_events": list(parsed.enabled_events),
137 + }
138 + if parsed.secret is not None:
139 + result["secret"] = parsed.secret
140 + if parsed.created_at is not None:
141 + result["created_at"] = parsed.created_at
142 + if parsed.updated_at is not None:
143 + result["updated_at"] = parsed.updated_at
144 + return result
145 +
146 +
147 +def first_webhook_subscription_id(response: object) -> t.Optional[str]:
148 + """Return the id of the first subscription in a list response.
149 +
150 + Accepts the client's typed list response (``.items`` of models with an
151 + ``.id``) as well as a plain dict of the same shape. Returns ``None`` only
152 + for an empty list; a payload without an ``items`` list, or whose first
153 + item has no id, raises :class:`~composio.exceptions.ValidationError` so
154 + the upsert never falls through to ``create`` on malformed data.
155 + """
156 + items = (
157 + response.get("items")
158 + if isinstance(response, dict)
159 + else getattr(response, "items", None)
160 + )
161 + if not isinstance(items, list):
162 + raise exceptions.ValidationError(
163 + "malformed webhook subscription list response: missing items"
164 + )
165 + if len(items) == 0:
166 + return None
167 +
168 + first = items[0]
169 + subscription_id = (
170 + first.get("id") if isinstance(first, dict) else getattr(first, "id", None)
171 + )
172 + if not isinstance(subscription_id, str) or not subscription_id:
173 + raise exceptions.ValidationError(
174 + "malformed webhook subscription list response: item without id"
175 + )
176 + return subscription_id
177 +
178 +
179 +class WebhookSubscriptions(Resource):
180 + """Manage the project webhook subscription.
181 +
182 + The API allows one subscription per project; the signing secret is
183 + returned in responses.
184 + """
185 +
186 + def list(
187 + self,
188 + *,
189 + limit: t.Optional[float] = None,
190 + cursor: t.Optional[str] = None,
191 + ) -> webhook_subscription_list_response.WebhookSubscriptionListResponse:
192 + """
193 + List webhook subscriptions for the project.
194 +
195 + :param limit: Maximum number of subscriptions to return.
196 + :param cursor: Pagination cursor from a previous response.
197 + :return: Paginated list of subscriptions.
198 +
199 + Example:
200 + subscriptions = composio.webhooks.subscriptions.list()
201 + """
202 + return self._client.webhook_subscriptions.list(
203 + limit=none_to_omit(limit),
204 + cursor=none_to_omit(cursor),
205 + )
206 +
207 + def get(
208 + self, id: str
209 + ) -> webhook_subscription_retrieve_response.WebhookSubscriptionRetrieveResponse:
210 + """
211 + Retrieve a webhook subscription by id.
212 +
213 + :param id: The subscription id.
214 + :return: The subscription, including its signing secret.
215 +
216 + Example:
217 + subscription = composio.webhooks.subscriptions.get("sub_123")
218 + """
219 + return self._client.webhook_subscriptions.retrieve(id)
220 +
221 + def set(
222 + self,
223 + *,
224 + webhook_url: str,
225 + enabled_events: t.Optional[t.Sequence[str]] = None,
226 + version: t.Union[WebhookVersion, str] = WebhookVersion.V3,
227 + ) -> WebhookSubscription:
228 + """
229 + Create or update the project webhook subscription used for webhook delivery.
230 +
231 + If a subscription already exists, the first subscription is updated. Otherwise a
232 + new subscription is created. By default this subscribes to V3 trigger message
233 + events.
234 +
235 + :param webhook_url: The URL Composio delivers events to.
236 + :param enabled_events: Event types to subscribe to. Defaults to
237 + ``composio.trigger.message``.
238 + :param version: Webhook payload version. Defaults to ``V3``.
239 + :return: The normalized subscription.
240 +
241 + Example:
242 + composio.webhooks.subscriptions.set(
243 + webhook_url=f"{APP_URL}/webhooks/composio",
244 + )
245 + """
246 + if not webhook_url:
247 + raise exceptions.ValidationError("please provide a valid `webhook_url`")
248 +
249 + events = list(
250 + DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS
251 + if enabled_events is None
252 + else enabled_events
253 + )
254 + if len(events) == 0:
255 + raise exceptions.ValidationError(
256 + "please provide at least one enabled event"
257 + )
258 +
259 + version_value = _webhook_version(version)
260 +
261 + existing = self._client.webhook_subscriptions.list(limit=1)
262 + subscription_id = first_webhook_subscription_id(existing)
263 +
264 + if subscription_id:
265 + return normalize_webhook_subscription(
266 + self._client.webhook_subscriptions.update(
267 + subscription_id,
268 + webhook_url=webhook_url,
269 + enabled_events=events,
270 + version=version_value,
271 + )
272 + )
273 +
274 + return normalize_webhook_subscription(
275 + self._client.webhook_subscriptions.create(
276 + webhook_url=webhook_url,
277 + enabled_events=events,
278 + version=version_value,
279 + )
280 + )
281 +
282 + def update(
283 + self,
284 + id: str,
285 + *,
286 + webhook_url: t.Optional[str] = None,
287 + enabled_events: t.Optional[t.Sequence[str]] = None,
288 + version: t.Union[WebhookVersion, str, None] = None,
289 + ) -> webhook_subscription_update_response.WebhookSubscriptionUpdateResponse:
290 + """
291 + Update an existing webhook subscription. Omitted fields are preserved.
292 +
293 + :param id: The subscription id.
294 + :param webhook_url: New delivery URL.
295 + :param enabled_events: New list of subscribed event types.
296 + :param version: New webhook payload version.
297 + :return: The updated subscription.
298 +
299 + Example:
300 + composio.webhooks.subscriptions.update(
301 + "sub_123",
302 + enabled_events=["composio.trigger.message"],
303 + )
304 + """
305 + version_value = None if version is None else _webhook_version(version)
306 + return self._client.webhook_subscriptions.update(
307 + id,
308 + webhook_url=none_to_omit(webhook_url),
309 + enabled_events=none_to_omit(
310 + list(enabled_events) if enabled_events is not None else None
311 + ),
312 + version=none_to_omit(version_value),
313 + )
314 +
315 + def delete(
316 + self, id: str
317 + ) -> webhook_subscription_delete_response.WebhookSubscriptionDeleteResponse:
318 + """
319 + Delete a webhook subscription.
320 +
321 + :param id: The subscription id.
322 + :return: The deletion response.
323 +
324 + Example:
325 + composio.webhooks.subscriptions.delete("sub_123")
326 + """
327 + return self._client.webhook_subscriptions.delete(id)
328 +
329 + def rotate_secret(
330 + self, id: str
331 + ) -> webhook_subscription_rotate_secret_response.WebhookSubscriptionRotateSecretResponse:
332 + """
333 + Rotate the signing secret of a webhook subscription.
334 +
335 + :param id: The subscription id.
336 + :return: The subscription with its new signing secret.
337 +
338 + Example:
339 + rotated = composio.webhooks.subscriptions.rotate_secret("sub_123")
340 + new_secret = rotated.secret
341 + """
342 + return self._client.webhook_subscriptions.rotate_secret(id)
343 +
344 + def list_event_types(
345 + self,
346 + ) -> webhook_subscription_list_event_types_response.WebhookSubscriptionListEventTypesResponse:
347 + """
348 + List the event types a subscription can be enabled for.
349 +
350 + :return: The available event types.
351 +
352 + Example:
353 + event_types = composio.webhooks.subscriptions.list_event_types()
354 + """
355 + return self._client.webhook_subscriptions.list_event_types()
356 +
357 +
358 +class WebhookEndpoints(Resource):
359 + """Manage inbound webhook endpoints (per toolkit + OAuth app ingress URLs)."""
360 +
361 + def list(
362 + self,
363 + *,
364 + toolkit_slug: t.Optional[str] = None,
365 + ) -> webhook_endpoint_list_response.WebhookEndpointListResponse:
366 + """
367 + List webhook endpoints, optionally filtered by toolkit.
368 +
369 + :param toolkit_slug: Only return endpoints for this toolkit.
370 + :return: The list of endpoints.
371 +
372 + Example:
373 + endpoints = composio.webhooks.endpoints.list(toolkit_slug="github")
374 + """
375 + return self._client.webhook_endpoints.list(
376 + toolkit_slug=none_to_omit(toolkit_slug),
377 + )
378 +
379 + def get(
380 + self, nano_id: str
381 + ) -> webhook_endpoint_retrieve_response.WebhookEndpointRetrieveResponse:
382 + """
383 + Retrieve a webhook endpoint by id.
384 +
385 + :param nano_id: The endpoint id.
386 + :return: The endpoint.
387 +
388 + Example:
389 + endpoint = composio.webhooks.endpoints.get("we_123")
390 + """
391 + return self._client.webhook_endpoints.retrieve(nano_id)
392 +
393 + def create(
394 + self,
395 + *,
396 + toolkit_slug: str,
397 + client_id: str,
398 + ) -> webhook_endpoint_create_response.WebhookEndpointCreateResponse:
399 + """
400 + Create a webhook endpoint for a toolkit and OAuth app.
401 +
402 + :param toolkit_slug: The toolkit the endpoint receives events for.
403 + :param client_id: The OAuth app client id the endpoint is bound to.
404 + :return: The created endpoint, including its ingress ``webhook_url``.
405 +
406 + Example:
407 + endpoint = composio.webhooks.endpoints.create(
408 + toolkit_slug="github",
409 + client_id="Iv1.abc123",
410 + )
411 + """
412 + return self._client.webhook_endpoints.create(
413 + toolkit_slug=toolkit_slug,
414 + client_id=client_id,
415 + )
416 +
417 + def replace(
418 + self,
419 + nano_id: str,
420 + *,
421 + data: t.Dict[str, t.Any],
422 + ) -> webhook_endpoint_replace_response.WebhookEndpointReplaceResponse:
423 + """
424 + Replace the stored data of a webhook endpoint (full replacement).
425 +
426 + :param nano_id: The endpoint id.
427 + :param data: The complete new endpoint data.
428 + :return: The updated endpoint.
429 +
430 + Example:
431 + composio.webhooks.endpoints.replace(
432 + "we_123",
433 + data={"secret": "new-signing-secret"},
434 + )
435 + """
436 + return self._client.webhook_endpoints.replace(nano_id, data=data)
437 +
438 + def update(
439 + self,
440 + nano_id: str,
441 + *,
442 + data: t.Dict[str, t.Any],
443 + ) -> webhook_endpoint_update_response.WebhookEndpointUpdateResponse:
444 + """
445 + Merge new data into a webhook endpoint (partial update).
446 +
447 + :param nano_id: The endpoint id.
448 + :param data: The fields to merge into the endpoint data.
449 + :return: The updated endpoint.
450 +
451 + Example:
452 + composio.webhooks.endpoints.update(
453 + "we_123",
454 + data={"secret": "new-signing-secret"},
455 + )
456 + """
457 + return self._client.webhook_endpoints.update(nano_id, data=data)
458 +
459 +
460 +class Webhooks(Resource):
461 + """Webhooks namespace, exposed as ``composio.webhooks``."""
462 +
463 + subscriptions: WebhookSubscriptions
464 + """Project webhook subscription used for event delivery."""
465 +
466 + endpoints: WebhookEndpoints
467 + """Inbound webhook endpoints (per toolkit + OAuth app)."""
468 +
469 + def __init__(self, client: HttpClient):
470 + super().__init__(client)
471 + self.subscriptions = WebhookSubscriptions(client)
472 + self.endpoints = WebhookEndpoints(client)
python/composio/exceptions.py
+23
@@ -5,6 +5,8 @@ Composio exceptions.
5 import difflib
6 import typing as t
7
8 +from composio_client import ComposioDeprecationWarning as ComposioDeprecationWarning
9 +
10 ENV_COMPOSIO_API_KEY = "COMPOSIO_API_KEY"
11
12
@@ -389,6 +391,27 @@ class ComposioLegacyConnectedAccountsEndpointRetiredError(ConnectedAccountError)
391 pass
392
393
394 +class ComposioConnectedAccountRevocationNotSupportedError(ConnectedAccountError):
395 + """Raised by ``composio.connected_accounts.revoke()`` when the toolkit
396 + behind the connected account does not support programmatic token
397 + revocation (API ``400``).
398 +
399 + Fix: delete or disable the connected account instead, and revoke the
400 + grant from the provider's own settings page.
401 + """
402 +
403 + pass
404 +
405 +
406 +class ComposioConnectedAccountNotRevokableError(ConnectedAccountError):
407 + """Raised by ``composio.connected_accounts.revoke()`` when the connected
408 + account is not in a state that can be revoked (API ``409``), for
409 + example because it was already revoked or never became ``ACTIVE``.
410 + """
411 +
412 + pass
413 +
414 +
415 class ComposioAclOnlyForSharedError(ConnectedAccountError):
416 """Raised when ACL fields (``allow_all_users``, ``allowed_user_ids``,
417 ``not_allowed_user_ids``) are sent on a ``PRIVATE`` connection. ACL
python/composio/sdk.py
+58 -6
@@ -1,8 +1,11 @@
1 from __future__ import annotations
2
3 +import logging
4 import os
5 import typing as t
6 +import warnings
7
8 +import httpx
9 import typing_extensions as te
10
11 from composio import exceptions
@@ -10,10 +13,13 @@ from composio.client import DEFAULT_MAX_RETRIES, APIEnvironment, HttpClient
13 from composio.core.models import (
14 AuthConfigs,
15 ConnectedAccounts,
16 + Keyring,
17 + Logs,
18 Toolkits,
19 ToolRouter,
20 Tools,
21 Triggers,
22 + Webhooks,
23 )
24 from composio.core.models.base import allow_tracking
25 from composio.core.models.mcp import MCP
@@ -25,13 +31,20 @@ from composio.core.provider._openai import (
31 )
32 from composio.core.provider.base import BaseProvider
33 from composio.core.types import ToolkitVersionParam
28 -from composio.utils.logging import WithLogger
34 +from composio.utils.logging import LogLevel, WithLogger
35 from composio.utils.toolkit_version import get_toolkit_versions
36
37 +_TOOL_ROUTER_DEPRECATION = (
38 + "`composio.tool_router` is deprecated; use `composio.sessions` instead "
39 + "(or the `composio.create` / `composio.use` shortcuts). It returns the same object."
40 +)
41 +
42
43 class SDKConfig(te.TypedDict):
44 environment: te.NotRequired[APIEnvironment]
45 api_key: te.NotRequired[str]
46 + user_api_key: te.NotRequired[str]
47 + org_api_key: te.NotRequired[str]
48 base_url: te.NotRequired[str]
49 timeout: te.NotRequired[int]
50 max_retries: te.NotRequired[int]
@@ -42,6 +55,9 @@ class SDKConfig(te.TypedDict):
55 sensitive_file_upload_protection: te.NotRequired[bool]
56 file_upload_path_deny_segments: te.NotRequired[t.Sequence[str]]
57 file_upload_dirs: te.NotRequired[t.Union[t.Sequence[str], t.Literal[False]]]
58 + http_client: te.NotRequired[httpx.Client]
59 + logger: te.NotRequired[logging.Logger]
60 + logging_level: te.NotRequired[LogLevel]
61
62
63 class Composio(t.Generic[TTool, TToolCollection], WithLogger):
@@ -96,6 +112,16 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
112 :param provider: The provider to use for the SDK. Defaults to OpenAIProvider.
113 :param environment: The environment to use for the SDK.
114 :param api_key: The API key to use for the SDK.
115 + :param user_api_key: User API key (``uak_*``) for the organization, consumer,
116 + and user-scoped endpoints reached through ``composio.client``. Sent as
117 + ``x-user-api-key`` only on operations whose security scheme requires it,
118 + never alongside the project key. Falls back to ``COMPOSIO_USER_API_KEY``.
119 + A project ``api_key`` is still required.
120 + :param org_api_key: Organization API key (``oak_*``) for the organization-owner
121 + endpoints reached through ``composio.client``. Sent as ``x-org-api-key`` only
122 + on operations whose security scheme requires it, never alongside the
123 + project key. Falls back to ``COMPOSIO_ORG_API_KEY``. A project ``api_key``
124 + is still required.
125 :param base_url: The base URL to use for the SDK.
126 :param timeout: The timeout to use for the SDK.
127 :param max_retries: The maximum number of retries to use for the SDK.
@@ -122,8 +148,24 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
148 - Providing a value REPLACES the default. Include ``~/.composio/temp`` in
149 your list if you want the default staging dir to keep working.
150 - On Windows, entries are compared case-insensitively.
151 + :param http_client: An ``httpx.Client`` the SDK sends every API request
152 + through (custom transports, proxies, or mocked transports in tests).
153 + :param logger: A ``logging.Logger`` that receives the ``Composio``
154 + instance's log records and the records the underlying
155 + ``composio_client`` emits (its per-request lifecycle records at
156 + DEBUG). Sensitive values are redacted and long lines truncated
157 + before a record reaches it. Other SDK components still log to the
158 + shared ``composio`` logger, and deprecation notices are raised as
159 + ``ComposioDeprecationWarning`` warnings rather than log records.
160 + Defaults to the shared ``composio`` logger.
161 + :param logging_level: The :class:`composio.utils.logging.LogLevel` applied
162 + to the SDK logger and to the ``composio_client`` logger. Defaults to
163 + ``LogLevel.INFO`` (``COMPOSIO_LOGGING_LEVEL`` overrides the default
164 + when no ``logger`` is passed).
165 """
126 - WithLogger.__init__(self)
166 + logger = kwargs.get("logger")
167 + logging_level = kwargs.get("logging_level")
168 + WithLogger.__init__(self, logger=logger, logging_level=logging_level)
169 api_key = kwargs.get("api_key", os.environ.get("COMPOSIO_API_KEY"))
170 if not api_key:
171 raise exceptions.ApiKeyNotProvidedError()
@@ -143,9 +185,14 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
185 environment=kwargs.get("environment", "production"),
186 provider=actual_provider.name,
187 api_key=api_key,
188 + user_api_key=kwargs.get("user_api_key"),
189 + org_api_key=kwargs.get("org_api_key"),
190 base_url=kwargs.get("base_url") or os.environ.get("COMPOSIO_BASE_URL"),
191 timeout=kwargs.get("timeout"),
192 max_retries=kwargs.get("max_retries", DEFAULT_MAX_RETRIES),
193 + http_client=kwargs.get("http_client"),
194 + logger=logger,
195 + logging_level=logging_level,
196 )
197 self.provider = actual_provider
198 sensitive_file_upload_protection: bool = kwargs.get(
@@ -175,6 +222,9 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
222 self.auth_configs = AuthConfigs(client=self._client)
223 self.connected_accounts = ConnectedAccounts(client=self._client)
224 self.mcp = MCP(client=self._client)
225 + self.webhooks = Webhooks(client=self._client)
226 + self.logs = Logs(client=self._client)
227 + self.keyring = Keyring(client=self._client)
228
229 # experimental API — decorators for custom tools and toolkits,
230 # plus experimental SDK methods (e.g. update_acl)
@@ -221,10 +271,7 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
271 return self._sessions
272
273 @property
224 - @te.deprecated(
225 - "`composio.tool_router` is deprecated; use `composio.sessions` instead "
226 - "(or the `composio.create` / `composio.use` shortcuts). It returns the same object."
227 - )
274 + @te.deprecated(_TOOL_ROUTER_DEPRECATION, category=None)
275 def tool_router(self) -> ToolRouter[TTool, TToolCollection]:
276 """Deprecated alias for :attr:`sessions`.
277
@@ -232,6 +279,11 @@ class Composio(t.Generic[TTool, TToolCollection], WithLogger):
279 Use :attr:`sessions` instead. ``tool_router`` is the old name for the
280 same object and will be removed in a future release.
281 """
282 + warnings.warn(
283 + _TOOL_ROUTER_DEPRECATION,
284 + exceptions.ComposioDeprecationWarning,
285 + stacklevel=2,
286 + )
287 return self._sessions
288
289 @property
python/composio/utils/logging.py
+7 -2
@@ -201,7 +201,7 @@ class WithLogger:
201 self,
202 logger: t.Optional[logging.Logger] = None,
203 logger_name: str = _DEFAULT_LOGGER_NAME,
204 - logging_level: LogLevel = LogLevel.INFO,
204 + logging_level: t.Optional[LogLevel] = None,
205 verbosity_level: t.Optional[int] = None,
206 ) -> None:
207 """
@@ -209,12 +209,17 @@ class WithLogger:
209
210 :param logger: the logger object.
211 :param logger_name: the default logger name, if a logger is not provided.
212 + :param logging_level: when given, applied to the logger in use (the
213 + provided ``logger`` or the shared default one).
214 """
215 self._logger = (
216 _VerbosityWrapper(logger, verbosity_level=verbosity_level)
217 if logger is not None
216 - else get(name=logger_name, level=logging_level)
218 + else get(name=logger_name, level=logging_level or LogLevel.INFO)
219 )
220 + if logging_level is not None:
221 + self._logger.logger.setLevel(_LEVELS[logging_level])
222 + self._logger.level = self._logger.logger.level
223 self._logger.setup(verbosity_level=verbosity_level)
224 self._logging_level = logging._levelToName[self._logger.level]
225
python/providers/anthropic/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-anthropic"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your Anthropic LLMs."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/anthropic/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_anthropic",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Anthropic LLMs.",
python/providers/autogen/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-autogen"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your autogen agent."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/autogen/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_autogen",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Autogen agent.",
python/providers/claude_agent_sdk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-claude-agent-sdk"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with Claude Code Agents SDK."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/claude_agent_sdk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_claude_agent_sdk",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools for Claude Agent SDK",
python/providers/crewai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-crewai"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your CrewAI agent."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/crewai/setup.py
+1 -1
@@ -6,7 +6,7 @@ from setuptools import setup
6
7 setup(
8 name="composio_crewai",
9 - version="0.22.0",
9 + version="0.23.0",
10 author="Composio",
11 author_email="tech@composio.dev",
12 description="Use Composio to get an array of tools with your CrewAI agent.",
python/providers/gemini/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-gemini"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your Gemini agent."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/gemini/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_gemini",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Gemini agent.",
python/providers/google/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/google/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/google_adk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google-adk"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/google_adk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google_adk",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/langchain/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langchain"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your Langchain agent."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/langchain/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langchain",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Langchain agent.",
python/providers/langgraph/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langgraph"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get array of tools with LangGraph Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/langgraph/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langgraph",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LangGraph Agent Workflows",
python/providers/llamaindex/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-llamaindex"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/llamaindex/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_llamaindex",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LlamaIndex Agent Workflows",
python/providers/openai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get an array of tools with your OpenAI Function Call."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/openai/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_openai",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your OpenAI Function Call.",
python/providers/openai_agents/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai-agents"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio to get array of strongly typed tools for OpenAI Agents"
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/openai_agents/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_openai_agents",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of strongly typed tools for OpenAI Agents",
python/providers/typesafe/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-typesafe"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "Use Composio tools with TypeSafe's Jev model: a tool call, a partial call, or an abstention, each with a confidence score."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/typesafe/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_typesafe",
11 - version="0.22.0",
11 + version="0.23.0",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio tools with TypeSafe's Jev model: a tool call, a partial call, or an abstention, each with a confidence score.",
python/pyproject.toml
+2 -2
@@ -1,13 +1,13 @@
1 [project]
2 name = "composio"
3 -version = "0.22.0"
3 +version = "0.23.0"
4 description = "SDK for integrating Composio with your applications."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
7 dependencies = [
8 "pysher>=1.0.8",
9 "pydantic>=2.11.9",
10 - "composio-client==1.43.0",
10 + "composio-client==2.0.0rc8",
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==1.43.0",
28 + "composio-client==2.0.0rc8",
29 "typing-extensions>=4.16.0",
30 "openai>=2.48.0",
31 "json-schema-to-pydantic>=0.4.11",
python/tests/test_client_errors.py
-9
@@ -109,15 +109,6 @@ def test_error_classes_are_reused_across_requests() -> None:
109 assert raised[0].__name__ == "AuthenticationError"
110
111
112 -def test_tool_not_found_mapping_still_applies() -> None:
113 - tools = Tools(client=_client_returning(404), provider=Mock())
114 -
115 - with pytest.raises(exceptions.ToolNotFoundError) as exc_info:
116 - tools.get_raw_composio_tool_by_slug("NONEXISTENT_TOOL")
117 -
118 - assert isinstance(exc_info.value.__cause__, composio_client.NotFoundError)
119 -
120 -
112 def test_schema_fetch_auth_error_is_a_composio_error() -> None:
113 tools = Tools(client=_client_returning(401), provider=Mock())
114
python/tests/test_connected_accounts.py
+124 -17
@@ -1,10 +1,11 @@
1 import logging
2 import time
3 +import typing as t
4 import warnings
5 from unittest.mock import Mock, patch
6
7 import pytest
7 -from composio_client import omit
8 +from composio_client import BadRequestError, ConflictError, omit
9
10 from composio import exceptions
11 from composio.core.models.connected_accounts import (
@@ -300,7 +301,96 @@ class TestConnectedAccounts:
301 connected_accounts.update_status
302 is mock_client.connected_accounts.update_status
303 )
303 - assert connected_accounts.refresh is mock_client.connected_accounts.refresh
304 +
305 + def test_refresh_is_deprecated_and_delegates(self, connected_accounts, mock_client):
306 + mock_client.connected_accounts.refresh.return_value = {"status": "ok"}
307 +
308 + with pytest.warns(
309 + exceptions.ComposioDeprecationWarning, match="refresh\\(\\) is deprecated"
310 + ):
311 + result = connected_accounts.refresh(
312 + "conn-1", query_redirect_url="https://example.com/callback"
313 + )
314 +
315 + assert result == {"status": "ok"}
316 + mock_client.connected_accounts.refresh.assert_called_once_with(
317 + "conn-1", query_redirect_url="https://example.com/callback"
318 + )
319 +
320 + def test_refresh_forwards_request_options(self, connected_accounts, mock_client):
321 + with pytest.warns(exceptions.ComposioDeprecationWarning):
322 + connected_accounts.refresh("conn-1", timeout=3) # type: ignore[call-arg]
323 +
324 + mock_client.connected_accounts.refresh.assert_called_once_with(
325 + "conn-1", timeout=3
326 + )
327 +
328 + def test_refresh_ignores_removed_validate_credentials(
329 + self, connected_accounts, mock_client
330 + ):
331 + with pytest.warns(exceptions.ComposioDeprecationWarning) as record:
332 + connected_accounts.refresh("conn-1", validate_credentials=True)
333 +
334 + assert any("validate_credentials" in str(w.message) for w in record)
335 + mock_client.connected_accounts.refresh.assert_called_once_with("conn-1")
336 +
337 + def test_revoke_delegates_to_client(self, connected_accounts, mock_client):
338 + mock_client.connected_accounts.revoke.return_value = {"revoked_tokens": []}
339 +
340 + result = connected_accounts.revoke("conn-1")
341 +
342 + assert result == {"revoked_tokens": []}
343 + mock_client.connected_accounts.revoke.assert_called_once_with("conn-1")
344 +
345 + def test_revoke_maps_400_to_not_supported(self, connected_accounts, mock_client):
346 + mock_client.connected_accounts.revoke.side_effect = _make_status_error(
347 + BadRequestError, "toolkit does not support revocation"
348 + )
349 +
350 + with pytest.raises(
351 + exceptions.ComposioConnectedAccountRevocationNotSupportedError
352 + ) as info:
353 + connected_accounts.revoke("conn-1")
354 +
355 + assert "conn-1" in str(info.value)
356 + assert "toolkit does not support revocation" in str(info.value)
357 + assert isinstance(info.value.__cause__, BadRequestError)
358 +
359 + def test_revoke_maps_409_to_not_revokable(self, connected_accounts, mock_client):
360 + mock_client.connected_accounts.revoke.side_effect = _make_status_error(
361 + ConflictError, "connection is not ACTIVE"
362 + )
363 +
364 + with pytest.raises(
365 + exceptions.ComposioConnectedAccountNotRevokableError
366 + ) as info:
367 + connected_accounts.revoke("conn-1")
368 +
369 + assert "not in a revokable state" in str(info.value)
370 + assert isinstance(info.value.__cause__, ConflictError)
371 +
372 + def test_revoke_does_not_swallow_other_errors(
373 + self, connected_accounts, mock_client
374 + ):
375 + mock_client.connected_accounts.revoke.side_effect = RuntimeError("boom")
376 +
377 + with pytest.raises(RuntimeError):
378 + connected_accounts.revoke("conn-1")
379 +
380 + def test_complete_auth_delegates_to_client(self, connected_accounts, mock_client):
381 + mock_client.connected_accounts.complete_auth.return_value = {
382 + "connected_account_id": "ca_1",
383 + "toolkit_slug": "github",
384 + }
385 +
386 + result = connected_accounts.complete_auth(
387 + user_id="user-1", session_uri="session-abc"
388 + )
389 +
390 + assert result == {"connected_account_id": "ca_1", "toolkit_slug": "github"}
391 + mock_client.connected_accounts.complete_auth.assert_called_once_with(
392 + user_id="user-1", session_uri="session-abc"
393 + )
394
395 def test_enable_and_disable_partials(self, connected_accounts, mock_client):
396 connected_accounts.enable("conn-1")
@@ -526,22 +616,27 @@ class TestConnectedAccounts:
616 assert result == "connected"
617
618
529 -def _make_bad_request_error(message: str):
530 - """Build a BadRequestError instance for testing the error mapper.
619 +def _make_status_error(error_type: t.Type[Exception], message: str):
620 + """Build an ``APIStatusError`` subclass instance for testing error mappers.
621
532 - The composio_client BadRequestError constructor signature is internal —
533 - rather than depend on it, we stub a minimal object that ``str(error)``
534 - surfaces the message and which is recognized as the BadRequestError type
535 - by ``isinstance``. This mirrors how production responses arrive: the
536 - error class with a message body.
622 + The composio_client error constructor signatures are internal — rather
623 + than depend on them, we stub a minimal object that ``str(error)``
624 + surfaces the message and which is recognized as the given type by
625 + ``isinstance``. This mirrors how production responses arrive: the error
626 + class with a message body.
627 """
538 - from composio_client import BadRequestError
539 -
540 - error = BadRequestError.__new__(BadRequestError)
628 + error = error_type.__new__(error_type)
629 Exception.__init__(error, message)
630 return error
631
632
633 +def _make_bad_request_error(message: str):
634 + """Build a BadRequestError instance for testing the error mapper."""
635 + from composio_client import BadRequestError
636 +
637 + return _make_status_error(BadRequestError, message)
638 +
639 +
640 class TestConnectedAccountsAcl:
641 """Tests for SHARED accounts surface on ``link()`` and
642 ``composio.experimental.update_acl()``."""
@@ -749,7 +844,7 @@ class TestConnectedAccountsAcl:
844 )
845
846
752 -# SEC-339: initiate() must gate its DeprecationWarning on the response
847 +# SEC-339: initiate() must gate its ComposioDeprecationWarning on the response
848 # `Deprecation` HTTP header (RFC 9745) that apollo emits only on the
849 # retiring branch (Composio-managed + redirectable OAuth). These tests pin
850 # that contract so the previous false-positive behavior — warning purely
@@ -788,7 +883,7 @@ class TestInitiateDeprecationHeaderGate:
883
884 def test_warns_once_when_response_carries_deprecation_header(self, mock_client):
885 """Managed + redirectable-OAuth path: apollo sets `Deprecation`,
791 - SDK emits a `DeprecationWarning` pointing callers at link()."""
886 + SDK emits a `ComposioDeprecationWarning` pointing callers at link()."""
887 self._no_existing_accounts(mock_client)
888 body = self._make_response()
889 _set_initiate_response(
@@ -810,7 +905,11 @@ class TestInitiateDeprecationHeaderGate:
905 req = connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")
906
907 assert isinstance(req, ConnectionRequest)
813 - deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)]
908 + deprecations = [
909 + w
910 + for w in caught
911 + if issubclass(w.category, exceptions.ComposioDeprecationWarning)
912 + ]
913 assert len(deprecations) == 1
914 message = str(deprecations[0].message)
915 assert "composio.connected_accounts.link()" in message
@@ -828,7 +927,11 @@ class TestInitiateDeprecationHeaderGate:
927 warnings.simplefilter("always")
928 connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")
929
831 - deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)]
930 + deprecations = [
931 + w
932 + for w in caught
933 + if issubclass(w.category, exceptions.ComposioDeprecationWarning)
934 + ]
935 assert deprecations == []
936
937 def test_warns_at_most_once_per_process_across_calls(self, mock_client):
@@ -852,5 +955,9 @@ class TestInitiateDeprecationHeaderGate:
955 mock_client.connected_accounts.list.return_value = empty
956 connected_accounts.initiate(user_id="user-1", auth_config_id="auth-1")
957
855 - deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)]
958 + deprecations = [
959 + w
960 + for w in caught
961 + if issubclass(w.category, exceptions.ComposioDeprecationWarning)
962 + ]
963 assert len(deprecations) == 1
python/tests/test_experimental_custom_toolkits.py new
+91
@@ -0,0 +1,91 @@
1 +"""Tests for ``composio.experimental.custom_toolkits``."""
2 +
3 +from unittest.mock import Mock
4 +
5 +import pytest
6 +from composio_client import omit
7 +
8 +from composio import exceptions
9 +from composio.client.types import custom_upsert_params
10 +from composio.core.models.experimental import (
11 + ExperimentalAPI,
12 + ExperimentalCustomToolkits,
13 +)
14 +
15 +TOOLKIT_CONFIG: custom_upsert_params.ToolkitConfig = {
16 + "name": "My Toolkit",
17 + "app_url": "https://mcp.example.com/mcp",
18 + "auth_schemes": [
19 + {
20 + "mode": "API_KEY",
21 + "headers": {"Authorization": "Bearer {{generic_api_key}}"},
22 + }
23 + ],
24 +}
25 +
26 +
27 +@pytest.fixture
28 +def mock_client() -> Mock:
29 + client = Mock()
30 + client.custom = Mock()
31 + return client
32 +
33 +
34 +@pytest.fixture
35 +def custom_toolkits(mock_client: Mock) -> ExperimentalCustomToolkits:
36 + return ExperimentalCustomToolkits(client=mock_client)
37 +
38 +
39 +class TestExperimentalCustomToolkits:
40 + def test_mounted_on_experimental_api(self, mock_client):
41 + experimental = ExperimentalAPI(client=mock_client)
42 +
43 + assert isinstance(experimental.custom_toolkits, ExperimentalCustomToolkits)
44 + assert experimental.custom_toolkits._client is mock_client
45 +
46 + def test_upsert_passes_params_through(self, custom_toolkits, mock_client):
47 + mock_client.custom.upsert.return_value = "upserted"
48 +
49 + result = custom_toolkits.upsert(
50 + slug="MY_TOOLKIT", toolkit_config=TOOLKIT_CONFIG
51 + )
52 +
53 + assert result == "upserted"
54 + mock_client.custom.upsert.assert_called_once_with(
55 + slug="MY_TOOLKIT", toolkit_config=TOOLKIT_CONFIG
56 + )
57 +
58 + def test_sync_with_connected_account(self, custom_toolkits, mock_client):
59 + mock_client.custom.sync.return_value = "synced"
60 +
61 + result = custom_toolkits.sync("CUSTOM_MY_TOOLKIT", connected_account_id="ca_1")
62 +
63 + assert result == "synced"
64 + mock_client.custom.sync.assert_called_once_with(
65 + slug="CUSTOM_MY_TOOLKIT", connected_account_id="ca_1"
66 + )
67 +
68 + def test_sync_without_connected_account(self, custom_toolkits, mock_client):
69 + custom_toolkits.sync("CUSTOM_MY_TOOLKIT")
70 +
71 + mock_client.custom.sync.assert_called_once_with(
72 + slug="CUSTOM_MY_TOOLKIT", connected_account_id=omit
73 + )
74 +
75 + def test_delete(self, custom_toolkits, mock_client):
76 + mock_client.custom.delete_toolkit.return_value = "deleted"
77 +
78 + result = custom_toolkits.delete("CUSTOM_MY_TOOLKIT")
79 +
80 + assert result == "deleted"
81 + mock_client.custom.delete_toolkit.assert_called_once_with("CUSTOM_MY_TOOLKIT")
82 +
83 + def test_requires_client(self):
84 + custom_toolkits = ExperimentalCustomToolkits(client=None)
85 +
86 + with pytest.raises(exceptions.ValidationError):
87 + custom_toolkits.upsert(slug="MY_TOOLKIT", toolkit_config=TOOLKIT_CONFIG)
88 + with pytest.raises(exceptions.ValidationError):
89 + custom_toolkits.sync("CUSTOM_MY_TOOLKIT")
90 + with pytest.raises(exceptions.ValidationError):
91 + custom_toolkits.delete("CUSTOM_MY_TOOLKIT")
python/tests/test_experimental_usage.py new
+80
@@ -0,0 +1,80 @@
1 +"""Tests for ``composio.experimental.usage``."""
2 +
3 +from unittest.mock import Mock
4 +
5 +import pytest
6 +
7 +from composio import exceptions
8 +from composio.core.models.experimental import ExperimentalAPI, ExperimentalUsage
9 +
10 +
11 +@pytest.fixture
12 +def mock_client() -> Mock:
13 + client = Mock()
14 + client.project = Mock()
15 + client.project.usage = Mock()
16 + return client
17 +
18 +
19 +@pytest.fixture
20 +def usage(mock_client: Mock) -> ExperimentalUsage:
21 + return ExperimentalUsage(client=mock_client)
22 +
23 +
24 +class TestExperimentalUsage:
25 + def test_mounted_on_experimental_api(self, mock_client):
26 + experimental = ExperimentalAPI(client=mock_client)
27 +
28 + assert isinstance(experimental.usage, ExperimentalUsage)
29 + assert experimental.usage._client is mock_client
30 +
31 + def test_summary_passes_params_through(self, usage, mock_client):
32 + mock_client.project.usage.retrieve_summary.return_value = "summary"
33 +
34 + result = usage.summary(
35 + from_=1.0,
36 + to=2.0,
37 + entity_types=["tool_execution"],
38 + filters={"toolkit_slug": "github"},
39 + )
40 +
41 + assert result == "summary"
42 + mock_client.project.usage.retrieve_summary.assert_called_once_with(
43 + from_=1.0,
44 + to=2.0,
45 + entity_types=["tool_execution"],
46 + filters={"toolkit_slug": "github"},
47 + )
48 +
49 + def test_summary_without_params(self, usage, mock_client):
50 + usage.summary()
51 +
52 + mock_client.project.usage.retrieve_summary.assert_called_once_with()
53 +
54 + def test_breakdown_passes_entity_type_and_params(self, usage, mock_client):
55 + mock_client.project.usage.retrieve.return_value = "breakdown"
56 +
57 + result = usage.breakdown(
58 + "tool_execution",
59 + group_by="toolkit_slug",
60 + order_by="total_quantity",
61 + order_direction="desc",
62 + limit=5,
63 + )
64 +
65 + assert result == "breakdown"
66 + mock_client.project.usage.retrieve.assert_called_once_with(
67 + "tool_execution",
68 + group_by="toolkit_slug",
69 + order_by="total_quantity",
70 + order_direction="desc",
71 + limit=5,
72 + )
73 +
74 + def test_requires_client(self):
75 + usage = ExperimentalUsage(client=None)
76 +
77 + with pytest.raises(exceptions.ValidationError):
78 + usage.summary()
79 + with pytest.raises(exceptions.ValidationError):
80 + usage.breakdown("tool_execution")
python/tests/test_generated_client_response_shape.py new
+161
@@ -0,0 +1,161 @@
1 +"""Guard the generated-client response shape the SDK reads by attribute.
2 +
3 +Several SDK code paths walk a generated-client response two or more levels deep
4 +-- ``item.meta.logo``, ``item.connected_account.auth_config.id``,
5 +``response.commands.claude``. That only works while the client constructs those
6 +nested objects as models.
7 +
8 +The rest of the suite mocks the client with ``MagicMock``, which answers every
9 +attribute regardless of the real response shape, so a client release that stops
10 +building nested models passes here and fails against the live backend instead.
11 +These tests close that gap: they build responses through the *installed*
12 +client's own response models, so a client whose nested fields decay to plain
13 +mappings fails locally.
14 +"""
15 +
16 +import typing as t
17 +from unittest.mock import MagicMock
18 +
19 +import pytest
20 +from composio_client.types.mcp.custom_create_response import CustomCreateResponse
21 +from composio_client.types.tool_router.session_toolkits_response import (
22 + SessionToolkitsResponse,
23 +)
24 +from pydantic import BaseModel
25 +
26 +from composio.core.models.mcp import MCP
27 +from composio.core.models.tool_router import ToolkitConnectionsDetails, ToolRouter
28 +
29 +TOOLKITS_PAYLOAD: t.Dict[str, t.Any] = {
30 + "current_page": 1,
31 + "total_items": 2,
32 + "total_pages": 1,
33 + "next_cursor": "cursor_789",
34 + "items": [
35 + {
36 + "slug": "gmail",
37 + "name": "Gmail",
38 + "enabled": True,
39 + "is_no_auth": False,
40 + "composio_managed_auth_schemes": ["OAUTH2"],
41 + "meta": {"description": "Gmail toolkit", "logo": "https://logo/gmail.png"},
42 + "connected_account": {
43 + "id": "conn_123",
44 + "status": "ACTIVE",
45 + "created_at": "2026-01-01T00:00:00Z",
46 + "user_id": "user_123",
47 + "auth_config": {
48 + "id": "auth_config_123",
49 + "auth_scheme": "OAUTH2",
50 + "is_composio_managed": True,
51 + },
52 + },
53 + },
54 + {
55 + "slug": "github",
56 + "name": "GitHub",
57 + "enabled": True,
58 + "is_no_auth": False,
59 + "composio_managed_auth_schemes": [],
60 + "meta": {"description": "GitHub toolkit", "logo": "https://logo/gh.png"},
61 + },
62 + ],
63 +}
64 +
65 +MCP_CREATE_PAYLOAD: t.Dict[str, t.Any] = {
66 + "id": "mcp_123",
67 + "name": "test-server",
68 + "allowed_tools": ["GITHUB_CREATE_ISSUE"],
69 + "auth_config_ids": ["ac_123"],
70 + "mcp_url": "https://mcp.composio.dev/mcp_123",
71 + "commands": {
72 + "claude": "claude mcp add ...",
73 + "cursor": "cursor://...",
74 + "windsurf": "windsurf://...",
75 + },
76 +}
77 +
78 +
79 +@pytest.mark.parametrize(
80 + ("model", "payload", "path"),
81 + [
82 + (SessionToolkitsResponse, TOOLKITS_PAYLOAD, "items.0.meta"),
83 + (SessionToolkitsResponse, TOOLKITS_PAYLOAD, "items.0.connected_account"),
84 + (
85 + SessionToolkitsResponse,
86 + TOOLKITS_PAYLOAD,
87 + "items.0.connected_account.auth_config",
88 + ),
89 + (CustomCreateResponse, MCP_CREATE_PAYLOAD, "commands"),
90 + ],
91 +)
92 +def test_generated_client_builds_nested_response_models(
93 + model: t.Type[BaseModel], payload: t.Dict[str, t.Any], path: str
94 +) -> None:
95 + """A nested response field must arrive as a model, not a bare mapping."""
96 + root: t.Any = model.model_validate(payload)
97 + for part in path.split("."):
98 + root = root[int(part)] if part.isdigit() else getattr(root, part)
99 +
100 + assert isinstance(root, BaseModel), (
101 + f"{model.__name__}.{path} is a {type(root).__name__}, not a model. The SDK "
102 + f"reads this field by attribute, so a generated client that leaves nested "
103 + f"objects as mappings breaks it at runtime."
104 + )
105 +
106 +
107 +def _client_with_session() -> MagicMock:
108 + """A mocked client whose session.create is just real enough to build a session."""
109 + client = MagicMock()
110 + session_response = MagicMock()
111 + session_response.session_id = "session_123"
112 + session_response.mcp.type = "http"
113 + session_response.mcp.url = "https://mcp.example.com/session_123"
114 + session_response.config.preload.tools = []
115 + session_response.experimental = None
116 + client.tool_router.session.create.return_value = session_response
117 + return client
118 +
119 +
120 +def test_session_toolkits_reads_nested_connection_models() -> None:
121 + """``Session.toolkits()`` walks meta and connected_account by attribute."""
122 + client = _client_with_session()
123 + client.tool_router.session.toolkits.return_value = (
124 + SessionToolkitsResponse.model_validate(TOOLKITS_PAYLOAD)
125 + )
126 + session = ToolRouter(client=client, provider=MagicMock()).create(user_id="user_123")
127 +
128 + result = session.toolkits()
129 +
130 + assert isinstance(result, ToolkitConnectionsDetails)
131 + gmail, github = result.items
132 +
133 + assert gmail.slug == "gmail"
134 + assert gmail.logo == "https://logo/gmail.png"
135 + assert gmail.connection is not None
136 + assert gmail.connection.is_active is True
137 + assert gmail.connection.auth_config is not None
138 + assert gmail.connection.auth_config.id == "auth_config_123"
139 + assert gmail.connection.auth_config.mode == "OAUTH2"
140 + assert gmail.connection.auth_config.is_composio_managed is True
141 + assert gmail.connection.connected_account is not None
142 + assert gmail.connection.connected_account.id == "conn_123"
143 +
144 + assert github.slug == "github"
145 + assert github.connection is not None
146 + assert github.connection.is_active is False
147 + assert github.connection.auth_config is None
148 +
149 +
150 +def test_mcp_create_returns_attribute_addressable_commands() -> None:
151 + """``mcp.create()`` hands callers a ``commands`` object, not a mapping."""
152 + client = MagicMock()
153 + client.mcp.custom.create.return_value = CustomCreateResponse.model_validate(
154 + MCP_CREATE_PAYLOAD
155 + )
156 +
157 + response = MCP(client=client).create(name="test-server", toolkits=["github"])
158 +
159 + assert response.commands.claude == "claude mcp add ..."
160 + assert response.commands.cursor == "cursor://..."
161 + assert response.commands.windsurf == "windsurf://..."
python/tests/test_keyring.py new
+24
@@ -0,0 +1,24 @@
1 +"""Tests for ``composio.keyring``."""
2 +
3 +from unittest.mock import Mock
4 +
5 +import pytest
6 +
7 +from composio.core.models.keyring import Keyring
8 +from tests.conftest import mock_http_client
9 +
10 +
11 +@pytest.fixture
12 +def mock_client() -> Mock:
13 + client = mock_http_client()
14 + client.keyring = Mock()
15 + return client
16 +
17 +
18 +def test_list_transfer_keys_delegates_to_client(mock_client):
19 + mock_client.keyring.list_transfer_keys.return_value = "transfer-keys"
20 +
21 + result = Keyring(client=mock_client).list_transfer_keys()
22 +
23 + assert result == "transfer-keys"
24 + mock_client.keyring.list_transfer_keys.assert_called_once_with()
python/tests/test_logs.py new
+51
@@ -0,0 +1,51 @@
1 +"""Tests for the ``composio.logs`` namespace."""
2 +
3 +from unittest.mock import Mock
4 +
5 +import pytest
6 +
7 +from composio.core.models.logs import Logs
8 +from tests.conftest import mock_http_client
9 +
10 +
11 +@pytest.fixture
12 +def mock_client() -> Mock:
13 + client = mock_http_client()
14 + client.logs = Mock()
15 + return client
16 +
17 +
18 +@pytest.fixture
19 +def logs(mock_client: Mock) -> Logs:
20 + return Logs(client=mock_client)
21 +
22 +
23 +class TestLogs:
24 + def test_search_passes_params_through(self, logs, mock_client):
25 + mock_client.logs.create_tool_execution.return_value = "page"
26 +
27 + result = logs.search(
28 + limit=20,
29 + cursor="c1",
30 + filters=[{"field": "toolkit_slug", "value": "github"}],
31 + time_range={"from": 1, "to": 2},
32 + )
33 +
34 + assert result == "page"
35 + mock_client.logs.create_tool_execution.assert_called_once_with(
36 + limit=20,
37 + cursor="c1",
38 + filters=[{"field": "toolkit_slug", "value": "github"}],
39 + time_range={"from": 1, "to": 2},
40 + )
41 +
42 + def test_search_without_params(self, logs, mock_client):
43 + logs.search()
44 +
45 + mock_client.logs.create_tool_execution.assert_called_once_with()
46 +
47 + def test_get(self, logs, mock_client):
48 + mock_client.logs.retrieve_tool_execution.return_value = "log"
49 +
50 + assert logs.get("log_123") == "log"
51 + mock_client.logs.retrieve_tool_execution.assert_called_once_with("log_123")
python/tests/test_sdk.py
+50
@@ -40,6 +40,29 @@ class TestComposioSDK:
40 sdk = Composio(api_key="test-key")
41 assert sdk is not None
42
43 + def test_sdk_forwards_user_and_org_api_keys_to_client(self):
44 + """User and org keys reach the API client, which selects them per operation."""
45 + sdk = Composio(
46 + api_key="ak_test", user_api_key="uak_test", org_api_key="oak_test"
47 + )
48 + assert sdk.client.api_key == "ak_test"
49 + assert sdk.client.user_api_key == "uak_test"
50 + assert sdk.client.org_api_key == "oak_test"
51 +
52 + def test_sdk_reads_user_and_org_api_keys_from_env(self):
53 + """The client resolves COMPOSIO_USER_API_KEY / COMPOSIO_ORG_API_KEY itself."""
54 + with patch.dict(
55 + os.environ,
56 + {
57 + "COMPOSIO_API_KEY": "ak_env",
58 + "COMPOSIO_USER_API_KEY": "uak_env",
59 + "COMPOSIO_ORG_API_KEY": "oak_env",
60 + },
61 + ):
62 + sdk = Composio()
63 + assert sdk.client.user_api_key == "uak_env"
64 + assert sdk.client.org_api_key == "oak_env"
65 +
66 def test_sdk_config_types(self):
67 """Test SDK configuration types."""
68 from composio.sdk import SDKConfig
@@ -51,6 +74,8 @@ class TestComposioSDK:
74 expected_fields = {
75 "environment",
76 "api_key",
77 + "user_api_key",
78 + "org_api_key",
79 "base_url",
80 "timeout",
81 "max_retries",
@@ -61,6 +86,9 @@ class TestComposioSDK:
86 "sensitive_file_upload_protection",
87 "file_upload_path_deny_segments",
88 "file_upload_dirs",
89 + "http_client",
90 + "logger",
91 + "logging_level",
92 }
93 assert set(SDKConfig.__annotations__.keys()) == expected_fields
94
@@ -78,6 +106,28 @@ class TestComposioSDK:
106 assert ToolkitVersions is not None
107 assert ToolkitVersionParam is not None
108
109 + def test_sdk_mounts_webhooks_and_logs(self):
110 + from composio.core.models import Logs, Webhooks
111 +
112 + composio = Composio(api_key="test-key")
113 +
114 + assert isinstance(composio.webhooks, Webhooks)
115 + assert isinstance(composio.logs, Logs)
116 + assert composio.webhooks._client is composio._client
117 + assert composio.logs._client is composio._client
118 +
119 + def test_sdk_mounts_keyring_and_custom_toolkits(self):
120 + from composio.core.models import ExperimentalCustomToolkits, Keyring
121 +
122 + composio = Composio(api_key="test-key")
123 +
124 + assert isinstance(composio.keyring, Keyring)
125 + assert composio.keyring._client is composio._client
126 + assert isinstance(
127 + composio.experimental.custom_toolkits, ExperimentalCustomToolkits
128 + )
129 + assert composio.experimental.custom_toolkits._client is composio._client
130 +
131 def test_sdk_has_required_attributes(self):
132 """Test that SDK has required attributes after initialization."""
133 with patch.dict(os.environ, {"COMPOSIO_API_KEY": "test-key"}):
python/tests/test_sdk_logging.py new
+339
@@ -0,0 +1,339 @@
1 +"""SDK-owned logging and deprecation surface.
2 +
3 +``Composio(...)`` accepts ``logger`` / ``logging_level`` and routes the
4 +generated ``composio_client`` logger through the SDK's redacting wrapper.
5 +Runtime deprecations (the client's response-driven ones and the SDK's own)
6 +all surface as :class:`ComposioDeprecationWarning`.
7 +"""
8 +
9 +import io
10 +import logging
11 +import typing as t
12 +import warnings
13 +
14 +import httpx
15 +import pytest
16 +
17 +from composio import Composio, ComposioDeprecationWarning, exceptions
18 +from composio.client import (
19 + CLIENT_LOGGER_NAME,
20 + _ClientLogForwarder,
21 + _forwarding_wrappers,
22 +)
23 +from composio.core.models.base import allow_tracking
24 +from composio.utils.logging import LogLevel
25 +
26 +_LIST_BODY: dict[str, t.Any] = {
27 + "items": [],
28 + "next_cursor": None,
29 + "total_pages": 1,
30 + "current_page": 1,
31 + "total_items": 0,
32 +}
33 +
34 +
35 +@pytest.fixture(autouse=True)
36 +def disable_telemetry():
37 + token = allow_tracking.set(False)
38 + yield
39 + allow_tracking.reset(token)
40 +
41 +
42 +@pytest.fixture(autouse=True)
43 +def reset_client_logger():
44 + """Start each test without the forwarder state earlier tests left behind.
45 +
46 + The forwarder and the set of live wrappers are process-wide, so a DEBUG
47 + instance from an earlier test would otherwise keep the client logger
48 + permissive and mask level assertions here.
49 + """
50 + client_logger = logging.getLogger(CLIENT_LOGGER_NAME)
51 + for handler in list(client_logger.handlers):
52 + if isinstance(handler, _ClientLogForwarder):
53 + client_logger.removeHandler(handler)
54 + _forwarding_wrappers.clear()
55 + client_logger.setLevel(logging.NOTSET)
56 + yield
57 +
58 +
59 +@pytest.fixture
60 +def custom_logger() -> t.Iterator[tuple[logging.Logger, io.StringIO]]:
61 + output = io.StringIO()
62 + logger = logging.getLogger("composio-test-sdk-owned-logger")
63 + logger.handlers = [logging.StreamHandler(output)]
64 + logger.propagate = False
65 + logger.setLevel(logging.DEBUG)
66 + yield logger, output
67 + logger.handlers = []
68 +
69 +
70 +def _mock_transport(
71 + headers: t.Optional[dict[str, str]] = None,
72 + seen: t.Optional[list[httpx.Request]] = None,
73 +) -> httpx.Client:
74 + def handler(request: httpx.Request) -> httpx.Response:
75 + if seen is not None:
76 + seen.append(request)
77 + return httpx.Response(200, json=_LIST_BODY, headers=headers or {})
78 +
79 + return httpx.Client(transport=httpx.MockTransport(handler))
80 +
81 +
82 +def _forwarders() -> list[_ClientLogForwarder]:
83 + return [
84 + handler
85 + for handler in logging.getLogger(CLIENT_LOGGER_NAME).handlers
86 + if isinstance(handler, _ClientLogForwarder)
87 + ]
88 +
89 +
90 +class TestCustomLogger:
91 + def test_sdk_logs_use_custom_logger_with_redaction(self, custom_logger):
92 + logger, output = custom_logger
93 + composio = Composio(api_key="test-key", logger=logger)
94 +
95 + assert composio.logger.logger is logger
96 + composio.logger.info("sdk record api_key=sdk-secret")
97 +
98 + text = output.getvalue()
99 + assert "sdk record" in text
100 + assert "sdk-secret" not in text
101 + assert "[REDACTED]" in text
102 +
103 + def test_client_records_are_forwarded_with_redaction(self, custom_logger):
104 + logger, output = custom_logger
105 + Composio(api_key="test-key", logger=logger)
106 +
107 + logging.getLogger(CLIENT_LOGGER_NAME).info(
108 + "Authorization: Bearer client-secret-token"
109 + )
110 +
111 + text = output.getvalue()
112 + assert "Authorization" in text
113 + assert "client-secret-token" not in text
114 + assert "[REDACTED]" in text
115 +
116 + def test_client_request_lifecycle_reaches_custom_logger(self, custom_logger):
117 + logger, output = custom_logger
118 + composio = Composio(
119 + api_key="test-key", http_client=_mock_transport(), logger=logger
120 + )
121 +
122 + composio.client.toolkits.list()
123 +
124 + text = output.getvalue()
125 + assert "path=/api/v3.1/toolkits" in text
126 + assert "status=200" in text
127 +
128 + def test_client_request_lifecycle_stays_out_of_info(self, custom_logger):
129 + logger, output = custom_logger
130 + logger.setLevel(logging.INFO)
131 + composio = Composio(
132 + api_key="test-key", http_client=_mock_transport(), logger=logger
133 + )
134 +
135 + composio.client.toolkits.list()
136 +
137 + assert logging.getLogger(CLIENT_LOGGER_NAME).level == logging.WARNING
138 + assert "path=/api/v3.1/toolkits" not in output.getvalue()
139 +
140 + def test_without_retries_clone_keeps_custom_logger(self, custom_logger):
141 + logger, output = custom_logger
142 + composio = Composio(
143 + api_key="test-key", http_client=_mock_transport(), logger=logger
144 + )
145 +
146 + composio.client.without_retries.toolkits.list()
147 +
148 + forwarders = _forwarders()
149 + assert len(forwarders) == 1
150 + assert forwarders[0].wrapper.logger is logger
151 + assert "path=/api/v3.1/toolkits" in output.getvalue()
152 +
153 + def test_client_logger_does_not_propagate_to_root(self, custom_logger):
154 + logger, _ = custom_logger
155 + Composio(api_key="test-key", logger=logger)
156 +
157 + client_logger = logging.getLogger(CLIENT_LOGGER_NAME)
158 + assert client_logger.propagate is False
159 +
160 + def test_forwarder_is_installed_once_per_logger(self, custom_logger):
161 + logger, _ = custom_logger
162 + Composio(api_key="test-key", logger=logger)
163 + Composio(api_key="test-key", logger=logger)
164 +
165 + forwarders = _forwarders()
166 + assert len(forwarders) == 1
167 + assert forwarders[0].wrapper.logger is logger
168 +
169 + def test_client_records_follow_the_requesting_instance(self, custom_logger):
170 + logger, output = custom_logger
171 + other = logging.getLogger("composio-test-sdk-owned-logger-other")
172 + other_output = io.StringIO()
173 + other.handlers = [logging.StreamHandler(other_output)]
174 + other.propagate = False
175 + other.setLevel(logging.DEBUG)
176 + try:
177 + first = Composio(
178 + api_key="test-key", http_client=_mock_transport(), logger=other
179 + )
180 + second = Composio(
181 + api_key="test-key", http_client=_mock_transport(), logger=logger
182 + )
183 + assert len(_forwarders()) == 1
184 +
185 + # A request through the earlier instance still logs to its own
186 + # logger, even though a newer instance was constructed since.
187 + first.client.without_retries.toolkits.list()
188 + assert "path=/api/v3.1/toolkits" in other_output.getvalue()
189 + assert "path=/api/v3.1/toolkits" not in output.getvalue()
190 +
191 + second.client.without_retries.toolkits.list()
192 + assert "path=/api/v3.1/toolkits" in output.getvalue()
193 +
194 + # Outside any request, records go to the most recent instance.
195 + logging.getLogger(CLIENT_LOGGER_NAME).info("delivered once")
196 + assert "delivered once" in output.getvalue()
197 + assert "delivered once" not in other_output.getvalue()
198 + finally:
199 + other.handlers = []
200 +
201 + def test_quieter_instance_does_not_silence_earlier_debug_instance(
202 + self, custom_logger
203 + ):
204 + logger, output = custom_logger
205 + quiet = logging.getLogger("composio-test-sdk-owned-logger-quiet")
206 + quiet_output = io.StringIO()
207 + quiet.handlers = [logging.StreamHandler(quiet_output)]
208 + quiet.propagate = False
209 + quiet.setLevel(logging.WARNING)
210 + try:
211 + debug_instance = Composio(
212 + api_key="test-key", http_client=_mock_transport(), logger=logger
213 + )
214 + quiet_instance = Composio(
215 + api_key="test-key", http_client=_mock_transport(), logger=quiet
216 + )
217 + # The shared source logger stays permissive enough for the DEBUG
218 + # instance; the quiet instance's wrapper filters its own output.
219 + assert logging.getLogger(CLIENT_LOGGER_NAME).level == logging.DEBUG
220 +
221 + debug_instance.client.without_retries.toolkits.list()
222 + assert "path=/api/v3.1/toolkits" in output.getvalue()
223 +
224 + quiet_instance.client.without_retries.toolkits.list()
225 + assert "path=/api/v3.1/toolkits" not in quiet_output.getvalue()
226 + finally:
227 + quiet.handlers = []
228 +
229 + def test_debug_instance_lowers_level_set_by_earlier_quiet_instance(
230 + self, custom_logger
231 + ):
232 + logger, output = custom_logger
233 + quiet = logging.getLogger("composio-test-sdk-owned-logger-quiet")
234 + quiet.handlers = [logging.StreamHandler(io.StringIO())]
235 + quiet.propagate = False
236 + quiet.setLevel(logging.WARNING)
237 + try:
238 + Composio(api_key="test-key", http_client=_mock_transport(), logger=quiet)
239 + assert logging.getLogger(CLIENT_LOGGER_NAME).level == logging.WARNING
240 +
241 + debug_instance = Composio(
242 + api_key="test-key", http_client=_mock_transport(), logger=logger
243 + )
244 + assert logging.getLogger(CLIENT_LOGGER_NAME).level == logging.DEBUG
245 +
246 + debug_instance.client.without_retries.toolkits.list()
247 + assert "path=/api/v3.1/toolkits" in output.getvalue()
248 + finally:
249 + quiet.handlers = []
250 +
251 +
252 +class TestLoggingLevel:
253 + def test_logging_level_applies_to_sdk_and_client_loggers(self, custom_logger):
254 + logger, output = custom_logger
255 + composio = Composio(
256 + api_key="test-key", logger=logger, logging_level=LogLevel.WARNING
257 + )
258 +
259 + assert logger.level == logging.WARNING
260 + assert logging.getLogger(CLIENT_LOGGER_NAME).level == logging.WARNING
261 + assert composio._logging_level == "WARNING"
262 +
263 + composio.logger.info("sdk info dropped")
264 + logging.getLogger(CLIENT_LOGGER_NAME).info("client info dropped")
265 + composio.logger.warning("sdk warning kept")
266 + logging.getLogger(CLIENT_LOGGER_NAME).warning("client warning kept")
267 +
268 + text = output.getvalue()
269 + assert "dropped" not in text
270 + assert "sdk warning kept" in text
271 + assert "client warning kept" in text
272 +
273 + def test_logging_level_debug_enables_debug_records(self, custom_logger):
274 + logger, output = custom_logger
275 + logger.setLevel(logging.WARNING)
276 + composio = Composio(
277 + api_key="test-key", logger=logger, logging_level=LogLevel.DEBUG
278 + )
279 +
280 + composio.logger.debug("sdk debug kept")
281 + logging.getLogger(CLIENT_LOGGER_NAME).debug("client debug kept")
282 +
283 + text = output.getvalue()
284 + assert "sdk debug kept" in text
285 + assert "client debug kept" in text
286 +
287 +
288 +class TestDeprecationWarnings:
289 + def test_category_is_re_exported(self):
290 + assert exceptions.ComposioDeprecationWarning is ComposioDeprecationWarning
291 + assert issubclass(ComposioDeprecationWarning, UserWarning)
292 + assert not issubclass(ComposioDeprecationWarning, DeprecationWarning)
293 +
294 + def test_client_deprecation_header_reaches_caller(self, custom_logger):
295 + logger, _ = custom_logger
296 + composio = Composio(
297 + api_key="test-key",
298 + http_client=_mock_transport(headers={"Deprecation": "@1688169599"}),
299 + logger=logger,
300 + )
301 +
302 + with pytest.warns(ComposioDeprecationWarning, match="toolkits.list"):
303 + composio.client.toolkits.list()
304 +
305 + def test_no_warning_without_deprecation_header(self, custom_logger):
306 + logger, _ = custom_logger
307 + composio = Composio(
308 + api_key="test-key", http_client=_mock_transport(), logger=logger
309 + )
310 +
311 + with warnings.catch_warnings():
312 + warnings.simplefilter("error", ComposioDeprecationWarning)
313 + composio.client.toolkits.list()
314 +
315 + def test_tool_router_alias_warns_with_sdk_category(self):
316 + composio = Composio(api_key="test-key")
317 +
318 + with pytest.warns(ComposioDeprecationWarning, match="tool_router"):
319 + alias = composio.tool_router
320 +
321 + assert alias is composio.sessions
322 +
323 +
324 +class TestToolsListWireParams:
325 + def test_search_is_sent_as_query(self, custom_logger):
326 + logger, _ = custom_logger
327 + seen: list[httpx.Request] = []
328 + composio = Composio(
329 + api_key="test-key", http_client=_mock_transport(seen=seen), logger=logger
330 + )
331 +
332 + with warnings.catch_warnings():
333 + warnings.simplefilter("error", ComposioDeprecationWarning)
334 + composio.tools.get_raw_composio_tools(search="github issues")
335 +
336 + assert len(seen) == 1
337 + params = seen[0].url.params
338 + assert params["query"] == "github issues"
339 + assert "search" not in params
python/tests/test_tool_router.py
+16
@@ -124,6 +124,22 @@ class TestToolRouter:
124 assert tool_router._client == mock_client
125 assert tool_router._provider == mock_provider
126
127 + def test_session_list_config_history(self, tool_router, mock_client):
128 + """``session.list_config_history`` passes the session id and pagination."""
129 + session = tool_router.create(user_id="user_123")
130 + mock_client.tool_router.session.config_history.return_value = "history"
131 +
132 + assert session.list_config_history() == "history"
133 + mock_client.tool_router.session.config_history.assert_called_once_with(
134 + session_id="session_123"
135 + )
136 +
137 + mock_client.tool_router.session.config_history.reset_mock()
138 + session.list_config_history(limit=10, cursor="c1")
139 + mock_client.tool_router.session.config_history.assert_called_once_with(
140 + session_id="session_123", limit=10, cursor="c1"
141 + )
142 +
143 def test_create_basic_session(self, tool_router, mock_client):
144 """Test creating a basic session with minimal configuration."""
145 session = tool_router.create(user_id="user_123")
python/tests/test_toolkits.py new
+107
@@ -0,0 +1,107 @@
1 +"""Tests for ``composio.toolkits.get_many`` and ``composio.toolkits.changelog``."""
2 +
3 +from unittest.mock import Mock
4 +
5 +import pytest
6 +from composio_client import omit
7 +
8 +from composio.core.models.toolkits import Toolkits
9 +from tests.conftest import mock_http_client
10 +
11 +
12 +@pytest.fixture
13 +def mock_client() -> Mock:
14 + client = mock_http_client()
15 + client.toolkits = Mock()
16 + client.connected_accounts = Mock()
17 + return client
18 +
19 +
20 +@pytest.fixture
21 +def toolkits(mock_client: Mock) -> Toolkits:
22 + return Toolkits(client=mock_client)
23 +
24 +
25 +class TestToolkitsGetMany:
26 + def test_get_many_by_slugs(self, toolkits, mock_client):
27 + mock_client.toolkits.retrieve_multi.return_value = Mock(items=["gh", "sl"])
28 +
29 + result = toolkits.get_many(("github", "slack"))
30 +
31 + assert result == ["gh", "sl"]
32 + mock_client.toolkits.retrieve_multi.assert_called_once_with(
33 + toolkits=["github", "slack"],
34 + category=omit,
35 + managed_by=omit,
36 + sort_by=omit,
37 + limit=omit,
38 + cursor=omit,
39 + )
40 +
41 + def test_get_many_forwards_filters(self, toolkits, mock_client):
42 + toolkits.get_many(
43 + ["github"],
44 + category="developer-tools",
45 + managed_by="composio",
46 + sort_by="usage",
47 + limit=10,
48 + cursor="c1",
49 + )
50 +
51 + mock_client.toolkits.retrieve_multi.assert_called_once_with(
52 + toolkits=["github"],
53 + category="developer-tools",
54 + managed_by="composio",
55 + sort_by="usage",
56 + limit=10,
57 + cursor="c1",
58 + )
59 +
60 +
61 +class TestToolkitsChangelog:
62 + def test_changelog(self, toolkits, mock_client):
63 + mock_client.toolkits.retrieve_changelog.return_value = "changelog"
64 +
65 + assert toolkits.changelog() == "changelog"
66 + mock_client.toolkits.retrieve_changelog.assert_called_once_with()
67 +
68 +
69 +class TestToolkitsScopes:
70 + def test_recommend_scopes_passes_params_through(self, toolkits, mock_client):
71 + mock_client.toolkits.recommend_scopes.return_value = "recommendation"
72 +
73 + result = toolkits.recommend_scopes(
74 + "gmail",
75 + tools=["GMAIL_SEND_EMAIL"],
76 + auth_scheme="OAUTH2",
77 + grant_context={"account_type": "Google Workspace"},
78 + available_scopes=["openid"],
79 + )
80 +
81 + assert result == "recommendation"
82 + mock_client.toolkits.recommend_scopes.assert_called_once_with(
83 + "gmail",
84 + tools=["GMAIL_SEND_EMAIL"],
85 + auth_scheme="OAUTH2",
86 + grant_context={"account_type": "Google Workspace"},
87 + available_scopes=["openid"],
88 + )
89 +
90 + def test_list_grant_contexts_passes_params_through(self, toolkits, mock_client):
91 + mock_client.toolkits.retrieve_scopes_grant_context.return_value = "contexts"
92 +
93 + result = toolkits.list_grant_contexts(
94 + "gmail", auth_scheme="OAUTH2", toolkit_version="20250909_00"
95 + )
96 +
97 + assert result == "contexts"
98 + mock_client.toolkits.retrieve_scopes_grant_context.assert_called_once_with(
99 + "gmail", auth_scheme="OAUTH2", toolkit_version="20250909_00"
100 + )
101 +
102 + def test_list_grant_contexts_without_params(self, toolkits, mock_client):
103 + toolkits.list_grant_contexts("gmail")
104 +
105 + mock_client.toolkits.retrieve_scopes_grant_context.assert_called_once_with(
106 + "gmail"
107 + )
python/tests/test_triggers.py
+22 -30
@@ -116,26 +116,18 @@ class TestTriggers:
116 "version": "V3",
117 "enabled_events": ["composio.trigger.message"],
118 }
119 - mock_client.get.return_value = {"items": []}
120 - mock_client.post.return_value = raw_subscription
119 + mock_client.webhook_subscriptions.list.return_value = Mock(items=[])
120 + mock_client.webhook_subscriptions.create.return_value = raw_subscription
121
122 result = triggers.set_webhook_subscription(webhook_url=webhook_url)
123
124 - mock_client.get.assert_called_once_with(
125 - "/api/v3.1/webhook_subscriptions",
126 - cast_to=object,
127 - options={"params": {"limit": 1}},
128 - )
129 - mock_client.post.assert_called_once_with(
130 - "/api/v3.1/webhook_subscriptions",
131 - cast_to=object,
132 - body={
133 - "webhook_url": webhook_url,
134 - "enabled_events": ["composio.trigger.message"],
135 - "version": "V3",
136 - },
124 + mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1)
125 + mock_client.webhook_subscriptions.create.assert_called_once_with(
126 + webhook_url=webhook_url,
127 + enabled_events=["composio.trigger.message"],
128 + version="V3",
129 )
138 - mock_client.patch.assert_not_called()
130 + mock_client.webhook_subscriptions.update.assert_not_called()
131 assert result == raw_subscription
132
133 def test_set_webhook_subscription_updates_first_existing(
@@ -152,8 +144,10 @@ class TestTriggers:
144 "composio.connected_account.expired",
145 ],
146 }
155 - mock_client.get.return_value = {"items": [{"id": "sub_123"}]}
156 - mock_client.patch.return_value = raw_subscription
147 + mock_client.webhook_subscriptions.list.return_value = Mock(
148 + items=[Mock(id="sub_123")]
149 + )
150 + mock_client.webhook_subscriptions.update.return_value = raw_subscription
151
152 result = triggers.set_webhook_subscription(
153 webhook_url=webhook_url,
@@ -164,19 +158,17 @@ class TestTriggers:
158 version="V3",
159 )
160
167 - mock_client.patch.assert_called_once_with(
168 - "/api/v3.1/webhook_subscriptions/sub_123",
169 - cast_to=object,
170 - body={
171 - "webhook_url": webhook_url,
172 - "enabled_events": [
173 - "composio.trigger.message",
174 - "composio.connected_account.expired",
175 - ],
176 - "version": "V3",
177 - },
161 + mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1)
162 + mock_client.webhook_subscriptions.update.assert_called_once_with(
163 + "sub_123",
164 + webhook_url=webhook_url,
165 + enabled_events=[
166 + "composio.trigger.message",
167 + "composio.connected_account.expired",
168 + ],
169 + version="V3",
170 )
179 - mock_client.post.assert_not_called()
171 + mock_client.webhook_subscriptions.create.assert_not_called()
172 assert result == raw_subscription
173
174 def test_set_webhook_subscription_rejects_empty_events(self, triggers):
python/tests/test_webhooks.py new
+410
@@ -0,0 +1,410 @@
1 +"""Tests for the ``composio.webhooks`` namespace."""
2 +
3 +import warnings
4 +from unittest.mock import Mock
5 +
6 +import pytest
7 +from composio_client import omit
8 +from composio_client.types import (
9 + WebhookSubscriptionCreateResponse,
10 + WebhookSubscriptionListResponse,
11 +)
12 +
13 +from composio import exceptions
14 +from composio.core.models.triggers import Triggers
15 +from composio.core.models.triggers import WebhookVersion as TriggersWebhookVersion
16 +from composio.core.models.webhooks import (
17 + WebhookEndpoints,
18 + Webhooks,
19 + WebhookSubscriptions,
20 + WebhookVersion,
21 +)
22 +from tests.conftest import mock_http_client
23 +
24 +
25 +@pytest.fixture
26 +def mock_client() -> Mock:
27 + client = mock_http_client()
28 + client.webhook_subscriptions = Mock()
29 + client.webhook_endpoints = Mock()
30 + return client
31 +
32 +
33 +@pytest.fixture
34 +def subscriptions(mock_client: Mock) -> WebhookSubscriptions:
35 + return WebhookSubscriptions(client=mock_client)
36 +
37 +
38 +@pytest.fixture
39 +def endpoints(mock_client: Mock) -> WebhookEndpoints:
40 + return WebhookEndpoints(client=mock_client)
41 +
42 +
43 +class TestWebhooksNamespace:
44 + def test_mounts_sub_namespaces(self, mock_client):
45 + webhooks = Webhooks(client=mock_client)
46 +
47 + assert isinstance(webhooks.subscriptions, WebhookSubscriptions)
48 + assert isinstance(webhooks.endpoints, WebhookEndpoints)
49 + assert webhooks.subscriptions._client is mock_client
50 + assert webhooks.endpoints._client is mock_client
51 +
52 + def test_webhook_version_is_shared_with_triggers(self):
53 + assert TriggersWebhookVersion is WebhookVersion
54 +
55 +
56 +class TestWebhookSubscriptions:
57 + def test_list(self, subscriptions, mock_client):
58 + mock_client.webhook_subscriptions.list.return_value = "listed"
59 +
60 + assert subscriptions.list() == "listed"
61 + mock_client.webhook_subscriptions.list.assert_called_once_with(
62 + limit=omit, cursor=omit
63 + )
64 +
65 + def test_list_forwards_pagination(self, subscriptions, mock_client):
66 + subscriptions.list(limit=5, cursor="abc")
67 +
68 + mock_client.webhook_subscriptions.list.assert_called_once_with(
69 + limit=5, cursor="abc"
70 + )
71 +
72 + def test_get(self, subscriptions, mock_client):
73 + mock_client.webhook_subscriptions.retrieve.return_value = "sub"
74 +
75 + assert subscriptions.get("sub_123") == "sub"
76 + mock_client.webhook_subscriptions.retrieve.assert_called_once_with("sub_123")
77 +
78 + def test_update_omits_absent_fields(self, subscriptions, mock_client):
79 + mock_client.webhook_subscriptions.update.return_value = "updated"
80 +
81 + assert subscriptions.update("sub_123", webhook_url="https://x") == "updated"
82 + mock_client.webhook_subscriptions.update.assert_called_once_with(
83 + "sub_123", webhook_url="https://x", enabled_events=omit, version=omit
84 + )
85 +
86 + def test_update_normalizes_events_and_version(self, subscriptions, mock_client):
87 + subscriptions.update(
88 + "sub_123",
89 + enabled_events=("composio.trigger.message",),
90 + version=WebhookVersion.V2,
91 + )
92 +
93 + mock_client.webhook_subscriptions.update.assert_called_once_with(
94 + "sub_123",
95 + webhook_url=omit,
96 + enabled_events=["composio.trigger.message"],
97 + version="V2",
98 + )
99 +
100 + def test_delete(self, subscriptions, mock_client):
101 + mock_client.webhook_subscriptions.delete.return_value = "deleted"
102 +
103 + assert subscriptions.delete("sub_123") == "deleted"
104 + mock_client.webhook_subscriptions.delete.assert_called_once_with("sub_123")
105 +
106 + def test_rotate_secret(self, subscriptions, mock_client):
107 + mock_client.webhook_subscriptions.rotate_secret.return_value = "rotated"
108 +
109 + assert subscriptions.rotate_secret("sub_123") == "rotated"
110 + mock_client.webhook_subscriptions.rotate_secret.assert_called_once_with(
111 + "sub_123"
112 + )
113 +
114 + def test_list_event_types(self, subscriptions, mock_client):
115 + mock_client.webhook_subscriptions.list_event_types.return_value = "types"
116 +
117 + assert subscriptions.list_event_types() == "types"
118 + mock_client.webhook_subscriptions.list_event_types.assert_called_once_with()
119 +
120 +
121 +class TestWebhookSubscriptionsSet:
122 + def test_creates_when_none_exists(self, subscriptions, mock_client):
123 + webhook_url = "https://example.com/webhooks/composio"
124 + raw = {
125 + "id": "sub_123",
126 + "webhook_url": webhook_url,
127 + "version": "V3",
128 + "enabled_events": ["composio.trigger.message"],
129 + "secret": "whsec_abc",
130 + }
131 + mock_client.webhook_subscriptions.list.return_value = Mock(items=[])
132 + mock_client.webhook_subscriptions.create.return_value = raw
133 +
134 + result = subscriptions.set(webhook_url=webhook_url)
135 +
136 + mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1)
137 + mock_client.webhook_subscriptions.create.assert_called_once_with(
138 + webhook_url=webhook_url,
139 + enabled_events=["composio.trigger.message"],
140 + version="V3",
141 + )
142 + mock_client.webhook_subscriptions.update.assert_not_called()
143 + assert result == raw
144 +
145 + def test_updates_first_existing(self, subscriptions, mock_client):
146 + webhook_url = "https://example.com/webhooks/composio"
147 + raw = {
148 + "id": "sub_123",
149 + "webhook_url": webhook_url,
150 + "version": "V2",
151 + "enabled_events": ["composio.connected_account.expired"],
152 + }
153 + mock_client.webhook_subscriptions.list.return_value = Mock(
154 + items=[Mock(id="sub_123")]
155 + )
156 + mock_client.webhook_subscriptions.update.return_value = raw
157 +
158 + result = subscriptions.set(
159 + webhook_url=webhook_url,
160 + enabled_events=["composio.connected_account.expired"],
161 + version=WebhookVersion.V2,
162 + )
163 +
164 + mock_client.webhook_subscriptions.list.assert_called_once_with(limit=1)
165 + mock_client.webhook_subscriptions.update.assert_called_once_with(
166 + "sub_123",
167 + webhook_url=webhook_url,
168 + enabled_events=["composio.connected_account.expired"],
169 + version="V2",
170 + )
171 + mock_client.webhook_subscriptions.create.assert_not_called()
172 + assert result == raw
173 +
174 + def test_normalizes_pydantic_response_models(self, subscriptions, mock_client):
175 + mock_client.webhook_subscriptions.list.return_value = (
176 + WebhookSubscriptionListResponse.model_validate(
177 + {
178 + "items": [],
179 + "total_pages": 0,
180 + "current_page": 1,
181 + "total_items": 0,
182 + }
183 + )
184 + )
185 + mock_client.webhook_subscriptions.create.return_value = (
186 + WebhookSubscriptionCreateResponse.model_validate(
187 + {
188 + "id": "sub_1",
189 + "webhook_url": "https://x",
190 + "version": "V3",
191 + "enabled_events": ["composio.trigger.message"],
192 + "secret": "whsec_abc",
193 + "created_at": "2026-01-01",
194 + "updated_at": "2026-01-02",
195 + }
196 + )
197 + )
198 +
199 + result = subscriptions.set(webhook_url="https://x")
200 +
201 + assert result == {
202 + "id": "sub_1",
203 + "webhook_url": "https://x",
204 + "version": "V3",
205 + "enabled_events": ["composio.trigger.message"],
206 + "secret": "whsec_abc",
207 + "created_at": "2026-01-01",
208 + "updated_at": "2026-01-02",
209 + }
210 + assert isinstance(result["version"], str)
211 + assert type(result["version"]) is str
212 +
213 + def test_normalizes_unvalidated_response_models_without_warnings(
214 + self, subscriptions, mock_client
215 + ):
216 + # The client builds response models without validation, so enum fields
217 + # hold plain strings.
218 + mock_client.webhook_subscriptions.list.return_value = (
219 + WebhookSubscriptionListResponse.model_construct(items=[])
220 + )
221 + mock_client.webhook_subscriptions.create.return_value = (
222 + WebhookSubscriptionCreateResponse.model_construct(
223 + id="sub_1",
224 + webhook_url="https://x",
225 + version="V3",
226 + enabled_events=["composio.trigger.message"],
227 + secret="whsec_abc",
228 + created_at="2026-01-01",
229 + updated_at="2026-01-02",
230 + )
231 + )
232 +
233 + with warnings.catch_warnings():
234 + warnings.simplefilter("error")
235 + result = subscriptions.set(webhook_url="https://x")
236 +
237 + assert result["version"] == "V3"
238 +
239 + def test_normalizes_camel_case_wire_keys(self, subscriptions, mock_client):
240 + mock_client.webhook_subscriptions.list.return_value = Mock(items=[])
241 + mock_client.webhook_subscriptions.create.return_value = {
242 + "id": "sub_1",
243 + "webhookUrl": "https://x",
244 + "version": "V3",
245 + "enabledEvents": ["composio.trigger.message"],
246 + "createdAt": "2026-01-01",
247 + }
248 +
249 + result = subscriptions.set(webhook_url="https://x")
250 +
251 + assert result == {
252 + "id": "sub_1",
253 + "webhook_url": "https://x",
254 + "version": "V3",
255 + "enabled_events": ["composio.trigger.message"],
256 + "created_at": "2026-01-01",
257 + }
258 +
259 + @pytest.mark.parametrize(
260 + "raw",
261 + [
262 + pytest.param({}, id="empty"),
263 + pytest.param(
264 + {"webhook_url": "https://x", "version": "V3", "enabled_events": []},
265 + id="missing-id",
266 + ),
267 + pytest.param(
268 + {"id": "sub_1", "webhook_url": "https://x", "enabled_events": []},
269 + id="missing-version",
270 + ),
271 + pytest.param(
272 + {
273 + "id": "sub_1",
274 + "webhook_url": "https://x",
275 + "version": "V3",
276 + "enabled_events": ["composio.trigger.message", 42],
277 + },
278 + id="non-string-event",
279 + ),
280 + pytest.param("not-an-object", id="not-an-object"),
281 + ],
282 + )
283 + def test_rejects_malformed_create_response(self, subscriptions, mock_client, raw):
284 + mock_client.webhook_subscriptions.list.return_value = Mock(items=[])
285 + mock_client.webhook_subscriptions.create.return_value = raw
286 +
287 + with pytest.raises(
288 + exceptions.ValidationError, match="malformed webhook subscription"
289 + ):
290 + subscriptions.set(webhook_url="https://x")
291 +
292 + @pytest.mark.parametrize(
293 + "listed",
294 + [
295 + pytest.param({}, id="missing-items"),
296 + pytest.param({"items": None}, id="null-items"),
297 + pytest.param({"items": [{"id": 42}]}, id="non-string-id"),
298 + pytest.param({"items": [{}]}, id="item-without-id"),
299 + ],
300 + )
301 + def test_rejects_malformed_list_probe_before_writing(
302 + self, subscriptions, mock_client, listed
303 + ):
304 + mock_client.webhook_subscriptions.list.return_value = listed
305 +
306 + with pytest.raises(
307 + exceptions.ValidationError, match="malformed webhook subscription list"
308 + ):
309 + subscriptions.set(webhook_url="https://x")
310 + mock_client.webhook_subscriptions.create.assert_not_called()
311 + mock_client.webhook_subscriptions.update.assert_not_called()
312 +
313 + def test_rejects_empty_webhook_url(self, subscriptions, mock_client):
314 + with pytest.raises(exceptions.ValidationError):
315 + subscriptions.set(webhook_url="")
316 + mock_client.webhook_subscriptions.list.assert_not_called()
317 +
318 + def test_rejects_empty_events(self, subscriptions, mock_client):
319 + with pytest.raises(exceptions.ValidationError):
320 + subscriptions.set(webhook_url="https://x", enabled_events=[])
321 + mock_client.webhook_subscriptions.list.assert_not_called()
322 +
323 +
324 +class TestTriggersDelegation:
325 + def test_set_webhook_subscription_delegates_to_webhooks(self, mock_client):
326 + """``triggers.set_webhook_subscription`` issues the same call sequence
327 + as ``webhooks.subscriptions.set`` and returns the same shape."""
328 + mock_client.triggers_types = Mock()
329 + mock_client.trigger_instances = Mock()
330 + resource = mock_client.webhook_subscriptions
331 + resource.list.return_value = Mock(items=[Mock(id="sub_9")])
332 + resource.update.return_value = {
333 + "id": "sub_9",
334 + "webhook_url": "https://x",
335 + "version": "V3",
336 + "enabled_events": ["composio.trigger.message"],
337 + }
338 +
339 + via_triggers = Triggers(client=mock_client).set_webhook_subscription(
340 + webhook_url="https://x"
341 + )
342 + triggers_calls = (
343 + resource.list.call_args_list,
344 + resource.update.call_args_list,
345 + resource.create.call_args_list,
346 + )
347 + mock_client.reset_mock()
348 + resource.list.return_value = Mock(items=[Mock(id="sub_9")])
349 + resource.update.return_value = {
350 + "id": "sub_9",
351 + "webhook_url": "https://x",
352 + "version": "V3",
353 + "enabled_events": ["composio.trigger.message"],
354 + }
355 +
356 + via_webhooks = WebhookSubscriptions(client=mock_client).set(
357 + webhook_url="https://x"
358 + )
359 +
360 + assert via_triggers == via_webhooks
361 + assert triggers_calls == (
362 + resource.list.call_args_list,
363 + resource.update.call_args_list,
364 + resource.create.call_args_list,
365 + )
366 +
367 +
368 +class TestWebhookEndpoints:
369 + def test_list(self, endpoints, mock_client):
370 + mock_client.webhook_endpoints.list.return_value = "listed"
371 +
372 + assert endpoints.list() == "listed"
373 + mock_client.webhook_endpoints.list.assert_called_once_with(toolkit_slug=omit)
374 +
375 + def test_list_with_toolkit_filter(self, endpoints, mock_client):
376 + endpoints.list(toolkit_slug="github")
377 +
378 + mock_client.webhook_endpoints.list.assert_called_once_with(
379 + toolkit_slug="github"
380 + )
381 +
382 + def test_get(self, endpoints, mock_client):
383 + mock_client.webhook_endpoints.retrieve.return_value = "endpoint"
384 +
385 + assert endpoints.get("we_1") == "endpoint"
386 + mock_client.webhook_endpoints.retrieve.assert_called_once_with("we_1")
387 +
388 + def test_create(self, endpoints, mock_client):
389 + mock_client.webhook_endpoints.create.return_value = "created"
390 +
391 + assert endpoints.create(toolkit_slug="github", client_id="cid") == "created"
392 + mock_client.webhook_endpoints.create.assert_called_once_with(
393 + toolkit_slug="github", client_id="cid"
394 + )
395 +
396 + def test_replace(self, endpoints, mock_client):
397 + mock_client.webhook_endpoints.replace.return_value = "replaced"
398 +
399 + assert endpoints.replace("we_1", data={"secret": "s"}) == "replaced"
400 + mock_client.webhook_endpoints.replace.assert_called_once_with(
401 + "we_1", data={"secret": "s"}
402 + )
403 +
404 + def test_update(self, endpoints, mock_client):
405 + mock_client.webhook_endpoints.update.return_value = "updated"
406 +
407 + assert endpoints.update("we_1", data={"secret": "s"}) == "updated"
408 + mock_client.webhook_endpoints.update.assert_called_once_with(
409 + "we_1", data={"secret": "s"}
410 + )
scripts/examples-provision.mjs
+48 -18
@@ -29,7 +29,20 @@
29 // Auth config ids and connected account ids are not secrets; no credential
30 // values are ever printed. The API-key demo value stored for serpapi is a
31 // deliberately fake placeholder, not a real key.
32 +//
33 +// Selection flags match harness/run.mjs: [--lang ts|py] [--ids a,b]
34 +// [--tiers 1,2,3] [--exclude-toolkits a,b]. Only resources required by the
35 +// selected entries are provisioned; garbage collection remains project-wide
36 +// within the examples-* ownership boundary above.
37
38 +import {
39 + BROWSER_GRANT_TOOLKITS,
40 + DEMO_TOOLKIT,
41 + loadManifest,
42 + requiredBrowserGrantToolkits,
43 + requiresDemoToolkit,
44 + selectManifestEntries,
45 +} from '../harness/manifest.mjs';
46 import { resolveBackendBaseUrl } from '../harness/backend-url.mjs';
47
48 let BASE_URL;
@@ -44,6 +57,23 @@ const USER_ID = process.env.COMPOSIO_EXAMPLES_USER_ID ?? 'examples';
57 const INITIATE_MISSING = process.argv.includes('--initiate-missing');
58 const GC = process.argv.includes('--gc');
59 const DRY_RUN = process.argv.includes('--dry-run');
60 +const option = name => {
61 + const index = process.argv.indexOf(`--${name}`);
62 + return index >= 0 ? process.argv[index + 1] : undefined;
63 +};
64 +
65 +const selection = selectManifestEntries(loadManifest(), {
66 + lang: option('lang'),
67 + ids: option('ids'),
68 + tiers: option('tiers') ?? '1,2,3',
69 + excludeToolkits: option('exclude-toolkits'),
70 +});
71 +if (selection.entries.length === 0) {
72 + console.error('no example entries selected for provisioning');
73 + process.exit(1);
74 +}
75 +const selectedBrowserGrantToolkits = requiredBrowserGrantToolkits(selection.entries);
76 +const needsDemoToolkit = requiresDemoToolkit(selection.entries);
77
78 // COMPOSIO_BASE_URL selects the backend and defaults to staging;
79 // resolveBackendBaseUrl refuses a structurally unusable one before the key is
@@ -54,20 +84,15 @@ if (!API_KEY) {
84 process.exit(1);
85 }
86
57 -// Toolkits the tier-2/3 entries depend on. OAuth toolkits need a one-time human
58 -// browser authorization. Only export ids that examples consume directly.
59 -const BROWSER_GRANT_TOOLKITS = [
60 - { exportPrefix: 'GMAIL', slug: 'gmail' },
61 - // googledrive exports nothing: examples reach Drive through the user's
62 - // standing connection (COMPOSIO_EXAMPLES_USER_ID), never through ids.
63 - { slug: 'googledrive' },
64 - { exportPrefix: 'GITHUB', slug: 'github' },
65 - { exportPrefix: 'SLACK', slug: 'slack' },
66 -];
67 -const DEMO_TOOLKIT = { exportPrefix: 'APIKEY', slug: 'serpapi', demoValue: 'examples-demo-key' };
68 -
87 const report = line => console.error(line);
88
89 +if (selection.excludedEntries.length > 0) {
90 + report(
91 + `excluding ${selection.excludedEntries.length} entries requiring ${selection.excludedToolkits.join(', ')}:`
92 + );
93 + for (const entry of selection.excludedEntries) report(` - ${entry.id}`);
94 +}
95 +
96 async function api(method, path, body) {
97 const res = await fetch(`${BASE_URL}${path}`, {
98 method,
@@ -224,7 +249,7 @@ function findActiveAccount(slug, authConfigId) {
249 );
250 }
251
227 -for (const { exportPrefix, slug } of BROWSER_GRANT_TOOLKITS) {
252 +for (const { exportPrefix, slug } of selectedBrowserGrantToolkits) {
253 let config = findAuthConfig(slug);
254 if (!config) {
255 const created = await api('POST', '/api/v3.1/auth_configs', {
@@ -247,12 +272,17 @@ for (const { exportPrefix, slug } of BROWSER_GRANT_TOOLKITS) {
272 } else {
273 ok = false;
274 if (INITIATE_MISSING) {
250 - const created = await api('POST', '/api/v3.1/connected_accounts', {
251 - auth_config: { id: config.id },
252 - connection: { user_id: USER_ID },
275 + // POST /connected_accounts is retired for Composio-managed OAuth auth
276 + // configs (it 400s with a migration message); every toolkit in this loop
277 + // is exactly that, so the auth-link endpoint is the only way in. It
278 + // returns the redirect URL directly rather than nesting it under
279 + // connectionData.
280 + const created = await api('POST', '/api/v3.1/connected_accounts/link', {
281 + auth_config_id: config.id,
282 + user_id: USER_ID,
283 });
284 pendingGrants.push(
255 - `${slug}: authorize in a browser -> ${created.connectionData?.val?.redirectUrl ?? created.redirect_url ?? created.redirect_uri ?? '(no redirect url returned)'}`
285 + `${slug}: authorize in a browser -> ${created.redirect_url ?? '(no redirect url returned)'}`
286 );
287 } else {
288 pendingGrants.push(
@@ -266,7 +296,7 @@ for (const { exportPrefix, slug } of BROWSER_GRANT_TOOLKITS) {
296 // their own connected accounts to demonstrate that API. The stored value is a
297 // placeholder; serpapi only validates it at tool-execution time and no example
298 // executes a serpapi tool.
269 -{
299 +if (needsDemoToolkit) {
300 const { exportPrefix, slug, demoValue } = DEMO_TOOLKIT;
301 let config = findAuthConfig(slug);
302 if (!config) {
test/release-workflow.test.ts
+229 -5
@@ -12,6 +12,7 @@ import {
12 import { tmpdir } from 'node:os';
13 import { join } from 'node:path';
14 import { spawnSync } from 'node:child_process';
15 +import semver from 'semver';
16 import {
17 findIgnoredChangesetReleases,
18 validateChangesets,
@@ -97,7 +98,7 @@ function readPyprojectVersion(text, label) {
98 function readSdkVersions(rows) {
99 const versions = new Set();
100 const pythonVersionPattern =
100 - /\bv?(\d+(?:\.\d+)+(?:[._-]?(?:a|b|c|rc|alpha|beta|pre|preview)\d*)?(?:[._-]?(?:post|rev|r)\d*)?(?:[._-]?dev\d*)?(?:\+[a-z0-9]+(?:[._-][a-z0-9]+)*)?)\b/gi;
101 + /\bv?(\d+(?:\.\d+)+(?:[._-]?(?:a|b|c|rc|alpha|beta|pre|preview)(?:[._-]?\d+)?)?(?:[._-]?(?:post|rev|r)\d*)?(?:[._-]?dev\d*)?(?:\+[a-z0-9]+(?:[._-][a-z0-9]+)*)?)\b/gi;
102
103 for (const row of rows) {
104 const cells = row
@@ -165,7 +166,12 @@ function readTypeScriptWorkspacePackages() {
166 return workspacePackages;
167 }
168
168 -function runPythonBuildFixture({ providers, providerFiles = [], failingProvider = '' }) {
169 +function runPythonBuildFixture({
170 + providers,
171 + providerFiles = [],
172 + failingProvider = '',
173 + target = 'build',
174 +}) {
175 const fixtureDir = mkdtempSync(join(tmpdir(), 'composio-python-build-'));
176 const buildLogPath = join(fixtureDir, 'build.log');
177
@@ -208,7 +214,7 @@ touch "$target/dist/provider.whl"
214 writeFileSync(join(fixtureDir, 'providers', providerFile), 'not a provider package\n');
215 }
216
211 - const result = spawnSync('make', ['-f', pythonMakefilePath, 'build'], {
217 + const result = spawnSync('make', ['-f', pythonMakefilePath, target], {
218 cwd: fixtureDir,
219 encoding: 'utf8',
220 env: {
@@ -227,6 +233,25 @@ touch "$target/dist/provider.whl"
233 }
234 }
235
236 +{
237 + const result = runPythonBuildFixture({
238 + providers: ['provider-must-not-build'],
239 + target: 'build-core',
240 + });
241 +
242 + if (result.status !== 0) {
243 + throw new Error(
244 + `Python core-only build fixture failed unexpectedly\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`
245 + );
246 + }
247 + if (!result.invocations.includes('<root>')) {
248 + throw new Error('Python core-only build must build the root SDK package');
249 + }
250 + if (result.invocations.includes('providers/provider-must-not-build')) {
251 + throw new Error('Python core-only build must not build provider packages');
252 + }
253 +}
254 +
255 {
256 const result = runPythonBuildFixture({
257 providers: ['valid'],
@@ -272,6 +297,7 @@ touch "$target/dist/provider.whl"
297 '| Python `composio` | `9.9.9.post1` |',
298 '| Python `composio` | `9.9.9.dev1` |',
299 ]);
300 + const semverPrerelease = readSdkVersions(['| TypeScript `@composio/core` | `1.0.0-beta.0` |']);
301
302 if (!directVersion.has('9.9.9') || !versionWithPrevious.has('9.9.9')) {
303 throw new Error('Python SDK changelog version rows must recognize the released version');
@@ -288,6 +314,9 @@ touch "$target/dist/provider.whl"
314 );
315 }
316 }
317 + if (!semverPrerelease.has('1.0.0-beta.0')) {
318 + throw new Error('SDK changelog version rows must recognize SemVer prerelease versions');
319 + }
320 }
321
322 if (!tsReleaseWorkflow.includes('publish-script: pnpm changeset:release')) {
@@ -452,9 +481,50 @@ if (
481
482 // --- Python release metadata: package version, runtime version, and docs changelog must agree ---
483
484 +// PEP 440 compact prereleases (0.23.1rc1) and the separator form that
485 +// python/scripts/bump.py --pre emits (0.23.1-rc.1) must both count as prereleases,
486 +// here and in the workflow's inline detector.
487 +const PYTHON_PRERELEASE_PATTERN = /(?:a|b|rc|dev)[-_.]?\d/i;
488 +const PYTHON_PRERELEASE_SAMPLES: ReadonlyArray<readonly [string, boolean]> = [
489 + ['0.23.0', false],
490 + ['0.23.1', false],
491 + ['0.23.1rc1', true],
492 + ['0.23.1-rc.1', true],
493 + ['0.23.1b2', true],
494 + ['0.23.1.dev3', true],
495 + ['0.23.1a1', true],
496 +];
497 +const workflowPrereleaseDetector = requireMatch(
498 + pythonReleaseWorkflow,
499 + /is_prerelease = re\.search\(r"([^"]+)", version, re\.IGNORECASE\) is not None/,
500 + 'py.release.yml prerelease detector'
501 +);
502 +for (const [sample, expected] of PYTHON_PRERELEASE_SAMPLES) {
503 + if (PYTHON_PRERELEASE_PATTERN.test(sample) !== expected) {
504 + throw new Error(`release-workflow prerelease detector misclassifies ${sample}`);
505 + }
506 + if (new RegExp(workflowPrereleaseDetector, 'i').test(sample) !== expected) {
507 + throw new Error(`py.release.yml prerelease detector misclassifies ${sample}`);
508 + }
509 +}
510 +
511 if (!pythonReleaseWorkflow.includes('run: pnpm test:release-workflow')) {
512 throw new Error('py.release.yml must validate release metadata before publishing');
513 }
514 +for (const input of ['id: release_mode', 'core_only=']) {
515 + if (!pythonReleaseWorkflow.includes(input)) {
516 + throw new Error(`py.release.yml must select the core-only build for prereleases: ${input}`);
517 + }
518 +}
519 +if (
520 + !/if \[\[ "\$\{\{ steps\.release_mode\.outputs\.core_only \}\}" == "true" \]\]; then\s+make build-core\s+else\s+make build\s+fi/.test(
521 + pythonReleaseWorkflow
522 + )
523 +) {
524 + throw new Error(
525 + 'py.release.yml must build only the core package for prereleases and all Python packages for stable releases'
526 + );
527 +}
528
529 {
530 const pythonVersion = readPyprojectVersion(pythonPyproject, 'python/pyproject.toml version');
@@ -478,6 +548,8 @@ if (!pythonReleaseWorkflow.includes('run: pnpm test:release-workflow')) {
548 }
549
550 const providerDir = new URL('../python/providers/', import.meta.url);
551 + const pythonIsPrerelease = PYTHON_PRERELEASE_PATTERN.test(pythonVersion);
552 + const providerVersions = new Map<string, string>();
553 for (const entry of readdirSync(providerDir, { withFileTypes: true })) {
554 if (!entry.isDirectory()) continue;
555
@@ -492,7 +564,14 @@ if (!pythonReleaseWorkflow.includes('run: pnpm test:release-workflow')) {
564 readFileSync(pyprojectPath, 'utf8'),
565 `python/providers/${entry.name}/pyproject.toml version`
566 );
495 - if (providerPyprojectVersion !== pythonVersion) {
567 + providerVersions.set(entry.name, providerPyprojectVersion);
568 + const providerIsPrerelease = PYTHON_PRERELEASE_PATTERN.test(providerPyprojectVersion);
569 + if (pythonIsPrerelease && providerIsPrerelease) {
570 + throw new Error(
571 + `python/providers/${entry.name}/pyproject.toml must remain stable during a composio prerelease (${providerPyprojectVersion})`
572 + );
573 + }
574 + if (!pythonIsPrerelease && providerPyprojectVersion !== pythonVersion) {
575 throw new Error(
576 `python/providers/${entry.name}/pyproject.toml must match python/pyproject.toml (${providerPyprojectVersion} !== ${pythonVersion})`
577 );
@@ -505,12 +584,31 @@ if (!pythonReleaseWorkflow.includes('run: pnpm test:release-workflow')) {
584 /version\s*=\s*"([^"]+)"/,
585 `python/providers/${entry.name}/setup.py version`
586 );
508 - if (providerSetupVersion !== pythonVersion) {
587 + if (providerSetupVersion !== providerPyprojectVersion) {
588 + throw new Error(
589 + `python/providers/${entry.name}/setup.py must match its pyproject.toml (${providerSetupVersion} !== ${providerPyprojectVersion})`
590 + );
591 + }
592 + const providerSetupIsPrerelease = PYTHON_PRERELEASE_PATTERN.test(providerSetupVersion);
593 + if (pythonIsPrerelease && providerSetupIsPrerelease) {
594 + throw new Error(
595 + `python/providers/${entry.name}/setup.py must remain stable during a composio prerelease (${providerSetupVersion})`
596 + );
597 + }
598 + if (!pythonIsPrerelease && providerSetupVersion !== pythonVersion) {
599 throw new Error(
600 `python/providers/${entry.name}/setup.py must match python/pyproject.toml (${providerSetupVersion} !== ${pythonVersion})`
601 );
602 }
603 }
604 +
605 + const distinctProviderVersions = new Set(providerVersions.values());
606 + if (distinctProviderVersions.size > 1) {
607 + const details = [...providerVersions]
608 + .map(([provider, version]) => `- ${provider}: ${version}`)
609 + .join('\n');
610 + throw new Error(`Python providers must share one stable version:\n${details}`);
611 + }
612 }
613
614 {
@@ -1110,6 +1208,132 @@ esac
1208 }
1209 }
1210
1211 +// Entering the core 1.0 beta must leave stable providers unversioned when their
1212 +// peer range explicitly accepts the prerelease. Providers should use the beta
1213 +// only when consumers install it at the workspace root.
1214 +{
1215 + const fixtureDir = mkdtempSync(join(tmpdir(), 'composio-changeset-beta-peer-'));
1216 + try {
1217 + mkdirSync(join(fixtureDir, '.changeset'), { recursive: true });
1218 + mkdirSync(join(fixtureDir, 'packages/core'), { recursive: true });
1219 + mkdirSync(join(fixtureDir, 'packages/openai'), { recursive: true });
1220 +
1221 + writeFileSync(
1222 + join(fixtureDir, 'package.json'),
1223 + JSON.stringify(
1224 + {
1225 + name: 'changeset-beta-peer-fixture',
1226 + private: true,
1227 + workspaces: ['packages/*'],
1228 + },
1229 + null,
1230 + 2
1231 + )
1232 + );
1233 + writeFileSync(join(fixtureDir, 'pnpm-workspace.yaml'), "packages:\n - 'packages/*'\n");
1234 + writeFileSync(
1235 + join(fixtureDir, '.changeset/config.json'),
1236 + JSON.stringify(
1237 + {
1238 + changelog: false,
1239 + commit: false,
1240 + fixed: [],
1241 + linked: [],
1242 + access: 'restricted',
1243 + baseBranch: 'next',
1244 + updateInternalDependencies: 'patch',
1245 + ___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH: {
1246 + onlyUpdatePeerDependentsWhenOutOfRange: true,
1247 + },
1248 + ignore: [],
1249 + },
1250 + null,
1251 + 2
1252 + )
1253 + );
1254 + writeFileSync(
1255 + join(fixtureDir, '.changeset/pre.json'),
1256 + JSON.stringify(
1257 + {
1258 + mode: 'pre',
1259 + tag: 'beta',
1260 + initialVersions: {
1261 + '@composio/core': '0.18.0',
1262 + '@composio/openai': '0.12.1',
1263 + },
1264 + changesets: [],
1265 + },
1266 + null,
1267 + 2
1268 + )
1269 + );
1270 + writeFileSync(
1271 + join(fixtureDir, '.changeset/core-beta.md'),
1272 + ['---', '"@composio/core": major', '---', '', 'Release the core 1.0 beta.', ''].join('\n')
1273 + );
1274 + writeFileSync(
1275 + join(fixtureDir, 'packages/core/package.json'),
1276 + JSON.stringify(
1277 + {
1278 + name: '@composio/core',
1279 + version: '0.18.0',
1280 + },
1281 + null,
1282 + 2
1283 + )
1284 + );
1285 + writeFileSync(
1286 + join(fixtureDir, 'packages/openai/package.json'),
1287 + JSON.stringify(
1288 + {
1289 + name: '@composio/openai',
1290 + version: '0.12.1',
1291 + peerDependencies: {
1292 + '@composio/core': '>=0.10.0 <1.0.0 || >=1.0.0-beta.0 <1.0.0',
1293 + },
1294 + devDependencies: {
1295 + '@composio/core': 'workspace:*',
1296 + },
1297 + },
1298 + null,
1299 + 2
1300 + )
1301 + );
1302 +
1303 + const result = spawnSync(changesetBinPath, ['version'], {
1304 + cwd: fixtureDir,
1305 + encoding: 'utf8',
1306 + env: process.env,
1307 + });
1308 +
1309 + if (result.status !== 0) {
1310 + throw new Error(
1311 + `changeset beta peer fixture failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`
1312 + );
1313 + }
1314 +
1315 + const coreFixturePackage = JSON.parse(
1316 + readFileSync(join(fixtureDir, 'packages/core/package.json'), 'utf8')
1317 + );
1318 + const providerFixturePackage = JSON.parse(
1319 + readFileSync(join(fixtureDir, 'packages/openai/package.json'), 'utf8')
1320 + );
1321 +
1322 + if (coreFixturePackage.version !== '1.0.0-beta.0') {
1323 + throw new Error(
1324 + `fixture core version should be 1.0.0-beta.0, got ${coreFixturePackage.version}`
1325 + );
1326 + }
1327 + if (providerFixturePackage.version !== '0.12.1') {
1328 + throw new Error(
1329 + `fixture provider should stay at 0.12.1, got ${providerFixturePackage.version}`
1330 + );
1331 + }
1332 + } finally {
1333 + rmSync(fixtureDir, { recursive: true, force: true });
1334 + }
1335 +}
1336 +
1337 // --- resolve-release-target.sh: executable tests for the release-target branching ---
1338 //
1339 // The script shells out to `gh` and `curl`; we stub both on PATH and feed fixtures, so these
ts/e2e-tests/cli/toolkits/info/e2e.test.ts
+1
@@ -35,6 +35,7 @@ e2e(import.meta.url, {
35
36 const envPrefix = [
37 `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
38 + 'COMPOSIO_ALLOW_INSECURE_HTTP=1',
39 'COMPOSIO_CACHE_DIR=/tmp/composio-toolkits-info',
40 'COMPOSIO_USER_API_KEY=uak_mock_toolkits_info',
41 ].join(' ');
ts/e2e-tests/cli/toolkits/list/e2e.test.ts
+1
@@ -28,6 +28,7 @@ e2e(import.meta.url, {
28
29 const envPrefix = [
30 `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
31 + 'COMPOSIO_ALLOW_INSECURE_HTTP=1',
32 'COMPOSIO_CACHE_DIR=/tmp/composio-toolkits-list',
33 'COMPOSIO_USER_API_KEY=uak_mock_toolkits_list',
34 ].join(' ');
ts/e2e-tests/cli/toolkits/search/e2e.test.ts
+1
@@ -35,6 +35,7 @@ e2e(import.meta.url, {
35
36 const envPrefix = [
37 `COMPOSIO_BASE_URL=${server.dockerBaseUrl}`,
38 + 'COMPOSIO_ALLOW_INSECURE_HTTP=1',
39 'COMPOSIO_CACHE_DIR=/tmp/composio-toolkits-search',
40 'COMPOSIO_USER_API_KEY=uak_mock_toolkits_search',
41 ].join(' ');
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+1
@@ -102,6 +102,7 @@ describe('CLI: composio dev connected-accounts link', () => {
102 execute: {},
103 search: {},
104 preload: { tools: [] },
105 + premium_usage: false as const,
106 },
107 config_version: 1,
108 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+2
@@ -109,6 +109,7 @@ describe('CLI: composio proxy', () => {
109 execute: {},
110 search: {},
111 preload: { tools: [] },
112 + premium_usage: false,
113 },
114 config_version: 1,
115 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -205,6 +206,7 @@ describe('CLI: composio proxy', () => {
206 execute: {},
207 search: {},
208 preload: { tools: [] },
209 + premium_usage: false,
210 },
211 config_version: 1,
212 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+5
@@ -335,6 +335,7 @@ describe('CLI: composio execute', () => {
335 execute: {},
336 search: {},
337 preload: { tools: [] },
338 + premium_usage: false,
339 },
340 config_version: 1,
341 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -450,6 +451,7 @@ describe('CLI: composio execute', () => {
451 execute: {},
452 search: {},
453 preload: { tools: [] },
454 + premium_usage: false,
455 },
456 config_version: 1,
457 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -576,6 +578,7 @@ describe('CLI: composio execute', () => {
578 execute: {},
579 search: {},
580 preload: { tools: [] },
581 + premium_usage: false,
582 },
583 config_version: 1,
584 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -663,6 +666,7 @@ describe('CLI: composio execute', () => {
666 execute: {},
667 search: {},
668 preload: { tools: [] },
669 + premium_usage: false,
670 },
671 config_version: 1,
672 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
@@ -720,6 +724,7 @@ describe('CLI: composio execute', () => {
724 execute: {},
725 search: {},
726 preload: { tools: [] },
727 + premium_usage: false,
728 },
729 config_version: 1,
730 mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+4
@@ -542,6 +542,7 @@ describe('CLI: composio search', () => {
542 execute: {},
543 search: {},
544 preload: { tools: [] },
545 + premium_usage: false,
546 },
547 config_version: 1,
548 mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
@@ -628,6 +629,7 @@ describe('CLI: composio search', () => {
629 execute: {},
630 search: {},
631 preload: { tools: [] },
632 + premium_usage: false,
633 },
634 config_version: 1,
635 mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
@@ -712,6 +714,7 @@ describe('CLI: composio search', () => {
714 execute: {},
715 search: {},
716 preload: { tools: [] },
717 + premium_usage: false,
718 },
719 config_version: 1,
720 mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
@@ -907,6 +910,7 @@ describe('CLI: composio search', () => {
910 execute: {},
911 search: {},
912 preload: { tools: [] },
913 + premium_usage: false,
914 },
915 config_version: 1,
916 mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
ts/packages/core/src/composio.ts
+112 -2
@@ -1,5 +1,6 @@
1 import type { BaseComposioProvider } from './provider/BaseProvider';
2 import ComposioClient from '@composio/client';
3 +import type { Logger as ClientLogger, LogLevel as ClientLogLevel } from '@composio/client';
4 import { Tools } from './models/Tools';
5 import { Toolkits } from './models/Toolkits';
6 import { Triggers } from './models/Triggers';
@@ -7,10 +8,14 @@ import { AuthConfigs } from './models/AuthConfigs';
8 import { ConnectedAccounts } from './models/ConnectedAccounts';
9 import { Experimental } from './models/Experimental';
10 import { MCP } from './models/MCP';
11 +import { Webhooks } from './models/Webhooks';
12 +import { Logs } from './models/Logs';
13 +import { Keyring } from './models/Keyring';
14 import { telemetry } from './telemetry/Telemetry';
15 import { getSDKConfig, getToolkitVersionsFromEnv } from './utils/sdk';
16 import logger from './utils/logger';
13 -import { COMPOSIO_LOG_LEVEL, IS_DEVELOPMENT_OR_CI } from './utils/constants';
17 +import type { ComposioLogger, LogLevel } from './utils/logger';
18 +import { IS_DEVELOPMENT_OR_CI } from './utils/constants';
19 import { checkForLatestVersionFromNPM } from './utils/version';
20 import { OpenAIProvider } from './provider/OpenAIProvider';
21 import { version } from '../package.json';
@@ -31,6 +36,24 @@ export type ComposioConfig<
36 * @example 'sk-1234567890'
37 */
38 apiKey?: string | null;
39 + /**
40 + * User API key (`uak_*`) for the organization, consumer, and user-scoped
41 + * endpoints reached through `getClient()` (for example `client.org.list()`).
42 + * Sent as `x-user-api-key` only on operations whose security scheme requires
43 + * it, never alongside the project key. Falls back to
44 + * `process.env['COMPOSIO_USER_API_KEY']`. A project `apiKey` is still required.
45 + * @example 'uak_1234567890'
46 + */
47 + userApiKey?: string | null;
48 + /**
49 + * Organization API key (`oak_*`) for the organization-owner endpoints reached
50 + * through `getClient()` (for example `client.org.owner.project.list()`).
51 + * Sent as `x-org-api-key` only on operations whose security scheme requires
52 + * it, never alongside the project key. Falls back to
53 + * `process.env['COMPOSIO_ORG_API_KEY']`. A project `apiKey` is still required.
54 + * @example 'oak_1234567890'
55 + */
56 + orgApiKey?: string | null;
57 /**
58 * The base URL of the Composio API.
59 * @example 'https://backend.composio.dev'
@@ -156,6 +179,68 @@ export type ComposioConfig<
179 * ```
180 */
181 toolkitVersions?: ToolkitVersionParam;
182 + /**
183 + * Destination for SDK log output. Messages are formatted and have
184 + * credential-shaped values redacted before they reach the sink, so any
185 + * object with `error`/`warn`/`info`/`debug` methods works (`console`, pino,
186 + * winston, ...).
187 + *
188 + * Runtime deprecation warnings raised by the underlying API client (response
189 + * `Deprecation`/`Sunset` headers and deprecated request inputs) are routed
190 + * through this logger as well.
191 + *
192 + * The SDK logger is process-wide: configuring it on one `Composio` instance
193 + * affects every instance, and the last configured instance wins.
194 + *
195 + * @default console
196 + * @example
197 + * ```typescript
198 + * const composio = new Composio({
199 + * apiKey: 'your-api-key',
200 + * logger: pino(),
201 + * logLevel: 'warn',
202 + * });
203 + * ```
204 + */
205 + logger?: ComposioLogger;
206 + /**
207 + * Minimum level to emit: `'silent' | 'error' | 'warn' | 'info' | 'debug'`.
208 + * Takes precedence over the `COMPOSIO_LOG_LEVEL` environment variable.
209 + * Also gates the API client's runtime deprecation warnings (`'silent'` turns
210 + * them off). The client's per-request lifecycle logs are emitted at
211 + * `'debug'` only.
212 + *
213 + * Like `logger`, this applies process-wide and the last configured instance
214 + * wins. The API client's own level is fixed when each instance is created.
215 + *
216 + * @default 'info' (or `COMPOSIO_LOG_LEVEL` when set)
217 + */
218 + logLevel?: LogLevel;
219 +};
220 +
221 +/**
222 + * Level for the API client given the SDK level. The client logs each request's
223 + * lifecycle at `info`, which is debug-grade for SDK users, so the client stays
224 + * at `warn` unless the SDK is at `debug`. The client's `LogLevel` has
225 + * `'off'` where the SDK has `'silent'`.
226 + */
227 +const toClientLogLevel = (level: LogLevel): ClientLogLevel => {
228 + if (level === 'silent') return 'off';
229 + if (level === 'info') return 'warn';
230 + return level;
231 +};
232 +
233 +/**
234 + * Forwards the API client's log records to the SDK singleton so they pick up
235 + * the SDK's formatting, redaction, and configured sink. Methods are looked up
236 + * at call time so a later `logger.configure()` is honoured. The client's
237 + * `info` records (per-request lifecycle) are forwarded as SDK `debug`.
238 + */
239 +const clientLoggerAdapter: ClientLogger = {
240 + error: (...args) => logger.error(...args),
241 + warn: (...args) => logger.warn(...args),
242 + info: (...args) => logger.debug(...args),
243 + debug: (...args) => logger.debug(...args),
244 };
245
246 /**
@@ -195,6 +280,15 @@ export class Composio<
280 authConfigs: AuthConfigs;
281 /** Manage authenticated connections */
282 connectedAccounts: ConnectedAccounts;
283 + /**
284 + * Manage the project's webhook subscription (`webhooks.subscriptions`) and
285 + * inbound per-toolkit webhook endpoints (`webhooks.endpoints`).
286 + */
287 + webhooks: Webhooks;
288 + /** Search and inspect tool-execution logs */
289 + logs: Logs;
290 + /** Public transfer keys of the organization's customer-managed keyring */
291 + keyring: Keyring;
292 /**
293 * Experimental SDK methods whose shape may change in future releases.
294 * Prefer domain-specific mounts (for example
@@ -307,6 +401,10 @@ export class Composio<
401 config?.apiKey
402 );
403
404 + if (config?.logger !== undefined || config?.logLevel !== undefined) {
405 + logger.configure({ level: config.logLevel, sink: config.logger });
406 + }
407 +
408 if (IS_DEVELOPMENT_OR_CI) {
409 logger.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
410 }
@@ -344,11 +442,20 @@ export class Composio<
442 */
443 this.client = new ComposioClient({
444 apiKey: apiKeyParsed,
445 + userApiKey: config?.userApiKey,
446 + orgApiKey: config?.orgApiKey,
447 baseURL: baseURLParsed,
448 defaultHeaders: defaultHeaders,
349 - logLevel: COMPOSIO_LOG_LEVEL,
449 + logger: clientLoggerAdapter,
450 + logLevel: toClientLogLevel(logger.getLevel()),
451 });
452
453 + // Store the resolved values, as with `apiKey`, so `getConfig()` and the
454 + // `createSession()` clone carry whatever the client resolved from env
455 + // rather than re-reading the environment later.
456 + this.config.userApiKey = this.client.userApiKey;
457 + this.config.orgApiKey = this.client.orgApiKey;
458 +
459 this.tools = new Tools(this.client, this.config);
460 this.mcp = new MCP(this.client);
461 this.toolkits = new Toolkits(this.client);
@@ -360,6 +467,9 @@ export class Composio<
467 fileDownloadDir: this.config.fileDownloadDir,
468 });
469 this.connectedAccounts = new ConnectedAccounts(this.client);
470 + this.webhooks = new Webhooks(this.client);
471 + this.logs = new Logs(this.client);
472 + this.keyring = new Keyring(this.client);
473 this.experimental = new Experimental(this.client);
474 this.sessions = new Sessions(this.client, this.config);
475 this.toolRouter = this.sessions;
ts/packages/core/src/errors/ConnectedAccountsErrors.ts
+47
@@ -8,6 +8,8 @@ export const ConnectedAccountErrorCodes = {
8 SHARED_ACCESS_DENIED: 'SHARED_ACCESS_DENIED',
9 ACL_ONLY_FOR_SHARED: 'ACL_ONLY_FOR_SHARED',
10 SHARED_CONNECTION_NOT_ACCESSIBLE: 'SHARED_CONNECTION_NOT_ACCESSIBLE',
11 + REVOCATION_NOT_SUPPORTED: 'CONNECTED_ACCOUNT_REVOCATION_NOT_SUPPORTED',
12 + NOT_REVOKABLE: 'CONNECTED_ACCOUNT_NOT_REVOKABLE',
13 } as const;
14
15 export class ComposioConnectedAccountNotFoundError extends ComposioError {
@@ -156,3 +158,48 @@ export class ComposioLegacyConnectedAccountsEndpointRetiredError extends Composi
158 this.name = 'ComposioLegacyConnectedAccountsEndpointRetiredError';
159 }
160 }
161 +
162 +/**
163 + * Thrown by `composio.connectedAccounts.revoke()` when the toolkit behind the
164 + * connection does not support programmatic revocation at the provider (API
165 + * 400).
166 + */
167 +export class ComposioConnectedAccountRevocationNotSupportedError extends ComposioError {
168 + constructor(
169 + message: string = 'This toolkit does not support programmatic revocation of connected accounts',
170 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
171 + ) {
172 + super(message, {
173 + ...options,
174 + code: ConnectedAccountErrorCodes.REVOCATION_NOT_SUPPORTED,
175 + statusCode: 400,
176 + possibleFixes: options.possibleFixes || [
177 + "Revoke the grant from the provider's own settings page, then disable or delete the connected account with composio.connectedAccounts.disable() / delete().",
178 + ],
179 + });
180 + this.name = 'ComposioConnectedAccountRevocationNotSupportedError';
181 + }
182 +}
183 +
184 +/**
185 + * Thrown by `composio.connectedAccounts.revoke()` when the connection is not
186 + * in a state that can be revoked (API 409), for example it never completed
187 + * authentication. Revoking an already revoked connection is not an error: it
188 + * returns an empty `revokedTokens` list.
189 + */
190 +export class ComposioConnectedAccountNotRevokableError extends ComposioError {
191 + constructor(
192 + message: string = 'The connected account is not in a revokable state',
193 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
194 + ) {
195 + super(message, {
196 + ...options,
197 + code: ConnectedAccountErrorCodes.NOT_REVOKABLE,
198 + statusCode: 409,
199 + possibleFixes: options.possibleFixes || [
200 + 'Check the connection status with composio.connectedAccounts.get(); only ACTIVE connections can be revoked.',
201 + ],
202 + });
203 + this.name = 'ComposioConnectedAccountNotRevokableError';
204 + }
205 +}
ts/packages/core/src/index.ts
+11
@@ -45,6 +45,11 @@ export {
45 export type { KeyMapping, KeySanitizationPolicy } from './utils/schemaPropertyKeys';
46 export { AuthScheme } from './models/AuthScheme';
47 export { MCP } from './models/MCP';
48 +export { Webhooks, WebhookSubscriptions, WebhookEndpoints } from './models/Webhooks';
49 +export { Logs } from './models/Logs';
50 +export { Usage } from './models/Usage';
51 +export { Keyring } from './models/Keyring';
52 +export { CustomToolkits } from './models/CustomToolkits';
53 export { RemoteFile } from './models/RemoteFile';
54 export { createConnectionRequest } from './models/ConnectionRequest';
55 export { ToolRouterSession } from './models/ToolRouterSession';
@@ -59,6 +64,11 @@ export * from './types/connectedAccounts.types';
64 export * from './types/toolkit.types';
65 export * from './types/triggers.types';
66 export * from './types/webhookEvents.types';
67 +export * from './types/webhooks.types';
68 +export * from './types/logs.types';
69 +export * from './types/usage.types';
70 +export * from './types/keyring.types';
71 +export * from './types/customToolkits.types';
72 export * from './types/mcp.types';
73 export * from './types/files.types';
74 export * from './types/connectionRequest.types';
@@ -68,6 +78,7 @@ export * from './types/requestOptions.types';
78 export * as constants from './utils/constants';
79
80 export { default as logger } from './utils/logger';
81 +export type { ComposioLogger, LogLevel } from './utils/logger';
82 export { telemetry } from './telemetry/Telemetry';
83
84 // Experimental custom tools — exported with experimental_ prefix for top-level import
ts/packages/core/src/models/ConnectedAccounts.ts
+118 -2
@@ -5,7 +5,7 @@
5 * @date 2025-05-05
6 * @module ConnectedAccounts
7 */
8 -import ComposioClient, { BadRequestError } from '@composio/client';
8 +import ComposioClient, { BadRequestError, ConflictError } from '@composio/client';
9 import {
10 ConnectedAccountCreateResponse,
11 ConnectedAccountDeleteResponse,
@@ -29,6 +29,10 @@ import {
29 ConnectedAccountStatuses,
30 ConnectedAccountRefreshOptions,
31 ConnectedAccountRefreshOptionsSchema,
32 + ConnectedAccountRevokeResponse,
33 + ConnectedAccountCompleteAuthParams,
34 + ConnectedAccountCompleteAuthParamsSchema,
35 + ConnectedAccountCompleteAuthResponse,
36 UpdateConnectedAccountAclParams,
37 UpdateConnectedAccountParams,
38 UpdateConnectedAccountParamsSchema,
@@ -45,9 +49,13 @@ import { telemetry } from '../telemetry/Telemetry';
49 import {
50 transformConnectedAccountListResponse,
51 transformConnectedAccountResponse,
52 + transformConnectedAccountRevokeResponse,
53 + transformConnectedAccountCompleteAuthResponse,
54 } from '../utils/transformers/connectedAccounts';
55 import {
56 ComposioAclOnlyForSharedError,
57 + ComposioConnectedAccountNotRevokableError,
58 + ComposioConnectedAccountRevocationNotSupportedError,
59 ComposioFailedToCreateConnectedAccountLink,
60 ComposioLegacyConnectedAccountsEndpointRetiredError,
61 ComposioMultipleConnectedAccountsError,
@@ -554,6 +562,11 @@ export class ConnectedAccounts {
562 * // Refresh a connected account's credentials
563 * const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');
564 * ```
565 + *
566 + * @deprecated The `POST /connected_accounts/{id}/refresh` endpoint is deprecated by the
567 + * Composio API. Re-initiate authentication instead: `composio.connectedAccounts.link(userId, authConfigId)`
568 + * for a fresh connection, or `session.authorize(toolkit)` from a session. Behaviour is unchanged
569 + * while the endpoint remains available; do not generate new code against `refresh`.
570 */
571 async refresh(
572 nanoid: string,
@@ -570,9 +583,14 @@ export class ConnectedAccounts {
583 });
584 }
585
586 + if (parsedOptions.data.validateCredentials !== undefined) {
587 + logger.warn(
588 + 'connectedAccounts.refresh(): the Composio API no longer accepts `validateCredentials`; the option is ignored.'
589 + );
590 + }
591 +
592 params = {
593 query_redirect_url: parsedOptions.data.redirectUrl,
575 - validate_credentials: parsedOptions.data.validateCredentials,
594 };
595 }
596
@@ -582,6 +600,104 @@ export class ConnectedAccounts {
600 );
601 }
602
603 + /**
604 + * Revoke a connected account at the upstream provider.
605 + *
606 + * Best-effort upstream revocation of the stored tokens/credentials; on
607 + * success the connection status becomes `REVOKED`. Revoking an already
608 + * revoked connection returns an empty `revokedTokens` list without an
609 + * upstream call.
610 + *
611 + * @param {string} nanoid - The unique identifier of the connected account to revoke
612 + * @returns {Promise<ConnectedAccountRevokeResponse>} Which tokens were revoked and the resulting status
613 + * @throws {ComposioConnectedAccountRevocationNotSupportedError} If the toolkit does not support programmatic revocation (400)
614 + * @throws {ComposioConnectedAccountNotRevokableError} If the connection is not in a revokable state (409)
615 + *
616 + * @example
617 + * ```typescript
618 + * const result = await composio.connectedAccounts.revoke('conn_abc123');
619 + * console.log(result.connectedAccount.status); // 'REVOKED'
620 + * console.log(result.revokedTokens); // e.g. ['access_token', 'refresh_token']
621 + * ```
622 + */
623 + async revoke(
624 + nanoid: string,
625 + requestOptions?: ComposioRequestOptions
626 + ): Promise<ConnectedAccountRevokeResponse> {
627 + try {
628 + const result = await withCancellation(
629 + () => this.client.connectedAccounts.revoke(nanoid, requestOptions),
630 + requestOptions?.signal
631 + );
632 + return transformConnectedAccountRevokeResponse(result);
633 + } catch (error) {
634 + if (error instanceof BadRequestError) {
635 + throw new ComposioConnectedAccountRevocationNotSupportedError(
636 + `Connected account ${nanoid} cannot be revoked programmatically: ${error.message}`,
637 + { cause: error, meta: { nanoid } }
638 + );
639 + }
640 + if (error instanceof ConflictError) {
641 + throw new ComposioConnectedAccountNotRevokableError(
642 + `Connected account ${nanoid} is not in a revokable state: ${error.message}`,
643 + { cause: error, meta: { nanoid } }
644 + );
645 + }
646 + throw error;
647 + }
648 + }
649 +
650 + /**
651 + * Complete a deferred OAuth connection once you have verified the user's
652 + * identity.
653 + *
654 + * When your project has an OAuth callback verifier configured, Composio
655 + * does not activate a new OAuth connection by itself: it redirects to your
656 + * verifier with a single-use session URI. After confirming who the user is,
657 + * redeem that session URI here; Composio checks that your project owns the
658 + * pending connection and that `userId` is its owner, completes the token
659 + * exchange, and the connection becomes `ACTIVE`.
660 + *
661 + * The session URI is single-use: redeeming it twice, or after it expires,
662 + * fails with a 404 from the API.
663 + *
664 + * @param {ConnectedAccountCompleteAuthParams} params - `userId` the connection was initiated for and the verifier's `sessionUri`
665 + * @returns {Promise<ConnectedAccountCompleteAuthResponse>} The completed connection's ID and toolkit
666 + * @throws {ValidationError} If the params fail validation
667 + *
668 + * @example
669 + * ```typescript
670 + * // In your verifier route, after authenticating the user:
671 + * const { connectedAccountId, toolkitSlug } = await composio.connectedAccounts.completeAuth({
672 + * userId: 'user_123',
673 + * sessionUri, // the session URI from the verifier redirect
674 + * });
675 + * ```
676 + */
677 + async completeAuth(
678 + params: ConnectedAccountCompleteAuthParams,
679 + requestOptions?: ComposioRequestOptions
680 + ): Promise<ConnectedAccountCompleteAuthResponse> {
681 + const parsedParams = ConnectedAccountCompleteAuthParamsSchema.safeParse(params);
682 + if (!parsedParams.success) {
683 + throw new ValidationError('Failed to parse connected account completeAuth params', {
684 + cause: parsedParams.error,
685 + });
686 + }
687 + const result = await withCancellation(
688 + () =>
689 + this.client.connectedAccounts.completeAuth(
690 + {
691 + user_id: parsedParams.data.userId,
692 + session_uri: parsedParams.data.sessionUri,
693 + },
694 + requestOptions
695 + ),
696 + requestOptions?.signal
697 + );
698 + return transformConnectedAccountCompleteAuthResponse(result);
699 + }
700 +
701 /**
702 * Update the status of a connected account
703 * @param {string} nanoid - Unique identifier of the connected account
ts/packages/core/src/models/CustomToolkits.ts new
+169
@@ -0,0 +1,169 @@
1 +/**
2 + * @fileoverview `composio.experimental.customToolkits`: register and manage
3 + * project-owned custom toolkits.
4 + * **Experimental — custom toolkits are in pilot; shape may change.**
5 + *
6 + * @module CustomToolkits
7 + */
8 +import ComposioClient from '@composio/client';
9 +import {
10 + CustomToolkitDeleteResponse,
11 + CustomToolkitSyncParams,
12 + CustomToolkitSyncParamsSchema,
13 + CustomToolkitSyncResponse,
14 + CustomToolkitUpsertParams,
15 + CustomToolkitUpsertParamsSchema,
16 + CustomToolkitUpsertResponse,
17 +} from '../types/customToolkits.types';
18 +import { ComposioRequestOptions } from '../types/requestOptions.types';
19 +import { ValidationError } from '../errors/ValidationErrors';
20 +import { telemetry } from '../telemetry/Telemetry';
21 +import { withCancellation } from '../utils/cancellation';
22 +import {
23 + transformCustomToolkitDeleteResponse,
24 + transformCustomToolkitSyncParams,
25 + transformCustomToolkitSyncResponse,
26 + transformCustomToolkitUpsertParams,
27 + transformCustomToolkitUpsertResponse,
28 +} from '../utils/transformers/customToolkits';
29 +
30 +/**
31 + * `composio.experimental.customToolkits` — toolkits your project registers
32 + * from its own app or MCP server, with their own auth configs and connected
33 + * accounts. **Experimental — custom toolkits are in pilot; shape may change.**
34 + *
35 + * These live on the Composio platform. They are unrelated to the in-process
36 + * toolkits built with `experimental_createToolkit()`, which run inside your
37 + * application.
38 + *
39 + * @example
40 + * ```typescript
41 + * const { slug } = await composio.experimental.customToolkits.upsert({
42 + * slug: 'MY_TOOLKIT',
43 + * toolkitConfig: {
44 + * name: 'My Toolkit',
45 + * appUrl: 'https://mcp.example.com/mcp',
46 + * authSchemes: [{ mode: 'DCR_OAUTH', discoveryUrl: 'https://mcp.example.com/.well-known/oauth-authorization-server' }],
47 + * },
48 + * });
49 + * await composio.experimental.customToolkits.sync(slug);
50 + * ```
51 + */
52 +export class CustomToolkits {
53 + private client: ComposioClient;
54 +
55 + constructor(client: ComposioClient) {
56 + this.client = client;
57 + telemetry.instrument(this, 'CustomToolkits');
58 + }
59 +
60 + /**
61 + * Creates a custom toolkit, or updates its display metadata (name, API key
62 + * field copy) when the project already owns a toolkit with this slug.
63 + * **Experimental — custom toolkits are in pilot; shape may change.**
64 + *
65 + * `appUrl` and `authSchemes` cannot change on an existing toolkit:
66 + * re-sending them unchanged is a no-op, and changing them fails with a 409.
67 + * Delete and re-register the toolkit instead, which revokes its connections.
68 + *
69 + * @param {CustomToolkitUpsertParams} params - The slug and toolkit configuration
70 + * @returns {Promise<CustomToolkitUpsertResponse>} The toolkit's slug
71 + * @throws {ValidationError} If the params fail validation
72 + *
73 + * @example
74 + * ```typescript
75 + * await composio.experimental.customToolkits.upsert({
76 + * slug: 'INTERNAL_API',
77 + * toolkitConfig: {
78 + * name: 'Internal API',
79 + * appUrl: 'https://mcp.internal.example.com/mcp',
80 + * authSchemes: [
81 + * { mode: 'API_KEY', headers: { Authorization: 'Bearer {{generic_api_key}}' } },
82 + * ],
83 + * },
84 + * });
85 + * ```
86 + */
87 + async upsert(
88 + params: CustomToolkitUpsertParams,
89 + requestOptions?: ComposioRequestOptions
90 + ): Promise<CustomToolkitUpsertResponse> {
91 + const parsedParams = CustomToolkitUpsertParamsSchema.safeParse(params);
92 + if (!parsedParams.success) {
93 + throw new ValidationError('Failed to parse custom toolkit upsert params', {
94 + cause: parsedParams.error,
95 + });
96 + }
97 + const body = transformCustomToolkitUpsertParams(parsedParams.data);
98 + const result = await withCancellation(
99 + () => this.client.custom.upsert(body, requestOptions),
100 + requestOptions?.signal
101 + );
102 + return transformCustomToolkitUpsertResponse(result);
103 + }
104 +
105 + /**
106 + * Re-fetches the tool definitions of a custom toolkit from its remote MCP
107 + * server. Call it when automatic sync fails or the remote tools change.
108 + * **Experimental — custom toolkits are in pilot; shape may change.**
109 + *
110 + * @param {string} slug - The custom toolkit slug (`CUSTOM_...`)
111 + * @param {CustomToolkitSyncParams} [params] - Optional connected account to fetch the definitions with
112 + * @returns {Promise<CustomToolkitSyncResponse>} The toolkit version and number of tools synced
113 + * @throws {ValidationError} If the params fail validation
114 + *
115 + * @example
116 + * ```typescript
117 + * const { version, syncedCount } = await composio.experimental.customToolkits.sync(
118 + * 'CUSTOM_MY_TOOLKIT',
119 + * { connectedAccountId: 'ca_abc123' }
120 + * );
121 + * ```
122 + */
123 + async sync(
124 + slug: string,
125 + params?: CustomToolkitSyncParams,
126 + requestOptions?: ComposioRequestOptions
127 + ): Promise<CustomToolkitSyncResponse> {
128 + const parsedParams = CustomToolkitSyncParamsSchema.safeParse(params ?? {});
129 + if (!parsedParams.success) {
130 + throw new ValidationError('Failed to parse custom toolkit sync params', {
131 + cause: parsedParams.error,
132 + });
133 + }
134 + const body = transformCustomToolkitSyncParams(slug, parsedParams.data);
135 + const result = await withCancellation(
136 + () => this.client.custom.sync(body, requestOptions),
137 + requestOptions?.signal
138 + );
139 + return transformCustomToolkitSyncResponse(result);
140 + }
141 +
142 + /**
143 + * Deletes a custom toolkit owned by the project, with its tools, auth
144 + * configs and connected accounts. The credentials behind those connected
145 + * accounts are revoked in background jobs (`revokeJobIds`).
146 + * **Experimental — custom toolkits are in pilot; shape may change.**
147 + *
148 + * Composio-managed toolkits cannot be deleted; the API answers 403.
149 + *
150 + * @param {string} slug - The custom toolkit slug (`CUSTOM_...`)
151 + * @returns {Promise<CustomToolkitDeleteResponse>} What was deleted
152 + *
153 + * @example
154 + * ```typescript
155 + * const result = await composio.experimental.customToolkits.delete('CUSTOM_MY_TOOLKIT');
156 + * console.log(result.connectedAccountsDeleted);
157 + * ```
158 + */
159 + async delete(
160 + slug: string,
161 + requestOptions?: ComposioRequestOptions
162 + ): Promise<CustomToolkitDeleteResponse> {
163 + const result = await withCancellation(
164 + () => this.client.custom.deleteToolkit(slug, requestOptions),
165 + requestOptions?.signal
166 + );
167 + return transformCustomToolkitDeleteResponse(result);
168 + }
169 +}
ts/packages/core/src/models/Experimental.ts
+27
@@ -21,6 +21,8 @@ import {
21 import { ValidationError } from '../errors/ValidationErrors';
22 import { ComposioAclOnlyForSharedError } from '../errors';
23 import { telemetry } from '../telemetry/Telemetry';
24 +import { Usage } from './Usage';
25 +import { CustomToolkits } from './CustomToolkits';
26
27 /**
28 * Server-side 400 message the API uses to reject ACL writes against a
@@ -129,8 +131,33 @@ export async function updateConnectedAccountAcl(
131 export class Experimental {
132 private client: ComposioClient;
133
134 + /**
135 + * Project-scoped usage metering (`summary()` / `breakdown()`).
136 + * **Experimental — shape may change in future releases.**
137 + *
138 + * @example
139 + * ```typescript
140 + * const summary = await composio.experimental.usage.summary();
141 + * const byTool = await composio.experimental.usage.breakdown('tool_calls');
142 + * ```
143 + */
144 + usage: Usage;
145 +
146 + /**
147 + * Register and manage project-owned custom toolkits (`upsert()` / `sync()` / `delete()`).
148 + * **Experimental — custom toolkits are in pilot; shape may change.**
149 + *
150 + * @example
151 + * ```typescript
152 + * await composio.experimental.customToolkits.sync('CUSTOM_MY_TOOLKIT');
153 + * ```
154 + */
155 + customToolkits: CustomToolkits;
156 +
157 constructor(client: ComposioClient) {
158 this.client = client;
159 + this.usage = new Usage(client);
160 + this.customToolkits = new CustomToolkits(client);
161 telemetry.instrument(this, 'Experimental');
162 }
163
ts/packages/core/src/models/Keyring.ts new
+65
@@ -0,0 +1,65 @@
1 +/**
2 + * @fileoverview The `composio.keyring` namespace: the public transfer keys of
3 + * the organization's customer-managed keyring.
4 + *
5 + * @module Keyring
6 + */
7 +import ComposioClient from '@composio/client';
8 +import { KeyringTransferKeysResponse } from '../types/keyring.types';
9 +import { ComposioRequestOptions } from '../types/requestOptions.types';
10 +import { telemetry } from '../telemetry/Telemetry';
11 +import { withCancellation } from '../utils/cancellation';
12 +import { transformKeyringTransferKeysResponse } from '../utils/transformers/keyring';
13 +
14 +/**
15 + * `composio.keyring` — the organization's customer-managed keyring.
16 + *
17 + * @example
18 + * ```typescript
19 + * const { activeKid, keys } = await composio.keyring.listTransferKeys();
20 + * const sealingKey = keys.find(key => key.kid === activeKid);
21 + * ```
22 + */
23 +export class Keyring {
24 + private client: ComposioClient;
25 +
26 + constructor(client: ComposioClient) {
27 + this.client = client;
28 + telemetry.instrument(this, 'Keyring');
29 + }
30 +
31 + /**
32 + * Lists the public transfer keys of the organization's active customer
33 + * keyring, the keys a secret is sealed to before it is sent to Composio.
34 + *
35 + * Always seal new secrets to the key whose `kid` is `activeKid`: a JWE with
36 + * `RSA-OAEP-256` key management, `A256GCM` content encryption, and the
37 + * `kid` in the protected header. Older keys stay listed so values sealed to
38 + * them remain openable.
39 + *
40 + * The organization behind the API key must have an ACTIVE customer keyring
41 + * instance; otherwise the API answers 404.
42 + *
43 + * @returns {Promise<KeyringTransferKeysResponse>} The active key ID and every accepted public JWK, newest first
44 + *
45 + * @example
46 + * ```typescript
47 + * import { CompactEncrypt, importJWK } from 'jose';
48 + *
49 + * const { activeKid, keys } = await composio.keyring.listTransferKeys();
50 + * const jwk = keys.find(key => key.kid === activeKid)!;
51 + * const sealed = await new CompactEncrypt(new TextEncoder().encode(secret))
52 + * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: activeKid })
53 + * .encrypt(await importJWK(jwk, 'RSA-OAEP-256'));
54 + * ```
55 + */
56 + async listTransferKeys(
57 + requestOptions?: ComposioRequestOptions
58 + ): Promise<KeyringTransferKeysResponse> {
59 + const result = await withCancellation(
60 + () => this.client.keyring.listTransferKeys(requestOptions),
61 + requestOptions?.signal
62 + );
63 + return transformKeyringTransferKeysResponse(result);
64 + }
65 +}
ts/packages/core/src/models/Logs.ts new
+101
@@ -0,0 +1,101 @@
1 +/**
2 + * @fileoverview The `composio.logs` namespace: search and inspect
3 + * tool-execution logs for the project.
4 + *
5 + * @module Logs
6 + */
7 +import ComposioClient from '@composio/client';
8 +import {
9 + LogSearchParams,
10 + LogSearchParamsSchema,
11 + LogSearchResponse,
12 + ToolExecutionLogDetail,
13 +} from '../types/logs.types';
14 +import { ComposioRequestOptions } from '../types/requestOptions.types';
15 +import { ValidationError } from '../errors/ValidationErrors';
16 +import { telemetry } from '../telemetry/Telemetry';
17 +import { withCancellation } from '../utils/cancellation';
18 +import {
19 + transformLogSearchParams,
20 + transformLogSearchResponse,
21 + transformToolExecutionLogDetail,
22 +} from '../utils/transformers/logs';
23 +
24 +/**
25 + * `composio.logs` — tool-execution logs.
26 + *
27 + * @example
28 + * ```typescript
29 + * const { logs, nextCursor } = await composio.logs.search({
30 + * filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],
31 + * limit: 20,
32 + * });
33 + * const detail = await composio.logs.get(logs[0].id);
34 + * ```
35 + */
36 +export class Logs {
37 + private client: ComposioClient;
38 +
39 + constructor(client: ComposioClient) {
40 + this.client = client;
41 + telemetry.instrument(this, 'Logs');
42 + }
43 +
44 + /**
45 + * Search tool-execution logs with filters, a time range and cursor
46 + * pagination.
47 + *
48 + * @param {LogSearchParams} [params] - Filters, `timeRange`, `limit` and `cursor`
49 + * @returns {Promise<LogSearchResponse>} Matching logs and the next cursor
50 + * @throws {ValidationError} If the params fail validation
51 + *
52 + * @example
53 + * ```typescript
54 + * const { logs } = await composio.logs.search({
55 + * filters: [
56 + * { field: 'status', operator: '==', value: 'failed' },
57 + * { field: 'user_id', operator: '==', value: 'user_123' },
58 + * ],
59 + * timeRange: { from: Date.now() - 24 * 60 * 60 * 1000, to: Date.now() },
60 + * });
61 + * ```
62 + */
63 + async search(
64 + params?: LogSearchParams,
65 + requestOptions?: ComposioRequestOptions
66 + ): Promise<LogSearchResponse> {
67 + const parsedParams = LogSearchParamsSchema.safeParse(params ?? {});
68 + if (!parsedParams.success) {
69 + throw new ValidationError('Failed to parse log search params', {
70 + cause: parsedParams.error,
71 + });
72 + }
73 + const body = transformLogSearchParams(parsedParams.data);
74 + const result = await withCancellation(
75 + () => this.client.logs.createToolExecution(body, requestOptions),
76 + requestOptions?.signal
77 + );
78 + return transformLogSearchResponse(result);
79 + }
80 +
81 + /**
82 + * Retrieve one tool-execution log with its full detail (timings, context,
83 + * source and raw `data`).
84 + *
85 + * @param {string} id - The log id
86 + * @returns {Promise<ToolExecutionLogDetail>} The log detail
87 + *
88 + * @example
89 + * ```typescript
90 + * const log = await composio.logs.get('log_abc123');
91 + * console.log(log.status, log.timings?.endTime);
92 + * ```
93 + */
94 + async get(id: string, requestOptions?: ComposioRequestOptions): Promise<ToolExecutionLogDetail> {
95 + const result = await withCancellation(
96 + () => this.client.logs.retrieveToolExecution(id, requestOptions),
97 + requestOptions?.signal
98 + );
99 + return transformToolExecutionLogDetail(result);
100 + }
101 +}
ts/packages/core/src/models/ToolRouterSession.ts
+52
@@ -26,6 +26,9 @@ import {
26 ToolRouterSessionEnsureConnectedOptions,
27 ToolRouterSessionEnsureConnectedOptionsSchema,
28 ToolRouterSessionEnsureConnectedResult,
29 + ToolRouterSessionListConfigHistoryOptions,
30 + ToolRouterSessionListConfigHistoryOptionsSchema,
31 + type ToolRouterSessionListConfigHistoryResponse,
32 type ToolRouterSessionDeleteResponse,
33 } from '../types/toolRouter.types';
34 import {
@@ -154,6 +157,7 @@ export class ToolRouterSession<
157 execute: {},
158 search: {},
159 preload: { tools: [] },
160 + premium_usage: false,
161 };
162 if (customToolsMap && !userId) {
163 throw new Error('userId is required when custom tools are bound to a session.');
@@ -789,6 +793,54 @@ export class ToolRouterSession<
793 return deleteToolRouterSession(this.client, this.sessionId, requestOptions);
794 }
795
796 + /**
797 + * Page through this session's configuration history, newest first. The
798 + * first page starts with the live config (`isCurrent: true`); every
799 + * `session.update()` archives the previous version as a history row.
800 + *
801 + * @param options - Optional `cursor` and `limit` (max 100)
802 + * @returns The config versions on this page plus pagination info
803 + * @throws {ValidationError} If the options fail validation
804 + *
805 + * @example
806 + * ```typescript
807 + * const { items, nextCursor } = await session.listConfigHistory({ limit: 10 });
808 + * console.log(items[0].version, items[0].isCurrent); // e.g. 3, true
809 + * console.log(items[1].config.toolkits);
810 + * ```
811 + */
812 + async listConfigHistory(
813 + options?: ToolRouterSessionListConfigHistoryOptions,
814 + requestOptions?: ComposioRequestOptions
815 + ): Promise<ToolRouterSessionListConfigHistoryResponse> {
816 + const parsedOptions = ToolRouterSessionListConfigHistoryOptionsSchema.safeParse(options ?? {});
817 + if (!parsedOptions.success) {
818 + throw new ValidationError('Failed to parse config history options', {
819 + cause: parsedOptions.error,
820 + });
821 + }
822 + const query = {
823 + cursor: parsedOptions.data.cursor,
824 + limit: parsedOptions.data.limit,
825 + };
826 + const response = await withCancellation(
827 + () => this.client.toolRouter.session.configHistory(this.sessionId, query, requestOptions),
828 + requestOptions?.signal
829 + );
830 + return {
831 + items: response.items.map(item => ({
832 + version: item.version,
833 + createdAt: item.created_at,
834 + isCurrent: item.is_current,
835 + config: item.config,
836 + })),
837 + nextCursor: response.next_cursor ?? null,
838 + totalPages: response.total_pages,
839 + currentPage: response.current_page,
840 + totalItems: response.total_items,
841 + };
842 + }
843 +
844 // ── Private helpers ──────────────────────────────────────────
845
846 /** Check if this session has any custom tools bound. */
ts/packages/core/src/models/Toolkits.ts
+180
@@ -6,6 +6,16 @@ import {
6 ToolkitsListParamsSchema,
7 ToolkitRetrieveCategoriesResponse,
8 ToolkitAuthFieldsResponse,
9 + ToolkitGetManyParams,
10 + ToolkitGetManySlugsSchema,
11 + ToolkitsGetManyParamsSchema,
12 + ToolkitChangelogResponse,
13 + ToolkitRecommendScopesParams,
14 + ToolkitRecommendScopesParamsSchema,
15 + ToolkitRecommendScopesResponse,
16 + ToolkitListGrantContextsParams,
17 + ToolkitListGrantContextsParamsSchema,
18 + ToolkitListGrantContextsResponse,
19 } from '../types/toolkit.types';
20 import { ComposioToolkitFetchError, ComposioToolkitNotFoundError } from '../errors';
21 import { ValidationError } from '../errors/ValidationErrors';
@@ -17,7 +27,12 @@ import { telemetry } from '../telemetry/Telemetry';
27 import { AuthSchemeType } from '../types/authConfigs.types';
28 import logger from '../utils/logger';
29 import {
30 + transformToolkitChangelogResponse,
31 + transformToolkitListGrantContextsParams,
32 + transformToolkitListGrantContextsResponse,
33 transformToolkitListResponse,
34 + transformToolkitRecommendScopesParams,
35 + transformToolkitRecommendScopesResponse,
36 transformToolkitRetrieveCategoriesResponse,
37 transformToolkitRetrieveResponse,
38 } from '../utils/transformers/toolkits';
@@ -190,6 +205,171 @@ export class Toolkits {
205 return this.getToolkits(arg ?? {}, requestOptions);
206 }
207
208 + /**
209 + * Retrieves several toolkits by slug in a single request.
210 + *
211 + * Returns the same transformed shape as `composio.toolkits.get({ ... })`.
212 + * Unknown slugs are simply absent from the result.
213 + *
214 + * @param {string[]} slugs - The toolkit slugs to retrieve (at least one)
215 + * @param {ToolkitGetManyParams} [params] - Optional filters and pagination, as for `list`
216 + * @returns {Promise<ToolKitListResponse>} The matching toolkits
217 + * @throws {ValidationError} If `slugs` is empty or the params fail validation
218 + * @throws {ComposioToolkitFetchError} If the request fails
219 + *
220 + * @example
221 + * ```typescript
222 + * const toolkits = await composio.toolkits.getMany(['github', 'slack']);
223 + * console.log(toolkits.map(toolkit => toolkit.name)); // ['GitHub', 'Slack']
224 + * ```
225 + */
226 + async getMany(
227 + slugs: string[],
228 + params?: ToolkitGetManyParams,
229 + requestOptions?: ComposioRequestOptions
230 + ): Promise<ToolKitListResponse> {
231 + const parsedSlugs = ToolkitGetManySlugsSchema.safeParse(slugs);
232 + if (!parsedSlugs.success) {
233 + throw new ValidationError('Failed to parse toolkit slugs', {
234 + cause: parsedSlugs.error,
235 + });
236 + }
237 + const parsedParams = ToolkitsGetManyParamsSchema.safeParse(params ?? {});
238 + if (!parsedParams.success) {
239 + throw new ValidationError('Failed to parse toolkit getMany params', {
240 + cause: parsedParams.error,
241 + });
242 + }
243 + const body = {
244 + toolkits: parsedSlugs.data,
245 + category: parsedParams.data.category,
246 + managed_by: parsedParams.data.managedBy,
247 + sort_by: parsedParams.data.sortBy,
248 + cursor: parsedParams.data.cursor,
249 + limit: parsedParams.data.limit,
250 + };
251 + try {
252 + const result = await withCancellation(
253 + () => this.client.toolkits.retrieveMulti(body, requestOptions),
254 + requestOptions?.signal
255 + );
256 + return transformToolkitListResponse(result);
257 + } catch (error) {
258 + if (error instanceof ComposioRequestCancelledError) {
259 + throw error;
260 + }
261 + throw new ComposioToolkitFetchError('Failed to fetch toolkits', {
262 + meta: { slugs: parsedSlugs.data },
263 + cause: error,
264 + });
265 + }
266 + }
267 +
268 + /**
269 + * Retrieves the version changelog of every toolkit (the last 10 versions
270 + * per toolkit).
271 + *
272 + * @returns {Promise<ToolkitChangelogResponse>} Toolkits with their recent version changelogs
273 + *
274 + * @example
275 + * ```typescript
276 + * const { items } = await composio.toolkits.changelog();
277 + * const github = items.find(item => item.slug === 'github');
278 + * console.log(github?.versions[0]); // { version: '20250909_00', changelog: '...' }
279 + * ```
280 + */
281 + async changelog(requestOptions?: ComposioRequestOptions): Promise<ToolkitChangelogResponse> {
282 + const result = await withCancellation(
283 + () => this.client.toolkits.retrieveChangelog(requestOptions),
284 + requestOptions?.signal
285 + );
286 + return transformToolkitChangelogResponse(result);
287 + }
288 +
289 + /**
290 + * Recommends the OAuth scopes to request so a connection can run the given
291 + * tools.
292 + * **Experimental — the API marks this endpoint beta; shape may change.**
293 + *
294 + * The answer comes in two variants: `leastPrivilege` (narrowest documented
295 + * scope per requirement) and `fewest` (smallest set covering everything).
296 + * Pass `toolkitVersion` from a previous answer to pin the computation.
297 + *
298 + * @param {string} toolkitSlug - The toolkit to recommend scopes for
299 + * @param {ToolkitRecommendScopesParams} params - Tools to cover (`[]` for the whole toolkit), auth scheme, grant context and scope constraints
300 + * @returns {Promise<ToolkitRecommendScopesResponse>} The recommended scope sets
301 + * @throws {ValidationError} If the params fail validation
302 + *
303 + * @example
304 + * ```typescript
305 + * const { scopes } = await composio.toolkits.recommendScopes('gmail', {
306 + * tools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],
307 + * });
308 + * console.log(scopes.leastPrivilege);
309 + * ```
310 + */
311 + async recommendScopes(
312 + toolkitSlug: string,
313 + params: ToolkitRecommendScopesParams,
314 + requestOptions?: ComposioRequestOptions
315 + ): Promise<ToolkitRecommendScopesResponse> {
316 + const parsedParams = ToolkitRecommendScopesParamsSchema.safeParse(params);
317 + if (!parsedParams.success) {
318 + throw new ValidationError('Failed to parse toolkit recommendScopes params', {
319 + cause: parsedParams.error,
320 + });
321 + }
322 + const body = transformToolkitRecommendScopesParams(parsedParams.data);
323 + const result = await withCancellation(
324 + () => this.client.toolkits.recommendScopes(toolkitSlug, body, requestOptions),
325 + requestOptions?.signal
326 + );
327 + return transformToolkitRecommendScopesResponse(result);
328 + }
329 +
330 + /**
331 + * Lists the grant-context dimensions a toolkit's scope recommendation
332 + * depends on (for example the Google account type), with their allowed
333 + * values and the default the API assumes.
334 + * **Experimental — the API marks this endpoint beta; shape may change.**
335 + *
336 + * Pass a dimension and a value as `grantContext` to
337 + * `composio.toolkits.recommendScopes()` to tailor the recommendation.
338 + *
339 + * @param {string} toolkitSlug - The toolkit to list grant contexts for
340 + * @param {ToolkitListGrantContextsParams} [params] - Optional auth scheme and toolkit version
341 + * @returns {Promise<ToolkitListGrantContextsResponse>} The dimensions and the default grant context
342 + * @throws {ValidationError} If the params fail validation
343 + *
344 + * @example
345 + * ```typescript
346 + * const { grantContextDimensions } = await composio.toolkits.listGrantContexts('gmail');
347 + * const [accountType] = grantContextDimensions;
348 + * const { scopes } = await composio.toolkits.recommendScopes('gmail', {
349 + * tools: ['GMAIL_SEND_EMAIL'],
350 + * grantContext: { [accountType.dimension]: accountType.values[0] },
351 + * });
352 + * ```
353 + */
354 + async listGrantContexts(
355 + toolkitSlug: string,
356 + params?: ToolkitListGrantContextsParams,
357 + requestOptions?: ComposioRequestOptions
358 + ): Promise<ToolkitListGrantContextsResponse> {
359 + const parsedParams = ToolkitListGrantContextsParamsSchema.safeParse(params ?? {});
360 + if (!parsedParams.success) {
361 + throw new ValidationError('Failed to parse toolkit listGrantContexts params', {
362 + cause: parsedParams.error,
363 + });
364 + }
365 + const query = transformToolkitListGrantContextsParams(parsedParams.data);
366 + const result = await withCancellation(
367 + () => this.client.toolkits.retrieveScopesGrantContext(toolkitSlug, query, requestOptions),
368 + requestOptions?.signal
369 + );
370 + return transformToolkitListGrantContextsResponse(result);
371 + }
372 +
373 private async getAuthConfigFields(
374 toolkitSlug: string,
375 authScheme: AuthSchemeType | null,
ts/packages/core/src/models/Tools.ts
+3 -1
@@ -541,7 +541,9 @@ export class Tools<
541 ...(limit ? { limit } : {}),
542 ...('tags' in queryParams.data ? { tags: queryParams.data.tags } : {}),
543 ...('scopes' in queryParams.data ? { scopes: queryParams.data.scopes } : {}),
544 - ...('search' in queryParams.data ? { search: queryParams.data.search } : {}),
544 + // `search` is the SDK's public option; the API deprecated the `search`
545 + // wire param in favour of `query`, so send the replacement.
546 + ...('search' in queryParams.data ? { query: queryParams.data.search } : {}),
547 ...('authConfigIds' in queryParams.data
548 ? { auth_config_ids: queryParams.data.authConfigIds }
549 : {}),
ts/packages/core/src/models/Triggers.ts
+2 -87
@@ -33,11 +33,10 @@ import {
33 WebhookTriggerPayloadV3Schema,
34 WebhookVersion,
35 WebhookVersions,
36 - DefaultWebhookSubscriptionEvents,
36 SetWebhookSubscriptionParams,
38 - SetWebhookSubscriptionParamsSchema,
37 WebhookSubscription,
38 } from '../types/triggers.types';
39 +import { upsertWebhookSubscription } from './Webhooks';
40 import logger from '../utils/logger';
41 import { telemetry } from '../telemetry/Telemetry';
42 import { ValidationError } from '../errors';
@@ -75,63 +74,6 @@ const toStringOrDefault = (value: unknown, defaultValue: string): string => {
74 return str.length > 0 ? str : defaultValue;
75 };
76
78 -const WEBHOOK_SUBSCRIPTIONS_PATH = '/api/v3.1/webhook_subscriptions';
79 -
80 -type RawWebhookSubscription = Record<string, unknown> & {
81 - id?: unknown;
82 - webhook_url?: unknown;
83 - webhookUrl?: unknown;
84 - version?: unknown;
85 - enabled_events?: unknown;
86 - enabledEvents?: unknown;
87 - secret?: unknown;
88 - created_at?: unknown;
89 - createdAt?: unknown;
90 - updated_at?: unknown;
91 - updatedAt?: unknown;
92 -};
93 -
94 -type RawWebhookSubscriptionListResponse = Record<string, unknown> & {
95 - items?: unknown;
96 -};
97 -
98 -const asRecord = (value: unknown): Record<string, unknown> =>
99 - value !== null && typeof value === 'object' && !Array.isArray(value)
100 - ? (value as Record<string, unknown>)
101 - : {};
102 -
103 -const firstString = (value: unknown): string | undefined =>
104 - typeof value === 'string' && value.length > 0 ? value : undefined;
105 -
106 -const stringArray = (value: unknown): string[] =>
107 - Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
108 -
109 -const transformWebhookSubscription = (subscription: unknown): WebhookSubscription => {
110 - const raw = asRecord(subscription) as RawWebhookSubscription;
111 -
112 - // Map to camelCase explicitly — do NOT spread `...raw`, or the response's
113 - // snake_case keys (webhook_url, enabled_events, created_at, ...) leak into the
114 - // public object alongside their camelCase counterparts.
115 - return {
116 - id: firstString(raw.id) ?? '',
117 - webhookUrl: firstString(raw.webhook_url) ?? firstString(raw.webhookUrl) ?? '',
118 - version: (firstString(raw.version) ?? WebhookVersions.V3) as WebhookVersion,
119 - enabledEvents: stringArray(raw.enabled_events).length
120 - ? stringArray(raw.enabled_events)
121 - : stringArray(raw.enabledEvents),
122 - secret: firstString(raw.secret),
123 - createdAt: firstString(raw.created_at) ?? firstString(raw.createdAt),
124 - updatedAt: firstString(raw.updated_at) ?? firstString(raw.updatedAt),
125 - };
126 -};
127 -
128 -const firstWebhookSubscriptionId = (
129 - response: RawWebhookSubscriptionListResponse
130 -): string | undefined => {
131 - const firstItem = Array.isArray(response.items) ? response.items[0] : undefined;
132 - return firstString(asRecord(firstItem).id);
133 -};
134 -
77 /**
78 * The signature header names Composio sends with every webhook delivery.
79 * @private
@@ -234,34 +176,7 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
176 * ```
177 */
178 async setWebhookSubscription(params: SetWebhookSubscriptionParams): Promise<WebhookSubscription> {
237 - const parsedParams = SetWebhookSubscriptionParamsSchema.safeParse(params);
238 -
239 - if (!parsedParams.success) {
240 - throw new ValidationError(`Invalid parameters passed to set webhook subscription`, {
241 - cause: parsedParams.error,
242 - });
243 - }
244 -
245 - const body = {
246 - webhook_url: parsedParams.data.webhookUrl,
247 - enabled_events: parsedParams.data.enabledEvents ?? [...DefaultWebhookSubscriptionEvents],
248 - version: parsedParams.data.version ?? WebhookVersions.V3,
249 - };
250 -
251 - const existing = await this.client.get<RawWebhookSubscriptionListResponse>(
252 - WEBHOOK_SUBSCRIPTIONS_PATH,
253 - { query: { limit: 1 } }
254 - );
255 - const subscriptionId = firstWebhookSubscriptionId(existing);
256 -
257 - const subscription = subscriptionId
258 - ? await this.client.patch<RawWebhookSubscription>(
259 - `${WEBHOOK_SUBSCRIPTIONS_PATH}/${encodeURIComponent(subscriptionId)}`,
260 - { body }
261 - )
262 - : await this.client.post<RawWebhookSubscription>(WEBHOOK_SUBSCRIPTIONS_PATH, { body });
263 -
264 - return transformWebhookSubscription(subscription);
179 + return upsertWebhookSubscription(this.client, params);
180 }
181
182 /**
ts/packages/core/src/models/Usage.ts new
+119
@@ -0,0 +1,119 @@
1 +/**
2 + * @fileoverview `composio.experimental.usage`: project-scoped metering.
3 + * **Experimental — shape may change in future releases.**
4 + *
5 + * @module Usage
6 + */
7 +import ComposioClient from '@composio/client';
8 +import {
9 + UsageBreakdownParams,
10 + UsageBreakdownParamsSchema,
11 + UsageBreakdownResponse,
12 + UsageSummaryParams,
13 + UsageSummaryParamsSchema,
14 + UsageSummaryResponse,
15 +} from '../types/usage.types';
16 +import { ComposioRequestOptions } from '../types/requestOptions.types';
17 +import { ValidationError } from '../errors/ValidationErrors';
18 +import { telemetry } from '../telemetry/Telemetry';
19 +import { withCancellation } from '../utils/cancellation';
20 +import {
21 + transformUsageBreakdownParams,
22 + transformUsageBreakdownResponse,
23 + transformUsageSummaryParams,
24 + transformUsageSummaryResponse,
25 +} from '../utils/transformers/usage';
26 +
27 +/**
28 + * `composio.experimental.usage` — metering for the project the API key
29 + * belongs to. **Experimental — shape may change in future releases.**
30 + *
31 + * @example
32 + * ```typescript
33 + * const summary = await composio.experimental.usage.summary();
34 + * console.log(summary.entities.tool_calls?.totalQuantity);
35 + *
36 + * const byTool = await composio.experimental.usage.breakdown('tool_calls', {
37 + * groupBy: 'tool_slug',
38 + * limit: 10,
39 + * });
40 + * ```
41 + */
42 +export class Usage {
43 + private client: ComposioClient;
44 +
45 + constructor(client: ComposioClient) {
46 + this.client = client;
47 + telemetry.instrument(this, 'Usage');
48 + }
49 +
50 + /**
51 + * Usage totals per metering entity type for a time range.
52 + * **Experimental — shape may change in future releases.**
53 + *
54 + * @param {UsageSummaryParams} [params] - Optional range, `entityTypes` and filters
55 + * @returns {Promise<UsageSummaryResponse>} Totals keyed by entity type
56 + * @throws {ValidationError} If the params fail validation
57 + *
58 + * @example
59 + * ```typescript
60 + * const summary = await composio.experimental.usage.summary({
61 + * from: Date.now() - 7 * 24 * 60 * 60 * 1000,
62 + * filters: { userId: ['user_123'] },
63 + * });
64 + * ```
65 + */
66 + async summary(
67 + params?: UsageSummaryParams,
68 + requestOptions?: ComposioRequestOptions
69 + ): Promise<UsageSummaryResponse> {
70 + const parsedParams = UsageSummaryParamsSchema.safeParse(params ?? {});
71 + if (!parsedParams.success) {
72 + throw new ValidationError('Failed to parse usage summary params', {
73 + cause: parsedParams.error,
74 + });
75 + }
76 + const body = transformUsageSummaryParams(parsedParams.data);
77 + const result = await withCancellation(
78 + () => this.client.project.usage.retrieveSummary(body, requestOptions),
79 + requestOptions?.signal
80 + );
81 + return transformUsageSummaryResponse(result);
82 + }
83 +
84 + /**
85 + * Usage for one metering entity type, grouped by a dimension.
86 + * **Experimental — shape may change in future releases.**
87 + *
88 + * @param {string} entityType - Entity type to break down (e.g. `tool_calls`, `sessions`)
89 + * @param {UsageBreakdownParams} [params] - Optional range, `groupBy`, ordering, `limit` and filters
90 + * @returns {Promise<UsageBreakdownResponse>} Totals plus per-group rows
91 + * @throws {ValidationError} If the params fail validation
92 + *
93 + * @example
94 + * ```typescript
95 + * const byUser = await composio.experimental.usage.breakdown('sessions', {
96 + * groupBy: 'user_id',
97 + * orderBy: 'event_count',
98 + * });
99 + * ```
100 + */
101 + async breakdown(
102 + entityType: string,
103 + params?: UsageBreakdownParams,
104 + requestOptions?: ComposioRequestOptions
105 + ): Promise<UsageBreakdownResponse> {
106 + const parsedParams = UsageBreakdownParamsSchema.safeParse(params ?? {});
107 + if (!parsedParams.success) {
108 + throw new ValidationError('Failed to parse usage breakdown params', {
109 + cause: parsedParams.error,
110 + });
111 + }
112 + const body = transformUsageBreakdownParams(parsedParams.data);
113 + const result = await withCancellation(
114 + () => this.client.project.usage.retrieve(entityType, body, requestOptions),
115 + requestOptions?.signal
116 + );
117 + return transformUsageBreakdownResponse(result);
118 + }
119 +}
ts/packages/core/src/models/Webhooks.ts new
+520
@@ -0,0 +1,520 @@
1 +/**
2 + * @fileoverview The `composio.webhooks` namespace: project webhook
3 + * subscriptions (outbound event delivery) and webhook endpoints (inbound
4 + * per-toolkit ingress URLs).
5 + *
6 + * @module Webhooks
7 + */
8 +import ComposioClient from '@composio/client';
9 +import { z } from 'zod/v3';
10 +import {
11 + DefaultWebhookSubscriptionEvents,
12 + WebhookSubscription,
13 + WebhookVersions,
14 +} from '../types/triggers.types';
15 +import {
16 + WebhookEndpoint,
17 + WebhookEndpointCreateParams,
18 + WebhookEndpointCreateParamsSchema,
19 + WebhookEndpointListParams,
20 + WebhookEndpointListParamsSchema,
21 + WebhookEndpointListResponse,
22 + WebhookEndpointReplaceParams,
23 + WebhookEndpointReplaceParamsSchema,
24 + WebhookEndpointUpdateParams,
25 + WebhookEndpointUpdateParamsSchema,
26 + WebhookSubscriptionEventTypesResponse,
27 + WebhookSubscriptionDeleteResponse,
28 + WebhookSubscriptionListParams,
29 + WebhookSubscriptionListParamsSchema,
30 + WebhookSubscriptionListResponse,
31 + WebhookSubscriptionRotateSecretResponse,
32 + WebhookSubscriptionSetParams,
33 + WebhookSubscriptionSetParamsSchema,
34 + WebhookSubscriptionUpdateParams,
35 + WebhookSubscriptionUpdateParamsSchema,
36 +} from '../types/webhooks.types';
37 +import { ComposioRequestOptions } from '../types/requestOptions.types';
38 +import { ValidationError } from '../errors/ValidationErrors';
39 +import { telemetry } from '../telemetry/Telemetry';
40 +import { withCancellation } from '../utils/cancellation';
41 +import {
42 + transformWebhookEndpoint,
43 + transformWebhookEndpointListResponse,
44 + transformWebhookSubscriptionEventTypesResponse,
45 + transformWebhookSubscription,
46 + transformWebhookSubscriptionDeleteResponse,
47 + transformWebhookSubscriptionListResponse,
48 + transformWebhookSubscriptionRotateSecretResponse,
49 +} from '../utils/transformers/webhooks';
50 +
51 +/**
52 + * The only part of the `list({ limit: 1 })` probe the upsert needs: the id of
53 + * the first (and, since the API allows one subscription per project, only)
54 + * subscription. Parsed at the boundary so a malformed payload never reaches
55 + * the update path.
56 + */
57 +const FirstWebhookSubscriptionIdSchema = z
58 + .object({
59 + items: z.array(z.object({ id: z.string().min(1) }).passthrough()),
60 + })
61 + .passthrough()
62 + .transform(response => response.items[0]?.id);
63 +
64 +/**
65 + * Create-or-update the project webhook subscription.
66 + *
67 + * Shared by `composio.webhooks.subscriptions.set()` and the legacy
68 + * `composio.triggers.setWebhookSubscription()` so both issue the exact same
69 + * call sequence: `webhookSubscriptions.list({ limit: 1 })`, then
70 + * `webhookSubscriptions.update(id, body)` when a subscription exists,
71 + * otherwise `webhookSubscriptions.create(body)`.
72 + *
73 + * @internal
74 + */
75 +export async function upsertWebhookSubscription(
76 + client: ComposioClient,
77 + params: WebhookSubscriptionSetParams,
78 + requestOptions?: ComposioRequestOptions
79 +): Promise<WebhookSubscription> {
80 + const parsedParams = WebhookSubscriptionSetParamsSchema.safeParse(params);
81 +
82 + if (!parsedParams.success) {
83 + throw new ValidationError(`Invalid parameters passed to set webhook subscription`, {
84 + cause: parsedParams.error,
85 + });
86 + }
87 +
88 + const body = {
89 + webhook_url: parsedParams.data.webhookUrl,
90 + enabled_events: parsedParams.data.enabledEvents ?? [...DefaultWebhookSubscriptionEvents],
91 + version: parsedParams.data.version ?? WebhookVersions.V3,
92 + };
93 +
94 + const existing = await withCancellation(
95 + () => client.webhookSubscriptions.list({ limit: 1 }, requestOptions),
96 + requestOptions?.signal
97 + );
98 + const parsedExisting = FirstWebhookSubscriptionIdSchema.safeParse(existing);
99 + if (!parsedExisting.success) {
100 + throw new ValidationError('Failed to parse webhook subscription list response', {
101 + cause: parsedExisting.error,
102 + });
103 + }
104 + const subscriptionId = parsedExisting.data;
105 +
106 + const subscription = await withCancellation(
107 + () =>
108 + subscriptionId
109 + ? client.webhookSubscriptions.update(subscriptionId, body, requestOptions)
110 + : client.webhookSubscriptions.create(body, requestOptions),
111 + requestOptions?.signal
112 + );
113 +
114 + return transformWebhookSubscription(subscription);
115 +}
116 +
117 +/**
118 + * `composio.webhooks.subscriptions` — the project's outbound webhook
119 + * subscription. The API allows one subscription per project; every response
120 + * includes the signing `secret` used to verify deliveries with
121 + * `composio.triggers.verifyWebhook()` / `composio.triggers.parse()`.
122 + */
123 +export class WebhookSubscriptions {
124 + private client: ComposioClient;
125 +
126 + constructor(client: ComposioClient) {
127 + this.client = client;
128 + telemetry.instrument(this, 'WebhookSubscriptions');
129 + }
130 +
131 + /**
132 + * List the project's webhook subscriptions.
133 + *
134 + * @param {WebhookSubscriptionListParams} [query] - Pagination options
135 + * @returns {Promise<WebhookSubscriptionListResponse>} Paginated subscriptions
136 + *
137 + * @example
138 + * ```typescript
139 + * const { items } = await composio.webhooks.subscriptions.list();
140 + * console.log(items[0]?.webhookUrl);
141 + * ```
142 + */
143 + async list(
144 + query?: WebhookSubscriptionListParams,
145 + requestOptions?: ComposioRequestOptions
146 + ): Promise<WebhookSubscriptionListResponse> {
147 + const parsedQuery = WebhookSubscriptionListParamsSchema.safeParse(query ?? {});
148 + if (!parsedQuery.success) {
149 + throw new ValidationError('Failed to parse webhook subscription list query', {
150 + cause: parsedQuery.error,
151 + });
152 + }
153 + const listParams = {
154 + limit: parsedQuery.data.limit,
155 + cursor: parsedQuery.data.cursor,
156 + };
157 + const result = await withCancellation(
158 + () => this.client.webhookSubscriptions.list(listParams, requestOptions),
159 + requestOptions?.signal
160 + );
161 + return transformWebhookSubscriptionListResponse(result);
162 + }
163 +
164 + /**
165 + * Retrieve a webhook subscription by id.
166 + *
167 + * @param {string} id - The subscription id
168 + * @returns {Promise<WebhookSubscription>} The subscription, including its signing secret
169 + *
170 + * @example
171 + * ```typescript
172 + * const subscription = await composio.webhooks.subscriptions.get('whs_abc123');
173 + * console.log(subscription.enabledEvents);
174 + * ```
175 + */
176 + async get(id: string, requestOptions?: ComposioRequestOptions): Promise<WebhookSubscription> {
177 + const result = await withCancellation(
178 + () => this.client.webhookSubscriptions.retrieve(id, requestOptions),
179 + requestOptions?.signal
180 + );
181 + return transformWebhookSubscription(result);
182 + }
183 +
184 + /**
185 + * Create or update the project webhook subscription.
186 + *
187 + * If a subscription already exists it is updated in place, otherwise a new
188 + * one is created. By default this subscribes to V3 trigger message events.
189 + *
190 + * @param {WebhookSubscriptionSetParams} params - `webhookUrl`, optional `enabledEvents` and `version`
191 + * @returns {Promise<WebhookSubscription>} The resulting subscription
192 + * @throws {ValidationError} If the params fail validation
193 + *
194 + * @example
195 + * ```typescript
196 + * const subscription = await composio.webhooks.subscriptions.set({
197 + * webhookUrl: `${APP_URL}/webhooks/composio`,
198 + * enabledEvents: ['composio.trigger.message', 'composio.connected_account.expired'],
199 + * });
200 + * process.env.COMPOSIO_WEBHOOK_SECRET = subscription.secret;
201 + * ```
202 + */
203 + async set(
204 + params: WebhookSubscriptionSetParams,
205 + requestOptions?: ComposioRequestOptions
206 + ): Promise<WebhookSubscription> {
207 + return upsertWebhookSubscription(this.client, params, requestOptions);
208 + }
209 +
210 + /**
211 + * Update an existing webhook subscription. Only the provided fields change.
212 + *
213 + * @param {string} id - The subscription id
214 + * @param {WebhookSubscriptionUpdateParams} params - Fields to update
215 + * @returns {Promise<WebhookSubscription>} The updated subscription
216 + * @throws {ValidationError} If the params fail validation
217 + *
218 + * @example
219 + * ```typescript
220 + * await composio.webhooks.subscriptions.update('whs_abc123', {
221 + * enabledEvents: ['composio.trigger.message'],
222 + * });
223 + * ```
224 + */
225 + async update(
226 + id: string,
227 + params: WebhookSubscriptionUpdateParams,
228 + requestOptions?: ComposioRequestOptions
229 + ): Promise<WebhookSubscription> {
230 + const parsedParams = WebhookSubscriptionUpdateParamsSchema.safeParse(params);
231 + if (!parsedParams.success) {
232 + throw new ValidationError('Failed to parse webhook subscription update params', {
233 + cause: parsedParams.error,
234 + });
235 + }
236 + const body = {
237 + webhook_url: parsedParams.data.webhookUrl,
238 + enabled_events: parsedParams.data.enabledEvents,
239 + version: parsedParams.data.version,
240 + };
241 + const result = await withCancellation(
242 + () => this.client.webhookSubscriptions.update(id, body, requestOptions),
243 + requestOptions?.signal
244 + );
245 + return transformWebhookSubscription(result);
246 + }
247 +
248 + /**
249 + * Delete a webhook subscription. Deliveries stop immediately.
250 + *
251 + * @param {string} id - The subscription id
252 + * @returns {Promise<WebhookSubscriptionDeleteResponse>} `{ success }`
253 + *
254 + * @example
255 + * ```typescript
256 + * await composio.webhooks.subscriptions.delete('whs_abc123');
257 + * ```
258 + */
259 + async delete(
260 + id: string,
261 + requestOptions?: ComposioRequestOptions
262 + ): Promise<WebhookSubscriptionDeleteResponse> {
263 + const result = await withCancellation(
264 + () => this.client.webhookSubscriptions.delete(id, requestOptions),
265 + requestOptions?.signal
266 + );
267 + return transformWebhookSubscriptionDeleteResponse(result);
268 + }
269 +
270 + /**
271 + * Rotate the signing secret of a webhook subscription. The previous secret
272 + * stops validating, so update your verifier with the returned `secret`.
273 + *
274 + * @param {string} id - The subscription id
275 + * @returns {Promise<WebhookSubscriptionRotateSecretResponse>} `{ id, secret }`
276 + *
277 + * @example
278 + * ```typescript
279 + * const { secret } = await composio.webhooks.subscriptions.rotateSecret('whs_abc123');
280 + * ```
281 + */
282 + async rotateSecret(
283 + id: string,
284 + requestOptions?: ComposioRequestOptions
285 + ): Promise<WebhookSubscriptionRotateSecretResponse> {
286 + const result = await withCancellation(
287 + () => this.client.webhookSubscriptions.rotateSecret(id, requestOptions),
288 + requestOptions?.signal
289 + );
290 + return transformWebhookSubscriptionRotateSecretResponse(result);
291 + }
292 +
293 + /**
294 + * List the event types a subscription can enable, with the payload
295 + * versions each one supports.
296 + *
297 + * @returns {Promise<WebhookSubscriptionEventTypesResponse>} The available event types
298 + *
299 + * @example
300 + * ```typescript
301 + * const { items } = await composio.webhooks.subscriptions.listEventTypes();
302 + * console.log(items.map(item => item.eventType));
303 + * ```
304 + */
305 + async listEventTypes(
306 + requestOptions?: ComposioRequestOptions
307 + ): Promise<WebhookSubscriptionEventTypesResponse> {
308 + const result = await withCancellation(
309 + () => this.client.webhookSubscriptions.listEventTypes(requestOptions),
310 + requestOptions?.signal
311 + );
312 + return transformWebhookSubscriptionEventTypesResponse(result);
313 + }
314 +}
315 +
316 +/**
317 + * `composio.webhooks.endpoints` — inbound webhook endpoints. Each endpoint is
318 + * the ingress URL Composio exposes for one toolkit + OAuth app pair, which you
319 + * register with the third-party provider so it can push events to Composio.
320 + */
321 +export class WebhookEndpoints {
322 + private client: ComposioClient;
323 +
324 + constructor(client: ComposioClient) {
325 + this.client = client;
326 + telemetry.instrument(this, 'WebhookEndpoints');
327 + }
328 +
329 + /**
330 + * List webhook endpoints, optionally filtered by toolkit.
331 + *
332 + * @param {WebhookEndpointListParams} [query] - Optional `toolkitSlug` filter
333 + * @returns {Promise<WebhookEndpointListResponse>} The endpoints
334 + *
335 + * @example
336 + * ```typescript
337 + * const { items } = await composio.webhooks.endpoints.list({ toolkitSlug: 'slack' });
338 + * ```
339 + */
340 + async list(
341 + query?: WebhookEndpointListParams,
342 + requestOptions?: ComposioRequestOptions
343 + ): Promise<WebhookEndpointListResponse> {
344 + const parsedQuery = WebhookEndpointListParamsSchema.safeParse(query ?? {});
345 + if (!parsedQuery.success) {
346 + throw new ValidationError('Failed to parse webhook endpoint list query', {
347 + cause: parsedQuery.error,
348 + });
349 + }
350 + const listParams = { toolkit_slug: parsedQuery.data.toolkitSlug };
351 + const result = await withCancellation(
352 + () => this.client.webhookEndpoints.list(listParams, requestOptions),
353 + requestOptions?.signal
354 + );
355 + return transformWebhookEndpointListResponse(result);
356 + }
357 +
358 + /**
359 + * Retrieve a webhook endpoint by its nano id.
360 + *
361 + * @param {string} nanoId - The endpoint nano id (e.g. `we_abc123`)
362 + * @returns {Promise<WebhookEndpoint>} The endpoint, with secret setup values masked
363 + *
364 + * @example
365 + * ```typescript
366 + * const endpoint = await composio.webhooks.endpoints.get('we_abc123');
367 + * console.log(endpoint.webhookUrl);
368 + * ```
369 + */
370 + async get(nanoId: string, requestOptions?: ComposioRequestOptions): Promise<WebhookEndpoint> {
371 + const result = await withCancellation(
372 + () => this.client.webhookEndpoints.retrieve(nanoId, requestOptions),
373 + requestOptions?.signal
374 + );
375 + return transformWebhookEndpoint(result);
376 + }
377 +
378 + /**
379 + * Create a webhook endpoint for a toolkit + OAuth app pair. Returns the
380 + * existing endpoint when one already exists for that pair.
381 + *
382 + * @param {WebhookEndpointCreateParams} params - `toolkitSlug` and `clientId`
383 + * @returns {Promise<WebhookEndpoint>} The endpoint; register `webhookUrl` with the provider
384 + * @throws {ValidationError} If the params fail validation
385 + *
386 + * @example
387 + * ```typescript
388 + * const endpoint = await composio.webhooks.endpoints.create({
389 + * toolkitSlug: 'slack',
390 + * clientId: 'my-slack-app-client-id',
391 + * });
392 + * ```
393 + */
394 + async create(
395 + params: WebhookEndpointCreateParams,
396 + requestOptions?: ComposioRequestOptions
397 + ): Promise<WebhookEndpoint> {
398 + const parsedParams = WebhookEndpointCreateParamsSchema.safeParse(params);
399 + if (!parsedParams.success) {
400 + throw new ValidationError('Failed to parse webhook endpoint create params', {
401 + cause: parsedParams.error,
402 + });
403 + }
404 + const body = {
405 + toolkit_slug: parsedParams.data.toolkitSlug,
406 + client_id: parsedParams.data.clientId,
407 + };
408 + const result = await withCancellation(
409 + () => this.client.webhookEndpoints.create(body, requestOptions),
410 + requestOptions?.signal
411 + );
412 + return transformWebhookEndpoint(result);
413 + }
414 +
415 + /**
416 + * Replace the setup fields of a webhook endpoint. All required setup fields
417 + * for the toolkit must be provided — this is the initial configuration.
418 + *
419 + * @param {string} nanoId - The endpoint nano id
420 + * @param {WebhookEndpointReplaceParams} params - `data` with every required setup field
421 + * @returns {Promise<WebhookEndpoint>} The configured endpoint
422 + * @throws {ValidationError} If the params fail validation
423 + *
424 + * @example
425 + * ```typescript
426 + * await composio.webhooks.endpoints.replace('we_abc123', {
427 + * data: { signing_secret: process.env.SLACK_SIGNING_SECRET! },
428 + * });
429 + * ```
430 + */
431 + async replace(
432 + nanoId: string,
433 + params: WebhookEndpointReplaceParams,
434 + requestOptions?: ComposioRequestOptions
435 + ): Promise<WebhookEndpoint> {
436 + const parsedParams = WebhookEndpointReplaceParamsSchema.safeParse(params);
437 + if (!parsedParams.success) {
438 + throw new ValidationError('Failed to parse webhook endpoint replace params', {
439 + cause: parsedParams.error,
440 + });
441 + }
442 + const result = await withCancellation(
443 + () =>
444 + this.client.webhookEndpoints.replace(
445 + nanoId,
446 + { data: parsedParams.data.data },
447 + requestOptions
448 + ),
449 + requestOptions?.signal
450 + );
451 + return transformWebhookEndpoint(result);
452 + }
453 +
454 + /**
455 + * Merge setup fields into a webhook endpoint. Omitted fields are preserved.
456 + *
457 + * @param {string} nanoId - The endpoint nano id
458 + * @param {WebhookEndpointUpdateParams} params - `data` with the fields to change
459 + * @returns {Promise<WebhookEndpoint>} The updated endpoint
460 + * @throws {ValidationError} If the params fail validation
461 + *
462 + * @example
463 + * ```typescript
464 + * await composio.webhooks.endpoints.update('we_abc123', {
465 + * data: { signing_secret: 'rotated-secret' },
466 + * });
467 + * ```
468 + */
469 + async update(
470 + nanoId: string,
471 + params: WebhookEndpointUpdateParams,
472 + requestOptions?: ComposioRequestOptions
473 + ): Promise<WebhookEndpoint> {
474 + const parsedParams = WebhookEndpointUpdateParamsSchema.safeParse(params);
475 + if (!parsedParams.success) {
476 + throw new ValidationError('Failed to parse webhook endpoint update params', {
477 + cause: parsedParams.error,
478 + });
479 + }
480 + const result = await withCancellation(
481 + () =>
482 + this.client.webhookEndpoints.update(
483 + nanoId,
484 + { data: parsedParams.data.data },
485 + requestOptions
486 + ),
487 + requestOptions?.signal
488 + );
489 + return transformWebhookEndpoint(result);
490 + }
491 +}
492 +
493 +/**
494 + * `composio.webhooks` namespace.
495 + *
496 + * - `subscriptions`: the project's outbound webhook subscription (where
497 + * Composio delivers trigger and lifecycle events).
498 + * - `endpoints`: inbound ingress URLs for third-party providers, one per
499 + * toolkit + OAuth app pair.
500 + *
501 + * @example
502 + * ```typescript
503 + * const subscription = await composio.webhooks.subscriptions.set({
504 + * webhookUrl: 'https://example.com/webhooks/composio',
505 + * });
506 + * const endpoints = await composio.webhooks.endpoints.list({ toolkitSlug: 'slack' });
507 + * ```
508 + */
509 +export class Webhooks {
510 + /** Manage the project's outbound webhook subscription. */
511 + subscriptions: WebhookSubscriptions;
512 + /** Manage inbound webhook endpoints per toolkit + OAuth app. */
513 + endpoints: WebhookEndpoints;
514 +
515 + constructor(client: ComposioClient) {
516 + this.subscriptions = new WebhookSubscriptions(client);
517 + this.endpoints = new WebhookEndpoints(client);
518 + telemetry.instrument(this, 'Webhooks');
519 + }
520 +}
ts/packages/core/src/types/authConfigs.types.ts
+2
@@ -20,6 +20,7 @@ export const AuthSchemeTypes = {
20 SERVICE_ACCOUNT: 'SERVICE_ACCOUNT',
21 SAML: 'SAML',
22 DCR_OAUTH: 'DCR_OAUTH',
23 + CIMD_OAUTH: 'CIMD_OAUTH',
24 S2S_OAUTH2: 'S2S_OAUTH2',
25 } as const;
26 export type AuthSchemeType = (typeof AuthSchemeTypes)[keyof typeof AuthSchemeTypes];
@@ -47,6 +48,7 @@ export const AuthSchemeEnum = z.enum([
48 'SERVICE_ACCOUNT',
49 'SAML',
50 'DCR_OAUTH',
51 + 'CIMD_OAUTH',
52 'S2S_OAUTH2',
53 ]);
54 export const CreateCustomAuthConfigParamsSchema = z.object({
ts/packages/core/src/types/connectedAccounts.types.ts
+54
@@ -356,6 +356,10 @@ export type CreateConnectedAccountLinkResponse = z.infer<
356
357 export const ConnectedAccountRefreshOptionsSchema = z.object({
358 redirectUrl: z.string().optional(),
359 + /**
360 + * @deprecated The Composio API no longer accepts this field. It is ignored
361 + * and `refresh()` logs a warning when it is set.
362 + */
363 validateCredentials: z.boolean().optional(),
364 });
365 export type ConnectedAccountRefreshOptions = z.infer<typeof ConnectedAccountRefreshOptionsSchema>;
@@ -393,3 +397,53 @@ export const UpdateConnectedAccountAclParamsSchema = ConnectedAccountAclConfigSc
397 }
398 );
399 export type UpdateConnectedAccountAclParams = z.infer<typeof UpdateConnectedAccountAclParamsSchema>;
400 +
401 +/**
402 + * Response of `composio.connectedAccounts.revoke()`.
403 + */
404 +export const ConnectedAccountRevokedTokenSchema = z.enum([
405 + 'access_token',
406 + 'refresh_token',
407 + 'credential',
408 +]);
409 +export type ConnectedAccountRevokedToken = z.infer<typeof ConnectedAccountRevokedTokenSchema>;
410 +
411 +export const ConnectedAccountRevokeResponseSchema = z.object({
412 + /**
413 + * Tokens revoked at the provider on this call. An empty array means the
414 + * connection was already revoked (no upstream dispatch).
415 + */
416 + revokedTokens: z.array(ConnectedAccountRevokedTokenSchema),
417 + connectedAccount: z.object({
418 + id: z.string(),
419 + /** The connection status after this call (`REVOKED` on success). */
420 + status: ConnectedAccountStatusSchema,
421 + }),
422 +});
423 +export type ConnectedAccountRevokeResponse = z.infer<typeof ConnectedAccountRevokeResponseSchema>;
424 +
425 +/**
426 + * Params for `composio.connectedAccounts.completeAuth()`.
427 + */
428 +export const ConnectedAccountCompleteAuthParamsSchema = z.object({
429 + /** The user the connection was initiated for. Must match the connection owner. */
430 + userId: z.string().min(1),
431 + /** The opaque, single-use session URI your OAuth callback verifier received. */
432 + sessionUri: z.string().min(1),
433 +});
434 +export type ConnectedAccountCompleteAuthParams = z.infer<
435 + typeof ConnectedAccountCompleteAuthParamsSchema
436 +>;
437 +
438 +/**
439 + * Response of `composio.connectedAccounts.completeAuth()`.
440 + */
441 +export const ConnectedAccountCompleteAuthResponseSchema = z.object({
442 + /** The connection that was completed; it is now `ACTIVE`. */
443 + connectedAccountId: z.string(),
444 + /** The toolkit the connection belongs to. */
445 + toolkitSlug: z.string(),
446 +});
447 +export type ConnectedAccountCompleteAuthResponse = z.infer<
448 + typeof ConnectedAccountCompleteAuthResponseSchema
449 +>;
ts/packages/core/src/types/customToolkits.types.ts new
+102
@@ -0,0 +1,102 @@
1 +import { z } from 'zod/v3';
2 +
3 +/**
4 + * How end users authenticate to a custom toolkit.
5 + * **Experimental — custom toolkits are in pilot; shape may change.**
6 + */
7 +export const CustomToolkitAuthSchemeSchema = z.discriminatedUnion('mode', [
8 + z.object({ mode: z.literal('NO_AUTH') }),
9 + z.object({
10 + mode: z.literal('API_KEY'),
11 + /**
12 + * Headers sent with each request. Write `{{generic_api_key}}` where the
13 + * end user's API key goes, for example
14 + * `{ Authorization: 'Bearer {{generic_api_key}}' }`.
15 + */
16 + headers: z.record(z.string(), z.string()),
17 + /** End-user copy for the API key input on the connect page. */
18 + apiKeyField: z
19 + .object({
20 + displayName: z.string().min(1).max(100).optional(),
21 + description: z.string().min(1).max(500).optional(),
22 + })
23 + .optional(),
24 + }),
25 + z.object({
26 + mode: z.literal('DCR_OAUTH'),
27 + /**
28 + * Where to fetch the full auth scheme, usually the
29 + * `/.well-known/oauth-authorization-server` path of your MCP URL.
30 + */
31 + discoveryUrl: z.string().url(),
32 + }),
33 +]);
34 +export type CustomToolkitAuthScheme = z.infer<typeof CustomToolkitAuthSchemeSchema>;
35 +
36 +/**
37 + * Params for `composio.experimental.customToolkits.upsert()`.
38 + * **Experimental — custom toolkits are in pilot; shape may change.**
39 + */
40 +export const CustomToolkitUpsertParamsSchema = z.object({
41 + /**
42 + * Letters, digits, underscores or spaces, up to 30 characters. The API
43 + * prefixes it with `CUSTOM_` and turns spaces into underscores.
44 + */
45 + slug: z
46 + .string()
47 + .min(1)
48 + .max(30)
49 + .regex(/^[a-zA-Z0-9_\s]+$/),
50 + toolkitConfig: z.object({
51 + /** Human-readable toolkit name. */
52 + name: z.string().min(1).max(200),
53 + /** The app URL. For an MCP app, the MCP server URL. */
54 + appUrl: z.string().url(),
55 + /** Square PNG or JPEG logo (256-1024px, max 3MB), base64-encoded. Defaults to the Composio logo. */
56 + logoFile: z
57 + .object({
58 + content: z.string().min(1),
59 + mimeType: z.enum(['image/png', 'image/jpeg']),
60 + })
61 + .optional(),
62 + /** At least one scheme. The schemes cannot change once the toolkit exists. */
63 + authSchemes: z.array(CustomToolkitAuthSchemeSchema).min(1),
64 + }),
65 +});
66 +export type CustomToolkitUpsertParams = z.infer<typeof CustomToolkitUpsertParamsSchema>;
67 +
68 +export const CustomToolkitUpsertResponseSchema = z.object({
69 + /** Slug of the created or updated toolkit. */
70 + slug: z.string(),
71 +});
72 +export type CustomToolkitUpsertResponse = z.infer<typeof CustomToolkitUpsertResponseSchema>;
73 +
74 +/**
75 + * Params for `composio.experimental.customToolkits.sync()`.
76 + * **Experimental — custom toolkits are in pilot; shape may change.**
77 + */
78 +export const CustomToolkitSyncParamsSchema = z.object({
79 + /** Connected account to use when fetching the remote tool definitions. */
80 + connectedAccountId: z.string().optional(),
81 +});
82 +export type CustomToolkitSyncParams = z.infer<typeof CustomToolkitSyncParamsSchema>;
83 +
84 +export const CustomToolkitSyncResponseSchema = z.object({
85 + slug: z.string(),
86 + /** Toolkit version after the sync. */
87 + version: z.string(),
88 + /** Number of tools synced. */
89 + syncedCount: z.number(),
90 +});
91 +export type CustomToolkitSyncResponse = z.infer<typeof CustomToolkitSyncResponseSchema>;
92 +
93 +export const CustomToolkitDeleteResponseSchema = z.object({
94 + /** Slug of the deleted toolkit. */
95 + slug: z.string(),
96 + deleted: z.boolean(),
97 + /** Background jobs revoking the credentials of the toolkit's connected accounts. */
98 + revokeJobIds: z.array(z.string()),
99 + authConfigsDeleted: z.number(),
100 + connectedAccountsDeleted: z.number(),
101 +});
102 +export type CustomToolkitDeleteResponse = z.infer<typeof CustomToolkitDeleteResponseSchema>;
ts/packages/core/src/types/keyring.types.ts new
+32
@@ -0,0 +1,32 @@
1 +import { z } from 'zod/v3';
2 +
3 +/**
4 + * A public JWK a secret can be sealed to. Fields keep their JWK names so a
5 + * key can be handed straight to WebCrypto or a JOSE library.
6 + */
7 +export const KeyringTransferKeySchema = z.object({
8 + /** Key type. Always `RSA`. */
9 + kty: z.string(),
10 + /** RSA modulus, base64url-encoded. */
11 + n: z.string(),
12 + /** RSA public exponent, base64url-encoded. */
13 + e: z.string(),
14 + /** Key-management algorithm for the JWE (`RSA-OAEP-256`). Pair it with `A256GCM` content encryption. */
15 + alg: z.string(),
16 + /** Key use. Always `enc`. */
17 + use: z.string(),
18 + /** Key identifier. Put it in the JWE protected header. */
19 + kid: z.string(),
20 +});
21 +export type KeyringTransferKey = z.infer<typeof KeyringTransferKeySchema>;
22 +
23 +/**
24 + * Response of `composio.keyring.listTransferKeys()`.
25 + */
26 +export const KeyringTransferKeysResponseSchema = z.object({
27 + /** The `kid` of the key to seal new secrets to. */
28 + activeKid: z.string(),
29 + /** Every currently accepted transfer key, newest first. */
30 + keys: z.array(KeyringTransferKeySchema),
31 +});
32 +export type KeyringTransferKeysResponse = z.infer<typeof KeyringTransferKeysResponseSchema>;
ts/packages/core/src/types/logs.types.ts new
+108
@@ -0,0 +1,108 @@
1 +import { z } from 'zod/v3';
2 +
3 +/**
4 + * Fields a tool-execution log search can filter on.
5 + */
6 +export const LogSearchFilterFieldSchema = z.enum([
7 + 'tool_slug',
8 + 'toolkit_slug',
9 + 'connected_account_id',
10 + 'auth_config_id',
11 + 'status',
12 + 'user_id',
13 + 'session_id',
14 + 'sandbox_id',
15 + 'request_id',
16 + 'log_id',
17 +]);
18 +export type LogSearchFilterField = z.infer<typeof LogSearchFilterFieldSchema>;
19 +
20 +export const LogSearchFilterOperatorSchema = z.enum(['==', '!=', 'contains', 'not_contains']);
21 +export type LogSearchFilterOperator = z.infer<typeof LogSearchFilterOperatorSchema>;
22 +
23 +export const LogSearchFilterSchema = z.object({
24 + field: LogSearchFilterFieldSchema,
25 + operator: LogSearchFilterOperatorSchema,
26 + value: z.string(),
27 +});
28 +export type LogSearchFilter = z.infer<typeof LogSearchFilterSchema>;
29 +
30 +export const LogSearchTimeRangeSchema = z.object({
31 + /** Start time in epoch milliseconds (inclusive). */
32 + from: z.number(),
33 + /** End time in epoch milliseconds. */
34 + to: z.number(),
35 +});
36 +export type LogSearchTimeRange = z.infer<typeof LogSearchTimeRangeSchema>;
37 +
38 +/**
39 + * Params for `composio.logs.search()`.
40 + */
41 +export const LogSearchParamsSchema = z.object({
42 + limit: z.number().optional(),
43 + cursor: z.string().nullable().optional(),
44 + filters: z.array(LogSearchFilterSchema).optional(),
45 + timeRange: LogSearchTimeRangeSchema.optional(),
46 +});
47 +export type LogSearchParams = z.infer<typeof LogSearchParamsSchema>;
48 +
49 +export const ToolExecutionLogStatusSchema = z.enum(['success', 'failed']);
50 +export const ToolExecutionLogLevelSchema = z.enum(['info', 'error', 'warn']);
51 +
52 +export const ToolExecutionLogParentSchema = z
53 + .object({
54 + logId: z.string(),
55 + toolSlug: z.string(),
56 + })
57 + .nullable();
58 +
59 +/**
60 + * A tool-execution log entry as returned by `composio.logs.search()`.
61 + */
62 +export const ToolExecutionLogSchema = z.object({
63 + id: z.string(),
64 + /** ISO 8601 timestamp. */
65 + timestamp: z.string(),
66 + /** Log event type, e.g. `tool.execution`. */
67 + type: z.string(),
68 + status: ToolExecutionLogStatusSchema,
69 + level: ToolExecutionLogLevelSchema,
70 + message: z.string().optional(),
71 + metadata: z.record(z.string(), z.unknown()),
72 + metrics: z.record(z.string(), z.unknown()),
73 + parent: ToolExecutionLogParentSchema,
74 +});
75 +export type ToolExecutionLog = z.infer<typeof ToolExecutionLogSchema>;
76 +
77 +export const LogSearchResponseSchema = z.object({
78 + logs: z.array(ToolExecutionLogSchema),
79 + nextCursor: z.string().nullable(),
80 +});
81 +export type LogSearchResponse = z.infer<typeof LogSearchResponseSchema>;
82 +
83 +/**
84 + * A single tool-execution log with its full detail, as returned by
85 + * `composio.logs.get()`.
86 + */
87 +export const ToolExecutionLogDetailSchema = ToolExecutionLogSchema.extend({
88 + timings: z
89 + .object({
90 + /** Epoch milliseconds. */
91 + startTime: z.number(),
92 + /** Epoch milliseconds. */
93 + endTime: z.number(),
94 + })
95 + .optional(),
96 + context: z.object({
97 + sessionId: z.string().optional(),
98 + traceId: z.string().optional(),
99 + requestId: z.string().optional(),
100 + }),
101 + source: z.object({
102 + host: z.string().optional(),
103 + framework: z.string().optional(),
104 + language: z.string().optional(),
105 + }),
106 + data: z.record(z.string(), z.unknown()),
107 +});
108 +export type ToolExecutionLogDetail = z.infer<typeof ToolExecutionLogDetailSchema>;
ts/packages/core/src/types/toolRouter.types.ts
+49 -1
@@ -4,8 +4,11 @@ import { SessionMetaToolOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5 import type { ComposioRequestOptions } from './requestOptions.types';
6 import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
7 -import type { SessionCreateResponse } from '@composio/client/resources/tool-router/session/session.mjs';
7 import { ConnectedAccountExperimentalSchema } from './connectedAccounts.types';
8 +import type {
9 + SessionConfigHistoryResponse,
10 + SessionCreateResponse,
11 +} from '@composio/client/resources/tool-router/session/session.mjs';
12 import type {
13 CustomTool,
14 CustomToolkit,
@@ -721,6 +724,49 @@ export const ToolRouterSessionDeleteResponseSchema = z.object({
724 });
725 export type ToolRouterSessionDeleteResponse = z.infer<typeof ToolRouterSessionDeleteResponseSchema>;
726
727 +/**
728 + * Options for `session.listConfigHistory()`.
729 + */
730 +export const ToolRouterSessionListConfigHistoryOptionsSchema = z.object({
731 + /** Cursor from a previous response's `nextCursor`. */
732 + cursor: z.string().optional(),
733 + /** Number of items per page, max allowed is 100. */
734 + limit: z.number().optional(),
735 +});
736 +export type ToolRouterSessionListConfigHistoryOptions = z.infer<
737 + typeof ToolRouterSessionListConfigHistoryOptionsSchema
738 +>;
739 +
740 +/**
741 + * The session configuration at one version, as stored by the API. This is
742 + * the wire shape (snake_case), typed from the generated client.
743 + */
744 +export type ToolRouterSessionConfigHistoryConfig = SessionConfigHistoryResponse.Item.Config;
745 +
746 +export type ToolRouterSessionConfigHistoryItem = {
747 + /** The config version this entry represents. */
748 + version: number;
749 + /** ISO timestamp — for archived rows, when the version was superseded by an update. */
750 + createdAt: string;
751 + /** True only for the live (current) config, present on the first page. */
752 + isCurrent: boolean;
753 + /** The session configuration at this version. */
754 + config: ToolRouterSessionConfigHistoryConfig;
755 +};
756 +
757 +export type ToolRouterSessionListConfigHistoryResponse = {
758 + items: ToolRouterSessionConfigHistoryItem[];
759 + nextCursor: string | null;
760 + totalPages: number;
761 + currentPage: number;
762 + totalItems: number;
763 +};
764 +
765 +export type ToolRouterSessionListConfigHistoryFn = (
766 + options?: ToolRouterSessionListConfigHistoryOptions,
767 + requestOptions?: ComposioRequestOptions
768 +) => Promise<ToolRouterSessionListConfigHistoryResponse>;
769 +
770 export type ToolRouterSessionDeleteFn = (
771 requestOptions?: ComposioRequestOptions
772 ) => Promise<ToolRouterSessionDeleteResponse>;
@@ -799,6 +845,8 @@ export interface Session<
845 update: ToolRouterSessionUpdateFn;
846 /** Delete the session. Deleted sessions are no longer retrievable or executable. */
847 delete: ToolRouterSessionDeleteFn;
848 + /** Page through the session's configuration history (newest first). */
849 + listConfigHistory: ToolRouterSessionListConfigHistoryFn;
850 /** Proxy an API call through Composio's auth layer using the session's connected account */
851 proxyExecute: ToolRouterSessionProxyExecuteFn;
852 /** List custom tools registered in this session, with their final slugs and schemas */
ts/packages/core/src/types/toolkit.types.ts
+144
@@ -18,6 +18,14 @@ export type ToolkitMangedByEnum = z.infer<typeof ToolkitMangedByEnumSchema>;
18 export type ToolkitSortByEnum = z.infer<typeof ToolkitSortByEnumSchema>;
19 export type ToolkitListParams = z.infer<typeof ToolkitsListParamsSchema>;
20
21 +/**
22 + * Toolkit getMany params — the slugs to fetch plus the same filters `list`
23 + * accepts.
24 + */
25 +export const ToolkitGetManySlugsSchema = z.array(z.string().min(1)).min(1);
26 +export const ToolkitsGetManyParamsSchema = ToolkitsListParamsSchema;
27 +export type ToolkitGetManyParams = z.infer<typeof ToolkitsGetManyParamsSchema>;
28 +
29 /**
30 * Toolkits response
31 */
@@ -78,6 +86,13 @@ export const ToolkitAuthFieldSchema = z.object({
86 * further documenting its semantics.
87 */
88 legacyTemplateName: z.string().optional(),
89 + /**
90 + * Whether the hosted connect flow shows this field to the end user, mapped
91 + * from `user_visible`. A field with `false` is never required: its `default`
92 + * applies unless the auth config supplies a value. Absent when the API omits
93 + * the flag.
94 + */
95 + userVisible: z.boolean().optional(),
96 });
97 export const ToolkitAuthConfigDetailsSchema = z.object({
98 name: z.string(),
@@ -87,6 +102,12 @@ export const ToolkitAuthConfigDetailsSchema = z.object({
102 * authentication method, e.g. `https://github.com/settings/tokens`.
103 */
104 authHintUrl: z.string().nullable().optional(),
105 + /**
106 + * OAuth scopes always requested for this auth method regardless of the
107 + * tool-specific scopes, such as token refresh (`offline_access`) and identity
108 + * scopes. Mapped from `required_scopes`; absent when the API omits it.
109 + */
110 + requiredScopes: z.array(z.string()).optional(),
111 fields: z.object({
112 authConfigCreation: z.object({
113 optional: z.array(ToolkitAuthFieldSchema),
@@ -138,6 +159,129 @@ export type ToolkitRetrieveCategoriesResponse = z.infer<
159 typeof ToolkitRetrieveCategoriesResponseSchema
160 >;
161
162 +/**
163 + * Toolkit changelog response
164 + */
165 +export const ToolkitVersionChangelogSchema = z.object({
166 + version: z.string(),
167 + changelog: z.string(),
168 +});
169 +export const ToolkitChangelogItemSchema = z.object({
170 + slug: z.string(),
171 + name: z.string(),
172 + displayName: z.string(),
173 + /** Most recent versions first; the API returns up to the last 10 per toolkit. */
174 + versions: z.array(ToolkitVersionChangelogSchema),
175 +});
176 +export const ToolkitChangelogResponseSchema = z.object({
177 + items: z.array(ToolkitChangelogItemSchema),
178 +});
179 +
180 +export type ToolkitVersionChangelog = z.infer<typeof ToolkitVersionChangelogSchema>;
181 +export type ToolkitChangelogItem = z.infer<typeof ToolkitChangelogItemSchema>;
182 +export type ToolkitChangelogResponse = z.infer<typeof ToolkitChangelogResponseSchema>;
183 +
184 +/**
185 + * Params for `composio.toolkits.recommendScopes()`.
186 + * **Experimental — shape may change in future releases.**
187 + */
188 +export const ToolkitRecommendScopesParamsSchema = z.object({
189 + /** Tool slugs to cover. Pass `[]` to cover every tool in the toolkit. */
190 + tools: z.array(z.string()),
191 + /** Auth scheme the connection will use. The API defaults to `OAUTH2`. */
192 + authScheme: AuthSchemeEnum.optional(),
193 + /** Toolkit version to compute from. The API defaults to the latest published version. */
194 + toolkitVersion: z.string().min(1).optional(),
195 + /**
196 + * Context the scopes will be granted in, as dimension → selected value,
197 + * for example `{ account_type: 'Google Workspace' }`. Discover the
198 + * dimensions with `composio.toolkits.listGrantContexts()`.
199 + */
200 + grantContext: z.record(z.string(), z.string()).optional(),
201 + /** Scopes the recommendation must include, whether or not the tools need them. */
202 + include: z.array(z.string()).optional(),
203 + /** Scopes the recommendation must not include; the API picks documented alternatives or fails. */
204 + exclude: z.array(z.string()).optional(),
205 + /** Scopes your OAuth app can request. The recommendation never goes outside this list. */
206 + availableScopes: z.array(z.string()).optional(),
207 +});
208 +export type ToolkitRecommendScopesParams = z.infer<typeof ToolkitRecommendScopesParamsSchema>;
209 +
210 +export const ToolkitConditionalScopeSchema = z.object({
211 + /** The scope needed only when the `when` guard matches. */
212 + scope: z.string(),
213 + /** Input field name → qualifying values. Any value matches within a field; all fields must match. */
214 + when: z.record(z.string(), z.array(z.string())),
215 + /** Tool slugs that need this scope under the guard. */
216 + for: z.array(z.string()),
217 +});
218 +export type ToolkitConditionalScope = z.infer<typeof ToolkitConditionalScopeSchema>;
219 +
220 +/**
221 + * Response of `composio.toolkits.recommendScopes()`.
222 + * **Experimental — shape may change in future releases.**
223 + */
224 +export const ToolkitRecommendScopesResponseSchema = z.object({
225 + /** Auth scheme the recommendation was computed under. */
226 + authScheme: z.string(),
227 + /** Concrete toolkit version the answer was computed from; pass it back as `toolkitVersion` to pin. */
228 + toolkitVersion: z.string(),
229 + /** The effective grant context: the toolkit default overlaid with your overrides. */
230 + grantContext: z.record(z.string(), z.string()),
231 + scopes: z.object({
232 + /** Narrowest documented option per requirement. */
233 + leastPrivilege: z.array(z.string()),
234 + /** Smallest scope set covering all requirements. */
235 + fewest: z.array(z.string()),
236 + /**
237 + * Scopes needed only for particular call-time inputs. Both lists above
238 + * already include them, so a caller that knows its inputs may drop the rest.
239 + */
240 + conditional: z.array(ToolkitConditionalScopeSchema),
241 + }),
242 +});
243 +export type ToolkitRecommendScopesResponse = z.infer<typeof ToolkitRecommendScopesResponseSchema>;
244 +
245 +/**
246 + * Params for `composio.toolkits.listGrantContexts()`.
247 + * **Experimental — shape may change in future releases.**
248 + */
249 +export const ToolkitListGrantContextsParamsSchema = z.object({
250 + /** Auth scheme the connection will use. The API defaults to `OAUTH2`. */
251 + authScheme: AuthSchemeEnum.optional(),
252 + /** Toolkit version to read the scope catalog from. The API defaults to the latest published version. */
253 + toolkitVersion: z.string().min(1).optional(),
254 +});
255 +export type ToolkitListGrantContextsParams = z.infer<typeof ToolkitListGrantContextsParamsSchema>;
256 +
257 +export const ToolkitGrantContextDimensionSchema = z.object({
258 + /** Dimension name to use as a `grantContext` key. */
259 + dimension: z.string(),
260 + /** What the dimension means and when to pass it. */
261 + description: z.string(),
262 + /** Values the dimension can take. */
263 + values: z.array(z.string()),
264 +});
265 +export type ToolkitGrantContextDimension = z.infer<typeof ToolkitGrantContextDimensionSchema>;
266 +
267 +/**
268 + * Response of `composio.toolkits.listGrantContexts()`.
269 + * **Experimental — shape may change in future releases.**
270 + */
271 +export const ToolkitListGrantContextsResponseSchema = z.object({
272 + /** Auth scheme whose scope catalog the dimensions were read from. */
273 + authScheme: z.string(),
274 + /** Concrete toolkit version the answer was computed from. */
275 + toolkitVersion: z.string(),
276 + /** Dimensions the toolkit accepts in `grantContext`; empty when no scope depends on one. */
277 + grantContextDimensions: z.array(ToolkitGrantContextDimensionSchema),
278 + /** The grant context assumed when you pass none. */
279 + defaultGrantContext: z.record(z.string(), z.string()),
280 +});
281 +export type ToolkitListGrantContextsResponse = z.infer<
282 + typeof ToolkitListGrantContextsResponseSchema
283 +>;
284 +
285 export const ToolkitAuthFieldsResponseSchema = z.array(
286 ToolkitAuthFieldSchema.extend({
287 required: z.boolean().optional(),
ts/packages/core/src/types/usage.types.ts new
+81
@@ -0,0 +1,81 @@
1 +import { z } from 'zod/v3';
2 +
3 +/**
4 + * Filters shared by the usage summary and breakdown queries.
5 + * **Experimental — shape may change in future releases.**
6 + */
7 +export const UsageFiltersSchema = z.object({
8 + /** Only count events for these external end-user IDs (OR logic). */
9 + userId: z.array(z.string()).nullable().optional(),
10 + /** Only count events for these session IDs (OR logic). */
11 + sessionId: z.array(z.string()).nullable().optional(),
12 +});
13 +export type UsageFilters = z.infer<typeof UsageFiltersSchema>;
14 +
15 +/**
16 + * Params for `composio.experimental.usage.summary()`.
17 + * **Experimental — shape may change in future releases.**
18 + */
19 +export const UsageSummaryParamsSchema = z.object({
20 + /** Inclusive range start (Unix epoch milliseconds). Defaults to 30 days before `to`. */
21 + from: z.number().optional(),
22 + /** Exclusive range end (Unix epoch milliseconds). Defaults to now. */
23 + to: z.number().optional(),
24 + /** Restrict to these metering entity types. Omit for all types. */
25 + entityTypes: z.array(z.string()).optional(),
26 + filters: UsageFiltersSchema.optional(),
27 +});
28 +export type UsageSummaryParams = z.infer<typeof UsageSummaryParamsSchema>;
29 +
30 +export const UsageOrderBySchema = z.enum(['key', 'total_quantity', 'event_count']);
31 +export const UsageOrderDirectionSchema = z.enum(['asc', 'desc']);
32 +
33 +/**
34 + * Params for `composio.experimental.usage.breakdown()`.
35 + * **Experimental — shape may change in future releases.**
36 + */
37 +export const UsageBreakdownParamsSchema = z.object({
38 + /** Inclusive range start (Unix epoch milliseconds). Defaults to 30 days before `to`. */
39 + from: z.number().optional(),
40 + /** Exclusive range end (Unix epoch milliseconds). Defaults to now. */
41 + to: z.number().optional(),
42 + /** Dimension to group by. Defaults to `tool_slug` for tool_calls and `user_id` for sessions. */
43 + groupBy: z.string().optional(),
44 + /** Field to order groups by. Defaults to `total_quantity`. */
45 + orderBy: UsageOrderBySchema.optional(),
46 + /** Sort direction. Defaults to `desc`. */
47 + orderDirection: UsageOrderDirectionSchema.optional(),
48 + /** Maximum number of groups to return. Defaults to 100, max 1000. */
49 + limit: z.number().optional(),
50 + filters: UsageFiltersSchema.optional(),
51 +});
52 +export type UsageBreakdownParams = z.infer<typeof UsageBreakdownParamsSchema>;
53 +
54 +export const UsageEntitySummarySchema = z.object({
55 + unit: z.string(),
56 + totalQuantity: z.string(),
57 + eventCount: z.number(),
58 +});
59 +export type UsageEntitySummary = z.infer<typeof UsageEntitySummarySchema>;
60 +
61 +export const UsageSummaryResponseSchema = z.object({
62 + /** Aggregates keyed by metering entity type (e.g. `tool_calls`, `sessions`). */
63 + entities: z.record(z.string(), UsageEntitySummarySchema),
64 +});
65 +export type UsageSummaryResponse = z.infer<typeof UsageSummaryResponseSchema>;
66 +
67 +export const UsageBreakdownGroupSchema = z.object({
68 + key: z.string(),
69 + totalQuantity: z.string(),
70 + eventCount: z.number(),
71 +});
72 +export type UsageBreakdownGroup = z.infer<typeof UsageBreakdownGroupSchema>;
73 +
74 +export const UsageBreakdownResponseSchema = z.object({
75 + entityType: z.string(),
76 + unit: z.string(),
77 + totalQuantity: z.string(),
78 + eventCount: z.number(),
79 + groups: z.array(UsageBreakdownGroupSchema),
80 +});
81 +export type UsageBreakdownResponse = z.infer<typeof UsageBreakdownResponseSchema>;
ts/packages/core/src/types/webhooks.types.ts new
+143
@@ -0,0 +1,143 @@
1 +import { z } from 'zod/v3';
2 +import { SetWebhookSubscriptionParamsSchema } from './triggers.types';
3 +
4 +/**
5 + * Webhook payload versions accepted by the webhook subscription endpoints.
6 + */
7 +export const WebhookVersionSchema = z.enum(['V1', 'V2', 'V3']);
8 +
9 +// ---------------------------------------------------------------------------
10 +// Webhook subscriptions
11 +// ---------------------------------------------------------------------------
12 +
13 +/**
14 + * A project webhook subscription in the SDK's camelCase shape. The signing
15 + * `secret` is returned by the API on every subscription read/write.
16 + */
17 +export const WebhookSubscriptionSchema = z.object({
18 + id: z.string(),
19 + webhookUrl: z.string(),
20 + version: WebhookVersionSchema,
21 + enabledEvents: z.array(z.string()),
22 + secret: z.string().optional(),
23 + createdAt: z.string().optional(),
24 + updatedAt: z.string().optional(),
25 +});
26 +
27 +export const WebhookSubscriptionListParamsSchema = z.object({
28 + /** Number of items per page, max allowed is 50. */
29 + limit: z.number().optional(),
30 + /** Cursor for pagination, taken from a previous response's `nextCursor`. */
31 + cursor: z.string().optional(),
32 +});
33 +export type WebhookSubscriptionListParams = z.infer<typeof WebhookSubscriptionListParamsSchema>;
34 +
35 +export const WebhookSubscriptionListResponseSchema = z.object({
36 + items: z.array(WebhookSubscriptionSchema),
37 + nextCursor: z.string().nullable(),
38 + totalPages: z.number(),
39 + currentPage: z.number(),
40 + totalItems: z.number(),
41 +});
42 +export type WebhookSubscriptionListResponse = z.infer<typeof WebhookSubscriptionListResponseSchema>;
43 +
44 +/**
45 + * Params for `composio.webhooks.subscriptions.set()`. Identical to the
46 + * params accepted by `composio.triggers.setWebhookSubscription()`.
47 + */
48 +export const WebhookSubscriptionSetParamsSchema = SetWebhookSubscriptionParamsSchema;
49 +export type WebhookSubscriptionSetParams = z.infer<typeof WebhookSubscriptionSetParamsSchema>;
50 +
51 +export const WebhookSubscriptionUpdateParamsSchema = z.object({
52 + /** HTTPS URL to receive webhook events. */
53 + webhookUrl: z.string().min(1).optional(),
54 + /** Event types to subscribe to. */
55 + enabledEvents: z.array(z.string()).min(1).optional(),
56 + /** Webhook payload version. */
57 + version: WebhookVersionSchema.optional(),
58 +});
59 +export type WebhookSubscriptionUpdateParams = z.infer<typeof WebhookSubscriptionUpdateParamsSchema>;
60 +
61 +export const WebhookSubscriptionDeleteResponseSchema = z.object({
62 + success: z.boolean(),
63 +});
64 +export type WebhookSubscriptionDeleteResponse = z.infer<
65 + typeof WebhookSubscriptionDeleteResponseSchema
66 +>;
67 +
68 +export const WebhookSubscriptionRotateSecretResponseSchema = z.object({
69 + id: z.string(),
70 + /** The new signing secret. Store it — the previous secret stops validating. */
71 + secret: z.string(),
72 +});
73 +export type WebhookSubscriptionRotateSecretResponse = z.infer<
74 + typeof WebhookSubscriptionRotateSecretResponseSchema
75 +>;
76 +
77 +export const WebhookSubscriptionEventTypeSchema = z.object({
78 + eventType: z.string(),
79 + description: z.string(),
80 + supportedVersions: z.array(WebhookVersionSchema),
81 +});
82 +export type WebhookSubscriptionEventType = z.infer<typeof WebhookSubscriptionEventTypeSchema>;
83 +
84 +export const WebhookSubscriptionEventTypesResponseSchema = z.object({
85 + items: z.array(WebhookSubscriptionEventTypeSchema),
86 +});
87 +export type WebhookSubscriptionEventTypesResponse = z.infer<
88 + typeof WebhookSubscriptionEventTypesResponseSchema
89 +>;
90 +
91 +// ---------------------------------------------------------------------------
92 +// Webhook endpoints (per toolkit + OAuth app inbound ingress URLs)
93 +// ---------------------------------------------------------------------------
94 +
95 +export const WebhookEndpointListParamsSchema = z.object({
96 + /** Only return endpoints for this toolkit slug. */
97 + toolkitSlug: z.string().optional(),
98 +});
99 +export type WebhookEndpointListParams = z.infer<typeof WebhookEndpointListParamsSchema>;
100 +
101 +export const WebhookEndpointListItemSchema = z.object({
102 + id: z.string(),
103 + toolkitSlug: z.string(),
104 + clientId: z.string().nullable(),
105 +});
106 +export type WebhookEndpointListItem = z.infer<typeof WebhookEndpointListItemSchema>;
107 +
108 +export const WebhookEndpointListResponseSchema = z.object({
109 + items: z.array(WebhookEndpointListItemSchema),
110 +});
111 +export type WebhookEndpointListResponse = z.infer<typeof WebhookEndpointListResponseSchema>;
112 +
113 +export const WebhookEndpointSchema = z.object({
114 + id: z.string(),
115 + toolkitSlug: z.string(),
116 + clientId: z.string().nullable(),
117 + /** The inbound URL to register with the third-party provider. */
118 + webhookUrl: z.string(),
119 + /** Configured setup fields with secret values masked. */
120 + data: z.record(z.string(), z.string()).nullable(),
121 + createdAt: z.string(),
122 +});
123 +export type WebhookEndpoint = z.infer<typeof WebhookEndpointSchema>;
124 +
125 +export const WebhookEndpointCreateParamsSchema = z.object({
126 + /** Toolkit identifier (e.g. `slack`, `discord`). */
127 + toolkitSlug: z.string().min(1),
128 + /** OAuth app client ID — identifies which app this endpoint is for. */
129 + clientId: z.string().min(1),
130 +});
131 +export type WebhookEndpointCreateParams = z.infer<typeof WebhookEndpointCreateParamsSchema>;
132 +
133 +export const WebhookEndpointReplaceParamsSchema = z.object({
134 + /** Key-value pairs for ALL required setup fields of the toolkit. */
135 + data: z.record(z.string(), z.string()),
136 +});
137 +export type WebhookEndpointReplaceParams = z.infer<typeof WebhookEndpointReplaceParamsSchema>;
138 +
139 +export const WebhookEndpointUpdateParamsSchema = z.object({
140 + /** Key-value pairs to merge into the setup fields. Omitted fields are preserved. */
141 + data: z.record(z.string(), z.string()),
142 +});
143 +export type WebhookEndpointUpdateParams = z.infer<typeof WebhookEndpointUpdateParamsSchema>;
ts/packages/core/src/utils/constants.ts
+1 -5
@@ -11,11 +11,7 @@ export const TELEMETRY_URL = 'https://app.composio.dev';
11 export const CLIENT_PUSHER_KEY = getEnvVariable('CLIENT_PUSHER_KEY') || 'ff9f18c208855d77a152';
12
13 export const COMPOSIO_LOG_LEVEL = getEnvVariable('COMPOSIO_LOG_LEVEL') as
14 - | 'debug'
15 - | 'info'
16 - | 'warn'
17 - | 'error'
18 - | undefined;
14 + 'silent' | 'debug' | 'info' | 'warn' | 'error' | undefined;
15
16 export const IS_DEVELOPMENT_OR_CI = getEnvVariable('DEVELOPMENT') || getEnvVariable('CI') || false;
17
ts/packages/core/src/utils/logger.ts
+39 -7
@@ -23,20 +23,52 @@ export const getLogLevel = (): LogLevel => {
23 return envLevel && envLevel in LOG_LEVELS ? (envLevel as LogLevel) : 'info';
24 };
25
26 +/**
27 + * Destination for SDK log output. Each method receives the already
28 + * formatted and redacted message as its single argument. `console` satisfies
29 + * this interface, and so do most structured loggers (pino, winston, ...).
30 + */
31 +export interface ComposioLogger {
32 + error: (...args: unknown[]) => void;
33 + warn: (...args: unknown[]) => void;
34 + info: (...args: unknown[]) => void;
35 + debug: (...args: unknown[]) => void;
36 +}
37 +
38 interface LoggerOptions {
39 level?: LogLevel;
40 includeTimestamp?: boolean;
41 + /** Where formatted output is written. Defaults to `console`. */
42 + sink?: ComposioLogger;
43 +}
44 +
45 +export interface LoggerConfigureOptions {
46 + level?: LogLevel;
47 + sink?: ComposioLogger;
48 }
49
50 export class Logger {
32 - private readonly level: LogLevel;
51 + private level: LogLevel;
52 private readonly includeTimestamp: boolean;
34 - private readonly console: Console;
53 + private sink: ComposioLogger;
54
55 constructor(options: LoggerOptions = {}) {
56 this.level = options.level ?? getLogLevel();
57 this.includeTimestamp = options.includeTimestamp ?? true;
39 - this.console = console;
58 + this.sink = options.sink ?? console;
59 + }
60 +
61 + /**
62 + * Reconfigure the level and/or sink in place. Omitted fields are left
63 + * unchanged, so `configure({ level: 'debug' })` keeps the current sink.
64 + */
65 + configure(options: LoggerConfigureOptions): void {
66 + if (options.level !== undefined) this.level = options.level;
67 + if (options.sink !== undefined) this.sink = options.sink;
68 + }
69 +
70 + getLevel(): LogLevel {
71 + return this.level;
72 }
73
74 private formatMessage(args: unknown[]): string {
@@ -71,25 +103,25 @@ export class Logger {
103
104 error(...args: unknown[]): void {
105 if (this.shouldLog('error')) {
74 - this.console.error(this.formatMessage(args));
106 + this.sink.error(this.formatMessage(args));
107 }
108 }
109
110 warn(...args: unknown[]): void {
111 if (this.shouldLog('warn')) {
80 - this.console.warn(this.formatMessage(args));
112 + this.sink.warn(this.formatMessage(args));
113 }
114 }
115
116 info(...args: unknown[]): void {
117 if (this.shouldLog('info')) {
86 - this.console.info(this.formatMessage(args));
118 + this.sink.info(this.formatMessage(args));
119 }
120 }
121
122 debug(...args: unknown[]): void {
123 if (this.shouldLog('debug')) {
92 - this.console.debug(this.formatMessage(args));
124 + this.sink.debug(this.formatMessage(args));
125 }
126 }
127 }
ts/packages/core/src/utils/transformers/connectedAccounts.ts
+37 -2
@@ -1,20 +1,30 @@
1 import {
2 ConnectedAccountListResponse as RawConnectedAccountListResponse,
3 ConnectedAccountRetrieveResponse as RawConnectedAccountRetrieveResponse,
4 + type ConnectedAccounts as ClientConnectedAccounts,
5 } from '@composio/client/resources/connected-accounts';
6 import {
7 ConnectedAccountListResponse,
8 ConnectedAccountListResponseSchema,
9 ConnectedAccountRetrieveResponse,
10 ConnectedAccountRetrieveResponseSchema,
11 + ConnectedAccountRevokeResponse,
12 + ConnectedAccountRevokeResponseSchema,
13 + ConnectedAccountCompleteAuthResponse,
14 + ConnectedAccountCompleteAuthResponseSchema,
15 } from '../../types/connectedAccounts.types';
16 +
17 +// The revoke and complete-auth response types are only reachable through the
18 +// resource class namespace on the published subpath.
19 +type RawConnectedAccountRevokeResponse = ClientConnectedAccounts.ConnectedAccountRevokeResponse;
20 +type RawConnectedAccountCompleteAuthResponse =
21 + ClientConnectedAccounts.ConnectedAccountCompleteAuthResponse;
22 import { ConnectionDataSchema } from '../../types/connectedAccountAuthStates.types';
23 import logger from '../logger';
24 import { transform } from '../transform';
25
26 type RawConnectedAccountResponseWithLabels = (
16 - | RawConnectedAccountRetrieveResponse
17 - | RawConnectedAccountListResponse['items'][0]
27 + RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]
28 ) & {
29 word_id?: string | null;
30 alias?: string | null;
@@ -117,3 +127,28 @@ export function transformConnectedAccountListResponse(
127 totalPages: response.total_pages,
128 }));
129 }
130 +
131 +export const transformConnectedAccountRevokeResponse = (
132 + response: RawConnectedAccountRevokeResponse
133 +): ConnectedAccountRevokeResponse => {
134 + return transform(response)
135 + .with(ConnectedAccountRevokeResponseSchema)
136 + .using(response => ({
137 + revokedTokens: response.revoked_tokens,
138 + connectedAccount: {
139 + id: response.connected_account.id,
140 + status: response.connected_account.status,
141 + },
142 + }));
143 +};
144 +
145 +export const transformConnectedAccountCompleteAuthResponse = (
146 + response: RawConnectedAccountCompleteAuthResponse
147 +): ConnectedAccountCompleteAuthResponse => {
148 + return transform(response)
149 + .with(ConnectedAccountCompleteAuthResponseSchema)
150 + .using(response => ({
151 + connectedAccountId: response.connected_account_id,
152 + toolkitSlug: response.toolkit_slug,
153 + }));
154 +};
ts/packages/core/src/utils/transformers/customToolkits.ts new
+98
@@ -0,0 +1,98 @@
1 +import type {
2 + CustomDeleteToolkitResponse as RawCustomDeleteToolkitResponse,
3 + CustomSyncParams as RawCustomSyncParams,
4 + CustomSyncResponse as RawCustomSyncResponse,
5 + CustomUpsertParams as RawCustomUpsertParams,
6 + CustomUpsertResponse as RawCustomUpsertResponse,
7 +} from '@composio/client/resources/custom';
8 +import {
9 + CustomToolkitAuthScheme,
10 + CustomToolkitDeleteResponse,
11 + CustomToolkitDeleteResponseSchema,
12 + CustomToolkitSyncParams,
13 + CustomToolkitSyncResponse,
14 + CustomToolkitSyncResponseSchema,
15 + CustomToolkitUpsertParams,
16 + CustomToolkitUpsertResponse,
17 + CustomToolkitUpsertResponseSchema,
18 +} from '../../types/customToolkits.types';
19 +import { transform } from '../transform';
20 +
21 +type RawCustomToolkitAuthScheme = RawCustomUpsertParams['toolkit_config']['auth_schemes'][number];
22 +
23 +const transformCustomToolkitAuthScheme = (
24 + scheme: CustomToolkitAuthScheme
25 +): RawCustomToolkitAuthScheme => {
26 + switch (scheme.mode) {
27 + case 'NO_AUTH':
28 + return { mode: 'NO_AUTH' };
29 + case 'API_KEY':
30 + return {
31 + mode: 'API_KEY',
32 + headers: scheme.headers,
33 + api_key_field: scheme.apiKeyField && {
34 + display_name: scheme.apiKeyField.displayName,
35 + description: scheme.apiKeyField.description,
36 + },
37 + };
38 + case 'DCR_OAUTH':
39 + return { mode: 'DCR_OAUTH', discovery_url: scheme.discoveryUrl };
40 + }
41 +};
42 +
43 +export const transformCustomToolkitUpsertParams = (
44 + params: CustomToolkitUpsertParams
45 +): RawCustomUpsertParams => ({
46 + slug: params.slug,
47 + toolkit_config: {
48 + name: params.toolkitConfig.name,
49 + app_url: params.toolkitConfig.appUrl,
50 + logo_file: params.toolkitConfig.logoFile && {
51 + content: params.toolkitConfig.logoFile.content,
52 + mime_type: params.toolkitConfig.logoFile.mimeType,
53 + },
54 + auth_schemes: params.toolkitConfig.authSchemes.map(transformCustomToolkitAuthScheme),
55 + },
56 +});
57 +
58 +export const transformCustomToolkitUpsertResponse = (
59 + response: RawCustomUpsertResponse
60 +): CustomToolkitUpsertResponse => {
61 + return transform(response)
62 + .with(CustomToolkitUpsertResponseSchema)
63 + .using(response => ({ slug: response.slug }));
64 +};
65 +
66 +export const transformCustomToolkitSyncParams = (
67 + slug: string,
68 + params: CustomToolkitSyncParams
69 +): RawCustomSyncParams => ({
70 + slug,
71 + connected_account_id: params.connectedAccountId,
72 +});
73 +
74 +export const transformCustomToolkitSyncResponse = (
75 + response: RawCustomSyncResponse
76 +): CustomToolkitSyncResponse => {
77 + return transform(response)
78 + .with(CustomToolkitSyncResponseSchema)
79 + .using(response => ({
80 + slug: response.slug,
81 + version: response.version,
82 + syncedCount: response.synced_count,
83 + }));
84 +};
85 +
86 +export const transformCustomToolkitDeleteResponse = (
87 + response: RawCustomDeleteToolkitResponse
88 +): CustomToolkitDeleteResponse => {
89 + return transform(response)
90 + .with(CustomToolkitDeleteResponseSchema)
91 + .using(response => ({
92 + slug: response.slug,
93 + deleted: response.deleted,
94 + revokeJobIds: response.revoke_job_ids,
95 + authConfigsDeleted: response.auth_configs_deleted,
96 + connectedAccountsDeleted: response.connected_accounts_deleted,
97 + }));
98 +};
ts/packages/core/src/utils/transformers/keyring.ts new
+24
@@ -0,0 +1,24 @@
1 +import type { KeyringListTransferKeysResponse as RawKeyringListTransferKeysResponse } from '@composio/client/resources/keyring';
2 +import {
3 + KeyringTransferKeysResponse,
4 + KeyringTransferKeysResponseSchema,
5 +} from '../../types/keyring.types';
6 +import { transform } from '../transform';
7 +
8 +export const transformKeyringTransferKeysResponse = (
9 + response: RawKeyringListTransferKeysResponse
10 +): KeyringTransferKeysResponse => {
11 + return transform(response)
12 + .with(KeyringTransferKeysResponseSchema)
13 + .using(response => ({
14 + activeKid: response.active_kid,
15 + keys: response.keys.map(key => ({
16 + kty: key.kty,
17 + n: key.n,
18 + e: key.e,
19 + alg: key.alg,
20 + use: key.use,
21 + kid: key.kid,
22 + })),
23 + }));
24 +};
ts/packages/core/src/utils/transformers/logs.ts new
+85
@@ -0,0 +1,85 @@
1 +import type {
2 + LogCreateToolExecutionParams as RawLogSearchParams,
3 + LogCreateToolExecutionResponse as RawLogSearchResponse,
4 + LogRetrieveToolExecutionResponse as RawToolExecutionLogDetail,
5 +} from '@composio/client/resources/logs';
6 +import {
7 + LogSearchParams,
8 + LogSearchResponse,
9 + LogSearchResponseSchema,
10 + ToolExecutionLog,
11 + ToolExecutionLogDetail,
12 + ToolExecutionLogDetailSchema,
13 + ToolExecutionLogSchema,
14 +} from '../../types/logs.types';
15 +import { transform } from '../transform';
16 +
17 +export const transformLogSearchParams = (params: LogSearchParams): RawLogSearchParams => ({
18 + limit: params.limit,
19 + cursor: params.cursor,
20 + filters: params.filters,
21 + time_range: params.timeRange,
22 +});
23 +
24 +export const transformToolExecutionLog = (
25 + response: RawLogSearchResponse['logs'][number]
26 +): ToolExecutionLog => {
27 + return transform(response)
28 + .with(ToolExecutionLogSchema)
29 + .using(response => ({
30 + id: response.id,
31 + timestamp: response.timestamp,
32 + type: response.type,
33 + status: response.status,
34 + level: response.level,
35 + message: response.message,
36 + metadata: response.metadata,
37 + metrics: response.metrics,
38 + parent: response.parent
39 + ? { logId: response.parent.log_id, toolSlug: response.parent.tool_slug }
40 + : null,
41 + }));
42 +};
43 +
44 +export const transformLogSearchResponse = (response: RawLogSearchResponse): LogSearchResponse => {
45 + return transform(response)
46 + .with(LogSearchResponseSchema)
47 + .using(response => ({
48 + logs: response.logs.map(transformToolExecutionLog),
49 + nextCursor: response.next_cursor,
50 + }));
51 +};
52 +
53 +export const transformToolExecutionLogDetail = (
54 + response: RawToolExecutionLogDetail
55 +): ToolExecutionLogDetail => {
56 + return transform(response)
57 + .with(ToolExecutionLogDetailSchema)
58 + .using(response => ({
59 + id: response.id,
60 + timestamp: response.timestamp,
61 + type: response.type,
62 + status: response.status,
63 + level: response.level,
64 + message: response.message,
65 + metadata: response.metadata,
66 + metrics: response.metrics,
67 + parent: response.parent
68 + ? { logId: response.parent.log_id, toolSlug: response.parent.tool_slug }
69 + : null,
70 + timings: response.timings
71 + ? { startTime: response.timings.start_time, endTime: response.timings.end_time }
72 + : undefined,
73 + context: {
74 + sessionId: response.context.session_id,
75 + traceId: response.context.trace_id,
76 + requestId: response.context.request_id,
77 + },
78 + source: {
79 + host: response.source.host,
80 + framework: response.source.framework,
81 + language: response.source.language,
82 + },
83 + data: response.data,
84 + }));
85 +};
ts/packages/core/src/utils/transformers/toolkits.ts
+106 -3
@@ -2,7 +2,19 @@ import {
2 ToolkitRetrieveResponse as RawToolkitRetrieveResponse,
3 ToolkitListResponse as RawToolkitListResponse,
4 ToolkitRetrieveCategoriesResponse as RawToolkitRetrieveCategoriesResponse,
5 + type Toolkits as ClientToolkits,
6 } from '@composio/client/resources/toolkits';
7 +
8 +// The `/toolkits/multi` and `/toolkits/changelog` response types are only
9 +// reachable through the resource class namespace on the published subpath.
10 +type RawToolkitRetrieveChangelogResponse = ClientToolkits.ToolkitRetrieveChangelogResponse;
11 +type RawToolkitRetrieveMultiResponse = ClientToolkits.ToolkitRetrieveMultiResponse;
12 +type RawToolkitRecommendScopesParams = ClientToolkits.ToolkitRecommendScopesParams;
13 +type RawToolkitRecommendScopesResponse = ClientToolkits.ToolkitRecommendScopesResponse;
14 +type RawToolkitRetrieveScopesGrantContextParams =
15 + ClientToolkits.ToolkitRetrieveScopesGrantContextParams;
16 +type RawToolkitRetrieveScopesGrantContextResponse =
17 + ClientToolkits.ToolkitRetrieveScopesGrantContextResponse;
18 import {
19 ToolKitListResponse,
20 ToolKitListResponseSchema,
@@ -11,6 +23,14 @@ import {
23 ToolkitRetrieveResponseSchema,
24 ToolkitRetrieveCategoriesResponse,
25 ToolkitRetrieveCategoriesResponseSchema,
26 + ToolkitChangelogResponse,
27 + ToolkitChangelogResponseSchema,
28 + ToolkitRecommendScopesParams,
29 + ToolkitRecommendScopesResponse,
30 + ToolkitRecommendScopesResponseSchema,
31 + ToolkitListGrantContextsParams,
32 + ToolkitListGrantContextsResponse,
33 + ToolkitListGrantContextsResponseSchema,
34 } from '../../types/toolkit.types';
35 import { transform } from '../transform';
36
@@ -24,8 +44,8 @@ type RawToolkitAuthConfigDetailFields = NonNullable<
44 * today, so the union costs nothing and keeps the mapping honest if they ever
45 * drift apart.
46 *
27 - * Most keys are already camelCase on the wire (`displayName`), but `is_secret`
28 - * and `legacy_template_name` are not, so the field needs an explicit mapping
47 + * Most keys are already camelCase on the wire (`displayName`), but `is_secret`,
48 + * `legacy_template_name`, and `user_visible` are not, so the field needs an explicit mapping
49 * instead of a pass-through: a pass-through leaves them under keys the schema
50 * does not know and zod strips them while validating.
51 *
@@ -56,6 +76,7 @@ const transformToolkitAuthField = (field: RawToolkitAuthField): ToolkitAuthField
76 ...(field.legacy_template_name !== undefined && {
77 legacyTemplateName: field.legacy_template_name,
78 }),
79 + ...(field.user_visible !== undefined && { userVisible: field.user_visible }),
80 });
81
82 /**
@@ -83,8 +104,12 @@ const transformToolkitAuthFieldGroup = (
104 optional: (group?.optional ?? []).map(transformToolkitAuthField),
105 });
106
107 +/**
108 + * `GET /toolkits` and `POST /toolkits/multi` return the same item shape; the
109 + * generated client only names them differently per operation.
110 + */
111 export const transformToolkitListResponse = (
87 - response: RawToolkitListResponse
112 + response: RawToolkitListResponse | RawToolkitRetrieveMultiResponse
113 ): ToolKitListResponse => {
114 return transform(response)
115 .with(ToolKitListResponseSchema)
@@ -143,6 +168,9 @@ export const transformToolkitRetrieveResponse = (
168 ...(authConfig.auth_hint_url !== undefined && {
169 authHintUrl: authConfig.auth_hint_url,
170 }),
171 + ...(authConfig.required_scopes !== undefined && {
172 + requiredScopes: authConfig.required_scopes,
173 + }),
174 fields: {
175 authConfigCreation: transformToolkitAuthFieldGroup(
176 authConfig.fields?.auth_config_creation
@@ -161,6 +189,24 @@ export const transformToolkitRetrieveResponse = (
189 }));
190 };
191
192 +export const transformToolkitChangelogResponse = (
193 + response: RawToolkitRetrieveChangelogResponse
194 +): ToolkitChangelogResponse => {
195 + return transform(response)
196 + .with(ToolkitChangelogResponseSchema)
197 + .using(response => ({
198 + items: response.items.map(item => ({
199 + slug: item.slug,
200 + name: item.name,
201 + displayName: item.display_name,
202 + versions: item.versions.map(version => ({
203 + version: version.version,
204 + changelog: version.changelog,
205 + })),
206 + })),
207 + }));
208 +};
209 +
210 export const transformToolkitRetrieveCategoriesResponse = (
211 response: RawToolkitRetrieveCategoriesResponse
212 ): ToolkitRetrieveCategoriesResponse => {
@@ -175,3 +221,60 @@ export const transformToolkitRetrieveCategoriesResponse = (
221 totalPages: response.total_pages,
222 }));
223 };
224 +
225 +export const transformToolkitRecommendScopesParams = (
226 + params: ToolkitRecommendScopesParams
227 +): RawToolkitRecommendScopesParams => ({
228 + tools: params.tools,
229 + auth_scheme: params.authScheme,
230 + toolkit_version: params.toolkitVersion,
231 + grant_context: params.grantContext,
232 + include: params.include,
233 + exclude: params.exclude,
234 + available_scopes: params.availableScopes,
235 +});
236 +
237 +export const transformToolkitRecommendScopesResponse = (
238 + response: RawToolkitRecommendScopesResponse
239 +): ToolkitRecommendScopesResponse => {
240 + return transform(response)
241 + .with(ToolkitRecommendScopesResponseSchema)
242 + .using(response => ({
243 + authScheme: response.auth_scheme,
244 + toolkitVersion: response.toolkit_version,
245 + grantContext: response.grant_context,
246 + scopes: {
247 + leastPrivilege: response.scopes.least_privilege,
248 + fewest: response.scopes.fewest,
249 + conditional: response.scopes.conditional.map(condition => ({
250 + scope: condition.scope,
251 + when: condition.when,
252 + for: condition.for,
253 + })),
254 + },
255 + }));
256 +};
257 +
258 +export const transformToolkitListGrantContextsParams = (
259 + params: ToolkitListGrantContextsParams
260 +): RawToolkitRetrieveScopesGrantContextParams => ({
261 + auth_scheme: params.authScheme,
262 + toolkit_version: params.toolkitVersion,
263 +});
264 +
265 +export const transformToolkitListGrantContextsResponse = (
266 + response: RawToolkitRetrieveScopesGrantContextResponse
267 +): ToolkitListGrantContextsResponse => {
268 + return transform(response)
269 + .with(ToolkitListGrantContextsResponseSchema)
270 + .using(response => ({
271 + authScheme: response.auth_scheme,
272 + toolkitVersion: response.toolkit_version,
273 + grantContextDimensions: response.grant_context_dimensions.map(dimension => ({
274 + dimension: dimension.dimension,
275 + description: dimension.description,
276 + values: dimension.values,
277 + })),
278 + defaultGrantContext: response.default_grant_context,
279 + }));
280 +};
ts/packages/core/src/utils/transformers/triggers.ts
+2 -2
@@ -96,8 +96,8 @@ export function transformTriggerInstanceListActiveItem(
96 id: response.id,
97 connectedAccountId: response.connected_account_id,
98 disabledAt: response.disabled_at,
99 - state: response.state,
100 - triggerConfig: response.trigger_config,
99 + state: response.state ?? {},
100 + triggerConfig: response.trigger_config ?? {},
101 triggerName: response.trigger_name,
102 updatedAt: response.updated_at,
103 triggerData: response.trigger_data,
ts/packages/core/src/utils/transformers/usage.ts new
+77
@@ -0,0 +1,77 @@
1 +import type {
2 + UsageRetrieveParams as RawUsageBreakdownParams,
3 + UsageRetrieveResponse as RawUsageBreakdownResponse,
4 + UsageRetrieveSummaryParams as RawUsageSummaryParams,
5 + UsageRetrieveSummaryResponse as RawUsageSummaryResponse,
6 +} from '@composio/client/resources/project/usage';
7 +import {
8 + UsageBreakdownParams,
9 + UsageBreakdownResponse,
10 + UsageBreakdownResponseSchema,
11 + UsageFilters,
12 + UsageSummaryParams,
13 + UsageSummaryResponse,
14 + UsageSummaryResponseSchema,
15 +} from '../../types/usage.types';
16 +import { transform } from '../transform';
17 +
18 +const transformUsageFilters = (
19 + filters: UsageFilters | undefined
20 +): RawUsageSummaryParams['filters'] =>
21 + filters ? { user_id: filters.userId, session_id: filters.sessionId } : undefined;
22 +
23 +export const transformUsageSummaryParams = (params: UsageSummaryParams): RawUsageSummaryParams => ({
24 + from: params.from,
25 + to: params.to,
26 + entity_types: params.entityTypes,
27 + filters: transformUsageFilters(params.filters),
28 +});
29 +
30 +export const transformUsageBreakdownParams = (
31 + params: UsageBreakdownParams
32 +): RawUsageBreakdownParams => ({
33 + from: params.from,
34 + to: params.to,
35 + group_by: params.groupBy,
36 + order_by: params.orderBy,
37 + order_direction: params.orderDirection,
38 + limit: params.limit,
39 + filters: transformUsageFilters(params.filters),
40 +});
41 +
42 +export const transformUsageSummaryResponse = (
43 + response: RawUsageSummaryResponse
44 +): UsageSummaryResponse => {
45 + return transform(response)
46 + .with(UsageSummaryResponseSchema)
47 + .using(response => ({
48 + entities: Object.fromEntries(
49 + Object.entries(response.entities).map(([entityType, entity]) => [
50 + entityType,
51 + {
52 + unit: entity.unit,
53 + totalQuantity: entity.total_quantity,
54 + eventCount: entity.event_count,
55 + },
56 + ])
57 + ),
58 + }));
59 +};
60 +
61 +export const transformUsageBreakdownResponse = (
62 + response: RawUsageBreakdownResponse
63 +): UsageBreakdownResponse => {
64 + return transform(response)
65 + .with(UsageBreakdownResponseSchema)
66 + .using(response => ({
67 + entityType: response.entity_type,
68 + unit: response.unit,
69 + totalQuantity: response.total_quantity,
70 + eventCount: response.event_count,
71 + groups: response.groups.map(group => ({
72 + key: group.key,
73 + totalQuantity: group.total_quantity,
74 + eventCount: group.event_count,
75 + })),
76 + }));
77 +};
ts/packages/core/src/utils/transformers/webhooks.ts new
+139
@@ -0,0 +1,139 @@
1 +import type {
2 + WebhookSubscriptionCreateResponse as RawWebhookSubscriptionCreateResponse,
3 + WebhookSubscriptionDeleteResponse as RawWebhookSubscriptionDeleteResponse,
4 + WebhookSubscriptionListEventTypesResponse as RawWebhookSubscriptionListEventTypesResponse,
5 + WebhookSubscriptionListResponse as RawWebhookSubscriptionListResponse,
6 + WebhookSubscriptionRetrieveResponse as RawWebhookSubscriptionRetrieveResponse,
7 + WebhookSubscriptionRotateSecretResponse as RawWebhookSubscriptionRotateSecretResponse,
8 + WebhookSubscriptionUpdateResponse as RawWebhookSubscriptionUpdateResponse,
9 +} from '@composio/client/resources/webhook-subscriptions';
10 +import type {
11 + WebhookEndpointCreateResponse as RawWebhookEndpointCreateResponse,
12 + WebhookEndpointListResponse as RawWebhookEndpointListResponse,
13 + WebhookEndpointReplaceResponse as RawWebhookEndpointReplaceResponse,
14 + WebhookEndpointRetrieveResponse as RawWebhookEndpointRetrieveResponse,
15 + WebhookEndpointUpdateResponse as RawWebhookEndpointUpdateResponse,
16 +} from '@composio/client/resources/webhook-endpoints';
17 +import type { WebhookSubscription } from '../../types/triggers.types';
18 +import {
19 + WebhookEndpoint,
20 + WebhookEndpointListResponse,
21 + WebhookEndpointListResponseSchema,
22 + WebhookEndpointSchema,
23 + WebhookSubscriptionEventTypesResponse,
24 + WebhookSubscriptionEventTypesResponseSchema,
25 + WebhookSubscriptionDeleteResponse,
26 + WebhookSubscriptionDeleteResponseSchema,
27 + WebhookSubscriptionListResponse,
28 + WebhookSubscriptionListResponseSchema,
29 + WebhookSubscriptionRotateSecretResponse,
30 + WebhookSubscriptionRotateSecretResponseSchema,
31 + WebhookSubscriptionSchema,
32 +} from '../../types/webhooks.types';
33 +import { transform } from '../transform';
34 +
35 +/**
36 + * Every subscription read/write on the wire returns the same object; the
37 + * generated client only gives it a different nominal name per operation.
38 + */
39 +export type RawWebhookSubscription =
40 + | RawWebhookSubscriptionCreateResponse
41 + | RawWebhookSubscriptionRetrieveResponse
42 + | RawWebhookSubscriptionUpdateResponse
43 + | RawWebhookSubscriptionListResponse['items'][number];
44 +
45 +export const transformWebhookSubscription = (
46 + response: RawWebhookSubscription
47 +): WebhookSubscription => {
48 + // Map to camelCase explicitly — do NOT spread `...response`, or the wire's
49 + // snake_case keys (webhook_url, enabled_events, created_at, ...) leak into
50 + // the public object alongside their camelCase counterparts.
51 + return transform(response)
52 + .with(WebhookSubscriptionSchema)
53 + .using(response => ({
54 + id: response.id,
55 + webhookUrl: response.webhook_url,
56 + version: response.version,
57 + enabledEvents: response.enabled_events,
58 + secret: response.secret,
59 + createdAt: response.created_at,
60 + updatedAt: response.updated_at,
61 + }));
62 +};
63 +
64 +export const transformWebhookSubscriptionListResponse = (
65 + response: RawWebhookSubscriptionListResponse
66 +): WebhookSubscriptionListResponse => {
67 + return transform(response)
68 + .with(WebhookSubscriptionListResponseSchema)
69 + .using(response => ({
70 + items: response.items.map(transformWebhookSubscription),
71 + nextCursor: response.next_cursor ?? null,
72 + totalPages: response.total_pages,
73 + currentPage: response.current_page,
74 + totalItems: response.total_items,
75 + }));
76 +};
77 +
78 +export const transformWebhookSubscriptionDeleteResponse = (
79 + response: RawWebhookSubscriptionDeleteResponse
80 +): WebhookSubscriptionDeleteResponse => {
81 + return transform(response)
82 + .with(WebhookSubscriptionDeleteResponseSchema)
83 + .using(response => ({ success: response.success }));
84 +};
85 +
86 +export const transformWebhookSubscriptionRotateSecretResponse = (
87 + response: RawWebhookSubscriptionRotateSecretResponse
88 +): WebhookSubscriptionRotateSecretResponse => {
89 + return transform(response)
90 + .with(WebhookSubscriptionRotateSecretResponseSchema)
91 + .using(response => ({ id: response.id, secret: response.secret }));
92 +};
93 +
94 +export const transformWebhookSubscriptionEventTypesResponse = (
95 + response: RawWebhookSubscriptionListEventTypesResponse
96 +): WebhookSubscriptionEventTypesResponse => {
97 + return transform(response)
98 + .with(WebhookSubscriptionEventTypesResponseSchema)
99 + .using(response => ({
100 + items: response.items.map(item => ({
101 + eventType: item.event_type,
102 + description: item.description,
103 + supportedVersions: item.supported_versions,
104 + })),
105 + }));
106 +};
107 +
108 +export type RawWebhookEndpoint =
109 + | RawWebhookEndpointCreateResponse
110 + | RawWebhookEndpointRetrieveResponse
111 + | RawWebhookEndpointReplaceResponse
112 + | RawWebhookEndpointUpdateResponse;
113 +
114 +export const transformWebhookEndpoint = (response: RawWebhookEndpoint): WebhookEndpoint => {
115 + return transform(response)
116 + .with(WebhookEndpointSchema)
117 + .using(response => ({
118 + id: response.id,
119 + toolkitSlug: response.toolkit_slug,
120 + clientId: response.client_id,
121 + webhookUrl: response.webhook_url,
122 + data: response.data,
123 + createdAt: response.created_at,
124 + }));
125 +};
126 +
127 +export const transformWebhookEndpointListResponse = (
128 + response: RawWebhookEndpointListResponse
129 +): WebhookEndpointListResponse => {
130 + return transform(response)
131 + .with(WebhookEndpointListResponseSchema)
132 + .using(response => ({
133 + items: response.items.map(item => ({
134 + id: item.id,
135 + toolkitSlug: item.toolkit_slug,
136 + clientId: item.client_id,
137 + })),
138 + }));
139 +};
ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+131 -6
@@ -7,14 +7,22 @@ import { ConnectedAccountRetrieveResponse } from '@composio/client/resources/con
7 import {
8 ComposioAclOnlyForSharedError,
9 ComposioConnectedAccountNotFoundError,
10 + ComposioConnectedAccountNotRevokableError,
11 + ComposioConnectedAccountRevocationNotSupportedError,
12 ComposioFailedToCreateConnectedAccountLink,
13 } from '../../src/errors';
12 -import { BadRequestError } from '@composio/client';
14 +import {
15 + BadRequestError,
16 + ConflictError,
17 + InternalServerError,
18 + NotFoundError,
19 +} from '@composio/client';
20 import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';
21 import { ComposioMultipleConnectedAccountsError } from '../../src/errors';
22 import { AuthSchemeTypes } from '../../src/types/authConfigs.types';
23 import { AuthScheme } from '../../src/models/AuthScheme';
24 import { ConnectionStatuses } from '../../src/types/connectedAccountAuthStates.types';
25 +import logger from '../../src/utils/logger';
26
27 // Extend the mock client object for ConnectedAccounts testing
28 const extendedMockClient = {
@@ -25,6 +33,8 @@ const extendedMockClient = {
33 retrieve: vi.fn(),
34 delete: vi.fn(),
35 refresh: vi.fn(),
36 + revoke: vi.fn(),
37 + completeAuth: vi.fn(),
38 patch: vi.fn(),
39 updateStatus: vi.fn(),
40 createConnectedAccountLink: vi.fn(),
@@ -808,16 +818,16 @@ describe('ConnectedAccounts', () => {
818 nanoid,
819 {
820 query_redirect_url: redirectUrl,
811 - validate_credentials: undefined,
821 },
822 undefined
823 );
824 expect(result).toEqual(mockResponse);
825 });
826
818 - it('should refresh a connected account with validateCredentials option', async () => {
827 + it('should ignore the removed validateCredentials option and warn', async () => {
828 const nanoid = 'conn_123';
829 const mockResponse = { id: nanoid, refreshed: true };
830 + const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});
831
832 extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
833
@@ -827,11 +837,12 @@ describe('ConnectedAccounts', () => {
837 nanoid,
838 {
839 query_redirect_url: undefined,
830 - validate_credentials: true,
840 },
841 undefined
842 );
843 + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('validateCredentials'));
844 expect(result).toEqual(mockResponse);
845 + warnSpy.mockRestore();
846 });
847
848 it('should refresh a connected account with both options', async () => {
@@ -850,7 +861,6 @@ describe('ConnectedAccounts', () => {
861 nanoid,
862 {
863 query_redirect_url: options.redirectUrl,
853 - validate_credentials: options.validateCredentials,
864 },
865 undefined
866 );
@@ -880,7 +890,6 @@ describe('ConnectedAccounts', () => {
890 nanoid,
891 {
892 query_redirect_url: undefined,
883 - validate_credentials: undefined,
893 },
894 undefined
895 );
@@ -1874,4 +1883,120 @@ describe('ConnectedAccounts', () => {
1883 );
1884 });
1885 });
1886 +
1887 + describe('revoke', () => {
1888 + const nanoid = 'conn_123';
1889 +
1890 + it('should revoke a connected account and transform the response', async () => {
1891 + extendedMockClient.connectedAccounts.revoke.mockResolvedValueOnce({
1892 + revoked_tokens: ['access_token', 'refresh_token'],
1893 + connected_account: { id: nanoid, status: 'REVOKED' },
1894 + });
1895 +
1896 + const result = await connectedAccounts.revoke(nanoid);
1897 +
1898 + expect(extendedMockClient.connectedAccounts.revoke).toHaveBeenCalledWith(nanoid, undefined);
1899 + expect(result).toEqual({
1900 + revokedTokens: ['access_token', 'refresh_token'],
1901 + connectedAccount: { id: nanoid, status: 'REVOKED' },
1902 + });
1903 + });
1904 +
1905 + it('should forward request options', async () => {
1906 + extendedMockClient.connectedAccounts.revoke.mockResolvedValueOnce({
1907 + revoked_tokens: [],
1908 + connected_account: { id: nanoid, status: 'REVOKED' },
1909 + });
1910 + const signal = new AbortController().signal;
1911 +
1912 + await connectedAccounts.revoke(nanoid, { signal });
1913 +
1914 + expect(extendedMockClient.connectedAccounts.revoke).toHaveBeenCalledWith(nanoid, { signal });
1915 + });
1916 +
1917 + it('should surface a 400 as ComposioConnectedAccountRevocationNotSupportedError', async () => {
1918 + extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(
1919 + new BadRequestError(400, undefined, 'Toolkit does not support revocation', {})
1920 + );
1921 +
1922 + const error = await connectedAccounts.revoke(nanoid).catch((caught: unknown) => caught);
1923 +
1924 + expect(error).toBeInstanceOf(ComposioConnectedAccountRevocationNotSupportedError);
1925 + expect(error).toMatchObject({
1926 + message: expect.stringContaining('does not support revocation'),
1927 + meta: { nanoid },
1928 + });
1929 + });
1930 +
1931 + it('should surface a 409 as ComposioConnectedAccountNotRevokableError', async () => {
1932 + extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(
1933 + new ConflictError(409, undefined, 'Connection is not in a revokable state', {})
1934 + );
1935 +
1936 + await expect(connectedAccounts.revoke(nanoid)).rejects.toThrow(
1937 + ComposioConnectedAccountNotRevokableError
1938 + );
1939 + });
1940 +
1941 + it('should rethrow other errors unchanged', async () => {
1942 + const serverError = new InternalServerError(500, undefined, 'boom', {});
1943 + extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(serverError);
1944 +
1945 + await expect(connectedAccounts.revoke(nanoid)).rejects.toBe(serverError);
1946 + });
1947 + });
1948 +
1949 + describe('completeAuth', () => {
1950 + it('should redeem the session and transform the response', async () => {
1951 + extendedMockClient.connectedAccounts.completeAuth.mockResolvedValueOnce({
1952 + connected_account_id: 'ca_123',
1953 + toolkit_slug: 'github',
1954 + });
1955 +
1956 + const result = await connectedAccounts.completeAuth({
1957 + userId: 'user_1',
1958 + sessionUri: 'session_abc',
1959 + });
1960 +
1961 + expect(extendedMockClient.connectedAccounts.completeAuth).toHaveBeenCalledWith(
1962 + { user_id: 'user_1', session_uri: 'session_abc' },
1963 + undefined
1964 + );
1965 + expect(result).toEqual({ connectedAccountId: 'ca_123', toolkitSlug: 'github' });
1966 + });
1967 +
1968 + it('should forward request options', async () => {
1969 + extendedMockClient.connectedAccounts.completeAuth.mockResolvedValueOnce({
1970 + connected_account_id: 'ca_123',
1971 + toolkit_slug: 'github',
1972 + });
1973 + const signal = new AbortController().signal;
1974 +
1975 + await connectedAccounts.completeAuth(
1976 + { userId: 'user_1', sessionUri: 'session_abc' },
1977 + { signal }
1978 + );
1979 +
1980 + expect(extendedMockClient.connectedAccounts.completeAuth).toHaveBeenCalledWith(
1981 + { user_id: 'user_1', session_uri: 'session_abc' },
1982 + { signal }
1983 + );
1984 + });
1985 +
1986 + it('should reject an empty userId before calling the API', async () => {
1987 + await expect(
1988 + connectedAccounts.completeAuth({ userId: '', sessionUri: 'session_abc' })
1989 + ).rejects.toThrow('Failed to parse connected account completeAuth params');
1990 + expect(extendedMockClient.connectedAccounts.completeAuth).not.toHaveBeenCalled();
1991 + });
1992 +
1993 + it('should rethrow API errors unchanged', async () => {
1994 + const notFound = new NotFoundError(404, undefined, 'Session not found', {});
1995 + extendedMockClient.connectedAccounts.completeAuth.mockRejectedValueOnce(notFound);
1996 +
1997 + await expect(
1998 + connectedAccounts.completeAuth({ userId: 'user_1', sessionUri: 'session_abc' })
1999 + ).rejects.toBe(notFound);
2000 + });
2001 + });
2002 });
ts/packages/core/test/core/credentials.test.ts new
+75
@@ -0,0 +1,75 @@
1 +import { describe, it, expect, afterEach, vi } from 'vitest';
2 +import { Composio } from '../../src/composio';
3 +import { MockProvider } from '../utils/mocks/provider.mock';
4 +
5 +/**
6 + * `userApiKey` / `orgApiKey` are forwarded to the API client, which selects the
7 + * credential per operation and resolves the env fallbacks itself.
8 + */
9 +describe('Composio user and organization API keys', () => {
10 + const baseConfig = {
11 + apiKey: 'ak_test',
12 + baseURL: 'https://api.test.com',
13 + provider: new MockProvider(),
14 + allowTracking: false,
15 + disableVersionCheck: true,
16 + };
17 +
18 + afterEach(() => {
19 + vi.unstubAllEnvs();
20 + });
21 +
22 + it('forwards both keys to the API client', () => {
23 + const composio = new Composio({
24 + ...baseConfig,
25 + userApiKey: 'uak_test',
26 + orgApiKey: 'oak_test',
27 + });
28 + const client = composio.getClient();
29 + expect(client.apiKey).toBe('ak_test');
30 + expect(client.userApiKey).toBe('uak_test');
31 + expect(client.orgApiKey).toBe('oak_test');
32 + });
33 +
34 + it('leaves both keys unset on the client when not configured', () => {
35 + vi.stubEnv('COMPOSIO_USER_API_KEY', '');
36 + vi.stubEnv('COMPOSIO_ORG_API_KEY', '');
37 + const client = new Composio(baseConfig).getClient();
38 + expect(client.userApiKey).toBeNull();
39 + expect(client.orgApiKey).toBeNull();
40 + });
41 +
42 + it('lets the client resolve the env fallbacks', () => {
43 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
44 + vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');
45 + const client = new Composio(baseConfig).getClient();
46 + expect(client.userApiKey).toBe('uak_env');
47 + expect(client.orgApiKey).toBe('oak_env');
48 + });
49 +
50 + it('exposes both keys on getConfig() and carries them into createSession()', () => {
51 + const composio = new Composio({
52 + ...baseConfig,
53 + userApiKey: 'uak_test',
54 + orgApiKey: 'oak_test',
55 + });
56 + expect(composio.getConfig()).toMatchObject({ userApiKey: 'uak_test', orgApiKey: 'oak_test' });
57 + const session = composio.createSession({ headers: { 'x-request-id': '1' } });
58 + expect(session.getConfig()).toMatchObject({ userApiKey: 'uak_test', orgApiKey: 'oak_test' });
59 + expect(session.getClient().userApiKey).toBe('uak_test');
60 + expect(session.getClient().orgApiKey).toBe('oak_test');
61 + });
62 +
63 + it('stores env-resolved keys on the config so createSession() keeps them after env changes', () => {
64 + vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_env');
65 + vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_env');
66 + const composio = new Composio(baseConfig);
67 + expect(composio.getConfig()).toMatchObject({ userApiKey: 'uak_env', orgApiKey: 'oak_env' });
68 +
69 + vi.stubEnv('COMPOSIO_USER_API_KEY', '');
70 + vi.stubEnv('COMPOSIO_ORG_API_KEY', 'oak_other');
71 + const session = composio.createSession({ headers: { 'x-request-id': '1' } });
72 + expect(session.getClient().userApiKey).toBe('uak_env');
73 + expect(session.getClient().orgApiKey).toBe('oak_env');
74 + });
75 +});
ts/packages/core/test/core/loggerConfig.test.ts new
+181
@@ -0,0 +1,181 @@
1 +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2 +import { Composio } from '../../src/composio';
3 +import logger from '../../src/utils/logger';
4 +import { MockProvider } from '../utils/mocks/provider.mock';
5 +
6 +const DEPRECATION_HEADER = '@1688169599';
7 +
8 +const jsonResponse = (body: unknown, headers: Record<string, string> = {}): Response =>
9 + new Response(JSON.stringify(body), {
10 + status: 200,
11 + headers: { 'content-type': 'application/json', ...headers },
12 + });
13 +
14 +const createSink = () => ({
15 + error: vi.fn(),
16 + warn: vi.fn(),
17 + info: vi.fn(),
18 + debug: vi.fn(),
19 +});
20 +
21 +const createComposio = (config: Partial<ConstructorParameters<typeof Composio>[0]> = {}) =>
22 + new Composio({
23 + apiKey: 'uak_test_secret',
24 + baseURL: 'https://backend.composio.test',
25 + provider: new MockProvider(),
26 + allowTracking: false,
27 + disableVersionCheck: true,
28 + ...config,
29 + });
30 +
31 +describe('Composio logger and logLevel configuration', () => {
32 + let fetchMock: ReturnType<typeof vi.fn>;
33 +
34 + beforeEach(() => {
35 + fetchMock = vi.fn();
36 + vi.stubGlobal('fetch', fetchMock);
37 + });
38 +
39 + afterEach(() => {
40 + vi.unstubAllGlobals();
41 + vi.restoreAllMocks();
42 + // The SDK logger is a process-wide singleton; restore the defaults so
43 + // later tests in this file start from a known state.
44 + logger.configure({ level: 'info', sink: console });
45 + });
46 +
47 + it('routes response Deprecation header warnings through the configured logger', async () => {
48 + const sink = createSink();
49 + fetchMock.mockResolvedValue(jsonResponse({ items: [] }, { Deprecation: DEPRECATION_HEADER }));
50 + const composio = createComposio({ logger: sink });
51 +
52 + await composio.getClient().toolkits.list();
53 +
54 + expect(sink.warn).toHaveBeenCalledTimes(1);
55 + const message = String(sink.warn.mock.calls[0]?.[0]);
56 + expect(message).toContain('deprecated');
57 + expect(message).toContain('toolkits.list');
58 + });
59 +
60 + it('formats and redacts client warnings with the SDK logger before they reach the sink', async () => {
61 + const sink = createSink();
62 + fetchMock.mockResolvedValue(
63 + jsonResponse(
64 + { items: [] },
65 + {
66 + Deprecation: DEPRECATION_HEADER,
67 + Link: '<https://backend.composio.test/docs?api_key=uak_leaked_secret>; rel="deprecation"',
68 + }
69 + )
70 + );
71 + const composio = createComposio({ logger: sink });
72 +
73 + await composio.getClient().toolkits.list();
74 +
75 + expect(sink.warn).toHaveBeenCalledTimes(1);
76 + const message = String(sink.warn.mock.calls[0]?.[0]);
77 + // SDK formatting prepends an ISO timestamp.
78 + expect(message).toMatch(/^\S*\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\S* - /);
79 + expect(message).not.toContain('uak_leaked_secret');
80 + expect(message).toContain('[REDACTED]');
81 + });
82 +
83 + it('warns about deprecated request inputs before the request is dispatched', async () => {
84 + const sink = createSink();
85 + const order: string[] = [];
86 + sink.warn.mockImplementation(() => order.push('warn'));
87 + fetchMock.mockImplementation(async () => {
88 + order.push('fetch');
89 + return jsonResponse({ items: [], total_pages: 1, current_page: 1, total_items: 0 });
90 + });
91 + const composio = createComposio({ logger: sink });
92 +
93 + await composio.getClient().tools.list({ search: 'x' });
94 +
95 + expect(sink.warn).toHaveBeenCalledTimes(1);
96 + const message = String(sink.warn.mock.calls[0]?.[0]);
97 + expect(message).toContain('`search`');
98 + expect(message).toContain('deprecated');
99 + expect(order).toEqual(['warn', 'fetch']);
100 + });
101 +
102 + it("suppresses both deprecation warnings when logLevel is 'silent'", async () => {
103 + const sink = createSink();
104 + fetchMock.mockResolvedValue(jsonResponse({ items: [] }, { Deprecation: DEPRECATION_HEADER }));
105 + const composio = createComposio({ logger: sink, logLevel: 'silent' });
106 +
107 + await composio.getClient().toolkits.list();
108 + await composio.getClient().tools.list({ search: 'x' });
109 +
110 + expect(sink.warn).not.toHaveBeenCalled();
111 + expect(sink.info).not.toHaveBeenCalled();
112 + expect(sink.debug).not.toHaveBeenCalled();
113 + expect(sink.error).not.toHaveBeenCalled();
114 + });
115 +
116 + it("suppresses warnings when logLevel is 'error'", async () => {
117 + const sink = createSink();
118 + fetchMock.mockResolvedValue(jsonResponse({ items: [] }, { Deprecation: DEPRECATION_HEADER }));
119 + const composio = createComposio({ logger: sink, logLevel: 'error' });
120 +
121 + await composio.getClient().toolkits.list();
122 + await composio.getClient().tools.list({ search: 'x' });
123 +
124 + expect(sink.warn).not.toHaveBeenCalled();
125 + expect(logger.getLevel()).toBe('error');
126 + });
127 +
128 + it('keeps per-request client logs out of the default info level', async () => {
129 + const sink = createSink();
130 + fetchMock.mockResolvedValue(jsonResponse({ items: [] }));
131 + const composio = createComposio({ logger: sink });
132 +
133 + await composio.getClient().toolkits.list();
134 +
135 + expect(sink.info).not.toHaveBeenCalled();
136 + expect(sink.debug).not.toHaveBeenCalled();
137 + expect(sink.warn).not.toHaveBeenCalled();
138 + });
139 +
140 + it("routes per-request client logs to debug when logLevel is 'debug'", async () => {
141 + const sink = createSink();
142 + fetchMock.mockResolvedValue(jsonResponse({ items: [] }));
143 + const composio = createComposio({ logger: sink, logLevel: 'debug' });
144 +
145 + await composio.getClient().toolkits.list();
146 +
147 + expect(sink.info).not.toHaveBeenCalled();
148 + expect(sink.debug.mock.calls.map(call => String(call[0])).join('\n')).toContain('/toolkits');
149 + });
150 +
151 + it('leaves the singleton untouched when neither option is provided', () => {
152 + const sink = createSink();
153 + logger.configure({ level: 'debug', sink });
154 +
155 + createComposio();
156 +
157 + expect(logger.getLevel()).toBe('debug');
158 + logger.debug('still routed');
159 + expect(String(sink.debug.mock.lastCall?.[0])).toContain('still routed');
160 + });
161 +
162 + it('applies logLevel without replacing the sink, and the last instance wins', () => {
163 + const first = createSink();
164 + const second = createSink();
165 +
166 + createComposio({ logger: first, logLevel: 'warn' });
167 + expect(logger.getLevel()).toBe('warn');
168 +
169 + createComposio({ logLevel: 'debug' });
170 + expect(logger.getLevel()).toBe('debug');
171 + logger.debug('to first');
172 + expect(String(first.debug.mock.lastCall?.[0])).toContain('to first');
173 + expect(second.debug).not.toHaveBeenCalled();
174 +
175 + createComposio({ logger: second });
176 + const firstCallsBefore = first.debug.mock.calls.length;
177 + logger.debug('to second');
178 + expect(first.debug.mock.calls.length).toBe(firstCallsBefore);
179 + expect(String(second.debug.mock.lastCall?.[0])).toContain('to second');
180 + });
181 +});
ts/packages/core/test/models/customToolkits.test.ts new
+197
@@ -0,0 +1,197 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 +import { CustomToolkits } from '../../src/models/CustomToolkits';
4 +import { Experimental } from '../../src/models/Experimental';
5 +import { telemetry } from '../../src/telemetry/Telemetry';
6 +import { ValidationError } from '../../src/errors/ValidationErrors';
7 +
8 +vi.mock('../../src/telemetry/Telemetry', () => ({
9 + telemetry: {
10 + instrument: vi.fn(),
11 + },
12 +}));
13 +
14 +const createMockClient = () => ({
15 + custom: {
16 + upsert: vi.fn(),
17 + sync: vi.fn(),
18 + deleteToolkit: vi.fn(),
19 + },
20 +});
21 +
22 +describe('Experimental.customToolkits', () => {
23 + let customToolkits: CustomToolkits;
24 + let mockClient: ReturnType<typeof createMockClient>;
25 +
26 + beforeEach(() => {
27 + vi.clearAllMocks();
28 + mockClient = createMockClient();
29 + customToolkits = new Experimental(mockClient as unknown as ComposioClient).customToolkits;
30 + });
31 +
32 + it('mounts on the experimental namespace and instruments it', () => {
33 + expect(customToolkits).toBeInstanceOf(CustomToolkits);
34 + expect(telemetry.instrument).toHaveBeenCalledWith(customToolkits, 'CustomToolkits');
35 + });
36 +
37 + describe('upsert', () => {
38 + it('maps every auth scheme and the logo to the wire', async () => {
39 + mockClient.custom.upsert.mockResolvedValue({ slug: 'CUSTOM_MY_TOOLKIT' });
40 +
41 + const result = await customToolkits.upsert({
42 + slug: 'MY TOOLKIT',
43 + toolkitConfig: {
44 + name: 'My Toolkit',
45 + appUrl: 'https://mcp.example.com/mcp',
46 + logoFile: { content: 'aGVsbG8=', mimeType: 'image/png' },
47 + authSchemes: [
48 + { mode: 'NO_AUTH' },
49 + {
50 + mode: 'API_KEY',
51 + headers: { Authorization: 'Bearer {{generic_api_key}}' },
52 + apiKeyField: { displayName: 'API key', description: 'From your settings page' },
53 + },
54 + {
55 + mode: 'DCR_OAUTH',
56 + discoveryUrl: 'https://mcp.example.com/.well-known/oauth-authorization-server',
57 + },
58 + ],
59 + },
60 + });
61 +
62 + expect(mockClient.custom.upsert).toHaveBeenCalledWith(
63 + {
64 + slug: 'MY TOOLKIT',
65 + toolkit_config: {
66 + name: 'My Toolkit',
67 + app_url: 'https://mcp.example.com/mcp',
68 + logo_file: { content: 'aGVsbG8=', mime_type: 'image/png' },
69 + auth_schemes: [
70 + { mode: 'NO_AUTH' },
71 + {
72 + mode: 'API_KEY',
73 + headers: { Authorization: 'Bearer {{generic_api_key}}' },
74 + api_key_field: { display_name: 'API key', description: 'From your settings page' },
75 + },
76 + {
77 + mode: 'DCR_OAUTH',
78 + discovery_url: 'https://mcp.example.com/.well-known/oauth-authorization-server',
79 + },
80 + ],
81 + },
82 + },
83 + undefined
84 + );
85 + expect(result).toEqual({ slug: 'CUSTOM_MY_TOOLKIT' });
86 + });
87 +
88 + it('omits the optional logo and API key copy', async () => {
89 + mockClient.custom.upsert.mockResolvedValue({ slug: 'CUSTOM_MY_TOOLKIT' });
90 +
91 + await customToolkits.upsert({
92 + slug: 'MY_TOOLKIT',
93 + toolkitConfig: {
94 + name: 'My Toolkit',
95 + appUrl: 'https://mcp.example.com/mcp',
96 + authSchemes: [{ mode: 'API_KEY', headers: { 'x-api-key': '{{generic_api_key}}' } }],
97 + },
98 + });
99 +
100 + const [body] = mockClient.custom.upsert.mock.calls[0];
101 + expect(JSON.parse(JSON.stringify(body))).toEqual({
102 + slug: 'MY_TOOLKIT',
103 + toolkit_config: {
104 + name: 'My Toolkit',
105 + app_url: 'https://mcp.example.com/mcp',
106 + auth_schemes: [{ mode: 'API_KEY', headers: { 'x-api-key': '{{generic_api_key}}' } }],
107 + },
108 + });
109 + });
110 +
111 + it.each([
112 + ['a slug outside the API grammar', { slug: 'my-toolkit' }],
113 + ['no auth schemes', { authSchemes: [] }],
114 + ['an app URL that is not a URL', { appUrl: 'not a url' }],
115 + ])('rejects %s before calling the API', async (_label, override) => {
116 + const { slug = 'MY_TOOLKIT', ...config } = override as Record<string, unknown>;
117 +
118 + await expect(
119 + customToolkits.upsert({
120 + slug: slug as string,
121 + toolkitConfig: {
122 + name: 'My Toolkit',
123 + appUrl: 'https://mcp.example.com/mcp',
124 + authSchemes: [{ mode: 'NO_AUTH' }],
125 + ...config,
126 + },
127 + })
128 + ).rejects.toThrow(ValidationError);
129 + expect(mockClient.custom.upsert).not.toHaveBeenCalled();
130 + });
131 + });
132 +
133 + describe('sync', () => {
134 + it('sends the slug and connected account and transforms the response', async () => {
135 + mockClient.custom.sync.mockResolvedValue({
136 + slug: 'CUSTOM_MY_TOOLKIT',
137 + version: '20260911_00',
138 + synced_count: 12,
139 + });
140 + const signal = new AbortController().signal;
141 +
142 + const result = await customToolkits.sync(
143 + 'CUSTOM_MY_TOOLKIT',
144 + { connectedAccountId: 'ca_abc123' },
145 + { signal }
146 + );
147 +
148 + expect(mockClient.custom.sync).toHaveBeenCalledWith(
149 + { slug: 'CUSTOM_MY_TOOLKIT', connected_account_id: 'ca_abc123' },
150 + { signal }
151 + );
152 + expect(result).toEqual({
153 + slug: 'CUSTOM_MY_TOOLKIT',
154 + version: '20260911_00',
155 + syncedCount: 12,
156 + });
157 + });
158 +
159 + it('sends only the slug when called without params', async () => {
160 + mockClient.custom.sync.mockResolvedValue({
161 + slug: 'CUSTOM_MY_TOOLKIT',
162 + version: '20260911_00',
163 + synced_count: 0,
164 + });
165 +
166 + await customToolkits.sync('CUSTOM_MY_TOOLKIT');
167 +
168 + expect(mockClient.custom.sync).toHaveBeenCalledWith(
169 + { slug: 'CUSTOM_MY_TOOLKIT', connected_account_id: undefined },
170 + undefined
171 + );
172 + });
173 + });
174 +
175 + describe('delete', () => {
176 + it('deletes the toolkit and transforms the response', async () => {
177 + mockClient.custom.deleteToolkit.mockResolvedValue({
178 + slug: 'CUSTOM_MY_TOOLKIT',
179 + deleted: true,
180 + revoke_job_ids: ['job_1'],
181 + auth_configs_deleted: 1,
182 + connected_accounts_deleted: 2,
183 + });
184 +
185 + const result = await customToolkits.delete('CUSTOM_MY_TOOLKIT');
186 +
187 + expect(mockClient.custom.deleteToolkit).toHaveBeenCalledWith('CUSTOM_MY_TOOLKIT', undefined);
188 + expect(result).toEqual({
189 + slug: 'CUSTOM_MY_TOOLKIT',
190 + deleted: true,
191 + revokeJobIds: ['job_1'],
192 + authConfigsDeleted: 1,
193 + connectedAccountsDeleted: 2,
194 + });
195 + });
196 + });
197 +});
ts/packages/core/test/models/keyring.test.ts new
+69
@@ -0,0 +1,69 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 +import { Keyring } from '../../src/models/Keyring';
4 +import { telemetry } from '../../src/telemetry/Telemetry';
5 +
6 +vi.mock('../../src/telemetry/Telemetry', () => ({
7 + telemetry: {
8 + instrument: vi.fn(),
9 + },
10 +}));
11 +
12 +const createMockClient = () => ({
13 + keyring: {
14 + listTransferKeys: vi.fn(),
15 + },
16 +});
17 +
18 +const rawKey = {
19 + kty: 'RSA',
20 + n: 'sXch3m2k0Yg',
21 + e: 'AQAB',
22 + alg: 'RSA-OAEP-256',
23 + use: 'enc',
24 + kid: 'kid_2',
25 +};
26 +
27 +describe('Keyring', () => {
28 + let keyring: Keyring;
29 + let mockClient: ReturnType<typeof createMockClient>;
30 +
31 + beforeEach(() => {
32 + vi.clearAllMocks();
33 + mockClient = createMockClient();
34 + keyring = new Keyring(mockClient as unknown as ComposioClient);
35 + });
36 +
37 + it('instruments itself', () => {
38 + expect(telemetry.instrument).toHaveBeenCalledWith(keyring, 'Keyring');
39 + });
40 +
41 + it('returns the active kid and keeps the JWK field names', async () => {
42 + mockClient.keyring.listTransferKeys.mockResolvedValue({
43 + success: true,
44 + active_kid: 'kid_2',
45 + keys: [rawKey, { ...rawKey, kid: 'kid_1' }],
46 + });
47 +
48 + const result = await keyring.listTransferKeys();
49 +
50 + expect(mockClient.keyring.listTransferKeys).toHaveBeenCalledWith(undefined);
51 + expect(result).toEqual({
52 + activeKid: 'kid_2',
53 + keys: [rawKey, { ...rawKey, kid: 'kid_1' }],
54 + });
55 + });
56 +
57 + it('forwards request options', async () => {
58 + mockClient.keyring.listTransferKeys.mockResolvedValue({
59 + success: true,
60 + active_kid: 'kid_2',
61 + keys: [rawKey],
62 + });
63 + const signal = new AbortController().signal;
64 +
65 + await keyring.listTransferKeys({ signal });
66 +
67 + expect(mockClient.keyring.listTransferKeys).toHaveBeenCalledWith({ signal });
68 + });
69 +});
ts/packages/core/test/models/logs.test.ts new
+153
@@ -0,0 +1,153 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 +import { Logs } from '../../src/models/Logs';
4 +import { telemetry } from '../../src/telemetry/Telemetry';
5 +import { ValidationError } from '../../src/errors/ValidationErrors';
6 +
7 +vi.mock('../../src/telemetry/Telemetry', () => ({
8 + telemetry: {
9 + instrument: vi.fn(),
10 + },
11 +}));
12 +
13 +const createMockClient = () => ({
14 + baseURL: 'https://api.composio.dev',
15 + apiKey: 'test-api-key',
16 + logs: {
17 + createToolExecution: vi.fn(),
18 + retrieveToolExecution: vi.fn(),
19 + },
20 +});
21 +
22 +const rawLog = {
23 + id: 'log_1',
24 + timestamp: '2026-01-01T00:00:00Z',
25 + type: 'tool.execution',
26 + status: 'success',
27 + level: 'info',
28 + message: 'ok',
29 + metadata: { tool_slug: 'GITHUB_GET_REPO' },
30 + metrics: { duration_ms: 12 },
31 + parent: { log_id: 'log_0', tool_slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' },
32 +};
33 +const transformedLog = {
34 + id: 'log_1',
35 + timestamp: '2026-01-01T00:00:00Z',
36 + type: 'tool.execution',
37 + status: 'success',
38 + level: 'info',
39 + message: 'ok',
40 + metadata: { tool_slug: 'GITHUB_GET_REPO' },
41 + metrics: { duration_ms: 12 },
42 + parent: { logId: 'log_0', toolSlug: 'COMPOSIO_MULTI_EXECUTE_TOOL' },
43 +};
44 +
45 +describe('Logs', () => {
46 + let logs: Logs;
47 + let mockClient: ReturnType<typeof createMockClient>;
48 +
49 + beforeEach(() => {
50 + vi.clearAllMocks();
51 + mockClient = createMockClient();
52 + logs = new Logs(mockClient as unknown as ComposioClient);
53 + });
54 +
55 + it('instruments the class with telemetry', () => {
56 + expect(telemetry.instrument).toHaveBeenCalledWith(logs, 'Logs');
57 + });
58 +
59 + describe('search', () => {
60 + it('sends an empty body when called without params', async () => {
61 + mockClient.logs.createToolExecution.mockResolvedValue({ logs: [], next_cursor: null });
62 +
63 + const result = await logs.search();
64 +
65 + expect(mockClient.logs.createToolExecution).toHaveBeenCalledWith(
66 + { limit: undefined, cursor: undefined, filters: undefined, time_range: undefined },
67 + undefined
68 + );
69 + expect(result).toEqual({ logs: [], nextCursor: null });
70 + });
71 +
72 + it('maps camelCase params to the wire and transforms the response', async () => {
73 + mockClient.logs.createToolExecution.mockResolvedValue({
74 + logs: [rawLog, { ...rawLog, id: 'log_2', parent: null, message: undefined }],
75 + next_cursor: 'cursor_2',
76 + });
77 + const signal = new AbortController().signal;
78 +
79 + const result = await logs.search(
80 + {
81 + limit: 2,
82 + cursor: 'cursor_1',
83 + filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],
84 + timeRange: { from: 1, to: 2 },
85 + },
86 + { signal }
87 + );
88 +
89 + expect(mockClient.logs.createToolExecution).toHaveBeenCalledWith(
90 + {
91 + limit: 2,
92 + cursor: 'cursor_1',
93 + filters: [{ field: 'toolkit_slug', operator: '==', value: 'github' }],
94 + time_range: { from: 1, to: 2 },
95 + },
96 + { signal }
97 + );
98 + expect(result).toEqual({
99 + logs: [
100 + transformedLog,
101 + { ...transformedLog, id: 'log_2', parent: null, message: undefined },
102 + ],
103 + nextCursor: 'cursor_2',
104 + });
105 + });
106 +
107 + it('throws a ValidationError for an unknown filter field', async () => {
108 + await expect(
109 + logs.search({
110 + filters: [{ field: 'nope' as 'tool_slug', operator: '==', value: 'x' }],
111 + })
112 + ).rejects.toThrow(ValidationError);
113 + expect(mockClient.logs.createToolExecution).not.toHaveBeenCalled();
114 + });
115 + });
116 +
117 + describe('get', () => {
118 + it('retrieves a log by id and transforms the detail fields', async () => {
119 + mockClient.logs.retrieveToolExecution.mockResolvedValue({
120 + ...rawLog,
121 + timings: { start_time: 10, end_time: 22 },
122 + context: { session_id: 'trs_1', trace_id: 'trace_1', request_id: 'req_1' },
123 + source: { host: 'node', framework: 'vercel', language: 'typescript' },
124 + data: { input: { owner: 'composio' } },
125 + });
126 +
127 + const result = await logs.get('log_1');
128 +
129 + expect(mockClient.logs.retrieveToolExecution).toHaveBeenCalledWith('log_1', undefined);
130 + expect(result).toEqual({
131 + ...transformedLog,
132 + timings: { startTime: 10, endTime: 22 },
133 + context: { sessionId: 'trs_1', traceId: 'trace_1', requestId: 'req_1' },
134 + source: { host: 'node', framework: 'vercel', language: 'typescript' },
135 + data: { input: { owner: 'composio' } },
136 + });
137 + });
138 +
139 + it('leaves timings undefined when the API omits them', async () => {
140 + mockClient.logs.retrieveToolExecution.mockResolvedValue({
141 + ...rawLog,
142 + context: {},
143 + source: {},
144 + data: {},
145 + });
146 +
147 + const result = await logs.get('log_1');
148 +
149 + expect(result.timings).toBeUndefined();
150 + expect(result.context).toEqual({});
151 + });
152 + });
153 +});
ts/packages/core/test/models/toolRouter.test.ts
+90
@@ -15,6 +15,7 @@ import {
15 import type { ConnectionRequest } from '../../src/types/connectionRequest.types';
16 import { createCustomTool } from '../../src/models/CustomTool';
17 import { DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX } from '../../src/models/ToolRouterSession';
18 +import { ValidationError } from '../../src/errors/ValidationErrors';
19
20 // Mock dependencies
21 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -53,6 +54,7 @@ const createMockClient = () => ({
54 toolkits: vi.fn(),
55 search: vi.fn(),
56 execute: vi.fn(),
57 + configHistory: vi.fn(),
58 },
59 },
60 tools: {
@@ -3815,4 +3817,92 @@ describe('ToolRouter', () => {
3817 ]);
3818 });
3819 });
3820 +
3821 + describe('session.listConfigHistory', () => {
3822 + const sessionId = 'session_123';
3823 + const rawHistoryItem = {
3824 + version: 2,
3825 + created_at: '2026-01-02T00:00:00Z',
3826 + is_current: true,
3827 + config: {
3828 + user_id: 'user_123',
3829 + toolkits: { enabled: ['github'] },
3830 + preload: { tools: [] },
3831 + search: {},
3832 + execute: {},
3833 + },
3834 + };
3835 +
3836 + it('should page through the session config history', async () => {
3837 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);
3838 + mockClient.toolRouter.session.configHistory.mockResolvedValueOnce({
3839 + items: [rawHistoryItem, { ...rawHistoryItem, version: 1, is_current: false }],
3840 + next_cursor: 'cursor_2',
3841 + total_pages: 2,
3842 + current_page: 1,
3843 + total_items: 3,
3844 + });
3845 +
3846 + const session = await toolRouter.use(sessionId);
3847 + const result = await session.listConfigHistory({ limit: 2 });
3848 +
3849 + expect(mockClient.toolRouter.session.configHistory).toHaveBeenCalledWith(
3850 + sessionId,
3851 + { cursor: undefined, limit: 2 },
3852 + undefined
3853 + );
3854 + expect(result).toEqual({
3855 + items: [
3856 + {
3857 + version: 2,
3858 + createdAt: '2026-01-02T00:00:00Z',
3859 + isCurrent: true,
3860 + config: rawHistoryItem.config,
3861 + },
3862 + {
3863 + version: 1,
3864 + createdAt: '2026-01-02T00:00:00Z',
3865 + isCurrent: false,
3866 + config: rawHistoryItem.config,
3867 + },
3868 + ],
3869 + nextCursor: 'cursor_2',
3870 + totalPages: 2,
3871 + currentPage: 1,
3872 + totalItems: 3,
3873 + });
3874 + });
3875 +
3876 + it('should default nextCursor to null and forward request options', async () => {
3877 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);
3878 + mockClient.toolRouter.session.configHistory.mockResolvedValueOnce({
3879 + items: [],
3880 + total_pages: 0,
3881 + current_page: 1,
3882 + total_items: 0,
3883 + });
3884 + const signal = new AbortController().signal;
3885 +
3886 + const session = await toolRouter.use(sessionId);
3887 + const result = await session.listConfigHistory(undefined, { signal });
3888 +
3889 + expect(mockClient.toolRouter.session.configHistory).toHaveBeenCalledWith(
3890 + sessionId,
3891 + { cursor: undefined, limit: undefined },
3892 + { signal }
3893 + );
3894 + expect(result.nextCursor).toBeNull();
3895 + });
3896 +
3897 + it('should throw a ValidationError for invalid options', async () => {
3898 + mockClient.toolRouter.session.retrieve.mockResolvedValueOnce(mockSessionRetrieveResponse);
3899 +
3900 + const session = await toolRouter.use(sessionId);
3901 +
3902 + await expect(
3903 + session.listConfigHistory({ limit: 'ten' as unknown as number })
3904 + ).rejects.toThrow(ValidationError);
3905 + expect(mockClient.toolRouter.session.configHistory).not.toHaveBeenCalled();
3906 + });
3907 + });
3908 });
ts/packages/core/test/models/toolkitScopes.test.ts new
+191
@@ -0,0 +1,191 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 +import { Toolkits } from '../../src/models/Toolkits';
4 +import { ValidationError } from '../../src/errors/ValidationErrors';
5 +
6 +vi.mock('../../src/telemetry/Telemetry', () => ({
7 + telemetry: {
8 + instrument: vi.fn(),
9 + },
10 +}));
11 +
12 +const createMockClient = () => ({
13 + toolkits: {
14 + recommendScopes: vi.fn(),
15 + retrieveScopesGrantContext: vi.fn(),
16 + },
17 +});
18 +
19 +const rawRecommendation = {
20 + auth_scheme: 'OAUTH2',
21 + toolkit_version: '20250909_00',
22 + grant_context: { account_type: 'Google Workspace' },
23 + scopes: {
24 + least_privilege: ['https://www.googleapis.com/auth/gmail.send'],
25 + fewest: ['https://mail.google.com/'],
26 + conditional: [
27 + {
28 + scope: 'https://www.googleapis.com/auth/gmail.modify',
29 + when: { label_ids: ['TRASH'] },
30 + for: ['GMAIL_FETCH_EMAILS'],
31 + },
32 + ],
33 + },
34 +};
35 +
36 +describe('Toolkits scope recommendation', () => {
37 + let toolkits: Toolkits;
38 + let mockClient: ReturnType<typeof createMockClient>;
39 +
40 + beforeEach(() => {
41 + vi.clearAllMocks();
42 + mockClient = createMockClient();
43 + toolkits = new Toolkits(mockClient as unknown as ComposioClient);
44 + });
45 +
46 + describe('recommendScopes', () => {
47 + it('covers every tool when tools is empty', async () => {
48 + mockClient.toolkits.recommendScopes.mockResolvedValue(rawRecommendation);
49 +
50 + await toolkits.recommendScopes('gmail', { tools: [] });
51 +
52 + expect(mockClient.toolkits.recommendScopes).toHaveBeenCalledWith(
53 + 'gmail',
54 + {
55 + tools: [],
56 + auth_scheme: undefined,
57 + toolkit_version: undefined,
58 + grant_context: undefined,
59 + include: undefined,
60 + exclude: undefined,
61 + available_scopes: undefined,
62 + },
63 + undefined
64 + );
65 + });
66 +
67 + it('maps params to the wire and transforms the response', async () => {
68 + mockClient.toolkits.recommendScopes.mockResolvedValue(rawRecommendation);
69 + const signal = new AbortController().signal;
70 +
71 + const result = await toolkits.recommendScopes(
72 + 'gmail',
73 + {
74 + tools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],
75 + authScheme: 'OAUTH2',
76 + toolkitVersion: '20250909_00',
77 + grantContext: { account_type: 'Google Workspace' },
78 + include: ['openid'],
79 + exclude: ['https://mail.google.com/'],
80 + availableScopes: ['openid', 'https://www.googleapis.com/auth/gmail.send'],
81 + },
82 + { signal }
83 + );
84 +
85 + expect(mockClient.toolkits.recommendScopes).toHaveBeenCalledWith(
86 + 'gmail',
87 + {
88 + tools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],
89 + auth_scheme: 'OAUTH2',
90 + toolkit_version: '20250909_00',
91 + grant_context: { account_type: 'Google Workspace' },
92 + include: ['openid'],
93 + exclude: ['https://mail.google.com/'],
94 + available_scopes: ['openid', 'https://www.googleapis.com/auth/gmail.send'],
95 + },
96 + { signal }
97 + );
98 + expect(result).toEqual({
99 + authScheme: 'OAUTH2',
100 + toolkitVersion: '20250909_00',
101 + grantContext: { account_type: 'Google Workspace' },
102 + scopes: {
103 + leastPrivilege: ['https://www.googleapis.com/auth/gmail.send'],
104 + fewest: ['https://mail.google.com/'],
105 + conditional: [
106 + {
107 + scope: 'https://www.googleapis.com/auth/gmail.modify',
108 + when: { label_ids: ['TRASH'] },
109 + for: ['GMAIL_FETCH_EMAILS'],
110 + },
111 + ],
112 + },
113 + });
114 + });
115 +
116 + it('rejects a missing tools list before calling the API', async () => {
117 + await expect(
118 + toolkits.recommendScopes('gmail', {} as Parameters<Toolkits['recommendScopes']>[1])
119 + ).rejects.toThrow(ValidationError);
120 + expect(mockClient.toolkits.recommendScopes).not.toHaveBeenCalled();
121 + });
122 +
123 + it('rejects an unknown auth scheme before calling the API', async () => {
124 + await expect(
125 + toolkits.recommendScopes('gmail', { tools: [], authScheme: 'NOT_A_SCHEME' as never })
126 + ).rejects.toThrow(ValidationError);
127 + expect(mockClient.toolkits.recommendScopes).not.toHaveBeenCalled();
128 + });
129 + });
130 +
131 + describe('listGrantContexts', () => {
132 + const rawGrantContexts = {
133 + auth_scheme: 'OAUTH2',
134 + toolkit_version: '20250909_00',
135 + grant_context_dimensions: [
136 + {
137 + dimension: 'account_type',
138 + description: 'Kind of Google account the user connects',
139 + values: ['Google Workspace', 'Personal'],
140 + },
141 + ],
142 + default_grant_context: { account_type: 'Personal' },
143 + };
144 +
145 + it('sends an empty query when called without params', async () => {
146 + mockClient.toolkits.retrieveScopesGrantContext.mockResolvedValue(rawGrantContexts);
147 +
148 + await toolkits.listGrantContexts('gmail');
149 +
150 + expect(mockClient.toolkits.retrieveScopesGrantContext).toHaveBeenCalledWith(
151 + 'gmail',
152 + { auth_scheme: undefined, toolkit_version: undefined },
153 + undefined
154 + );
155 + });
156 +
157 + it('maps params to the wire and transforms the response', async () => {
158 + mockClient.toolkits.retrieveScopesGrantContext.mockResolvedValue(rawGrantContexts);
159 +
160 + const result = await toolkits.listGrantContexts('gmail', {
161 + authScheme: 'OAUTH2',
162 + toolkitVersion: '20250909_00',
163 + });
164 +
165 + expect(mockClient.toolkits.retrieveScopesGrantContext).toHaveBeenCalledWith(
166 + 'gmail',
167 + { auth_scheme: 'OAUTH2', toolkit_version: '20250909_00' },
168 + undefined
169 + );
170 + expect(result).toEqual({
171 + authScheme: 'OAUTH2',
172 + toolkitVersion: '20250909_00',
173 + grantContextDimensions: [
174 + {
175 + dimension: 'account_type',
176 + description: 'Kind of Google account the user connects',
177 + values: ['Google Workspace', 'Personal'],
178 + },
179 + ],
180 + defaultGrantContext: { account_type: 'Personal' },
181 + });
182 + });
183 +
184 + it('rejects an empty toolkit version before calling the API', async () => {
185 + await expect(toolkits.listGrantContexts('gmail', { toolkitVersion: '' })).rejects.toThrow(
186 + ValidationError
187 + );
188 + expect(mockClient.toolkits.retrieveScopesGrantContext).not.toHaveBeenCalled();
189 + });
190 + });
191 +});
ts/packages/core/test/models/toolkits.test.ts
+104
@@ -7,6 +7,7 @@ import {
7 ComposioToolkitFetchError,
8 ComposioToolkitNotFoundError,
9 } from '../../src/errors/ToolkitErrors';
10 +import { ValidationError } from '../../src/errors/ValidationErrors';
11 import { AuthSchemeTypes } from '../../src/types/authConfigs.types';
12 import { APIError } from '@composio/client';
13 import type { ToolkitListParams } from '../../src/types/toolkit.types';
@@ -32,6 +33,8 @@ const createMockClient = () => ({
33 list: vi.fn(),
34 retrieve: vi.fn(),
35 retrieveCategories: vi.fn(),
36 + retrieveMulti: vi.fn(),
37 + retrieveChangelog: vi.fn(),
38 listCategories: vi.fn(),
39 authorize: vi.fn(),
40 get: vi.fn(),
@@ -302,6 +305,107 @@ describe('Toolkits', () => {
305 });
306 });
307
308 + describe('getMany', () => {
309 + it('should fetch toolkits by slug and return the list shape', async () => {
310 + mockClient.toolkits.retrieveMulti.mockResolvedValue(mockToolkitListResponse);
311 +
312 + const result = await toolkits.getMany(['github', 'slack']);
313 +
314 + expect(mockClient.toolkits.retrieveMulti).toHaveBeenCalledWith(
315 + {
316 + toolkits: ['github', 'slack'],
317 + category: undefined,
318 + managed_by: undefined,
319 + sort_by: undefined,
320 + cursor: undefined,
321 + limit: undefined,
322 + },
323 + undefined
324 + );
325 + expect(result).toEqual([
326 + {
327 + name: 'GitHub',
328 + slug: 'github',
329 + meta: {
330 + createdAt: '2024-01-01',
331 + updatedAt: '2024-01-02',
332 + toolsCount: 10,
333 + triggersCount: 5,
334 + },
335 + isLocalToolkit: false,
336 + authSchemes: ['oauth2'],
337 + composioManagedAuthSchemes: ['oauth2'],
338 + noAuth: false,
339 + },
340 + ]);
341 + });
342 +
343 + it('should forward filters and request options', async () => {
344 + mockClient.toolkits.retrieveMulti.mockResolvedValue({ items: [] });
345 + const signal = new AbortController().signal;
346 +
347 + await toolkits.getMany(
348 + ['github'],
349 + { managedBy: 'composio', sortBy: 'usage', limit: 5 },
350 + {
351 + signal,
352 + }
353 + );
354 +
355 + expect(mockClient.toolkits.retrieveMulti).toHaveBeenCalledWith(
356 + {
357 + toolkits: ['github'],
358 + category: undefined,
359 + managed_by: 'composio',
360 + sort_by: 'usage',
361 + cursor: undefined,
362 + limit: 5,
363 + },
364 + { signal }
365 + );
366 + });
367 +
368 + it('should throw a ValidationError for an empty slug list', async () => {
369 + await expect(toolkits.getMany([])).rejects.toThrow(ValidationError);
370 + expect(mockClient.toolkits.retrieveMulti).not.toHaveBeenCalled();
371 + });
372 +
373 + it('should wrap request failures in ComposioToolkitFetchError', async () => {
374 + mockClient.toolkits.retrieveMulti.mockRejectedValue(new Error('boom'));
375 +
376 + await expect(toolkits.getMany(['github'])).rejects.toThrow(ComposioToolkitFetchError);
377 + });
378 + });
379 +
380 + describe('changelog', () => {
381 + it('should return the toolkit changelog in camelCase', async () => {
382 + mockClient.toolkits.retrieveChangelog.mockResolvedValue({
383 + items: [
384 + {
385 + slug: 'github',
386 + name: 'github',
387 + display_name: 'GitHub',
388 + versions: [{ version: '20250909_00', changelog: 'Added issues tools' }],
389 + },
390 + ],
391 + });
392 +
393 + const result = await toolkits.changelog();
394 +
395 + expect(mockClient.toolkits.retrieveChangelog).toHaveBeenCalledWith(undefined);
396 + expect(result).toEqual({
397 + items: [
398 + {
399 + slug: 'github',
400 + name: 'github',
401 + displayName: 'GitHub',
402 + versions: [{ version: '20250909_00', changelog: 'Added issues tools' }],
403 + },
404 + ],
405 + });
406 + });
407 + });
408 +
409 describe('authorize', () => {
410 const userId = 'user_123';
411 const toolkitSlug = 'test-toolkit';
ts/packages/core/test/models/triggers.test.ts
+22 -19
@@ -30,9 +30,11 @@ vi.mock('../../src/services/pusher/Pusher');
30 const createMockClient = () => ({
31 baseURL: 'https://api.composio.dev',
32 apiKey: 'test-api-key',
33 - get: vi.fn(),
34 - post: vi.fn(),
35 - patch: vi.fn(),
33 + webhookSubscriptions: {
34 + list: vi.fn(),
35 + create: vi.fn(),
36 + update: vi.fn(),
37 + },
38 triggerInstances: {
39 listActive: vi.fn(),
40 upsert: vi.fn(),
@@ -257,22 +259,21 @@ describe('Triggers', () => {
259 };
260
261 it('should create a webhook subscription when none exists', async () => {
260 - mockClient.get.mockResolvedValue({ items: [] });
261 - mockClient.post.mockResolvedValue(rawSubscription);
262 + mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [] });
263 + mockClient.webhookSubscriptions.create.mockResolvedValue(rawSubscription);
264
265 const result = await triggers.setWebhookSubscription({ webhookUrl });
266
265 - expect(mockClient.get).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions', {
266 - query: { limit: 1 },
267 - });
268 - expect(mockClient.post).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions', {
269 - body: {
267 + expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith({ limit: 1 }, undefined);
268 + expect(mockClient.webhookSubscriptions.create).toHaveBeenCalledWith(
269 + {
270 webhook_url: webhookUrl,
271 enabled_events: ['composio.trigger.message'],
272 version: 'V3',
273 },
274 - });
275 - expect(mockClient.patch).not.toHaveBeenCalled();
274 + undefined
275 + );
276 + expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();
277 // Only camelCase keys — the snake_case wire fields must not leak through.
278 expect(result).toEqual({
279 id: 'sub_123',
@@ -286,8 +287,8 @@ describe('Triggers', () => {
287 });
288
289 it('should update the first webhook subscription when one exists', async () => {
289 - mockClient.get.mockResolvedValue({ items: [{ id: 'sub_123' }] });
290 - mockClient.patch.mockResolvedValue(rawSubscription);
290 + mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [{ id: 'sub_123' }] });
291 + mockClient.webhookSubscriptions.update.mockResolvedValue(rawSubscription);
292
293 await triggers.setWebhookSubscription({
294 webhookUrl,
@@ -295,21 +296,23 @@ describe('Triggers', () => {
296 version: 'V3',
297 });
298
298 - expect(mockClient.patch).toHaveBeenCalledWith('/api/v3.1/webhook_subscriptions/sub_123', {
299 - body: {
299 + expect(mockClient.webhookSubscriptions.update).toHaveBeenCalledWith(
300 + 'sub_123',
301 + {
302 webhook_url: webhookUrl,
303 enabled_events: ['composio.trigger.message', 'composio.connected_account.expired'],
304 version: 'V3',
305 },
304 - });
305 - expect(mockClient.post).not.toHaveBeenCalled();
306 + undefined
307 + );
308 + expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled();
309 });
310
311 it('should throw validation error for invalid webhook subscription parameters', async () => {
312 await expect(
313 triggers.setWebhookSubscription({ webhookUrl, enabledEvents: [] })
314 ).rejects.toThrow(ValidationError);
312 - expect(mockClient.get).not.toHaveBeenCalled();
315 + expect(mockClient.webhookSubscriptions.list).not.toHaveBeenCalled();
316 });
317 });
318
ts/packages/core/test/models/usage.test.ts new
+148
@@ -0,0 +1,148 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 +import { Experimental } from '../../src/models/Experimental';
4 +import { Usage } from '../../src/models/Usage';
5 +import { telemetry } from '../../src/telemetry/Telemetry';
6 +import { ValidationError } from '../../src/errors/ValidationErrors';
7 +
8 +vi.mock('../../src/telemetry/Telemetry', () => ({
9 + telemetry: {
10 + instrument: vi.fn(),
11 + },
12 +}));
13 +
14 +const createMockClient = () => ({
15 + baseURL: 'https://api.composio.dev',
16 + apiKey: 'test-api-key',
17 + connectedAccounts: {
18 + patch: vi.fn(),
19 + },
20 + project: {
21 + usage: {
22 + retrieveSummary: vi.fn(),
23 + retrieve: vi.fn(),
24 + },
25 + },
26 +});
27 +
28 +describe('Experimental.usage', () => {
29 + let experimental: Experimental;
30 + let mockClient: ReturnType<typeof createMockClient>;
31 +
32 + beforeEach(() => {
33 + vi.clearAllMocks();
34 + mockClient = createMockClient();
35 + experimental = new Experimental(mockClient as unknown as ComposioClient);
36 + });
37 +
38 + it('mounts usage on the experimental namespace and instruments it', () => {
39 + expect(experimental.usage).toBeInstanceOf(Usage);
40 + expect(telemetry.instrument).toHaveBeenCalledWith(experimental.usage, 'Usage');
41 + expect(telemetry.instrument).toHaveBeenCalledWith(experimental, 'Experimental');
42 + });
43 +
44 + describe('summary', () => {
45 + it('sends an empty body when called without params', async () => {
46 + mockClient.project.usage.retrieveSummary.mockResolvedValue({ entities: {} });
47 +
48 + const result = await experimental.usage.summary();
49 +
50 + expect(mockClient.project.usage.retrieveSummary).toHaveBeenCalledWith(
51 + { from: undefined, to: undefined, entity_types: undefined, filters: undefined },
52 + undefined
53 + );
54 + expect(result).toEqual({ entities: {} });
55 + });
56 +
57 + it('maps params to the wire and transforms the response', async () => {
58 + mockClient.project.usage.retrieveSummary.mockResolvedValue({
59 + entities: {
60 + tool_calls: { unit: 'call', total_quantity: '42', event_count: 42 },
61 + sessions: { unit: 'session', total_quantity: '3', event_count: 3 },
62 + },
63 + });
64 + const signal = new AbortController().signal;
65 +
66 + const result = await experimental.usage.summary(
67 + {
68 + from: 1,
69 + to: 2,
70 + entityTypes: ['tool_calls', 'sessions'],
71 + filters: { userId: ['user_1'], sessionId: null },
72 + },
73 + { signal }
74 + );
75 +
76 + expect(mockClient.project.usage.retrieveSummary).toHaveBeenCalledWith(
77 + {
78 + from: 1,
79 + to: 2,
80 + entity_types: ['tool_calls', 'sessions'],
81 + filters: { user_id: ['user_1'], session_id: null },
82 + },
83 + { signal }
84 + );
85 + expect(result).toEqual({
86 + entities: {
87 + tool_calls: { unit: 'call', totalQuantity: '42', eventCount: 42 },
88 + sessions: { unit: 'session', totalQuantity: '3', eventCount: 3 },
89 + },
90 + });
91 + });
92 +
93 + it('throws a ValidationError for invalid params', async () => {
94 + await expect(
95 + experimental.usage.summary({ from: 'yesterday' as unknown as number })
96 + ).rejects.toThrow(ValidationError);
97 + expect(mockClient.project.usage.retrieveSummary).not.toHaveBeenCalled();
98 + });
99 + });
100 +
101 + describe('breakdown', () => {
102 + it('passes the entity type positionally and maps params', async () => {
103 + mockClient.project.usage.retrieve.mockResolvedValue({
104 + entity_type: 'tool_calls',
105 + unit: 'call',
106 + total_quantity: '10',
107 + event_count: 10,
108 + groups: [{ key: 'GITHUB_GET_REPO', total_quantity: '10', event_count: 10 }],
109 + });
110 +
111 + const result = await experimental.usage.breakdown('tool_calls', {
112 + groupBy: 'tool_slug',
113 + orderBy: 'event_count',
114 + orderDirection: 'asc',
115 + limit: 5,
116 + filters: { sessionId: ['trs_1'] },
117 + });
118 +
119 + expect(mockClient.project.usage.retrieve).toHaveBeenCalledWith(
120 + 'tool_calls',
121 + {
122 + from: undefined,
123 + to: undefined,
124 + group_by: 'tool_slug',
125 + order_by: 'event_count',
126 + order_direction: 'asc',
127 + limit: 5,
128 + filters: { user_id: undefined, session_id: ['trs_1'] },
129 + },
130 + undefined
131 + );
132 + expect(result).toEqual({
133 + entityType: 'tool_calls',
134 + unit: 'call',
135 + totalQuantity: '10',
136 + eventCount: 10,
137 + groups: [{ key: 'GITHUB_GET_REPO', totalQuantity: '10', eventCount: 10 }],
138 + });
139 + });
140 +
141 + it('throws a ValidationError for an unknown orderBy', async () => {
142 + await expect(
143 + experimental.usage.breakdown('tool_calls', { orderBy: 'name' as 'key' })
144 + ).rejects.toThrow(ValidationError);
145 + expect(mockClient.project.usage.retrieve).not.toHaveBeenCalled();
146 + });
147 + });
148 +});
ts/packages/core/test/models/webhooks.test.ts new
+435
@@ -0,0 +1,435 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 +import { Webhooks, WebhookSubscriptions, WebhookEndpoints } from '../../src/models/Webhooks';
4 +import { telemetry } from '../../src/telemetry/Telemetry';
5 +import { ValidationError } from '../../src/errors/ValidationErrors';
6 +
7 +vi.mock('../../src/telemetry/Telemetry', () => ({
8 + telemetry: {
9 + instrument: vi.fn(),
10 + },
11 +}));
12 +
13 +const createMockClient = () => ({
14 + baseURL: 'https://api.composio.dev',
15 + apiKey: 'test-api-key',
16 + webhookSubscriptions: {
17 + list: vi.fn(),
18 + retrieve: vi.fn(),
19 + create: vi.fn(),
20 + update: vi.fn(),
21 + delete: vi.fn(),
22 + rotateSecret: vi.fn(),
23 + listEventTypes: vi.fn(),
24 + },
25 + webhookEndpoints: {
26 + list: vi.fn(),
27 + retrieve: vi.fn(),
28 + create: vi.fn(),
29 + replace: vi.fn(),
30 + update: vi.fn(),
31 + },
32 +});
33 +
34 +const webhookUrl = 'https://example.com/webhooks/composio';
35 +const rawSubscription = {
36 + id: 'sub_123',
37 + webhook_url: webhookUrl,
38 + version: 'V3',
39 + enabled_events: ['composio.trigger.message'],
40 + secret: 'whsec_123',
41 + created_at: '2026-01-01T00:00:00Z',
42 + updated_at: '2026-01-01T00:00:00Z',
43 +};
44 +const transformedSubscription = {
45 + id: 'sub_123',
46 + webhookUrl,
47 + version: 'V3',
48 + enabledEvents: ['composio.trigger.message'],
49 + secret: 'whsec_123',
50 + createdAt: '2026-01-01T00:00:00Z',
51 + updatedAt: '2026-01-01T00:00:00Z',
52 +};
53 +
54 +const rawEndpoint = {
55 + id: 'we_abc123',
56 + toolkit_slug: 'slack',
57 + client_id: 'client_1',
58 + webhook_url: 'https://backend.composio.dev/webhook/slack/we_abc123',
59 + data: { signing_secret: '***' },
60 + created_at: '2026-01-01T00:00:00Z',
61 +};
62 +const transformedEndpoint = {
63 + id: 'we_abc123',
64 + toolkitSlug: 'slack',
65 + clientId: 'client_1',
66 + webhookUrl: 'https://backend.composio.dev/webhook/slack/we_abc123',
67 + data: { signing_secret: '***' },
68 + createdAt: '2026-01-01T00:00:00Z',
69 +};
70 +
71 +describe('Webhooks', () => {
72 + let webhooks: Webhooks;
73 + let mockClient: ReturnType<typeof createMockClient>;
74 +
75 + beforeEach(() => {
76 + vi.clearAllMocks();
77 + mockClient = createMockClient();
78 + webhooks = new Webhooks(mockClient as unknown as ComposioClient);
79 + });
80 +
81 + describe('constructor', () => {
82 + it('mounts the subscriptions and endpoints sub-namespaces', () => {
83 + expect(webhooks.subscriptions).toBeInstanceOf(WebhookSubscriptions);
84 + expect(webhooks.endpoints).toBeInstanceOf(WebhookEndpoints);
85 + });
86 +
87 + it('instruments every class with telemetry', () => {
88 + expect(telemetry.instrument).toHaveBeenCalledWith(webhooks, 'Webhooks');
89 + expect(telemetry.instrument).toHaveBeenCalledWith(
90 + webhooks.subscriptions,
91 + 'WebhookSubscriptions'
92 + );
93 + expect(telemetry.instrument).toHaveBeenCalledWith(webhooks.endpoints, 'WebhookEndpoints');
94 + });
95 + });
96 +
97 + describe('subscriptions', () => {
98 + describe('list', () => {
99 + it('lists subscriptions and transforms the response', async () => {
100 + mockClient.webhookSubscriptions.list.mockResolvedValue({
101 + items: [rawSubscription],
102 + next_cursor: null,
103 + total_pages: 1,
104 + current_page: 1,
105 + total_items: 1,
106 + });
107 +
108 + const result = await webhooks.subscriptions.list();
109 +
110 + expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith(
111 + { limit: undefined, cursor: undefined },
112 + undefined
113 + );
114 + expect(result).toEqual({
115 + items: [transformedSubscription],
116 + nextCursor: null,
117 + totalPages: 1,
118 + currentPage: 1,
119 + totalItems: 1,
120 + });
121 + });
122 +
123 + it('forwards pagination params and request options', async () => {
124 + mockClient.webhookSubscriptions.list.mockResolvedValue({
125 + items: [],
126 + next_cursor: 'next',
127 + total_pages: 2,
128 + current_page: 1,
129 + total_items: 3,
130 + });
131 + const signal = new AbortController().signal;
132 +
133 + const result = await webhooks.subscriptions.list({ limit: 2, cursor: 'abc' }, { signal });
134 +
135 + expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith(
136 + { limit: 2, cursor: 'abc' },
137 + { signal }
138 + );
139 + expect(result.nextCursor).toBe('next');
140 + });
141 +
142 + it('throws a ValidationError for invalid params', async () => {
143 + await expect(
144 + webhooks.subscriptions.list({ limit: 'ten' } as unknown as { limit: number })
145 + ).rejects.toThrow(ValidationError);
146 + expect(mockClient.webhookSubscriptions.list).not.toHaveBeenCalled();
147 + });
148 + });
149 +
150 + describe('get', () => {
151 + it('retrieves a subscription by id', async () => {
152 + mockClient.webhookSubscriptions.retrieve.mockResolvedValue(rawSubscription);
153 +
154 + const result = await webhooks.subscriptions.get('sub_123');
155 +
156 + expect(mockClient.webhookSubscriptions.retrieve).toHaveBeenCalledWith('sub_123', undefined);
157 + expect(result).toEqual(transformedSubscription);
158 + });
159 + });
160 +
161 + describe('set', () => {
162 + it('creates a subscription when none exists', async () => {
163 + mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [] });
164 + mockClient.webhookSubscriptions.create.mockResolvedValue(rawSubscription);
165 +
166 + const result = await webhooks.subscriptions.set({ webhookUrl });
167 +
168 + expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith({ limit: 1 }, undefined);
169 + expect(mockClient.webhookSubscriptions.create).toHaveBeenCalledWith(
170 + {
171 + webhook_url: webhookUrl,
172 + enabled_events: ['composio.trigger.message'],
173 + version: 'V3',
174 + },
175 + undefined
176 + );
177 + expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();
178 + expect(result).toEqual(transformedSubscription);
179 + });
180 +
181 + it('updates the existing subscription when one exists', async () => {
182 + mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [{ id: 'sub_123' }] });
183 + mockClient.webhookSubscriptions.update.mockResolvedValue(rawSubscription);
184 +
185 + await webhooks.subscriptions.set({
186 + webhookUrl,
187 + enabledEvents: ['composio.trigger.message', 'composio.connected_account.expired'],
188 + version: 'V2',
189 + });
190 +
191 + expect(mockClient.webhookSubscriptions.update).toHaveBeenCalledWith(
192 + 'sub_123',
193 + {
194 + webhook_url: webhookUrl,
195 + enabled_events: ['composio.trigger.message', 'composio.connected_account.expired'],
196 + version: 'V2',
197 + },
198 + undefined
199 + );
200 + expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled();
201 + });
202 +
203 + it('forwards request options to both calls', async () => {
204 + mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [] });
205 + mockClient.webhookSubscriptions.create.mockResolvedValue(rawSubscription);
206 + const signal = new AbortController().signal;
207 +
208 + await webhooks.subscriptions.set({ webhookUrl }, { signal });
209 +
210 + expect(mockClient.webhookSubscriptions.list).toHaveBeenCalledWith({ limit: 1 }, { signal });
211 + expect(mockClient.webhookSubscriptions.create).toHaveBeenCalledWith(expect.any(Object), {
212 + signal,
213 + });
214 + });
215 +
216 + it('throws a ValidationError for invalid params before any request', async () => {
217 + await expect(webhooks.subscriptions.set({ webhookUrl, enabledEvents: [] })).rejects.toThrow(
218 + ValidationError
219 + );
220 + expect(mockClient.webhookSubscriptions.list).not.toHaveBeenCalled();
221 + });
222 +
223 + it('throws a ValidationError when the list probe has no items', async () => {
224 + mockClient.webhookSubscriptions.list.mockResolvedValue({ total_items: 0 });
225 +
226 + await expect(webhooks.subscriptions.set({ webhookUrl })).rejects.toThrow(ValidationError);
227 + expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled();
228 + expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();
229 + });
230 +
231 + it('throws a ValidationError when the list probe is malformed', async () => {
232 + mockClient.webhookSubscriptions.list.mockResolvedValue({ items: [{ id: 42 }] });
233 +
234 + await expect(webhooks.subscriptions.set({ webhookUrl })).rejects.toThrow(ValidationError);
235 + expect(mockClient.webhookSubscriptions.create).not.toHaveBeenCalled();
236 + expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();
237 + });
238 + });
239 +
240 + describe('update', () => {
241 + it('updates only the provided fields', async () => {
242 + mockClient.webhookSubscriptions.update.mockResolvedValue(rawSubscription);
243 +
244 + const result = await webhooks.subscriptions.update('sub_123', {
245 + enabledEvents: ['composio.trigger.message'],
246 + });
247 +
248 + expect(mockClient.webhookSubscriptions.update).toHaveBeenCalledWith(
249 + 'sub_123',
250 + {
251 + webhook_url: undefined,
252 + enabled_events: ['composio.trigger.message'],
253 + version: undefined,
254 + },
255 + undefined
256 + );
257 + expect(result).toEqual(transformedSubscription);
258 + });
259 +
260 + it('throws a ValidationError for invalid params', async () => {
261 + await expect(
262 + webhooks.subscriptions.update('sub_123', { version: 'V9' as 'V3' })
263 + ).rejects.toThrow(ValidationError);
264 + expect(mockClient.webhookSubscriptions.update).not.toHaveBeenCalled();
265 + });
266 + });
267 +
268 + describe('delete', () => {
269 + it('deletes a subscription', async () => {
270 + mockClient.webhookSubscriptions.delete.mockResolvedValue({ success: true });
271 +
272 + const result = await webhooks.subscriptions.delete('sub_123');
273 +
274 + expect(mockClient.webhookSubscriptions.delete).toHaveBeenCalledWith('sub_123', undefined);
275 + expect(result).toEqual({ success: true });
276 + });
277 + });
278 +
279 + describe('rotateSecret', () => {
280 + it('rotates the signing secret', async () => {
281 + mockClient.webhookSubscriptions.rotateSecret.mockResolvedValue({
282 + id: 'sub_123',
283 + secret: 'whsec_new',
284 + });
285 +
286 + const result = await webhooks.subscriptions.rotateSecret('sub_123');
287 +
288 + expect(mockClient.webhookSubscriptions.rotateSecret).toHaveBeenCalledWith(
289 + 'sub_123',
290 + undefined
291 + );
292 + expect(result).toEqual({ id: 'sub_123', secret: 'whsec_new' });
293 + });
294 + });
295 +
296 + describe('listEventTypes', () => {
297 + it('lists event types in camelCase', async () => {
298 + mockClient.webhookSubscriptions.listEventTypes.mockResolvedValue({
299 + items: [
300 + {
301 + event_type: 'composio.trigger.message',
302 + description: 'Trigger fired',
303 + supported_versions: ['V2', 'V3'],
304 + },
305 + ],
306 + });
307 +
308 + const result = await webhooks.subscriptions.listEventTypes();
309 +
310 + expect(mockClient.webhookSubscriptions.listEventTypes).toHaveBeenCalledWith(undefined);
311 + expect(result).toEqual({
312 + items: [
313 + {
314 + eventType: 'composio.trigger.message',
315 + description: 'Trigger fired',
316 + supportedVersions: ['V2', 'V3'],
317 + },
318 + ],
319 + });
320 + });
321 + });
322 + });
323 +
324 + describe('endpoints', () => {
325 + describe('list', () => {
326 + it('lists endpoints without a filter', async () => {
327 + mockClient.webhookEndpoints.list.mockResolvedValue({
328 + items: [{ id: 'we_abc123', toolkit_slug: 'slack', client_id: null }],
329 + });
330 +
331 + const result = await webhooks.endpoints.list();
332 +
333 + expect(mockClient.webhookEndpoints.list).toHaveBeenCalledWith(
334 + { toolkit_slug: undefined },
335 + undefined
336 + );
337 + expect(result).toEqual({
338 + items: [{ id: 'we_abc123', toolkitSlug: 'slack', clientId: null }],
339 + });
340 + });
341 +
342 + it('maps the toolkitSlug filter to toolkit_slug', async () => {
343 + mockClient.webhookEndpoints.list.mockResolvedValue({ items: [] });
344 +
345 + await webhooks.endpoints.list({ toolkitSlug: 'slack' });
346 +
347 + expect(mockClient.webhookEndpoints.list).toHaveBeenCalledWith(
348 + { toolkit_slug: 'slack' },
349 + undefined
350 + );
351 + });
352 + });
353 +
354 + describe('get', () => {
355 + it('retrieves an endpoint by nano id', async () => {
356 + mockClient.webhookEndpoints.retrieve.mockResolvedValue(rawEndpoint);
357 +
358 + const result = await webhooks.endpoints.get('we_abc123');
359 +
360 + expect(mockClient.webhookEndpoints.retrieve).toHaveBeenCalledWith('we_abc123', undefined);
361 + expect(result).toEqual(transformedEndpoint);
362 + });
363 + });
364 +
365 + describe('create', () => {
366 + it('creates an endpoint for a toolkit and OAuth app', async () => {
367 + mockClient.webhookEndpoints.create.mockResolvedValue(rawEndpoint);
368 +
369 + const result = await webhooks.endpoints.create({
370 + toolkitSlug: 'slack',
371 + clientId: 'client_1',
372 + });
373 +
374 + expect(mockClient.webhookEndpoints.create).toHaveBeenCalledWith(
375 + { toolkit_slug: 'slack', client_id: 'client_1' },
376 + undefined
377 + );
378 + expect(result).toEqual(transformedEndpoint);
379 + });
380 +
381 + it('throws a ValidationError when required fields are missing', async () => {
382 + await expect(
383 + webhooks.endpoints.create({ toolkitSlug: 'slack' } as {
384 + toolkitSlug: string;
385 + clientId: string;
386 + })
387 + ).rejects.toThrow(ValidationError);
388 + expect(mockClient.webhookEndpoints.create).not.toHaveBeenCalled();
389 + });
390 + });
391 +
392 + describe('replace', () => {
393 + it('replaces the setup fields', async () => {
394 + mockClient.webhookEndpoints.replace.mockResolvedValue(rawEndpoint);
395 +
396 + const result = await webhooks.endpoints.replace('we_abc123', {
397 + data: { signing_secret: 'secret' },
398 + });
399 +
400 + expect(mockClient.webhookEndpoints.replace).toHaveBeenCalledWith(
401 + 'we_abc123',
402 + { data: { signing_secret: 'secret' } },
403 + undefined
404 + );
405 + expect(result).toEqual(transformedEndpoint);
406 + });
407 +
408 + it('throws a ValidationError for non-string values', async () => {
409 + await expect(
410 + webhooks.endpoints.replace('we_abc123', {
411 + data: { enabled: true } as unknown as Record<string, string>,
412 + })
413 + ).rejects.toThrow(ValidationError);
414 + expect(mockClient.webhookEndpoints.replace).not.toHaveBeenCalled();
415 + });
416 + });
417 +
418 + describe('update', () => {
419 + it('merges the setup fields', async () => {
420 + mockClient.webhookEndpoints.update.mockResolvedValue(rawEndpoint);
421 +
422 + const result = await webhooks.endpoints.update('we_abc123', {
423 + data: { signing_secret: 'rotated' },
424 + });
425 +
426 + expect(mockClient.webhookEndpoints.update).toHaveBeenCalledWith(
427 + 'we_abc123',
428 + { data: { signing_secret: 'rotated' } },
429 + undefined
430 + );
431 + expect(result).toEqual(transformedEndpoint);
432 + });
433 + });
434 + });
435 +});
ts/packages/core/test/tools/tools.test.ts
+3 -3
@@ -152,7 +152,7 @@ describe('Tools', () => {
152 {
153 toolkit_slug: 'github',
154 limit: 10,
155 - search: 'test',
155 + query: 'test',
156 toolkit_versions: 'latest',
157 },
158 undefined
@@ -202,7 +202,7 @@ describe('Tools', () => {
202 {
203 toolkit_slug: 'todoist',
204 limit: 10,
205 - search: 'add task',
205 + query: 'add task',
206 scopes: ['task:add'],
207 toolkit_versions: 'latest',
208 },
@@ -1838,7 +1838,7 @@ describe('Tools', () => {
1838
1839 expect(mockClient.tools.list).toHaveBeenCalledWith(
1840 {
1841 - search: 'create issue',
1841 + query: 'create issue',
1842 toolkit_versions: 'latest',
1843 },
1844 undefined
ts/packages/core/test/utils/logger.test.ts
+67
@@ -25,3 +25,70 @@ describe('Logger credential redaction', () => {
25 expect(output).toContain('visible');
26 });
27 });
28 +
29 +describe('Logger sink and configure', () => {
30 + afterEach(() => vi.restoreAllMocks());
31 +
32 + const createSink = () => ({
33 + error: vi.fn(),
34 + warn: vi.fn(),
35 + info: vi.fn(),
36 + debug: vi.fn(),
37 + });
38 +
39 + it('writes formatted, redacted output to a custom sink instead of console', () => {
40 + const sink = createSink();
41 + const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
42 + const logger = new Logger({ level: 'warn', includeTimestamp: false, sink });
43 +
44 + logger.warn('token', { apiKey: 'uak_test_secret' });
45 +
46 + expect(consoleWarn).not.toHaveBeenCalled();
47 + expect(sink.warn).toHaveBeenCalledTimes(1);
48 + const output = String(sink.warn.mock.calls[0]?.[0]);
49 + expect(output).not.toContain('uak_test_secret');
50 + expect(output).toContain('[REDACTED]');
51 + });
52 +
53 + it('configure updates the level in place', () => {
54 + const sink = createSink();
55 + const logger = new Logger({ level: 'error', includeTimestamp: false, sink });
56 +
57 + logger.warn('dropped');
58 + expect(sink.warn).not.toHaveBeenCalled();
59 +
60 + logger.configure({ level: 'warn' });
61 + expect(logger.getLevel()).toBe('warn');
62 + logger.warn('emitted');
63 + expect(sink.warn).toHaveBeenCalledWith('emitted');
64 + });
65 +
66 + it('configure swaps the sink and keeps the level when level is omitted', () => {
67 + const first = createSink();
68 + const second = createSink();
69 + const logger = new Logger({ level: 'debug', includeTimestamp: false, sink: first });
70 +
71 + logger.configure({ sink: second });
72 + logger.debug('hello');
73 +
74 + expect(logger.getLevel()).toBe('debug');
75 + expect(first.debug).not.toHaveBeenCalled();
76 + expect(second.debug).toHaveBeenCalledWith('hello');
77 + });
78 +
79 + it("'silent' suppresses every level", () => {
80 + const sink = createSink();
81 + const logger = new Logger({ level: 'debug', includeTimestamp: false, sink });
82 +
83 + logger.configure({ level: 'silent' });
84 + logger.error('e');
85 + logger.warn('w');
86 + logger.info('i');
87 + logger.debug('d');
88 +
89 + expect(sink.error).not.toHaveBeenCalled();
90 + expect(sink.warn).not.toHaveBeenCalled();
91 + expect(sink.info).not.toHaveBeenCalled();
92 + expect(sink.debug).not.toHaveBeenCalled();
93 + });
94 +});
ts/packages/core/test/utils/transformers/toolkits.test.ts
+22 -3
@@ -29,6 +29,7 @@ const rawToolkit = {
29 name: 'API Key',
30 mode: 'API_KEY',
31 auth_hint_url: 'https://shopify.dev/api-keys',
32 + required_scopes: ['offline_access'],
33 fields: {
34 auth_config_creation: {
35 required: [
@@ -65,6 +66,7 @@ const rawToolkit = {
66 required: true,
67 is_secret: true,
68 legacy_template_name: 'apiKey',
69 + user_visible: true,
70 },
71 ],
72 optional: [
@@ -76,6 +78,7 @@ const rawToolkit = {
78 required: false,
79 is_secret: false,
80 default: 'example.myshopify.com',
81 + user_visible: false,
82 },
83 ],
84 },
@@ -141,6 +144,7 @@ describe('transformToolkitRetrieveResponse', () => {
144 required: true,
145 isSecret: true,
146 legacyTemplateName: 'apiKey',
147 + userVisible: true,
148 });
149 });
150
@@ -153,6 +157,19 @@ describe('transformToolkitRetrieveResponse', () => {
157 expect(field?.isSecret).toBe(false);
158 });
159
160 + it('maps user_visible to userVisible, keeping false', () => {
161 + const fields = transformToolkitRetrieveResponse(rawToolkit).authConfigDetails?.[0].fields;
162 +
163 + expect(fields?.connectedAccountInitiation.required[0].userVisible).toBe(true);
164 + expect(fields?.connectedAccountInitiation.optional[0].userVisible).toBe(false);
165 + });
166 +
167 + it('maps required_scopes to requiredScopes', () => {
168 + const details = transformToolkitRetrieveResponse(rawToolkit).authConfigDetails?.[0];
169 +
170 + expect(details?.requiredScopes).toEqual(['offline_access']);
171 + });
172 +
173 it('maps auth_hint_url to authHintUrl', () => {
174 const details = transformToolkitRetrieveResponse(rawToolkit).authConfigDetails?.[0];
175
@@ -170,9 +187,11 @@ describe('transformToolkitRetrieveResponse', () => {
187 expect(field).not.toHaveProperty('default');
188 expect(field).not.toHaveProperty('isSecret');
189 expect(field).not.toHaveProperty('legacyTemplateName');
173 - expect(
174 - transformToolkitRetrieveResponse(rawToolkitWithoutOptionalKeys).authConfigDetails?.[0]
175 - ).not.toHaveProperty('authHintUrl');
190 + expect(field).not.toHaveProperty('userVisible');
191 + const details = transformToolkitRetrieveResponse(rawToolkitWithoutOptionalKeys)
192 + .authConfigDetails?.[0];
193 + expect(details).not.toHaveProperty('authHintUrl');
194 + expect(details).not.toHaveProperty('requiredScopes');
195 });
196
197 /**
ts/packages/core/type-tests/toolkit-auth-field-mapping.test-d.ts
+12 -4
@@ -48,7 +48,8 @@ type MappedFieldKeys =
48 | 'required'
49 | 'default'
50 | 'is_secret'
51 - | 'legacy_template_name';
51 + | 'legacy_template_name'
52 + | 'user_visible';
53
54 const everyFieldKeyIsMapped: NoneLeftOver<Exclude<KeysOfUnion<RawAuthField>, MappedFieldKeys>> =
55 true;
@@ -60,7 +61,13 @@ void everyFieldKeyIsMapped;
61 * marks it `@deprecated` and warns against further use.
62 */
63 type CoveredDetailKeys =
63 - 'name' | 'mode' | 'fields' | 'proxy' | 'auth_hint_url' | 'deprecated_auth_provider_details';
64 + | 'name'
65 + | 'mode'
66 + | 'fields'
67 + | 'proxy'
68 + | 'auth_hint_url'
69 + | 'required_scopes'
70 + | 'deprecated_auth_provider_details';
71
72 const everyDetailKeyIsCovered: NoneLeftOver<
73 Exclude<KeysOfUnion<RawAuthConfigDetail>, CoveredDetailKeys>
@@ -76,14 +83,15 @@ type MissingOnField = Exclude<
83 | 'required'
84 | 'default'
85 | 'isSecret'
79 - | 'legacyTemplateName',
86 + | 'legacyTemplateName'
87 + | 'userVisible',
88 keyof ToolkitAuthField
89 >;
90 const fieldTargetsExist: NoneLeftOver<MissingOnField> = true;
91 void fieldTargetsExist;
92
93 type MissingOnDetail = Exclude<
86 - 'name' | 'mode' | 'fields' | 'proxy' | 'authHintUrl',
94 + 'name' | 'mode' | 'fields' | 'proxy' | 'authHintUrl' | 'requiredScopes',
95 keyof ToolkitAuthConfigDetails
96 >;
97 const detailTargetsExist: NoneLeftOver<MissingOnDetail> = true;
uv.lock
+13 -16
@@ -786,7 +786,7 @@ wheels = [
786
787 [[package]]
788 name = "composio"
789 -version = "0.22.0"
789 +version = "0.23.0"
790 source = { editable = "python" }
791 dependencies = [
792 { name = "composio-client" },
@@ -820,7 +820,7 @@ dev = [
820
821 [package.metadata]
822 requires-dist = [
823 - { name = "composio-client", specifier = "==1.43.0" },
823 + { name = "composio-client", specifier = "==2.0.0rc8" },
824 { name = "json-schema-to-pydantic", specifier = ">=0.4.11" },
825 { name = "jsonschema", specifier = ">=4.23.0" },
826 { name = "openai", specifier = ">=2.48.0" },
@@ -851,7 +851,7 @@ dev = [
851
852 [[package]]
853 name = "composio-anthropic"
854 -version = "0.22.0"
854 +version = "0.23.0"
855 source = { editable = "python/providers/anthropic" }
856 dependencies = [
857 { name = "anthropic" },
@@ -866,24 +866,21 @@ requires-dist = [
866
867 [[package]]
868 name = "composio-client"
869 -version = "1.43.0"
869 +version = "2.0.0rc8"
870 source = { registry = "https://pypi.org/simple" }
871 dependencies = [
872 - { name = "anyio" },
873 - { name = "distro" },
872 { name = "httpx" },
873 { name = "pydantic" },
876 - { name = "sniffio" },
874 { name = "typing-extensions" },
875 ]
879 -sdist = { url = "https://files.pythonhosted.org/packages/b9/4b/3789f4c1347fd01349b66ecaeffb5ef623434c3b1fa4f5c5993fddb69c68/composio_client-1.43.0.tar.gz", hash = "sha256:bb96700da0c2aabc394cebc954be0ebf419557cc42b40f5d148aac52a5aff6f9", size = 246767, upload-time = "2026-07-08T09:06:02.42Z" }
876 +sdist = { url = "https://files.pythonhosted.org/packages/b1/76/35ce3aa815d18f611fbc402c443df73fb9d66035a013fe512d64620cce11/composio_client-2.0.0rc8.tar.gz", hash = "sha256:cd03a2a02d42c15dbb363c1dddaece1c2889aa8e10e36cd1ee62022e871aebb4", size = 593419, upload-time = "2026-09-21T21:50:44.236Z" }
877 wheels = [
881 - { url = "https://files.pythonhosted.org/packages/07/a2/3ae1f5471a52189ac558de6b0e088dc3575d695a0f91278cddf464274694/composio_client-1.43.0-py3-none-any.whl", hash = "sha256:3274d965b9efb6be90a51977f4c068ed24e2cad9160de4d40d3176d8bb4ce2d9", size = 277716, upload-time = "2026-07-08T09:06:01.007Z" },
878 + { url = "https://files.pythonhosted.org/packages/84/b1/07e0972086a5d8c3859d2d340308333dd13eac669e6987b6a0f89a9011fe/composio_client-2.0.0rc8-py3-none-any.whl", hash = "sha256:759f856aa132b10c1bb3ed503ab3d73c44d71fd48bfd62547b1a663be7d99543", size = 432943, upload-time = "2026-09-21T21:50:42.389Z" },
879 ]
880
881 [[package]]
882 name = "composio-crewai"
886 -version = "0.22.0"
883 +version = "0.23.0"
884 source = { editable = "python/providers/crewai" }
885 dependencies = [
886 { name = "composio" },
@@ -898,7 +895,7 @@ requires-dist = [
895
896 [[package]]
897 name = "composio-gemini"
901 -version = "0.22.0"
898 +version = "0.23.0"
899 source = { virtual = "python/providers/gemini" }
900 dependencies = [
901 { name = "composio" },
@@ -913,7 +910,7 @@ requires-dist = [
910
911 [[package]]
912 name = "composio-google"
916 -version = "0.22.0"
913 +version = "0.23.0"
914 source = { editable = "python/providers/google" }
915 dependencies = [
916 { name = "composio" },
@@ -928,7 +925,7 @@ requires-dist = [
925
926 [[package]]
927 name = "composio-google-adk"
931 -version = "0.22.0"
928 +version = "0.23.0"
929 source = { editable = "python/providers/google_adk" }
930 dependencies = [
931 { name = "composio" },
@@ -943,7 +940,7 @@ requires-dist = [
940
941 [[package]]
942 name = "composio-langchain"
946 -version = "0.22.0"
943 +version = "0.23.0"
944 source = { editable = "python/providers/langchain" }
945 dependencies = [
946 { name = "composio" },
@@ -958,7 +955,7 @@ requires-dist = [
955
956 [[package]]
957 name = "composio-openai"
961 -version = "0.22.0"
958 +version = "0.23.0"
959 source = { editable = "python/providers/openai" }
960 dependencies = [
961 { name = "composio" },
@@ -973,7 +970,7 @@ requires-dist = [
970
971 [[package]]
972 name = "composio-openai-agents"
976 -version = "0.22.0"
973 +version = "0.23.0"
974 source = { editable = "python/providers/openai_agents" }
975 dependencies = [
976 { name = "composio" },