@devries-cameron20 / composio Mirror · read-only
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
md 487 lines 15.2 KB
Rendered Raw
1 # Connected Accounts API
2
3 The `ConnectedAccounts` class provides methods to manage user connections to external services (toolkits). Connected accounts store authentication tokens and other information needed to access these services.
4
5 ## Methods
6
7 ### list(query?)
8
9 Lists all connected accounts based on provided filter criteria.
10
11 ```typescript
12 // List all connected accounts
13 const allAccounts = await composio.connectedAccounts.list();
14
15 // List accounts for a specific user
16 const userAccounts = await composio.connectedAccounts.list({
17 userIds: ['user123'],
18 });
19
20 // List accounts for a specific toolkit
21 const githubAccounts = await composio.connectedAccounts.list({
22 toolkitSlugs: ['github'],
23 });
24 ```
25
26 **Parameters:**
27
28 - `query` (ConnectedAccountListParams): Optional query parameters for filtering connected accounts
29
30 **Returns:** Promise<ConnectedAccountListResponse> - A paginated list of connected accounts
31
32 **Throws:** ValidationError if the query fails validation against the expected schema
33
34
35 ### link(userId, authConfigId, options?)
36
37 Creates a Composio Connect Link for a user to connect their account to a given auth config. This method returns an external link which you can use for the user to connect their account through Composio's hosted authentication flow.
38
39 ```typescript
40 // Create a connection request and redirect the user to the redirect URL
41 const connectionRequest = await composio.connectedAccounts.link('user_123', 'auth_config_123');
42 const redirectUrl = connectionRequest.redirectUrl;
43 console.log(`Visit: ${redirectUrl} to authenticate your account`);
44
45 // Wait for the connection to be established
46 const connectedAccount = await connectionRequest.waitForConnection();
47 ```
48
49 ```typescript
50 // Create a connection request with callback URL
51 const connectionRequest = await composio.connectedAccounts.link('user_123', 'auth_config_123', {
52 callbackUrl: 'https://your-app.com/callback'
53 });
54 const redirectUrl = connectionRequest.redirectUrl;
55 console.log(`Visit: ${redirectUrl} to authenticate your account`);
56
57 // Wait for the connection to be established
58 const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);
59 ```
60
61 **Parameters:**
62
63 - `userId` (string): The external user ID to create the connected account for
64 - `authConfigId` (string): The auth config ID to create the connected account for
65 - `options` (CreateConnectedAccountLinkOptions): Optional configuration for the link
66 - `callbackUrl` (string): The URL to redirect the user to after connecting their account
67
68 **Returns:** Promise<ConnectionRequest> - Connection request object with redirect URL
69
70 **Throws:**
71 - `ValidationError`: If the options fail validation
72 - `ComposioFailedToCreateConnectedAccountLink`: If the link creation fails
73
74 ### initiate(userId, authConfigId, options?)
75
76 Creates a new connected account by accepting the parameters manually and returns a connection request. Users can then wait for the connection to be established using the `waitForConnection` method.
77
78 ```typescript
79 // For OAuth based auth configs (no additional parameters needed)
80 const oauthConnection = await composio.connectedAccounts.initiate('user_123', 'auth_config_123', {
81 callbackUrl: 'https://myapp.com/auth/callback',
82 });
83
84 // For OAuth configs requiring additional parameters (e.g., Zendesk, PostHog)
85 const zendeskConnection = await composio.connectedAccounts.initiate('user_123', 'zendesk_auth_config', {
86 config: AuthScheme.OAuth2({
87 subdomain: "yout_subdomain_here"
88 })
89 });
90
91 // For API Key based auth configs (requires additional parameters)
92 const apiKeyConnection = await composio.connectedAccounts.initiate('user_123', 'auth_config_456', {
93 config: AuthScheme.ApiKey({
94 api_key: 'your_api_key_here',
95 }),
96 });
97
98 // For Basic Auth based auth configs (requires username/password)
99 const basicAuthConnection = await composio.connectedAccounts.initiate(
100 'user_123',
101 'auth_config_789',
102 {
103 config: AuthScheme.Basic({
104 username: 'your_username',
105 password: 'your_password',
106 }),
107 }
108 );
109
110 // The redirectUrl is where the user should be redirected to authenticate (for OAuth flows)
111 console.log(oauthConnection.redirectUrl);
112
113 // wait for the user to connect the account
114 const connectedAccount = await oauthConnection.waitForConnection();
115 ```
116
117 **Parameters:**
118
119 - `userId` (string): User ID of the connected account
120 - `authConfigId` (string): Auth config ID of the connected account
121 - `options` (CreateConnectedAccountOptions): Options for creating a new connected account
122 - `config`: Connection configuration using AuthScheme helpers
123 - `callbackUrl`: URL to redirect after OAuth authentication
124
125 **Returns:** Promise<ConnectionRequest> - Connection request object
126
127
128 ### waitForConnection(connectedAccountId, timeout?)
129
130 Waits for a connection request to complete and become active.
131
132 ```typescript
133 // Wait for a connection to complete with default timeout
134 const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc');
135
136 // Wait with a custom timeout of 2 minutes
137 const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc', 120000);
138 ```
139
140 **Parameters:**
141
142 - `connectedAccountId` (string): The ID of the connected account to wait for
143 - `timeout` (number): Maximum time to wait in milliseconds (default: 60 seconds)
144
145 **Returns:** Promise<ConnectedAccountRetrieveResponse> - The finalized connected account data
146
147 **Throws:**
148
149 - `ComposioConnectedAccountNotFoundError`: If the connected account cannot be found
150 - `ConnectionRequestFailedError`: If the connection enters a failed, expired, or deleted state
151 - `ConnectionRequestTimeoutError`: If the connection does not complete within the timeout period
152
153 ### get(nanoid)
154
155 Retrieves a specific connected account by its ID.
156
157 ```typescript
158 // Get a connected account by ID
159 const account = await composio.connectedAccounts.get('conn_abc123');
160 console.log(account.status); // e.g., 'ACTIVE'
161 console.log(account.toolkit.slug); // e.g., 'github'
162 ```
163
164 **Parameters:**
165
166 - `nanoid` (string): The unique identifier of the connected account
167
168 **Returns:** Promise<ConnectedAccountRetrieveResponse> - The connected account details
169
170 **Throws:** Error if the connected account cannot be found or an API error occurs
171
172 ### delete(nanoid)
173
174 Deletes a connected account.
175
176 ```typescript
177 // Delete a connected account
178 await composio.connectedAccounts.delete('conn_abc123');
179 ```
180
181 **Parameters:**
182
183 - `nanoid` (string): The unique identifier of the connected account to delete
184
185 **Returns:** Promise<ConnectedAccountDeleteResponse> - The deletion response
186
187 **Throws:** Error if the account doesn't exist or cannot be deleted
188
189 ### refresh(nanoid)
190
191 Refreshes a connected account's authentication credentials.
192
193 ```typescript
194 // Refresh a connected account's credentials
195 const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');
196 ```
197
198 **Parameters:**
199
200 - `nanoid` (string): The unique identifier of the connected account to refresh
201
202 **Returns:** Promise<ConnectedAccountRefreshResponse> - The response containing the refreshed account details
203
204 **Throws:** Error if the account doesn't exist or credentials cannot be refreshed
205
206 ### updateStatus(nanoid, params)
207
208 Updates the status of a connected account.
209
210 ```typescript
211 // Update the status of a connected account
212 const updatedAccount = await composio.connectedAccounts.updateStatus('conn_abc123', {
213 enabled: true,
214 });
215 ```
216
217 **Parameters:**
218
219 - `nanoid` (string): The unique identifier of the connected account
220 - `params` (ConnectedAccountUpdateStatusParams): The parameters for updating the status
221
222 **Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details
223
224 ### enable(nanoid)
225
226 Enables a connected account.
227
228 ```typescript
229 // Enable a connected account
230 const enabledAccount = await composio.connectedAccounts.enable('conn_abc123');
231 ```
232
233 **Parameters:**
234
235 - `nanoid` (string): The unique identifier of the connected account
236
237 **Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details
238
239 ### disable(nanoid)
240
241 Disables a connected account.
242
243 ```typescript
244 // Disable a connected account
245 const disabledAccount = await composio.connectedAccounts.disable('conn_abc123');
246 ```
247
248 **Parameters:**
249
250 - `nanoid` (string): The unique identifier of the connected account
251
252 **Returns:** Promise<ConnectedAccountUpdateStatusResponse> - The updated account details
253
254 ## Types
255
256 ### ConnectedAccountListParams
257
258 ```typescript
259 interface ConnectedAccountListParams {
260 authConfigIds?: string[]; // Filter by auth config IDs
261 cursor?: string; // Pagination cursor
262 labels?: string[]; // Filter by labels
263 limit?: number; // Limit the number of results
264 orderBy?: string; // Order by field
265 statuses?: string[]; // Filter by statuses
266 toolkitSlugs?: string[]; // Filter by toolkit slugs
267 userIds?: string[]; // Filter by user IDs
268 }
269 ```
270
271 ### ConnectedAccountListResponse
272
273 ```typescript
274 interface ConnectedAccountListResponse {
275 items: ConnectedAccountRetrieveResponse[]; // List of connected accounts
276 nextCursor: string | null; // Pagination cursor
277 totalPages: number; // Total number of pages
278 }
279 ```
280
281 ### ConnectedAccountRetrieveResponse
282
283 ```typescript
284 interface ConnectedAccountRetrieveResponse {
285 id: string; // Connected account ID
286 status: string; // Status (e.g., 'ACTIVE', 'PENDING')
287 statusReason: string | null; // Reason for the status
288 userId: string; // User ID
289 toolkit: {
290 // Associated toolkit
291 id: string; // Toolkit ID
292 slug: string; // Toolkit slug
293 name: string; // Toolkit name
294 };
295 authConfig: {
296 // Associated auth config
297 id: string; // Auth config ID
298 authScheme: string; // Auth scheme (e.g., 'oauth2')
299 isComposioManaged: boolean; // Whether it's managed by Composio
300 isDisabled: boolean; // Whether it's disabled
301 };
302 isDisabled: boolean; // Whether the connected account is disabled
303 meta: Record<string, unknown>; // Additional metadata
304 createdAt: string; // Creation timestamp
305 updatedAt: string; // Last update timestamp
306 testRequestEndpoint: string | null; // Endpoint for testing the connection
307 }
308 ```
309
310 ### CreateConnectedAccountOptions
311
312 ```typescript
313 interface CreateConnectedAccountOptions {
314 config?: ConnectionData; // Connection configuration using AuthScheme helpers
315 callbackUrl?: string; // URL to redirect after authentication
316 }
317 ```
318
319 ### CreateConnectedAccountLinkOptions
320
321 ```typescript
322 interface CreateConnectedAccountLinkOptions {
323 callbackUrl?: string; // URL to redirect the user to after connecting their account
324 }
325 ```
326
327 ### ConnectedAccountUpdateStatusParams
328
329 ```typescript
330 interface ConnectedAccountUpdateStatusParams {
331 enabled: boolean; // Whether the account should be enabled
332 }
333 ```
334
335 ### Available Authentication Types
336
337 The SDK provides helper functions through the `AuthScheme` class for creating properly typed connection configurations. Here's a list of all available authentication schemes and their helper functions:
338
339 1. **OAuth2** - No additional parameters needed
340
341 ```typescript
342 await composio.connectedAccounts.initiate(userId, authConfigId);
343 ```
344
345 2. **OAuth1** - No additional parameters needed
346
347 ```typescript
348 await composio.connectedAccounts.initiate(userId, authConfigId);
349 ```
350
351 3. **API Key** - Requires API key parameter
352
353 ```typescript
354 await composio.connectedAccounts.initiate(userId, authConfigId, {
355 config: AuthScheme.ApiKey({
356 api_key: 'your_api_key',
357 }),
358 });
359 ```
360
361 4. **Basic Auth** - Requires username and password
362
363 ```typescript
364 await composio.connectedAccounts.initiate(userId, authConfigId, {
365 config: AuthScheme.Basic({
366 username: 'your_username',
367 password: 'your_password',
368 }),
369 });
370 ```
371
372 5. **Bearer Token** - Requires token
373
374 ```typescript
375 await composio.connectedAccounts.initiate(userId, authConfigId, {
376 config: AuthScheme.BearerToken({
377 token: 'your_bearer_token',
378 }),
379 });
380 ```
381
382 6. **Google Service Account** - Requires credentials JSON
383
384 ```typescript
385 await composio.connectedAccounts.initiate(userId, authConfigId, {
386 config: AuthScheme.GoogleServiceAccount({
387 credentials_json: 'your_credentials_json',
388 }),
389 });
390 ```
391
392 7. **Basic with JWT** - Requires username, password, and JWT
393
394 ```typescript
395 await composio.connectedAccounts.initiate(userId, authConfigId, {
396 config: AuthScheme.BasicWithJwt({
397 username: 'your_username',
398 password: 'your_password',
399 jwt: 'your_jwt_token',
400 }),
401 });
402 ```
403
404 8. **Bill.com Auth** - Requires session ID and dev key
405
406 ```typescript
407 await composio.connectedAccounts.initiate(userId, authConfigId, {
408 config: AuthScheme.BillcomAuth({
409 sessionId: 'your_session_id',
410 devKey: 'your_dev_key',
411 }),
412 });
413 ```
414
415 9. **Composio Link** - No additional parameters needed
416
417 ```typescript
418 await composio.connectedAccounts.initiate(userId, authConfigId, {
419 config: AuthScheme.ComposioLink(),
420 });
421 ```
422
423 10. **Cal.com Auth** - No additional parameters needed
424
425 ```typescript
426 await composio.connectedAccounts.initiate(userId, authConfigId, {
427 config: AuthScheme.CalcomAuth(),
428 });
429 ```
430
431 11. **Snowflake** - No additional parameters needed
432
433 ```typescript
434 await composio.connectedAccounts.initiate(userId, authConfigId, {
435 config: AuthScheme.Snowflake(),
436 });
437 ```
438
439 12. **No Auth** - No additional parameters needed
440 ```typescript
441 await composio.connectedAccounts.initiate(userId, authConfigId, {
442 config: AuthScheme.NoAuth(),
443 });
444 ```
445
446 Each helper function returns a properly typed `ConnectionData` object that ensures type safety and validation through Zod schemas. The connection status will be set to:
447
448 - `INITIALIZING` for OAuth2, OAuth1, and ComposioLink schemes
449 - `ACTIVE` for all other schemes
450
451 ## Multiple Connected Accounts
452
453 By default, Composio prevents users from having multiple connected accounts for the same auth configuration. This is to prevent potential conflicts and ensure consistent behavior. However, you can override this behavior if your use case requires multiple connections.
454
455 ### Default Behavior
456
457 When attempting to create a new connected account, if the user already has an active connection for that auth configuration, Composio will throw a `ComposioMultipleConnectedAccountsError`.
458
459 ```typescript
460 // This will throw if the user already has a connection
461 try {
462 await composio.connectedAccounts.initiate('user_123', 'auth_config_123');
463 } catch (error) {
464 if (error instanceof ComposioMultipleConnectedAccountsError) {
465 console.log('User already has a connected account for this auth config');
466 }
467 }
468 ```
469
470 ### Allowing Multiple Connections
471
472 If your application needs to support multiple connections for the same auth configuration (e.g., connecting to multiple GitHub accounts), you can enable this by passing the `allowMultiple` option:
473
474 ```typescript
475 // This will allow creating multiple connections
476 const connection = await composio.connectedAccounts.initiate('user_123', 'auth_config_123', {
477 allowMultiple: true,
478 });
479 ```
480
481 When `allowMultiple` is enabled:
482
483 - Multiple active connections are allowed for the same user and auth configuration
484 - A warning will be logged to help track this behavior
485 - You'll need to manage these multiple connections appropriately in your application logic
486
487 > **Note:** Be cautious when enabling multiple connections as it may require additional handling in your application to manage which connection to use for specific operations.