Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 04:45 UTC
| 1 | import ComposioClient, { APIError } from '@composio/client'; |
| 2 | import { |
| 3 | ToolkitListParams, |
| 4 | ToolKitListResponse, |
| 5 | ToolkitRetrieveResponse, |
| 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'; |
| 22 | import { AuthConfigs } from './AuthConfigs'; |
| 23 | import { ComposioAuthConfigNotFoundError } from '../errors/AuthConfigErrors'; |
| 24 | import { ConnectedAccounts } from './ConnectedAccounts'; |
| 25 | import { ConnectionRequest } from '../types/connectionRequest.types'; |
| 26 | 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'; |
| 39 | import { ComposioRequestOptions } from '../types/requestOptions.types'; |
| 40 | import { withCancellation } from '../utils/cancellation'; |
| 41 | import { ComposioRequestCancelledError } from '../errors/SDKErrors'; |
| 42 | /** |
| 43 | * Toolkits class |
| 44 | * |
| 45 | * Toolkits are a collection of tools that can be used to perform various tasks. |
| 46 | * This is similar/replacement of `apps` in the Composio API. |
| 47 | */ |
| 48 | export class Toolkits { |
| 49 | private client: ComposioClient; |
| 50 | |
| 51 | constructor(client: ComposioClient) { |
| 52 | this.client = client; |
| 53 | this.authorize = this.authorize.bind(this); |
| 54 | telemetry.instrument(this, 'Toolkits'); |
| 55 | } |
| 56 | /** |
| 57 | * Retrieves a list of toolkits based on the provided query parameters. |
| 58 | * |
| 59 | * This method fetches toolkits from the Composio API and transforms the response |
| 60 | * from snake_case to camelCase format for consistency with JavaScript/TypeScript conventions. |
| 61 | * |
| 62 | * @param {ToolkitListParams} query - The query parameters to filter toolkits |
| 63 | * @returns {Promise<ToolKitListResponse>} The transformed list of toolkits |
| 64 | * |
| 65 | * @private |
| 66 | */ |
| 67 | private async getToolkits( |
| 68 | query: ToolkitListParams, |
| 69 | requestOptions?: ComposioRequestOptions |
| 70 | ): Promise<ToolKitListResponse> { |
| 71 | try { |
| 72 | const parsedQuery = ToolkitsListParamsSchema.safeParse(query); |
| 73 | if (!parsedQuery.success) { |
| 74 | throw new ValidationError('Failed to parse toolkit list query', { |
| 75 | cause: parsedQuery.error, |
| 76 | }); |
| 77 | } |
| 78 | const listParams = { |
| 79 | category: parsedQuery.data.category, |
| 80 | managed_by: parsedQuery.data.managedBy, |
| 81 | sort_by: parsedQuery.data.sortBy, |
| 82 | cursor: parsedQuery.data.cursor, |
| 83 | limit: parsedQuery.data.limit, |
| 84 | }; |
| 85 | const result = await withCancellation( |
| 86 | () => this.client.toolkits.list(listParams, requestOptions), |
| 87 | requestOptions?.signal |
| 88 | ); |
| 89 | |
| 90 | return transformToolkitListResponse(result); |
| 91 | } catch (error) { |
| 92 | if (error instanceof ComposioRequestCancelledError) { |
| 93 | throw error; |
| 94 | } |
| 95 | throw new ComposioToolkitFetchError('Failed to fetch toolkits', { |
| 96 | cause: error, |
| 97 | }); |
| 98 | } |
| 99 | } |
| 100 | /** |
| 101 | * Retrieves a specific toolkit by its slug identifier. |
| 102 | * |
| 103 | * This method fetches a single toolkit from the Composio API and transforms |
| 104 | * the response to use camelCase property naming consistent with JavaScript/TypeScript conventions. |
| 105 | * |
| 106 | * @param {string} slug - The unique slug identifier of the toolkit to retrieve |
| 107 | * @returns {Promise<ToolkitRetrieveResponse>} The transformed toolkit object |
| 108 | * @throws {ValidationError} If the response cannot be properly parsed |
| 109 | * @throws {ComposioToolNotFoundError} If no toolkit with the given slug exists |
| 110 | * |
| 111 | * @private |
| 112 | */ |
| 113 | protected async getToolkitBySlug( |
| 114 | slug: string, |
| 115 | requestOptions?: ComposioRequestOptions |
| 116 | ): Promise<ToolkitRetrieveResponse> { |
| 117 | try { |
| 118 | const result = await withCancellation( |
| 119 | () => this.client.toolkits.retrieve(slug, undefined, requestOptions), |
| 120 | requestOptions?.signal |
| 121 | ); |
| 122 | return transformToolkitRetrieveResponse(result); |
| 123 | } catch (error) { |
| 124 | if (error instanceof ComposioRequestCancelledError) { |
| 125 | throw error; |
| 126 | } |
| 127 | if (error instanceof APIError && (error.status === 404 || error.status === 400)) { |
| 128 | throw new ComposioToolkitNotFoundError(`Toolkit with slug ${slug} not found`, { |
| 129 | meta: { |
| 130 | slug, |
| 131 | }, |
| 132 | cause: error, |
| 133 | }); |
| 134 | } |
| 135 | throw new ComposioToolkitFetchError(`Couldn't fetch Toolkit with slug: ${slug}`, { |
| 136 | meta: { |
| 137 | slug, |
| 138 | }, |
| 139 | cause: error, |
| 140 | }); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /** |
| 145 | * Retrieves a specific toolkit by its slug identifier. |
| 146 | * |
| 147 | * @param {string} slug - The unique slug identifier of the toolkit to retrieve |
| 148 | * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object with detailed information |
| 149 | * @throws {ComposioToolNotFoundError} If no toolkit with the given slug exists |
| 150 | * |
| 151 | * @example |
| 152 | * ```typescript |
| 153 | * // Get a specific toolkit |
| 154 | * const githubToolkit = await composio.toolkits.get('github'); |
| 155 | * console.log(githubToolkit.name); // GitHub |
| 156 | * console.log(githubToolkit.authConfigDetails); // Authentication configuration details |
| 157 | * ``` |
| 158 | */ |
| 159 | async get( |
| 160 | slug: string, |
| 161 | requestOptions?: ComposioRequestOptions |
| 162 | ): Promise<ToolkitRetrieveResponse>; |
| 163 | |
| 164 | /** |
| 165 | * Retrieves a list of toolkits based on the provided query parameters. |
| 166 | * |
| 167 | * @param {ToolkitListParams} query - The query parameters to filter toolkits |
| 168 | * @returns {Promise<ToolKitListResponse>} A paginated list of toolkits matching the query criteria |
| 169 | * |
| 170 | * @example |
| 171 | * ```typescript |
| 172 | * // Get all toolkits |
| 173 | * const allToolkits = await composio.toolkits.get({}); |
| 174 | * |
| 175 | * // Get toolkits by category |
| 176 | * const devToolkits = await composio.toolkits.get({ |
| 177 | * category: 'developer-tools' |
| 178 | * }); |
| 179 | * |
| 180 | * // Get local toolkits |
| 181 | * const localToolkits = await composio.toolkits.get({ |
| 182 | * isLocal: true |
| 183 | * }); |
| 184 | * ``` |
| 185 | */ |
| 186 | async get( |
| 187 | query?: ToolkitListParams, |
| 188 | requestOptions?: ComposioRequestOptions |
| 189 | ): Promise<ToolKitListResponse>; |
| 190 | |
| 191 | /** |
| 192 | * Implementation method that handles both overloads for retrieving toolkits. |
| 193 | * |
| 194 | * @param {string | ToolkitListParams} arg - Either a toolkit slug or query parameters |
| 195 | * @param {ComposioRequestOptions} [requestOptions] - Per-request cancellation/timeout options |
| 196 | * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit or list of toolkits |
| 197 | */ |
| 198 | async get( |
| 199 | arg?: string | ToolkitListParams, |
| 200 | requestOptions?: ComposioRequestOptions |
| 201 | ): Promise<ToolkitRetrieveResponse | ToolKitListResponse> { |
| 202 | if (typeof arg === 'string') { |
| 203 | return this.getToolkitBySlug(arg, requestOptions); |
| 204 | } |
| 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, |
| 376 | authConfigType: 'authConfigCreation' | 'connectedAccountInitiation', |
| 377 | requiredOnly: boolean |
| 378 | ): Promise<ToolkitAuthFieldsResponse> { |
| 379 | const toolkit = await this.getToolkitBySlug(toolkitSlug); |
| 380 | if (!toolkit.authConfigDetails) { |
| 381 | throw new ComposioAuthConfigNotFoundError('No auth config found for toolkit', { |
| 382 | meta: { |
| 383 | toolkitSlug, |
| 384 | }, |
| 385 | }); |
| 386 | } |
| 387 | |
| 388 | // if multiple auth configs are found, warn the user and select the first one |
| 389 | if (toolkit.authConfigDetails.length > 1 && !authScheme) { |
| 390 | logger.warn( |
| 391 | `Multiple auth configs found for ${toolkitSlug}, please specify the auth scheme to get details of specific auth scheme. Selecting the first scheme by default.`, |
| 392 | { |
| 393 | meta: { |
| 394 | toolkitSlug, |
| 395 | }, |
| 396 | } |
| 397 | ); |
| 398 | } |
| 399 | |
| 400 | // if authScheme is provided, find the auth config for the given auth scheme |
| 401 | // otherwise, use the first auth config |
| 402 | const authConfig = authScheme |
| 403 | ? toolkit.authConfigDetails.find(authConfig => authConfig.mode === authScheme) |
| 404 | : toolkit.authConfigDetails[0]; |
| 405 | |
| 406 | if (!authConfig) { |
| 407 | throw new ComposioAuthConfigNotFoundError( |
| 408 | `Auth schema ${authScheme} not found for toolkit ${toolkitSlug} with auth scheme ${authScheme}`, |
| 409 | { |
| 410 | meta: { |
| 411 | toolkitSlug, |
| 412 | authScheme, |
| 413 | }, |
| 414 | } |
| 415 | ); |
| 416 | } |
| 417 | |
| 418 | const requiredFields = authConfig.fields[authConfigType].required.map(field => ({ |
| 419 | ...field, |
| 420 | required: true, |
| 421 | })); |
| 422 | if (requiredOnly) { |
| 423 | return requiredFields; |
| 424 | } |
| 425 | |
| 426 | const optionalFields = authConfig.fields[authConfigType].optional.map(field => ({ |
| 427 | ...field, |
| 428 | required: false, |
| 429 | })); |
| 430 | |
| 431 | return [...requiredFields, ...optionalFields]; |
| 432 | } |
| 433 | |
| 434 | /** |
| 435 | * Retrieves the fields required for creating an auth config for a toolkit. |
| 436 | * @param toolkitSlug - The slug of the toolkit to retrieve the fields for |
| 437 | * @param authScheme - The auth scheme to retrieve the fields for |
| 438 | * @param options.requiredOnly - Whether to only return the required fields |
| 439 | * @returns {Promise<ToolkitAuthFieldsResponse>} The fields required for creating an auth config |
| 440 | */ |
| 441 | async getAuthConfigCreationFields( |
| 442 | toolkitSlug: string, |
| 443 | authScheme: AuthSchemeType, |
| 444 | { requiredOnly = false }: { requiredOnly?: boolean } = {} |
| 445 | ): Promise<ToolkitAuthFieldsResponse> { |
| 446 | return this.getAuthConfigFields( |
| 447 | toolkitSlug, |
| 448 | authScheme ?? null, |
| 449 | 'authConfigCreation', |
| 450 | requiredOnly |
| 451 | ); |
| 452 | } |
| 453 | |
| 454 | /** |
| 455 | * Retrieves the fields required for initiating a connected account for a toolkit. |
| 456 | * @param toolkitSlug - The slug of the toolkit to retrieve the fields for |
| 457 | * @param authScheme - The auth scheme to retrieve the fields for |
| 458 | * @param options.requiredOnly - Whether to only return the required fields |
| 459 | * @returns {Promise<ToolkitAuthFieldsResponse>} The fields required for initiating a connected account |
| 460 | */ |
| 461 | async getConnectedAccountInitiationFields( |
| 462 | toolkitSlug: string, |
| 463 | authScheme: AuthSchemeType, |
| 464 | { requiredOnly = false }: { requiredOnly?: boolean } = {} |
| 465 | ): Promise<ToolkitAuthFieldsResponse> { |
| 466 | return this.getAuthConfigFields( |
| 467 | toolkitSlug, |
| 468 | authScheme ?? null, |
| 469 | 'connectedAccountInitiation', |
| 470 | requiredOnly |
| 471 | ); |
| 472 | } |
| 473 | |
| 474 | /** |
| 475 | * Retrieves all toolkit categories available in the Composio SDK. |
| 476 | * |
| 477 | * This method fetches the complete list of categories from the Composio API |
| 478 | * and transforms the response to use camelCase property naming. |
| 479 | * |
| 480 | * @returns {Promise<ToolkitRetrieveCategoriesResponse>} The list of toolkit categories |
| 481 | * |
| 482 | * @example |
| 483 | * ```typescript |
| 484 | * // Get all toolkit categories |
| 485 | * const categories = await composio.toolkits.listCategories(); |
| 486 | * console.log(categories.items); // Array of category objects |
| 487 | * ``` |
| 488 | */ |
| 489 | async listCategories( |
| 490 | requestOptions?: ComposioRequestOptions |
| 491 | ): Promise<ToolkitRetrieveCategoriesResponse> { |
| 492 | const result = await withCancellation( |
| 493 | () => this.client.toolkits.retrieveCategories(requestOptions), |
| 494 | requestOptions?.signal |
| 495 | ); |
| 496 | return transformToolkitRetrieveCategoriesResponse(result); |
| 497 | } |
| 498 | |
| 499 | /** |
| 500 | * Authorizes a user to use a toolkit. |
| 501 | * This method will create an auth config if one doesn't exist and initiate a connection request. |
| 502 | * @param {string} userId - The user id of the user to authorize |
| 503 | * @param {string} toolkitSlug - The slug of the toolkit to authorize |
| 504 | * @returns {Promise<ConnectionRequest>} The connection request object |
| 505 | * |
| 506 | * @example |
| 507 | * ```typescript |
| 508 | * const connectionRequest = await composio.toolkits.authorize(userId, 'github'); |
| 509 | * ``` |
| 510 | * |
| 511 | */ |
| 512 | async authorize( |
| 513 | userId: string, |
| 514 | toolkitSlug: string, |
| 515 | authConfigId?: string, |
| 516 | requestOptions?: ComposioRequestOptions |
| 517 | ): Promise<ConnectionRequest> { |
| 518 | // High-level helper that fans out to 3-4 network calls (toolkit retrieve, |
| 519 | // optional authConfigs list, optional authConfigs create, then |
| 520 | // connectedAccounts.initiate). Forward the caller's signal to every |
| 521 | // underlying call so the whole composite is cancellable as a single unit. |
| 522 | const toolkit = await this.getToolkitBySlug(toolkitSlug, requestOptions); |
| 523 | const composioAuthConfig = new AuthConfigs(this.client); |
| 524 | let authConfigIdToUse: string | undefined = authConfigId; |
| 525 | |
| 526 | if (!authConfigIdToUse) { |
| 527 | const authConfig = await composioAuthConfig.list( |
| 528 | { |
| 529 | toolkit: toolkitSlug, |
| 530 | }, |
| 531 | requestOptions |
| 532 | ); |
| 533 | // pick the first auth config if none is passed |
| 534 | authConfigIdToUse = authConfig.items[0]?.id; |
| 535 | } |
| 536 | |
| 537 | // if no auth config is found, create one for the toolkit |
| 538 | if (!authConfigIdToUse) { |
| 539 | // create authConfig using composioManagedAuthSchemes |
| 540 | if (toolkit.authConfigDetails && toolkit.authConfigDetails.length > 0) { |
| 541 | try { |
| 542 | const authConfig = await composioAuthConfig.create( |
| 543 | toolkitSlug, |
| 544 | { |
| 545 | type: 'use_composio_managed_auth', |
| 546 | name: `${toolkit.name} Auth Config`, |
| 547 | }, |
| 548 | requestOptions |
| 549 | ); |
| 550 | authConfigIdToUse = authConfig.id; |
| 551 | } catch (error) { |
| 552 | if (error instanceof ComposioClient.APIError && error.status === 400) { |
| 553 | throw new ComposioAuthConfigNotFoundError( |
| 554 | `No Default auth config found for toolkit ${toolkitSlug}`, |
| 555 | { |
| 556 | meta: { |
| 557 | toolkitSlug, |
| 558 | }, |
| 559 | cause: error, |
| 560 | possibleFixes: [ |
| 561 | `Please Create an auth config for the toolkit ${toolkitSlug} via the dashboard`, |
| 562 | ], |
| 563 | } |
| 564 | ); |
| 565 | } |
| 566 | throw error; |
| 567 | } |
| 568 | } else { |
| 569 | throw new ComposioAuthConfigNotFoundError( |
| 570 | `No auth configs found for toolkit ${toolkitSlug}`, |
| 571 | { |
| 572 | meta: { |
| 573 | toolkitSlug, |
| 574 | }, |
| 575 | } |
| 576 | ); |
| 577 | } |
| 578 | } |
| 579 | // create the auth config |
| 580 | const composioConnectedAccount = new ConnectedAccounts(this.client); |
| 581 | return await composioConnectedAccount.initiate( |
| 582 | userId, |
| 583 | authConfigIdToUse, |
| 584 | { |
| 585 | // in this magic function we allow multiple connected accounts per user for an auth config |
| 586 | allowMultiple: true, |
| 587 | }, |
| 588 | requestOptions |
| 589 | ); |
| 590 | } |
| 591 | } |