Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { getEnvVariable } from './utils/env'; |
| 2 | import type { BaseComposioProvider } from './provider/BaseProvider'; |
| 3 | import ComposioClient, { createFetchTransport } from '@composio/client'; |
| 4 | import type { LogLevel as ClientLogLevel } from '@composio/client'; |
| 5 | import { Tools } from './models/Tools'; |
| 6 | import { Toolkits } from './models/Toolkits'; |
| 7 | import { Triggers } from './models/Triggers'; |
| 8 | import { AuthConfigs } from './models/AuthConfigs'; |
| 9 | import { ConnectedAccounts } from './models/ConnectedAccounts'; |
| 10 | import { Experimental } from './models/Experimental'; |
| 11 | import { CustomToolkits } from './models/CustomToolkits'; |
| 12 | import { MCP } from './models/MCP'; |
| 13 | import { Webhooks } from './models/Webhooks'; |
| 14 | import { Logs } from './models/Logs'; |
| 15 | import { SessionConfigs } from './models/SessionConfigs'; |
| 16 | import { Keyring } from './models/Keyring'; |
| 17 | import { telemetry } from './telemetry/Telemetry'; |
| 18 | import { |
| 19 | getSDKConfig, |
| 20 | getToolkitVersionsFromEnv, |
| 21 | resolveSDKCredentials, |
| 22 | resolveSDKScope, |
| 23 | toClientAuth, |
| 24 | toClientScope, |
| 25 | withoutSDKOwnedHeaders, |
| 26 | } from './utils/sdk'; |
| 27 | import logger from './utils/logger'; |
| 28 | import type { ComposioLogger, LogLevel } from './utils/logger'; |
| 29 | import { IS_DEVELOPMENT_OR_CI } from './utils/constants'; |
| 30 | import { checkForLatestVersionFromNPM } from './utils/version'; |
| 31 | import { OpenAIProvider } from './provider/OpenAIProvider'; |
| 32 | import { version } from '../package.json'; |
| 33 | import type { ComposioRequestHeaders } from './types/composio.types'; |
| 34 | import type { ComposioRequestOptions } from './types/requestOptions.types'; |
| 35 | import { Files } from '#files'; |
| 36 | import { getClientIdentity } from './utils/session'; |
| 37 | import { ToolkitVersionParam } from './types/tool.types'; |
| 38 | import { ToolRouter } from './models/ToolRouter'; |
| 39 | import { Sessions } from './models/Sessions'; |
| 40 | import { CONFIG_DEFAULTS } from './utils/config-defaults'; |
| 41 | import { expandHomeAndResolve, expandHomeAndResolveMany } from './utils/fileDirs'; |
| 42 | import { createToolkitDeprecationFetch } from './utils/toolkitDeprecation'; |
| 43 | export type ComposioConfig< |
| 44 | TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider, |
| 45 | > = { |
| 46 | /** |
| 47 | * The project API key for the Composio API, sent as the `x-api-key` header. |
| 48 | * |
| 49 | * - A string is used as-is; the environment and the CLI user config file are not consulted. |
| 50 | * - Omitted: falls back to `COMPOSIO_API_KEY`, then to the project key stored by the Composio |
| 51 | * CLI in `~/.composio/user_data.json`. A stored user key (`uak_...`) is never used as a |
| 52 | * project key; the SDK throws instead of sending it. |
| 53 | * - `null`: disables project-key authentication entirely, including both fallbacks. The SDK |
| 54 | * then requires another credential (`userApiKey`, `orgApiKey`, or an `x-user-api-key` |
| 55 | * or `x-org-api-key` entry in `defaultHeaders`) and sends no `x-api-key`; an `x-api-key` entry in |
| 56 | * `defaultHeaders` is rejected, also on `createSession()` clones. The user API key |
| 57 | * then authenticates every request; the organization API key does when it is the |
| 58 | * only credential held. |
| 59 | * |
| 60 | * @example 'ak_1234567890' |
| 61 | */ |
| 62 | apiKey?: string | null; |
| 63 | /** |
| 64 | * User API key (`uak_*`) for the organization, consumer, and user-scoped |
| 65 | * endpoints reached through `getClient()` (for example `client.org.list()`). |
| 66 | * Sent as `x-user-api-key` only on operations whose security scheme accepts |
| 67 | * it, never alongside the project key. Falls back to |
| 68 | * `process.env['COMPOSIO_USER_API_KEY']`; `null` disables that fallback. |
| 69 | * Combine with `apiKey: null` to authenticate with the user key alone. |
| 70 | * @example 'uak_1234567890' |
| 71 | */ |
| 72 | userApiKey?: string | null; |
| 73 | /** |
| 74 | * Organization API key (`oak_*`) for the organization-owner endpoints reached |
| 75 | * through `getClient()` (for example `client.org.owner.project.list()`). |
| 76 | * Sent as `x-org-api-key` only on operations whose security scheme accepts |
| 77 | * it, never alongside the project key. Falls back to |
| 78 | * `process.env['COMPOSIO_ORG_API_KEY']`; `null` disables that fallback. |
| 79 | * Combine with `apiKey: null` (and no user API key) to authenticate every |
| 80 | * request with the organization key alone. |
| 81 | * @example 'oak_1234567890' |
| 82 | */ |
| 83 | orgApiKey?: string | null; |
| 84 | /** |
| 85 | * Organization nano ID that scopes user-key requests, sent as the |
| 86 | * `x-org-id` header on every request and exported with the session MCP |
| 87 | * config. This is the short public identifier the API returns as `org_id` |
| 88 | * (for example from the consumer project resolve endpoint), not a UUID. |
| 89 | * Must be supplied together with `projectId`; without an explicit scope a |
| 90 | * user API key addresses the API default (the developer project). May also |
| 91 | * be supplied as the `x-org-id` entry in `defaultHeaders`; the two must |
| 92 | * agree. |
| 93 | * @example 'org_9f2k1x' |
| 94 | */ |
| 95 | orgId?: string; |
| 96 | /** |
| 97 | * Project nano ID that scopes user-key requests, sent as the |
| 98 | * `x-project-id` header on every request and exported with the session MCP |
| 99 | * config. This is the short public identifier the API returns as |
| 100 | * `project_nano_id`, not the project UUID. Must be supplied together with |
| 101 | * `orgId`. May also be supplied as the `x-project-id` entry in |
| 102 | * `defaultHeaders`; the two must agree. |
| 103 | * @example 'proj_4b8m2q' |
| 104 | */ |
| 105 | projectId?: string; |
| 106 | /** |
| 107 | * The base URL of the Composio API. |
| 108 | * @example 'https://backend.composio.dev' |
| 109 | */ |
| 110 | baseURL?: string | null; |
| 111 | /** |
| 112 | * Whether to allow tracking for the Composio instance. |
| 113 | * @example true, false |
| 114 | * @default true |
| 115 | */ |
| 116 | allowTracking?: boolean; |
| 117 | /** |
| 118 | * Opt in to automatic file upload and download during tool execution (reads local paths |
| 119 | * and fetches URLs marked as file-uploadable in tool schemas). Disabled by default. |
| 120 | * @default false |
| 121 | */ |
| 122 | dangerouslyAllowAutoUploadDownloadFiles?: boolean; |
| 123 | /** |
| 124 | * When true, local file paths for auto-upload and `files.upload` are checked against |
| 125 | * a built-in denylist of sensitive path segments (e.g. `.ssh`, `.aws`) and |
| 126 | * credential-like file names (e.g. `.env`, default SSH private key names). URLs and |
| 127 | * {@link File} objects are not path-checked. |
| 128 | * @default true |
| 129 | */ |
| 130 | sensitiveFileUploadProtection?: boolean; |
| 131 | /** |
| 132 | * Extra path components (a single directory or file name) to treat as sensitive when |
| 133 | * they appear anywhere in the resolved path. Merged with the built-in list. |
| 134 | */ |
| 135 | fileUploadPathDenySegments?: string[]; |
| 136 | /** |
| 137 | * Allowlist of directories from which the SDK is allowed to read local files |
| 138 | * during **automatic** file upload (when |
| 139 | * `dangerouslyAllowAutoUploadDownloadFiles: true`). Manual |
| 140 | * `composio.files.upload()` calls are NOT subject to this allowlist. |
| 141 | * |
| 142 | * - `undefined` (default) → `[<home>/.composio/temp]`. |
| 143 | * - `false` → reject every local path during auto-upload. URLs |
| 144 | * (`http(s)://...`) and `File`/`Blob` objects continue to work. |
| 145 | * - `string[]` (non-empty) → use as the allowlist. A file is accepted iff |
| 146 | * its symlink-resolved absolute path is inside one of these directories |
| 147 | * on a path-component boundary (so `/tmp/foo` allows `/tmp/foo/bar` but |
| 148 | * NOT `/tmp/foo-bar`). |
| 149 | * - `[]` → behaves like `false` (kept as an alias; prefer `false` for |
| 150 | * readability). |
| 151 | * - Providing any value **replaces** the default. Include `~/.composio/temp` |
| 152 | * in your list if you want the default staging dir to keep working. |
| 153 | * - On Windows, entries are compared case-insensitively. |
| 154 | */ |
| 155 | fileUploadDirs?: string[] | false; |
| 156 | /** |
| 157 | * Directory where files downloaded during tool execution (and |
| 158 | * `composio.files.download()`) are written. Defaults to |
| 159 | * `<home>/.composio/files`. Path is expanded at SDK-init time; relative |
| 160 | * paths resolve against `process.cwd()`. |
| 161 | */ |
| 162 | fileDownloadDir?: string; |
| 163 | /** |
| 164 | * The tool provider to use for this Composio instance. |
| 165 | * @example new OpenAIProvider() |
| 166 | */ |
| 167 | provider?: TProvider; |
| 168 | /** |
| 169 | * The host service name of the SDK where the SDK is running. |
| 170 | * This is used to identify the host for telemetry. Ignore it if you are not using telemetry. |
| 171 | * @example 'mcp', 'apollo', ' etc |
| 172 | */ |
| 173 | host?: string; |
| 174 | /** |
| 175 | * Default headers attached to every request made through this instance. |
| 176 | * |
| 177 | * Credential and scope headers are not forwarded as headers: the SDK folds |
| 178 | * them into its own options, which `getConfig()` then reports. |
| 179 | * A non-empty `x-user-api-key` (or `x-org-api-key`) entry becomes the |
| 180 | * credential every request carries, in place of the configured keys; together |
| 181 | * with `apiKey: null` it authenticates with that key instead of a project key. |
| 182 | * An `x-api-key` entry replaces the project key, and is rejected when `apiKey` |
| 183 | * is `null`. At most one of the three may be set. `x-org-id` / `x-project-id` |
| 184 | * entries supply `orgId` / `projectId`. |
| 185 | * |
| 186 | * The SDK reports itself through the API client's identity headers |
| 187 | * (`x-client-provenance`, `x-client-version`, `x-client-library`, |
| 188 | * `x-client-library-version`, `x-client-language`, `x-client-runtime`, |
| 189 | * `x-sdk-version`, `x-source`, `x-framework`, `x-runtime` and |
| 190 | * `x-runtime-version`); an entry naming one of them is rejected with a |
| 191 | * `ComposioError` from `@composio/client`. Every other header is passed |
| 192 | * through untouched. |
| 193 | * @example |
| 194 | * ```typescript |
| 195 | * const composio = new Composio({ |
| 196 | * defaultHeaders: { |
| 197 | * 'x-request-id': '1234567890', |
| 198 | * }, |
| 199 | * }); |
| 200 | * ``` |
| 201 | */ |
| 202 | defaultHeaders?: ComposioRequestHeaders; |
| 203 | /** |
| 204 | * Whether to disable version check for the Composio SDK. |
| 205 | * @example true, false |
| 206 | * @default false |
| 207 | */ |
| 208 | disableVersionCheck?: boolean; |
| 209 | /** |
| 210 | * The versions of the toolkits to use for tool execution and retrieval. |
| 211 | * Omit to use 'latest' for all toolkits. |
| 212 | * |
| 213 | * **Version Control:** |
| 214 | * When executing tools manually (via `tools.execute()`), if this resolves to "latest", |
| 215 | * you must either: |
| 216 | * - Set `dangerouslySkipVersionCheck: true` in the execute params (not recommended for production) |
| 217 | * - Specify a concrete version here or in environment variables |
| 218 | * - Pass a specific `version` parameter to the execute call |
| 219 | * |
| 220 | * Defaults to 'latest' if nothing is provided. |
| 221 | * You can specify individual toolkit versions via environment variables: `COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00` |
| 222 | * |
| 223 | * @example Global version for all toolkits, omit to use 'latest' |
| 224 | * ```typescript |
| 225 | * const composio = new Composio(); |
| 226 | * ``` |
| 227 | * |
| 228 | * @example Specific versions for different toolkits (recommended for production) |
| 229 | * ```typescript |
| 230 | * const composio = new Composio({ |
| 231 | * toolkitVersions: { |
| 232 | * github: '20250909_00', |
| 233 | * slack: '20250902_00' |
| 234 | * } |
| 235 | * }); |
| 236 | * ``` |
| 237 | * |
| 238 | * @example Set via environment variables |
| 239 | * ```typescript |
| 240 | * // Set environment variables: |
| 241 | * // COMPOSIO_TOOLKIT_VERSION_GITHUB=20250909_00 |
| 242 | * // COMPOSIO_TOOLKIT_VERSION_SLACK=20250902_00 |
| 243 | * const composio = new Composio(); // Will use env variables |
| 244 | * ``` |
| 245 | */ |
| 246 | toolkitVersions?: ToolkitVersionParam; |
| 247 | /** |
| 248 | * Destination for SDK log output. Messages are formatted and have |
| 249 | * credential-shaped values redacted before they reach the sink, so any |
| 250 | * object with `error`/`warn`/`info`/`debug` methods works (`console`, pino, |
| 251 | * winston, ...). |
| 252 | * |
| 253 | * Runtime deprecation warnings raised by the underlying API client (response |
| 254 | * `Deprecation`/`Sunset` headers and deprecated request inputs) are routed |
| 255 | * through this logger as well. |
| 256 | * |
| 257 | * The SDK logger is process-wide: configuring it on one `Composio` instance |
| 258 | * affects every instance, and the last configured instance wins. |
| 259 | * |
| 260 | * @default console |
| 261 | * @example |
| 262 | * ```typescript |
| 263 | * const composio = new Composio({ |
| 264 | * apiKey: 'your-api-key', |
| 265 | * logger: pino(), |
| 266 | * logLevel: 'warn', |
| 267 | * }); |
| 268 | * ``` |
| 269 | */ |
| 270 | logger?: ComposioLogger; |
| 271 | /** |
| 272 | * Minimum level to emit: `'silent' | 'error' | 'warn' | 'info' | 'debug'`. |
| 273 | * Takes precedence over the `COMPOSIO_LOG_LEVEL` environment variable. |
| 274 | * Also gates the API client's runtime deprecation warnings (`'silent'` turns |
| 275 | * them off). The client's per-request lifecycle logs are emitted at |
| 276 | * `'debug'` only. |
| 277 | * |
| 278 | * Like `logger`, this applies process-wide and the last configured instance |
| 279 | * wins. The API client's own level is fixed when each instance is created. |
| 280 | * |
| 281 | * @default 'info' (or `COMPOSIO_LOG_LEVEL` when set) |
| 282 | */ |
| 283 | logLevel?: LogLevel; |
| 284 | }; |
| 285 | |
| 286 | /** |
| 287 | * Level for the API client given the SDK level. The client logs each request's |
| 288 | * lifecycle at `info`, which is debug-grade for SDK users, so the client stays |
| 289 | * at `warn` unless the SDK is at `debug`. The client's `LogLevel` has |
| 290 | * `'off'` where the SDK has `'silent'`. |
| 291 | */ |
| 292 | const toClientLogLevel = (level: LogLevel): ClientLogLevel => { |
| 293 | if (level === 'silent') return 'off'; |
| 294 | if (level === 'info') return 'warn'; |
| 295 | return level; |
| 296 | }; |
| 297 | |
| 298 | /** |
| 299 | * Forwards the API client's log records to the SDK singleton so they pick up |
| 300 | * the SDK's formatting, redaction, and configured sink. Methods are looked up |
| 301 | * at call time so a later `logger.configure()` is honoured. The client's |
| 302 | * `info` records (per-request lifecycle) are forwarded as SDK `debug`. |
| 303 | */ |
| 304 | const clientLogForwarder: Pick<Console, 'debug' | 'info' | 'warn' | 'error'> = { |
| 305 | error: (...args: unknown[]) => logger.error(...args), |
| 306 | warn: (...args: unknown[]) => logger.warn(...args), |
| 307 | info: (...args: unknown[]) => logger.debug(...args), |
| 308 | debug: (...args: unknown[]) => logger.debug(...args), |
| 309 | }; |
| 310 | |
| 311 | /** |
| 312 | * This is the core class for Composio. |
| 313 | * It is used to initialize the Composio SDK and provide a global configuration. |
| 314 | */ |
| 315 | export class Composio< |
| 316 | TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider, |
| 317 | > { |
| 318 | /** |
| 319 | * The Composio API client. |
| 320 | * @type {ComposioClient} |
| 321 | */ |
| 322 | protected client: ComposioClient; |
| 323 | |
| 324 | /** |
| 325 | * The configuration for the Composio SDK. |
| 326 | * @type {ComposioConfig<TProvider>} |
| 327 | */ |
| 328 | private config: ComposioConfig<TProvider>; |
| 329 | |
| 330 | /** |
| 331 | * Core models for Composio. |
| 332 | */ |
| 333 | |
| 334 | /** List, retrieve, and execute tools */ |
| 335 | tools: Tools<unknown, unknown, TProvider>; |
| 336 | /** Retrieve toolkit metadata and authorize user connections */ |
| 337 | toolkits: Toolkits; |
| 338 | /** Manage webhook triggers and event subscriptions */ |
| 339 | triggers: Triggers<TProvider>; |
| 340 | /** The tool provider instance used for wrapping tools in framework-specific formats */ |
| 341 | provider: TProvider; |
| 342 | /** Upload and download files */ |
| 343 | files: Files; |
| 344 | /** Manage authentication configurations for toolkits */ |
| 345 | authConfigs: AuthConfigs; |
| 346 | /** Manage authenticated connections */ |
| 347 | connectedAccounts: ConnectedAccounts; |
| 348 | /** |
| 349 | * Manage the project's webhook subscription (`webhooks.subscriptions`) and |
| 350 | * inbound per-toolkit webhook endpoints (`webhooks.endpoints`). |
| 351 | */ |
| 352 | webhooks: Webhooks; |
| 353 | /** Search and inspect tool-execution logs */ |
| 354 | logs: Logs; |
| 355 | /** Public transfer keys of the organization's customer-managed keyring */ |
| 356 | keyring: Keyring; |
| 357 | /** |
| 358 | * Register and manage project-owned custom toolkits, such as a remote MCP |
| 359 | * server (`create()` / `update()` / `sync()` / `delete()`). |
| 360 | * |
| 361 | * @example |
| 362 | * ```typescript |
| 363 | * await composio.customToolkits.sync('CUSTOM_MY_TOOLKIT'); |
| 364 | * ``` |
| 365 | */ |
| 366 | customToolkits: CustomToolkits; |
| 367 | /** |
| 368 | * Experimental SDK methods whose shape may change in future releases. |
| 369 | * Prefer domain-specific mounts (for example |
| 370 | * `composio.connectedAccounts.updateAcl(...)`) when available; this |
| 371 | * namespace keeps compatibility aliases while APIs are experimental. |
| 372 | * Stateless experimental factories (e.g. `experimental_createTool`) stay |
| 373 | * at the top level. |
| 374 | * @experimental |
| 375 | */ |
| 376 | experimental: Experimental; |
| 377 | /** |
| 378 | * Model Context Protocol server management. |
| 379 | * @deprecated Use a session's MCP endpoint instead: `composio.create(userId, { mcp: true })` |
| 380 | * returns a session that exposes `session.mcp.url` / `session.mcp.headers`. MCP is now opt-in |
| 381 | * per session; this standalone server-management API is kept only for backwards compatibility. |
| 382 | * Prefer the session MCP endpoint; do not generate new code against `composio.mcp`. |
| 383 | * See https://docs.composio.dev/docs/sessions-via-mcp |
| 384 | */ |
| 385 | mcp: MCP; |
| 386 | /** |
| 387 | * Create and reuse Composio sessions. |
| 388 | * |
| 389 | * Prefer `composio.sessions.create(...)` for new code. The top-level |
| 390 | * `composio.create(...)` method is kept as an alias. |
| 391 | */ |
| 392 | sessions: Sessions<unknown, unknown, TProvider>; |
| 393 | /** |
| 394 | * Read the project's saved Session configs. Apply one with |
| 395 | * `experimental.sessionConfigId` on `sessions.create()` or `session.update()`. |
| 396 | * Requires Session configs to be enabled for the project. |
| 397 | */ |
| 398 | sessionConfigs: SessionConfigs; |
| 399 | /** |
| 400 | * Legacy alias for `composio.sessions`. |
| 401 | * @deprecated Use `composio.sessions` instead — `toolRouter` was renamed to `sessions` and is kept only for backwards compatibility. Prefer `composio.sessions`; do not generate new code against `composio.toolRouter`. |
| 402 | */ |
| 403 | toolRouter: ToolRouter<unknown, unknown, TProvider>; |
| 404 | /** |
| 405 | * Creates a new tool router session for a user. |
| 406 | * Use `sessionPreset: SessionPreset.DIRECT_TOOLS` when all needed tools |
| 407 | * should be exposed directly; see `ToolRouterCreateSessionConfig`. |
| 408 | * |
| 409 | * @param userId {string} The user id to create the session for |
| 410 | * @param config {ToolRouterConfig} The config for the tool router session |
| 411 | * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session |
| 412 | * |
| 413 | * @example |
| 414 | * ```typescript |
| 415 | * import { Composio } from '@composio/core'; |
| 416 | * |
| 417 | * const composio = new Composio(); |
| 418 | * const userId = 'user_123'; |
| 419 | * |
| 420 | * const session = await composio.sessions.create(userId, { |
| 421 | * manageConnections: true, |
| 422 | * }); |
| 423 | * |
| 424 | * // Backwards-compatible alias: |
| 425 | * const same = await composio.create(userId, { |
| 426 | * manageConnections: true, |
| 427 | * }); |
| 428 | * |
| 429 | * console.log(session.sessionId); |
| 430 | * console.log(session.url); |
| 431 | * console.log(session.tools()); |
| 432 | * ``` |
| 433 | */ |
| 434 | create: Sessions<unknown, unknown, TProvider>['create']; |
| 435 | |
| 436 | /** |
| 437 | * Use an existing tool router session |
| 438 | * |
| 439 | * @param id {string} The id of the session to use |
| 440 | * @param options {object} Custom tools / toolkits to attach to the session |
| 441 | * @param requestOptions {ComposioRequestOptions} Per-request cancellation |
| 442 | * options. The supplied AbortSignal aborts the underlying session |
| 443 | * retrieve/attach call only. Subsequent session method calls accept |
| 444 | * their own per-call requestOptions. |
| 445 | * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session |
| 446 | */ |
| 447 | use: Sessions<unknown, unknown, TProvider>['use']; |
| 448 | |
| 449 | /** |
| 450 | * Creates a new instance of the Composio SDK. |
| 451 | * |
| 452 | * The constructor initializes the SDK with the provided configuration options, |
| 453 | * sets up the API client, and initializes all core models (tools, toolkits, etc.). |
| 454 | * |
| 455 | * @param {ComposioConfig<TProvider>} config - Configuration options for the Composio SDK |
| 456 | * @param {string} [config.apiKey] - The API key for authenticating with the Composio API |
| 457 | * @param {string} [config.baseURL] - The base URL for the Composio API (defaults to production URL) |
| 458 | * @param {boolean} [config.allowTracking=true] - Whether to allow anonymous usage analytics |
| 459 | * @param {TProvider} [config.provider] - The provider to use for this Composio instance (defaults to OpenAIProvider) |
| 460 | * |
| 461 | * @example |
| 462 | * ```typescript |
| 463 | * // Initialize with default configuration |
| 464 | * const composio = new Composio(); |
| 465 | * |
| 466 | * // Initialize with custom API key and base URL |
| 467 | * const composio = new Composio({ |
| 468 | * apiKey: 'your-api-key', |
| 469 | * baseURL: 'https://api.composio.dev' |
| 470 | * }); |
| 471 | * |
| 472 | * // Initialize with custom provider |
| 473 | * const composio = new Composio({ |
| 474 | * apiKey: 'your-api-key', |
| 475 | * provider: new CustomProvider() |
| 476 | * }); |
| 477 | * ``` |
| 478 | */ |
| 479 | constructor(config?: ComposioConfig<TProvider>) { |
| 480 | const scope = resolveSDKScope({ |
| 481 | orgId: config?.orgId, |
| 482 | projectId: config?.projectId, |
| 483 | defaultHeaders: config?.defaultHeaders, |
| 484 | }); |
| 485 | const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig( |
| 486 | config?.baseURL, |
| 487 | config?.apiKey, |
| 488 | { |
| 489 | defaultHeaders: config?.defaultHeaders, |
| 490 | userApiKey: config?.userApiKey, |
| 491 | orgApiKey: config?.orgApiKey, |
| 492 | } |
| 493 | ); |
| 494 | |
| 495 | // The SDK owns the credential: it resolves the keys (with their |
| 496 | // environment fallbacks) and folds a credential default header into them, |
| 497 | // so the API client receives one `auth` and never a credential header. |
| 498 | // The resolved keys are stored on the config, so clones, the MCP export |
| 499 | // and trigger subscriptions read the same values. |
| 500 | const credentials = resolveSDKCredentials({ |
| 501 | apiKey: apiKeyParsed, |
| 502 | userApiKey: config?.userApiKey, |
| 503 | orgApiKey: config?.orgApiKey, |
| 504 | defaultHeaders: config?.defaultHeaders, |
| 505 | }); |
| 506 | // Credential and scope entries travel as `auth` and `scope`; the client |
| 507 | // refuses them in `defaultHeaders`. |
| 508 | const defaultHeaders = withoutSDKOwnedHeaders(config?.defaultHeaders); |
| 509 | |
| 510 | if (config?.logger !== undefined || config?.logLevel !== undefined) { |
| 511 | logger.configure({ level: config.logLevel, sink: config.logger }); |
| 512 | } |
| 513 | |
| 514 | if (IS_DEVELOPMENT_OR_CI) { |
| 515 | logger.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`); |
| 516 | } |
| 517 | |
| 518 | /** |
| 519 | * Set the default provider, if not provided by the user. |
| 520 | */ |
| 521 | this.provider = (config?.provider ?? new OpenAIProvider()) as TProvider; |
| 522 | |
| 523 | /** |
| 524 | * Keep a reference to the config object. |
| 525 | * This is useful for creating a builder pattern, debugging and logging. |
| 526 | */ |
| 527 | this.config = { |
| 528 | ...config, |
| 529 | baseURL: baseURLParsed, |
| 530 | apiKey: credentials.apiKey, |
| 531 | userApiKey: credentials.userApiKey, |
| 532 | orgApiKey: credentials.orgApiKey, |
| 533 | defaultHeaders, |
| 534 | toolkitVersions: getToolkitVersionsFromEnv(config?.toolkitVersions), |
| 535 | allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking, |
| 536 | dangerouslyAllowAutoUploadDownloadFiles: |
| 537 | config?.dangerouslyAllowAutoUploadDownloadFiles ?? |
| 538 | CONFIG_DEFAULTS.dangerouslyAllowAutoUploadDownloadFiles, |
| 539 | sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection, |
| 540 | fileUploadPathDenySegments: config?.fileUploadPathDenySegments, |
| 541 | fileUploadDirs: expandHomeAndResolveMany(config?.fileUploadDirs), |
| 542 | fileDownloadDir: expandHomeAndResolve(config?.fileDownloadDir), |
| 543 | provider: config?.provider ?? this.provider, |
| 544 | orgId: scope.orgId, |
| 545 | projectId: scope.projectId, |
| 546 | }; |
| 547 | |
| 548 | /** |
| 549 | * Initialize the Composio SDK client. |
| 550 | * The client is used to make API calls to the Composio API. It sends the |
| 551 | * credential from `auth`, the resolved org/project scope from `scope`, and |
| 552 | * the SDK's identity headers from `identity`, and refuses all three in |
| 553 | * `defaultHeaders`. |
| 554 | */ |
| 555 | this.client = new ComposioClient({ |
| 556 | auth: toClientAuth(credentials), |
| 557 | scope: toClientScope(scope), |
| 558 | baseURL: baseURLParsed, |
| 559 | // The client stopped reading the process environment in rc.18; this |
| 560 | // opt-in for a plain-HTTP development origin is the one setting of its |
| 561 | // own that core forwards. |
| 562 | ...(getEnvVariable('COMPOSIO_ALLOW_INSECURE_HTTP') === '1' |
| 563 | ? { allowInsecureHTTP: true } |
| 564 | : {}), |
| 565 | defaultHeaders, |
| 566 | identity: getClientIdentity(this.provider), |
| 567 | logger: clientLogForwarder, |
| 568 | logLevel: toClientLogLevel(logger.getLevel()), |
| 569 | // Warns once per deprecated toolkit version reported through the |
| 570 | // `Composio-Deprecated-Toolkits` response header. `createSession()` |
| 571 | // clones go through this same constructor and inherit it. |
| 572 | transport: createFetchTransport({ fetch: createToolkitDeprecationFetch() }), |
| 573 | }); |
| 574 | |
| 575 | this.tools = new Tools(this.client, this.config); |
| 576 | this.mcp = new MCP(this.client); |
| 577 | this.toolkits = new Toolkits(this.client); |
| 578 | this.triggers = new Triggers(this.client, this.config); |
| 579 | this.authConfigs = new AuthConfigs(this.client); |
| 580 | this.files = new Files(this.client, { |
| 581 | sensitiveFileUploadProtection: this.config.sensitiveFileUploadProtection, |
| 582 | fileUploadPathDenySegments: this.config.fileUploadPathDenySegments, |
| 583 | fileDownloadDir: this.config.fileDownloadDir, |
| 584 | }); |
| 585 | this.connectedAccounts = new ConnectedAccounts(this.client); |
| 586 | this.webhooks = new Webhooks(this.client); |
| 587 | this.logs = new Logs(this.client); |
| 588 | this.keyring = new Keyring(this.client); |
| 589 | this.experimental = new Experimental(this.client); |
| 590 | this.customToolkits = this.experimental.customToolkits; |
| 591 | this.sessions = new Sessions(this.client, this.config); |
| 592 | this.toolRouter = this.sessions; |
| 593 | this.sessionConfigs = new SessionConfigs(this.client); |
| 594 | |
| 595 | /** |
| 596 | * Initialize session aliases. |
| 597 | * Properly bind the methods to maintain the correct 'this' context. |
| 598 | */ |
| 599 | // Cast: Function.prototype.bind collapses the create/use overloads to a |
| 600 | // single signature; re-assert the overloaded type. Runtime behaviour is |
| 601 | // unchanged — bind only rebinds `this`. |
| 602 | this.create = this.sessions.create.bind(this.sessions) as Composio<TProvider>['create']; |
| 603 | this.use = this.sessions.use.bind(this.sessions) as Composio<TProvider>['use']; |
| 604 | |
| 605 | /** |
| 606 | * Initialize the client telemetry. |
| 607 | */ |
| 608 | if (this.config.allowTracking) { |
| 609 | telemetry.setup({ |
| 610 | apiKey: credentials.apiKey ?? '', |
| 611 | baseUrl: baseURLParsed ?? '', |
| 612 | isAgentic: this.provider?._isAgentic || false, |
| 613 | version: version, |
| 614 | isBrowser: typeof window !== 'undefined', |
| 615 | provider: this.provider?.name ?? 'openai', |
| 616 | host: this.config.host, |
| 617 | }); |
| 618 | } |
| 619 | // instrument the composio instance |
| 620 | telemetry.instrument(this, 'Composio'); |
| 621 | // instrument the provider since we are not using the provider class directly |
| 622 | telemetry.instrument( |
| 623 | this.provider, |
| 624 | this.provider.name ?? this.provider.constructor.name ?? 'unknown' |
| 625 | ); |
| 626 | |
| 627 | // Check for the latest version of the Composio SDK from NPM. |
| 628 | if (!this.config.disableVersionCheck) { |
| 629 | checkForLatestVersionFromNPM(version); |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | /** |
| 634 | * Get the Composio SDK client. |
| 635 | * @returns {ComposioClient} The Composio API client. |
| 636 | */ |
| 637 | getClient(): ComposioClient { |
| 638 | if (!this.client) { |
| 639 | throw new Error('Composio client is not initialized. Please initialize it first.'); |
| 640 | } |
| 641 | return this.client; |
| 642 | } |
| 643 | |
| 644 | /** |
| 645 | * Get the configuration SDK is initialized with. |
| 646 | * |
| 647 | * Returns a frozen shallow clone — the SDK has already snapshotted |
| 648 | * configuration values such as `dangerouslyAllowAutoUploadDownloadFiles`, |
| 649 | * `fileUploadDirs`, and `fileDownloadDir` into its internal models, so |
| 650 | * mutating the live config object would silently no-op. Freezing makes |
| 651 | * that contract visible at the call site instead of letting the mutation |
| 652 | * appear successful. |
| 653 | * |
| 654 | * @returns {Readonly<ComposioConfig<TProvider>>} The frozen configuration |
| 655 | * the SDK is initialized with. |
| 656 | */ |
| 657 | getConfig(): Readonly<ComposioConfig<TProvider>> { |
| 658 | return Object.freeze({ ...this.config }); |
| 659 | } |
| 660 | |
| 661 | /** |
| 662 | * Creates a new instance of the Composio SDK with custom request options while preserving the existing configuration. |
| 663 | * This method is particularly useful when you need to: |
| 664 | * - Add custom headers for specific requests |
| 665 | * - Track request contexts with unique identifiers |
| 666 | * - Override default request behavior for a subset of operations |
| 667 | * |
| 668 | * The new instance inherits all configuration from the parent instance (apiKey, baseURL, provider, etc.) |
| 669 | * but allows you to specify custom request options that will be used for all API calls made through this session. |
| 670 | * |
| 671 | * @deprecated Will be removed in a future version of the SDK. Instead, construct a new |
| 672 | * instance directly with the headers you need: `new Composio({ ...existingConfig, defaultHeaders })`. |
| 673 | * For one-off overrides, pass per-call `requestOptions` where supported. |
| 674 | * |
| 675 | * @param {object} [options] - Options for the new instance. |
| 676 | * @param {ComposioRequestHeaders} [options.headers] - Headers sent with every API call the new instance makes. |
| 677 | * @returns {Composio<TProvider>} A new Composio instance with the custom request options applied. |
| 678 | * |
| 679 | * @example |
| 680 | * ```typescript |
| 681 | * // Create a base Composio instance |
| 682 | * const composio = new Composio({ |
| 683 | * apiKey: 'your-api-key' |
| 684 | * }); |
| 685 | * |
| 686 | * // Create a session with request tracking headers |
| 687 | * const composioWithCustomHeaders = composio.createSession({ |
| 688 | * headers: { |
| 689 | * 'x-request-id': '1234567890', |
| 690 | * 'x-correlation-id': 'session-abc-123', |
| 691 | * 'x-custom-header': 'custom-value' |
| 692 | * } |
| 693 | * }); |
| 694 | * |
| 695 | * // Use the session for making API calls with the custom headers |
| 696 | * await composioWithCustomHeaders.tools.list(); |
| 697 | * ``` |
| 698 | */ |
| 699 | createSession(options?: { headers?: ComposioRequestHeaders }): Composio<TProvider> { |
| 700 | // The clone inherits the resolved credentials and scope through |
| 701 | // `this.config`, where a credential or scope default header has already |
| 702 | // been folded in; `headers` replaces the default headers, and a |
| 703 | // credential or scope header in it is folded in the same way. |
| 704 | return new Composio({ |
| 705 | ...this.config, |
| 706 | defaultHeaders: options?.headers, |
| 707 | }); |
| 708 | } |
| 709 | |
| 710 | /** |
| 711 | * Flush any pending telemetry and wait for it to complete. |
| 712 | * |
| 713 | * In Node.js-compatible environments, telemetry is automatically flushed on process exit. |
| 714 | * However, in environments like Cloudflare Workers that don't support process exit events, |
| 715 | * you should call this method manually to ensure all telemetry is sent. |
| 716 | * |
| 717 | * @returns {Promise<void>} A promise that resolves when all pending telemetry has been sent. |
| 718 | * |
| 719 | * @example |
| 720 | * ```typescript |
| 721 | * // In a Cloudflare Worker, use ctx.waitUntil to ensure telemetry is flushed |
| 722 | * export default { |
| 723 | * async fetch(request: Request, env: Env, ctx: ExecutionContext) { |
| 724 | * const composio = new Composio({ apiKey: env.COMPOSIO_API_KEY }); |
| 725 | * |
| 726 | * // Do your work... |
| 727 | * const result = await composio.tools.execute(...); |
| 728 | * |
| 729 | * // Ensure telemetry flushes before worker terminates |
| 730 | * ctx.waitUntil(composio.flush()); |
| 731 | * |
| 732 | * return new Response(JSON.stringify(result)); |
| 733 | * } |
| 734 | * }; |
| 735 | * ``` |
| 736 | */ |
| 737 | async flush(): Promise<void> { |
| 738 | await telemetry.flush(); |
| 739 | } |
| 740 | } |