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 22, 23:15 UTC
Remove core concepts page
haxzie committed
Jun 26, 2025 at 11:05 UTC
dce9036f3acccafac970f0800fd17e5f7b214694
10 files changed
+6
-4272
fern/docs.yml
+6
-27
@@ -101,30 +101,12 @@ navigation:
101
- page: Quickstart
102
path: pages/dist/get-started/quickstart.mdx
103
slug: quickstart
104
- - section: Core Concepts
105
- skip-slug: true
106
- contents:
107
- - page: Overview
108
- path: pages/dist/core-concepts/overview.mdx
109
- slug: core-concepts
110
- - page: User IDs
111
- path: pages/dist/core-concepts/user-ids.mdx
112
- slug: user-ids
113
- - page: Tools and Toolkits
114
- path: pages/dist/core-concepts/tools-and-toolkits.mdx
115
- slug: tools-and-toolkits
116
- - page: Providers
117
- path: pages/dist/core-concepts/providers.mdx
118
- slug: providers
119
- - page: Connected Accounts
120
- path: pages/dist/core-concepts/connected-accounts.mdx
121
- slug: connected-accounts
122
- - page: Auth Configs
123
- path: pages/dist/core-concepts/auth-configs.mdx
124
- slug: auth-configs
125
- - page: Triggers
126
- path: pages/dist/core-concepts/triggers.mdx
127
- slug: triggers
104
+ - page: IDE and Agent Setup
105
+ path: pages/dist/get-started/dev-setup.mdx
106
+ slug: ide-and-agent-setup
107
+ - page: Providers
108
+ path: pages/dist/get-started/providers.mdx
109
+ slug: providers
110
- section: Tools
111
icon: tools
112
skip-slug: true
@@ -196,9 +178,6 @@ navigation:
178
- page: Migration Guide
179
path: pages/dist/migration-guide.mdx
180
slug: migration
199
- - page: IDE and Agent Setup
200
- path: pages/dist/get-started/dev-setup.mdx
201
- slug: ide-and-agent-setup
181
- tab: examples
182
layout:
183
- section: Getting Started
fern/pages/src/core-concepts/auth-configs.mdx
deleted
-694
@@ -1,694 +0,0 @@
1
----
2
-title: Auth Configs
3
-subtitle: Understanding the auth configs in Composio
4
-image: 'https://og.composio.dev/api/og?title=Auth%20Configs' # image for socials
5
-keywords: ''
6
-hide-nav-links: true
7
----
8
-Auth Configs define how authentication works for each toolkit. They specify the authentication method, required credentials, and configuration needed for users to connect their accounts.
9
-
10
-## What Are Auth Configs?
11
-
12
-An Auth Config is a template that defines:
13
-- **Authentication Method**: OAuth2, API Key, Basic Auth, etc.
14
-- **Required Fields**: What credentials users need to provide
15
-- **Service Configuration**: OAuth app settings, API endpoints, scopes
16
-
17
-<CodeGroup>
18
-
19
-```python
20
-# Create an auth config for GitHub
21
-auth_config = await composio.auth_configs.create('github', {
22
- 'type': 'use_composio_managed_auth',
23
- 'name': 'GitHub Integration'
24
-})
25
-```
26
-```typescript
27
-// Create an auth config for GitHub
28
-const authConfig = await composio.authConfigs.create('github', {
29
- type: 'use_composio_managed_auth',
30
- name: 'GitHub Integration'
31
-});
32
-```
33
-
34
-</CodeGroup>
35
-
36
-## Auth Config Types
37
-
38
-### Composio Managed Auth
39
-Composio handles OAuth applications and credentials for you:
40
-
41
-<CodeGroup>
42
-
43
-
44
-```python
45
-auth_config = await composio.auth_configs.create('github', {
46
- 'type': 'use_composio_managed_auth',
47
- 'name': 'GitHub - Composio Managed'
48
-})
49
-```
50
-```typescript
51
-const authConfig = await composio.authConfigs.create('github', {
52
- type: 'use_composio_managed_auth',
53
- name: 'GitHub - Composio Managed'
54
-});
55
-```
56
-</CodeGroup>
57
-
58
-**Benefits:**
59
-- No OAuth app setup required
60
-- Composio handles token management
61
-- Quick setup for development and testing
62
-- Built-in security best practices
63
-
64
-### User Credentials
65
-Users provide their own API keys or credentials:
66
-
67
-<CodeGroup>
68
-
69
-
70
-```python
71
-auth_config = await composio.auth_configs.create('openai', {
72
- 'type': 'user_credentials',
73
- 'name': 'OpenAI API Key',
74
- 'fields': {
75
- 'api_key': {
76
- 'type': 'string',
77
- 'description': 'Your OpenAI API key',
78
- 'required': True
79
- }
80
- }
81
-})
82
-```
83
-```typescript
84
-const authConfig = await composio.authConfigs.create('openai', {
85
- type: 'user_credentials',
86
- name: 'OpenAI API Key',
87
- fields: {
88
- api_key: {
89
- type: 'string',
90
- description: 'Your OpenAI API key',
91
- required: true
92
- }
93
- }
94
-});
95
-```
96
-</CodeGroup>
97
-
98
-### Custom Auth
99
-Define custom authentication flows:
100
-
101
-<CodeGroup>
102
-```python Python
103
-auth_config = await composio.auth_configs.create('custom_service', {
104
- 'type': 'custom_auth',
105
- 'name': 'Custom Service Auth',
106
- 'fields': {
107
- 'client_id': {
108
- 'type': 'string',
109
- 'description': 'Your OAuth client ID',
110
- 'required': True
111
- },
112
- 'client_secret': {
113
- 'type': 'string',
114
- 'description': 'Your OAuth client secret',
115
- 'required': True,
116
- 'sensitive': True
117
- },
118
- 'redirect_uri': {
119
- 'type': 'string',
120
- 'description': 'OAuth redirect URI',
121
- 'default': 'https://backend.composio.dev/api/v1/auth-apps/add'
122
- }
123
- }
124
-})
125
-```
126
-
127
-```typescript TypeScript
128
-const authConfig = await composio.authConfigs.create('custom_service', {
129
- type: 'custom_auth',
130
- name: 'Custom Service Auth',
131
- fields: {
132
- client_id: {
133
- type: 'string',
134
- description: 'Your OAuth client ID',
135
- required: true
136
- },
137
- client_secret: {
138
- type: 'string',
139
- description: 'Your OAuth client secret',
140
- required: true,
141
- sensitive: true
142
- },
143
- redirect_uri: {
144
- type: 'string',
145
- description: 'OAuth redirect URI',
146
- default: 'https://backend.composio.dev/api/v1/auth-apps/add'
147
- }
148
- }
149
-});
150
-```
151
-</CodeGroup>
152
-
153
-### No Auth
154
-For public APIs that don't require authentication:
155
-
156
-<CodeGroup>
157
-```python Python
158
-auth_config = await composio.auth_configs.create('hackernews', {
159
- 'type': 'no_auth',
160
- 'name': 'HackerNews Public API'
161
-})
162
-```
163
-
164
-```typescript TypeScript
165
-const authConfig = await composio.authConfigs.create('hackernews', {
166
- type: 'no_auth',
167
- name: 'HackerNews Public API'
168
-});
169
-```
170
-</CodeGroup>
171
-
172
-## Authentication Schemes
173
-
174
-Auth configs support different authentication schemes:
175
-
176
-### OAuth2
177
-Most modern services use OAuth2:
178
-
179
-<CodeGroup>
180
-
181
-```python
182
-# Get required fields for OAuth2 setup
183
-fields = await composio.toolkits.get_auth_config_creation_fields('github', 'OAUTH2')
184
-
185
-# Create OAuth2 auth config
186
-auth_config = await composio.auth_configs.create('github', {
187
- 'type': 'custom_auth',
188
- 'name': 'My GitHub App',
189
- 'fields': {
190
- 'client_id': 'your_github_client_id',
191
- 'client_secret': 'your_github_client_secret',
192
- 'scopes': 'repo,user:email'
193
- }
194
-})
195
-```
196
-```typescript
197
-// Get required fields for OAuth2 setup
198
-const fields = await composio.toolkits.getAuthConfigCreationFields('github', 'OAUTH2');
199
-
200
-// Create OAuth2 auth config
201
-const authConfig = await composio.authConfigs.create('github', {
202
- type: 'custom_auth',
203
- name: 'My GitHub App',
204
- fields: {
205
- client_id: 'your_github_client_id',
206
- client_secret: 'your_github_client_secret',
207
- scopes: 'repo,user:email'
208
- }
209
-});
210
-```
211
-
212
-</CodeGroup>
213
-
214
-### API Key
215
-Services that use API keys for authentication:
216
-
217
-<CodeGroup>
218
-
219
-```python
220
-auth_config = await composio.auth_configs.create('openai', {
221
- 'type': 'user_credentials',
222
- 'name': 'OpenAI API',
223
- 'fields': {
224
- 'api_key': 'user_will_provide_this'
225
- }
226
-})
227
-```
228
-```typescript
229
-const authConfig = await composio.authConfigs.create('openai', {
230
- type: 'user_credentials',
231
- name: 'OpenAI API',
232
- fields: {
233
- api_key: 'user_will_provide_this'
234
- }
235
-});
236
-```
237
-
238
-</CodeGroup>
239
-
240
-### Basic Auth
241
-Username and password authentication:
242
-
243
-<CodeGroup>
244
-
245
-```python
246
-auth_config = await composio.auth_configs.create('basic_service', {
247
- 'type': 'user_credentials',
248
- 'name': 'Basic Auth Service',
249
- 'fields': {
250
- 'username': 'user_username',
251
- 'password': 'user_password'
252
- }
253
-})
254
-```
255
-```typescript
256
-const authConfig = await composio.authConfigs.create('basic_service', {
257
- type: 'user_credentials',
258
- name: 'Basic Auth Service',
259
- fields: {
260
- username: 'user_username',
261
- password: 'user_password'
262
- }
263
-});
264
-```
265
-
266
-</CodeGroup>
267
-
268
-## Working with Auth Configs
269
-
270
-### List Auth Configs
271
-<CodeGroup>
272
-
273
-
274
-```python
275
-# Get all auth configs
276
-auth_configs = await composio.auth_configs.list()
277
-
278
-# Filter by toolkit
279
-github_configs = await composio.auth_configs.list(
280
- toolkit='github'
281
-)
282
-```
283
-```typescript
284
-// Get all auth configs
285
-const authConfigs = await composio.authConfigs.list();
286
-
287
-// Filter by toolkit
288
-const githubConfigs = await composio.authConfigs.list({
289
- toolkit: 'github'
290
-});
291
-```
292
-</CodeGroup>
293
-
294
-### Get Specific Auth Config
295
-<CodeGroup>
296
-
297
-```python
298
-auth_config = await composio.auth_configs.get('auth_config_123')
299
-
300
-print('Name:', auth_config.name)
301
-print('Type:', auth_config.type)
302
-print('Toolkit:', auth_config.toolkit.slug)
303
-print('Auth Scheme:', auth_config.auth_scheme)
304
-```
305
-```typescript
306
-const authConfig = await composio.authConfigs.get('auth_config_123');
307
-
308
-console.log('Name:', authConfig.name);
309
-console.log('Type:', authConfig.type);
310
-console.log('Toolkit:', authConfig.toolkit.slug);
311
-console.log('Auth Scheme:', authConfig.authScheme);
312
-```
313
-
314
-</CodeGroup>
315
-
316
-### Update Auth Config
317
-<CodeGroup>
318
-
319
-```python
320
-updated_config = await composio.auth_configs.update('auth_config_123', {
321
- 'name': 'Updated GitHub Integration',
322
- 'fields': {
323
- 'client_id': 'new_client_id',
324
- 'client_secret': 'new_client_secret'
325
- }
326
-})
327
-```
328
-```typescript
329
-const updatedConfig = await composio.authConfigs.update('auth_config_123', {
330
- name: 'Updated GitHub Integration',
331
- fields: {
332
- client_id: 'new_client_id',
333
- client_secret: 'new_client_secret'
334
- }
335
-});
336
-```
337
-
338
-</CodeGroup>
339
-
340
-### Delete Auth Config
341
-<CodeGroup>
342
-
343
-```python
344
-await composio.auth_configs.delete('auth_config_123')
345
-```
346
-```typescript
347
-await composio.authConfigs.delete('auth_config_123');
348
-```
349
-
350
-</CodeGroup>
351
-
352
-## Configuration Requirements
353
-
354
-### Get Required Fields
355
-Before creating auth configs, check what fields are required:
356
-
357
-<CodeGroup>
358
-
359
-```python
360
-# Get fields needed for creating an auth config
361
-creation_fields = await composio.toolkits.get_auth_config_creation_fields(
362
- 'github',
363
- 'OAUTH2'
364
-)
365
-
366
-print('Required fields:', creation_fields)
367
-# Output:
368
-# [
369
-# {
370
-# 'name': 'client_id',
371
-# 'display_name': 'Client ID',
372
-# 'type': 'string',
373
-# 'required': True
374
-# },
375
-# {
376
-# 'name': 'client_secret',
377
-# 'display_name': 'Client Secret',
378
-# 'type': 'string',
379
-# 'required': True
380
-# }
381
-# ]
382
-```
383
-```typescript
384
-// Get fields needed for creating an auth config
385
-const creationFields = await composio.toolkits.getAuthConfigCreationFields(
386
- 'github',
387
- 'OAUTH2'
388
-);
389
-
390
-console.log('Required fields:', creationFields);
391
-// Output:
392
-// [
393
-// {
394
-// name: 'client_id',
395
-// displayName: 'Client ID',
396
-// type: 'string',
397
-// required: true
398
-// },
399
-// {
400
-// name: 'client_secret',
401
-// displayName: 'Client Secret',
402
-// type: 'string',
403
-// required: true
404
-// }
405
-// ]
406
-```
407
-
408
-</CodeGroup>
409
-
410
-### Get Connection Fields
411
-Check what users need to provide when connecting:
412
-
413
-<CodeGroup>
414
-
415
-```python
416
-# Get fields needed for user connection
417
-connection_fields = await composio.toolkits.get_connected_account_initiation_fields(
418
- 'shopify',
419
- 'OAUTH2'
420
-)
421
-
422
-print('User must provide:', connection_fields)
423
-# Output:
424
-# [
425
-# {
426
-# 'name': 'shop',
427
-# 'display_name': 'Store Subdomain',
428
-# 'type': 'string',
429
-# 'required': True
430
-# }
431
-# ]
432
-```
433
-```typescript
434
-// Get fields needed for user connection
435
-const connectionFields = await composio.toolkits.getConnectedAccountInitiationFields(
436
- 'shopify',
437
- 'OAUTH2'
438
-);
439
-
440
-console.log('User must provide:', connectionFields);
441
-// Output:
442
-// [
443
-// {
444
-// name: 'shop',
445
-// displayName: 'Store Subdomain',
446
-// type: 'string',
447
-// required: true
448
-// }
449
-// ]
450
-```
451
-
452
-</CodeGroup>
453
-
454
-### Missing Fields
455
-<CodeGroup>
456
-
457
-```python
458
-# Check what fields are required
459
-fields = await composio.toolkits.get_auth_config_creation_fields('toolkit', 'OAUTH2')
460
-print('Required fields:', [f for f in fields if f.required])
461
-```
462
-```typescript
463
-// Check what fields are required
464
-const fields = await composio.toolkits.getAuthConfigCreationFields('toolkit', 'OAUTH2');
465
-console.log('Required fields:', fields.filter(f => f.required));
466
-```
467
-
468
-</CodeGroup>
469
-
470
-## OAuth App Setup
471
-
472
-### GitHub Example
473
-<CodeGroup>
474
-
475
-```python
476
-# 1. Create OAuth app in GitHub
477
-# 2. Get client ID and secret
478
-# 3. Create auth config in Composio
479
-
480
-github_auth = await composio.auth_configs.create('github', {
481
- 'type': 'custom_auth',
482
- 'name': 'My GitHub App',
483
- 'fields': {
484
- 'client_id': 'your_github_client_id',
485
- 'client_secret': 'your_github_client_secret',
486
- 'scopes': 'repo,user:email'
487
- }
488
-})
489
-```
490
-```typescript
491
-// 1. Create OAuth app in GitHub
492
-// 2. Get client ID and secret
493
-// 3. Create auth config in Composio
494
-
495
-const githubAuth = await composio.authConfigs.create('github', {
496
- type: 'custom_auth',
497
- name: 'My GitHub App',
498
- fields: {
499
- client_id: 'your_github_client_id',
500
- client_secret: 'your_github_client_secret',
501
- scopes: 'repo,user:email'
502
- }
503
-});
504
-```
505
-
506
-</CodeGroup>
507
-
508
-### Google Example
509
-
510
-
511
-<CodeGroup>
512
-
513
-```python
514
-google_auth = await composio.auth_configs.create('gmail', {
515
- 'type': 'custom_auth',
516
- 'name': 'My Google App',
517
- 'fields': {
518
- 'client_id': os.environ.get('GOOGLE_CLIENT_ID'),
519
- 'client_secret': os.environ.get('GOOGLE_CLIENT_SECRET'),
520
- 'oauth_redirect_uri': 'https://backend.composio.dev/api/v1/auth-apps/add',
521
- 'scopes': 'https://www.googleapis.com/auth/gmail.modify'
522
- }
523
-})
524
-```
525
-```typescript
526
-const googleAuth = await composio.authConfigs.create('gmail', {
527
- type: 'custom_auth',
528
- name: 'My Google App',
529
- fields: {
530
- client_id: process.env.GOOGLE_CLIENT_ID,
531
- client_secret: process.env.GOOGLE_CLIENT_SECRET,
532
- oauth_redirect_uri: 'https://backend.composio.dev/api/v1/auth-apps/add',
533
- scopes: 'https://www.googleapis.com/auth/gmail.modify'
534
- }
535
-});
536
-```
537
-
538
-</CodeGroup>
539
-
540
-## Using Auth Configs
541
-
542
-### With Connected Accounts
543
-
544
-<CodeGroup>
545
-
546
-
547
-```python
548
-# Create connected account using specific auth config
549
-connection = await composio.connected_accounts.initiate(
550
- 'user_123',
551
- 'auth_config_456', # Specific auth config ID
552
- config=AuthScheme.api_key(
553
- api_key='user_provided_key'
554
- )
555
-)
556
-```
557
-```typescript
558
-// Create connected account using specific auth config
559
-const connection = await composio.connectedAccounts.initiate(
560
- 'user_123',
561
- 'auth_config_456', // Specific auth config ID
562
- {
563
- config: AuthScheme.ApiKey({
564
- api_key: 'user_provided_key'
565
- })
566
- }
567
-);
568
-```
569
-</CodeGroup>
570
-
571
-### Automatic Selection
572
-
573
-<CodeGroup>
574
-
575
-```python
576
-# Composio automatically selects appropriate auth config
577
-connection = await composio.toolkits.authorize('user_123', 'github')
578
-```
579
-```typescript
580
-// Composio automatically selects appropriate auth config
581
-const connection = await composio.toolkits.authorize('user_123', 'github');
582
-```
583
-</CodeGroup>
584
-
585
-## Best Practices
586
-
587
-### Development vs Production
588
-<CodeGroup>
589
-
590
-```python
591
-# Development - use Composio managed auth
592
-dev_config = await composio.auth_configs.create('github', {
593
- 'type': 'use_composio_managed_auth',
594
- 'name': 'GitHub Dev'
595
-})
596
-
597
-# Production - use your own OAuth app
598
-prod_config = await composio.auth_configs.create('github', {
599
- 'type': 'custom_auth',
600
- 'name': 'GitHub Production',
601
- 'fields': {
602
- 'client_id': os.environ.get('GITHUB_CLIENT_ID'),
603
- 'client_secret': os.environ.get('GITHUB_CLIENT_SECRET')
604
- }
605
-})
606
-```
607
-```typescript
608
-// Development - use Composio managed auth
609
-const devConfig = await composio.authConfigs.create('github', {
610
- type: 'use_composio_managed_auth',
611
- name: 'GitHub Dev'
612
-});
613
-
614
-// Production - use your own OAuth app
615
-const prodConfig = await composio.authConfigs.create('github', {
616
- type: 'custom_auth',
617
- name: 'GitHub Production',
618
- fields: {
619
- client_id: process.env.GITHUB_CLIENT_ID,
620
- client_secret: process.env.GITHUB_CLIENT_SECRET
621
- }
622
-});
623
-```
624
-
625
-</CodeGroup>
626
-
627
-### Secure Credential Management
628
-<CodeGroup>
629
-
630
-
631
-```python
632
-# Use environment variables for sensitive data
633
-auth_config = await composio.auth_configs.create('service', {
634
- 'type': 'custom_auth',
635
- 'name': 'Service Auth',
636
- 'fields': {
637
- 'client_id': os.environ.get('SERVICE_CLIENT_ID'),
638
- 'client_secret': os.environ.get('SERVICE_CLIENT_SECRET'),
639
- # Never hardcode secrets in your code
640
- }
641
-})
642
-```
643
-```typescript
644
-// Use environment variables for sensitive data
645
-const authConfig = await composio.authConfigs.create('service', {
646
- type: 'custom_auth',
647
- name: 'Service Auth',
648
- fields: {
649
- client_id: process.env.SERVICE_CLIENT_ID,
650
- client_secret: process.env.SERVICE_CLIENT_SECRET,
651
- // Never hardcode secrets in your code
652
- }
653
-});
654
-```
655
-</CodeGroup>
656
-
657
-## Troubleshooting
658
-
659
-### OAuth Redirect Issues
660
-- Ensure redirect URI matches exactly
661
-- Check if the OAuth app is configured correctly
662
-- Verify the redirect URI is accessible
663
-
664
-### Missing Fields
665
-```javascript
666
-// Check what fields are required
667
-const fields = await composio.toolkits.getAuthConfigCreationFields('toolkit', 'OAUTH2');
668
-console.log('Required fields:', fields.filter(f => f.required));
669
-```
670
-
671
-### Connection Failures
672
-- Verify client ID and secret are correct
673
-- Check OAuth app permissions and scopes
674
-- Ensure the auth config is not disabled
675
-
676
-## Security Considerations
677
-
678
-### Credential Protection
679
-- Never commit secrets to version control
680
-- Use environment variables or secure secret management
681
-- Rotate credentials regularly
682
-
683
-### Scope Management
684
-- Request only necessary permissions
685
-- Use least privilege principle
686
-- Document required scopes clearly
687
-
688
-### Access Control
689
-- Limit who can create/modify auth configs
690
-- Use different configs for different environments
691
-- Monitor auth config usage
692
-
693
-
694
-Auth configs are the foundation of secure authentication in Composio. Understanding how to create and manage them effectively ensures your users can safely connect their accounts to your application.
\ No newline at end of file
fern/pages/src/core-concepts/connected-accounts.mdx
deleted
-593
@@ -1,593 +0,0 @@
1
----
2
-title: Connected Accounts
3
-subtitle: Understanding the connected accounts in Composio
4
-image: 'https://og.composio.dev/api/og?title=Connected%20Accounts' # image for socials
5
-keywords: ''
6
-hide-nav-links: true
7
----
8
-Connected Accounts represent a user's authorized connection to an external service. They store authentication tokens and credentials needed to execute tools on behalf of the user.
9
-
10
-## What Are Connected Accounts?
11
-
12
-A Connected Account is created when a user authorizes your application to access their external service account (like GitHub, Gmail, or Slack). It acts as a secure bridge between your application and the external service.
13
-
14
-<CodeGroup>
15
-```python
16
-# A connected account enables tool execution
17
-result = await composio.tools.execute('GITHUB_GET_REPO',
18
- user_id='user_123',
19
- connected_account_id='ca_abc123', # References the connected account
20
- arguments={'owner': 'composio', 'repo': 'sdk'}
21
-)
22
-```
23
-```typescript
24
-// A connected account enables tool execution
25
-const result = await composio.tools.execute('GITHUB_GET_REPO', {
26
- userId: 'user_123',
27
- connectedAccountId: 'ca_abc123', // References the connected account
28
- arguments: { owner: 'composio', repo: 'sdk' }
29
-});
30
-```
31
-
32
-</CodeGroup>
33
-
34
-## The Connection Flow
35
-
36
-### 1. Initiate Connection
37
-Start the authorization process for a user and toolkit:
38
-
39
-<CodeGroup>
40
-```python
41
-connection_request = await composio.toolkits.authorize(
42
- 'user_123', # Your user's ID
43
- 'github' # Toolkit to connect
44
-)
45
-
46
-print('Redirect user to:', connection_request.redirect_url)
47
-```
48
-```typescript
49
-const connectionRequest = await composio.toolkits.authorize(
50
- 'user_123', // Your user's ID
51
- 'github' // Toolkit to connect
52
-);
53
-
54
-console.log('Redirect user to:', connectionRequest.redirectUrl);
55
-```
56
-
57
-</CodeGroup>
58
-
59
-If your want to use a specific auth config, you can do so by passing the auth config ID to the `initiate` method:
60
-
61
-<CodeGroup>
62
-```python Python
63
-connection_request = await composio.connected_accounts.initiate(
64
- 'user_123',
65
- 'ac_123322' # Auth config ID to connect
66
-)
67
-```
68
-
69
-```typescript TypeScript
70
-const connectionRequest = await composio.connectedAccounts.initiate(
71
- 'user_123',
72
- 'ac_123322' // Auth config ID to connect
73
-);
74
-```
75
-</CodeGroup>
76
-
77
-### 2. User Authorization
78
-The user visits the redirect URL and authorizes access through the external service (OAuth flow).
79
-
80
-### 3. Connection Completion
81
-Wait for the user to complete authorization:
82
-
83
-<CodeGroup>
84
-```python Python
85
-connected_account = await connection_request.wait_for_connection(
86
- 120000 # 2 minutes timeout
87
-)
88
-
89
-print('Connected account ID:', connected_account.id)
90
-```
91
-
92
-```typescript TypeScript
93
-const connectedAccount = await connectionRequest.waitForConnection(
94
- 120000 // 2 minutes timeout
95
-);
96
-
97
-console.log('Connected account ID:', connectedAccount.id);
98
-```
99
-</CodeGroup>
100
-
101
-### 4. Use Connected Account
102
-Execute tools using the connected account:
103
-
104
-<CodeGroup>
105
-```python Python
106
-repos = await composio.tools.execute('GITHUB_LIST_REPOS',
107
- user_id='user_123',
108
- connected_account_id=connected_account.id,
109
- arguments={'per_page': 10}
110
-)
111
-```
112
-
113
-```typescript TypeScript
114
-const repos = await composio.tools.execute('GITHUB_LIST_REPOS', {
115
- userId: 'user_123',
116
- connectedAccountId: connectedAccount.id,
117
- arguments: { per_page: 10 }
118
-});
119
-```
120
-</CodeGroup>
121
-
122
-## Authentication Schemes
123
-
124
-Connected accounts support different authentication methods:
125
-
126
-### OAuth2 (Most Common)
127
-<CodeGroup>
128
-```python
129
-# OAuth2 flow - user authorizes in browser
130
-connection_request = await composio.toolkits.authorize('user_123', 'github')
131
-#-- or use connected_accounts.initiate for specific auth config
132
-connection_request = await composio.connected_accounts.initiate('user_123', 'ac_123322')
133
-
134
-# use the redirect_url to redirect the user to the auth flow
135
-print(connection_request.redirect_url)
136
-
137
-# User completes OAuth flow at connection.redirect_url
138
-connected_account = await connection_request.wait_for_connection()
139
-```
140
-```typescript
141
-// OAuth2 flow - user authorizes in browser
142
-const connectionRequest = await composio.toolkits.authorize('user_123', 'github');
143
-//-- or use connectedAccounts.initiate for specific auth config
144
-const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'ac_123322');
145
-
146
-// use the redirectUrl to redirect the user to the auth flow
147
-console.log(connectionRequest.redirectUrl);
148
-
149
-// User completes OAuth flow at connection.redirectUrl
150
-const connectedAccount = await connectionRequest.waitForConnection();
151
-```
152
-
153
-</CodeGroup>
154
-
155
-### API Keys
156
-<CodeGroup>
157
-
158
-```python
159
-# User provides their API key
160
-connection = await composio.connected_accounts.initiate(
161
- 'user_123',
162
- 'auth_config_id',
163
- config=AuthScheme.api_key(
164
- api_key='user_provided_key'
165
- )
166
-)
167
-```
168
-
169
-```typescript
170
-// User provides their API key
171
-const connection = await composio.connectedAccounts.initiate(
172
- 'user_123',
173
- 'auth_config_id',
174
- {
175
- config: AuthScheme.ApiKey({
176
- api_key: 'user_provided_key'
177
- })
178
- }
179
-);
180
-```
181
-
182
-
183
-</CodeGroup>
184
-
185
-### Basic Authentication
186
-<CodeGroup>
187
-
188
-
189
-```python
190
-# Username and password
191
-connection = await composio.connected_accounts.initiate(
192
- 'user_123',
193
- 'auth_config_id',
194
- config=AuthScheme.basic(
195
- username='user_name',
196
- password='user_password'
197
- )
198
-)
199
-```
200
-```typescript
201
-// Username and password
202
-const connection = await composio.connectedAccounts.initiate(
203
- 'user_123',
204
- 'auth_config_id',
205
- {
206
- config: AuthScheme.Basic({
207
- username: 'user_name',
208
- password: 'user_password'
209
- })
210
- }
211
-);
212
-```
213
-</CodeGroup>
214
-
215
-### Bearer Tokens
216
-<CodeGroup>
217
-
218
-```python
219
-# Bearer token authentication
220
-connection = await composio.connected_accounts.initiate(
221
- 'user_123',
222
- 'auth_config_id',
223
- config=AuthScheme.bearer_token(
224
- token='bearer_token_value'
225
- )
226
-)
227
-```
228
-```typescript
229
-// Bearer token authentication
230
-const connection = await composio.connectedAccounts.initiate(
231
- 'user_123',
232
- 'auth_config_id',
233
- {
234
- config: AuthScheme.BearerToken({
235
- token: 'bearer_token_value'
236
- })
237
- }
238
-);
239
-```
240
-
241
-</CodeGroup>
242
-
243
-## Managing Connected Accounts
244
-
245
-### List User's Connections
246
-<CodeGroup>
247
-
248
-
249
-```python
250
-# Get all connected accounts for a user
251
-accounts = await composio.connected_accounts.list(
252
- user_ids=['user_123']
253
-)
254
-
255
-# Filter by specific toolkit
256
-github_accounts = await composio.connected_accounts.list(
257
- user_ids=['user_123'],
258
- toolkit_slugs=['github']
259
-)
260
-```
261
-```typescript
262
-// Get all connected accounts for a user
263
-const accounts = await composio.connectedAccounts.list({
264
- userIds: ['user_123']
265
-});
266
-
267
-// Filter by specific toolkit
268
-const githubAccounts = await composio.connectedAccounts.list({
269
- userIds: ['user_123'],
270
- toolkitSlugs: ['github']
271
-});
272
-```
273
-</CodeGroup>
274
-
275
-### Check Connection Status
276
-<CodeGroup>
277
-
278
-```python
279
-account = await composio.connected_accounts.get('ca_abc123')
280
-
281
-print('Status:', account.status) # 'ACTIVE', 'PENDING', 'EXPIRED'
282
-print('Toolkit:', account.toolkit.slug)
283
-print('User:', account.user_id)
284
-```
285
-```typescript
286
-const account = await composio.connectedAccounts.get('ca_abc123');
287
-
288
-console.log('Status:', account.status); // 'ACTIVE', 'PENDING', 'EXPIRED'
289
-console.log('Toolkit:', account.toolkit.slug);
290
-console.log('User:', account.userId);
291
-```
292
-
293
-</CodeGroup>
294
-
295
-### Disable/Enable Connections
296
-<CodeGroup>
297
-
298
-```python
299
-# Temporarily disable a connection
300
-await composio.connected_accounts.disable('ca_abc123')
301
-
302
-# Re-enable when needed
303
-await composio.connected_accounts.enable('ca_abc123')
304
-```
305
-```typescript
306
-// Temporarily disable a connection
307
-await composio.connectedAccounts.disable('ca_abc123');
308
-
309
-// Re-enable when needed
310
-await composio.connectedAccounts.enable('ca_abc123');
311
-```
312
-
313
-</CodeGroup>
314
-
315
-### Delete Connections
316
-<CodeGroup>
317
-
318
-```python
319
-# Permanently remove a connection
320
-await composio.connected_accounts.delete('ca_abc123')
321
-```
322
-```typescript
323
-// Permanently remove a connection
324
-await composio.connectedAccounts.delete('ca_abc123');
325
-```
326
-
327
-</CodeGroup>
328
-
329
-
330
-## Multiple Accounts
331
-
332
-By default, Composio prevents multiple connected accounts for the same toolkit to avoid conflicts. You can override this behavior:
333
-
334
-<CodeGroup>
335
-
336
-```python
337
-# Allow multiple connections for the same toolkit
338
-connection = await composio.connected_accounts.initiate(
339
- 'user_123',
340
- 'auth_config_id',
341
- allow_multiple=True
342
-)
343
-```
344
-```typescript
345
-// Allow multiple connections for the same toolkit
346
-const connection = await composio.connectedAccounts.initiate(
347
- 'user_123',
348
- 'auth_config_id',
349
- {
350
- allowMultiple: true
351
- }
352
-);
353
-```
354
-</CodeGroup>
355
-
356
-**Use cases for multiple accounts:**
357
-- User has multiple GitHub accounts (personal + work)
358
-- Different email accounts for different purposes
359
-- Separate accounts for different environments
360
-
361
-## Error Handling
362
-
363
-### Connection Timeout
364
-<CodeGroup>
365
-
366
-```python
367
-try:
368
- account = await composio.connected_accounts.wait_for_connection(
369
- connection_id,
370
- 300000 # 5 minutes
371
- )
372
-except ConnectionRequestTimeoutError:
373
- print('User did not complete authorization in time')
374
-```
375
-```typescript
376
-try {
377
- const account = await composio.connectedAccounts.waitForConnection(
378
- connectionId,
379
- 300000 // 5 minutes
380
- );
381
-} catch (error) {
382
- if (error instanceof ConnectionRequestTimeoutError) {
383
- console.log('User did not complete authorization in time');
384
- }
385
-}
386
-```
387
-
388
-</CodeGroup>
389
-
390
-### Connection Failed
391
-<CodeGroup>
392
-
393
-
394
-```python
395
-try:
396
- account = await composio.connected_accounts.wait_for_connection(connection_id)
397
-except ConnectionRequestFailedError:
398
- print('Authorization was denied or failed')
399
-```
400
-```typescript
401
-try {
402
- const account = await composio.connectedAccounts.waitForConnection(connectionId);
403
-} catch (error) {
404
- if (error instanceof ConnectionRequestFailedError) {
405
- console.log('Authorization was denied or failed');
406
- }
407
-}
408
-```
409
-</CodeGroup>
410
-
411
-### Missing Connected Account
412
-<CodeGroup>
413
-
414
-```python
415
-try:
416
- result = await composio.tools.execute('GITHUB_GET_REPO',
417
- user_id='user_123',
418
- arguments={'owner': 'composio', 'repo': 'sdk'}
419
- )
420
-except MissingConnectedAccountError:
421
- print('User needs to connect their GitHub account first')
422
-```
423
-```typescript
424
-try {
425
- const result = await composio.tools.execute('GITHUB_GET_REPO', {
426
- userId: 'user_123',
427
- arguments: { owner: 'composio', repo: 'sdk' }
428
- });
429
-} catch (error) {
430
- if (error instanceof MissingConnectedAccountError) {
431
- console.log('User needs to connect their GitHub account first');
432
- }
433
-}
434
-```
435
-
436
-</CodeGroup>
437
-
438
-## Best Practices
439
-
440
-### Connection Management
441
-<CodeGroup>
442
-
443
-
444
-```python
445
-# Check for existing connections before creating new ones
446
-async def ensure_connection(user_id: str, toolkit: str):
447
- existing = await composio.connected_accounts.list(
448
- user_ids=[user_id],
449
- toolkit_slugs=[toolkit]
450
- )
451
-
452
- if len(existing.items) > 0 and existing.items[0].status == 'ACTIVE':
453
- return existing.items[0]
454
-
455
- # Create new connection
456
- connection = await composio.toolkits.authorize(user_id, toolkit)
457
- return await composio.connected_accounts.wait_for_connection(connection.id)
458
-```
459
-```typescript
460
-// Check for existing connections before creating new ones
461
-async function ensureConnection(userId: string, toolkit: string) {
462
- const existing = await composio.connectedAccounts.list({
463
- userIds: [userId],
464
- toolkitSlugs: [toolkit]
465
- });
466
-
467
- if (existing.items.length > 0 && existing.items[0].status === 'ACTIVE') {
468
- return existing.items[0];
469
- }
470
-
471
- // Create new connection
472
- const connection = await composio.toolkits.authorize(userId, toolkit);
473
- return await composio.connectedAccounts.waitForConnection(connection.id);
474
-}
475
-```
476
-</CodeGroup>
477
-
478
-### Graceful Degradation
479
-
480
-<CodeGroup>
481
-
482
-
483
-```python
484
-# Handle missing connections gracefully
485
-async def execute_with_fallback(user_id: str, tool_slug: str, args: dict):
486
- try:
487
- return await composio.tools.execute(tool_slug,
488
- user_id=user_id,
489
- arguments=args
490
- )
491
- except ComposioConnectedAccountNotFoundError:
492
- # Return connection URL instead of failing
493
- connection = await composio.toolkits.authorize(user_id, 'github')
494
- return {
495
- 'requires_connection': True,
496
- 'redirect_url': connection.redirect_url
497
- }
498
-```
499
-```typescript
500
-// Handle missing connections gracefully
501
-async function executeWithFallback(userId: string, toolSlug: string, args: Record<string, any>) {
502
- try {
503
- return await composio.tools.execute(toolSlug, {
504
- userId,
505
- arguments: args
506
- });
507
- } catch (error) {
508
- if (error instanceof ComposioConnectedAccountNotFoundError) {
509
- // Return connection URL instead of failing
510
- const connection = await composio.toolkits.authorize(userId, 'github');
511
- return {
512
- requiresConnection: true,
513
- redirectUrl: connection.redirectUrl
514
- };
515
- }
516
- throw error;
517
- }
518
-}
519
-```
520
-</CodeGroup>
521
-
522
-### Connection Health Monitoring
523
-
524
-<CodeGroup>
525
-
526
-
527
-```python
528
-# Periodically check connection health
529
-async def check_connection_health(user_id: str):
530
- accounts = await composio.connected_accounts.list(
531
- user_ids=[user_id]
532
- )
533
-
534
- unhealthy = [
535
- account for account in accounts.items
536
- if account.status != 'ACTIVE'
537
- ]
538
-
539
- if len(unhealthy) > 0:
540
- print(f"User {user_id} has {len(unhealthy)} unhealthy connections")
541
- # Notify user or attempt refresh
542
-```
543
-```typescript
544
-// Periodically check connection health
545
-async function checkConnectionHealth(userId: string) {
546
- const accounts = await composio.connectedAccounts.list({
547
- userIds: [userId]
548
- });
549
-
550
- const unhealthy = accounts.items.filter(
551
- account => account.status !== 'ACTIVE'
552
- );
553
-
554
- if (unhealthy.length > 0) {
555
- console.log(`User ${userId} has ${unhealthy.length} unhealthy connections`);
556
- // Notify user or attempt refresh
557
- }
558
-}
559
-```
560
-</CodeGroup>
561
-
562
-## Security Considerations
563
-
564
-### Token Storage
565
-Composio securely stores all authentication tokens. You never need to handle sensitive credentials directly.
566
-
567
-### Access Control
568
-Connected accounts are scoped to specific users. One user cannot access another user's connected accounts.
569
-
570
-### Token Refresh
571
-Composio automatically handles token refresh for OAuth2 connections when possible.
572
-
573
-### Secure Deletion
574
-When a connected account is deleted, all associated tokens are securely removed.
575
-
576
-## Troubleshooting
577
-
578
-### Connection Stuck in PENDING
579
-- Check if user completed the OAuth flow
580
-- Verify the redirect URL is accessible
581
-- Increase the timeout duration
582
-
583
-### EXPIRED Connections
584
-- Try refreshing the connection
585
-- If refresh fails, user needs to reconnect
586
-
587
-### Multiple Connections Not Working
588
-- Ensure `allowMultiple: true` is set
589
-- Check if the auth config supports multiple connections
590
-
591
----
592
-
593
-Connected accounts are the bridge between your users and external services. Understanding how to create, manage, and use them effectively is crucial for building reliable integrations.
\ No newline at end of file
fern/pages/src/core-concepts/overview.mdx
deleted
-560
@@ -1,560 +0,0 @@
1
----
2
-title: Core Concepts
3
-subtitle: Overview of the core concepts of Composio
4
-image: 'https://og.composio.dev/api/og?title=Core%20Concepts' # image for socials
5
-keywords: ''
6
-hide-nav-links: true
7
----
8
-
9
-Understanding Composio's core concepts is essential for building robust applications. This guide explains the fundamental building blocks and how they work together to provide seamless integration with external services.
10
-
11
-## Essential Concepts
12
-
13
-### 1. **User IDs** - The Foundation
14
-
15
-User IDs are the cornerstone of Composio's security model. Every operation requires a User ID to ensure proper data isolation. You can use the default user ID `default` for public APIs, or create a user ID for each user in your application.
16
-
17
-<CodeGroup>
18
-```python Python
19
-# ✅ Each user has their own isolated context
20
-user_a_tools = await composio.tools.get('user_a', toolkits=['github'])
21
-user_b_tools = await composio.tools.get('user_b', toolkits=['github'])
22
-```
23
-
24
-```typescript TypeScript
25
-// ✅ Each user has their own isolated context
26
-const userATools = await composio.tools.get('user_a', { toolkits: ['github'] });
27
-const userBTools = await composio.tools.get('user_b', { toolkits: ['github'] });
28
-```
29
-</CodeGroup>
30
-
31
-**Why User IDs Matter:**
32
-
33
-- **Security**: Prevents users from accessing each other's data
34
-- **Isolation**: Each user's connected accounts are separate
35
-- **Scaling**: Supports multi-tenant applications
36
-- **Compliance**: Meets data privacy requirements
37
-
38
-[**→ Learn more about User IDs**](./user-ids)
39
-
40
-
41
-### 2. **Tools** - Individual Actions
42
-
43
-Tools are specific actions you can perform, like "Get GitHub Repository" or "Send Email". Each tool has defined inputs and outputs.
44
-
45
-<CodeGroup>
46
-```python Python
47
-# A tool execution
48
-result = await composio.tools.execute('GITHUB_GET_REPO',
49
- user_id='user_123',
50
- arguments={
51
- 'owner': 'composio',
52
- 'repo': 'sdk'
53
- }
54
-)
55
-```
56
-
57
-```typescript TypeScript
58
-// A tool execution
59
-const result = await composio.tools.execute('GITHUB_GET_REPO', {
60
- userId: 'user_123',
61
- arguments: {
62
- owner: 'composio',
63
- repo: 'sdk',
64
- },
65
-});
66
-```
67
-</CodeGroup>
68
-
69
-**Tool Properties:**
70
-
71
-- **Slug**: Unique identifier (e.g., `GITHUB_GET_REPO`)
72
-- **Input Parameters**: What data the tool needs
73
-- **Output**: What data the tool returns
74
-- **Authentication**: Whether the tool requires user authorization
75
-
76
-
77
-### 3. **Toolkits** - Collections of Tools
78
-
79
-Toolkits group related tools from the same service. For example, the GitHub toolkit contains tools for repositories, issues, pull requests, and more.
80
-
81
-<CodeGroup>
82
-```python Python
83
-# Get all tools from the GitHub toolkit
84
-github_tools = await composio.tools.get('user_123',
85
- toolkits=['github']
86
-)
87
-
88
-# Available toolkits include: gmail, slack, notion, hubspot, salesforce, etc.
89
-```
90
-
91
-```typescript TypeScript
92
-// Get all tools from GitHub toolkit
93
-const githubTools = await composio.tools.get('user_123', {
94
- toolkits: ['github'],
95
-});
96
-
97
-// Available toolkits include: gmail, slack, notion, hubspot, salesforce, etc.
98
-```
99
-</CodeGroup>
100
-
101
-**Popular Toolkits:**
102
-
103
-- **GitHub**: Repository management, issues, PRs
104
-- **Gmail**: Email sending, reading, searching
105
-- **Slack**: Messaging, channels, user management
106
-- **Google Calendar**: Event management, scheduling
107
-- **Notion**: Database operations, page creation
108
-
109
-[**→ Explore Tools & Toolkits**](./tools-and-toolkits)
110
-
111
-
112
-### 4. **Connected Accounts** - User Authorizations
113
-
114
-Connected Accounts represent a user's authorized connection to an external service. Users must authorize access before tools can act on their behalf.
115
-
116
-<CodeGroup>
117
-```python Python
118
-# User authorizes GitHub access
119
-connection_request = await composio.connected_accounts.initiate('user_123', 'ac_authconfig_id')
120
-
121
-# After user completes OAuth flow
122
-connected_account = await composio.connected_accounts.wait_for_connection(connection_request.id)
123
-
124
-# Now tools can access user's GitHub data
125
-repos = await composio.tools.execute('GITHUB_LIST_REPOS',
126
- user_id='user_123',
127
- connected_account_id=connected_account.id
128
-)
129
-```
130
-
131
-```typescript TypeScript
132
-// User authorizes GitHub access
133
-const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'ac_authconfig_id');
134
-
135
-// After user completes OAuth flow
136
-const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);
137
-
138
-// Now tools can access user's GitHub data
139
-const repos = await composio.tools.execute('GITHUB_LIST_REPOS', {
140
- userId: 'user_123',
141
- connectedAccountId: connectedAccount.id,
142
-});
143
-```
144
-</CodeGroup>
145
-
146
-**Connection Types:**
147
-
148
-- **OAuth2**: Most common (GitHub, Google, Slack)
149
-- **API Keys**: For services like OpenAI, Anthropic
150
-- **Basic Auth**: Username/password authentication
151
-- **Custom**: Service-specific authentication methods
152
-
153
-[**→ Learn about Connected Accounts**](./connected-accounts)
154
-
155
-
156
-### 5. **Auth Configs** - Authentication Templates
157
-
158
-Auth Configs define how authentication works for each toolkit. They specify the authentication method and required credentials.
159
-
160
-<CodeGroup>
161
-```python Python
162
-# Create a custom auth config for GitHub
163
-auth_config = await composio.auth_configs.create('github', {
164
- 'type': 'use_composio_managed_auth',
165
- 'name': 'My GitHub Integration'
166
-})
167
-```
168
-
169
-```typescript TypeScript
170
-// Create a custom auth config for GitHub
171
-const authConfig = await composio.authConfigs.create('github', {
172
- type: 'use_composio_managed_auth',
173
- name: 'My GitHub Integration',
174
-});
175
-```
176
-</CodeGroup>
177
-
178
-**Auth Config Types:**
179
-
180
-- **Composio Managed**: Composio handles OAuth apps and credentials
181
-- **User Credentials**: Users provide their own API keys/credentials
182
-- **Custom Auth**: Custom authentication flows
183
-- **No Auth**: For public APIs that don't require authentication
184
-
185
-[**→ Understanding Auth Configs**](./auth-configs)
186
-
187
-
188
-### 6. **Providers** - AI Platform Integration
189
-
190
-Providers adapt Composio tools for different AI platforms, handling the formatting and execution patterns each platform expects.
191
-
192
-<CodeGroup>
193
-```python Python
194
-from composio.providers.openai import OpenAIProvider
195
-from composio.providers.langchain import LangChainProvider
196
-
197
-# OpenAI Provider (non-agentic)
198
-openai_composio = Composio(
199
- provider=OpenAIProvider()
200
-)
201
-
202
-# LangChain Provider (agentic)
203
-langchain_composio = Composio(
204
- provider=LangChainProvider()
205
-)
206
-```
207
-
208
-```typescript TypeScript
209
-import { OpenAIProvider } from '@composio/openai';
210
-import { LangChainProvider } from '@composio/langchain';
211
-
212
-// OpenAI Provider (non-agentic)
213
-const openaiComposio = new Composio({
214
- provider: new OpenAIProvider(),
215
-});
216
-
217
-// LangChain Provider (agentic)
218
-const langchainComposio = new Composio({
219
- provider: new LangChainProvider(),
220
-});
221
-```
222
-</CodeGroup>
223
-
224
-**Provider Types:**
225
-
226
-- **Non-Agentic**: Format tools for external use (OpenAI, Anthropic, Google)
227
-- **Agentic**: Control tool execution internally (LangChain, Vercel AI)
228
-
229
-[**→ Learn about Providers**](./providers)
230
-
231
-## How It All Works Together
232
-
233
-Here's how these concepts work together in a typical application:
234
-
235
-### 1. **Setup Phase**
236
-
237
-<CodeGroup>
238
-```typescript TypeScript
239
-// Initialize with your preferred provider
240
-const composio = new Composio({
241
- apiKey: process.env.COMPOSIO_API_KEY,
242
- provider: new OpenAIProvider(),
243
-});
244
-```
245
-
246
-```python Python
247
-# Initialize with your preferred provider
248
-composio = Composio(
249
- api_key=os.environ.get('COMPOSIO_API_KEY'),
250
- provider=OpenAIProvider()
251
-)
252
-```
253
-</CodeGroup>
254
-
255
-### 2. **User Onboarding**
256
-
257
-<CodeGroup>
258
-```typescript TypeScript
259
-// When a user wants to connect GitHub
260
-const connectionRequest = await composio.connectedAccounts.initiate(
261
- user.id, // Your user's ID
262
- 'ac_123322' // Auth config ID to connect
263
-);
264
-
265
-// User completes OAuth flow in browser
266
-// Connection is established automatically
267
-```
268
-
269
-```python Python
270
-# When a user wants to connect GitHub
271
-connection_request = await composio.connected_accounts.initiate(
272
- user.id, # Your user's ID
273
- 'ac_123322' # Auth config ID to connect
274
-)
275
-
276
-# User completes OAuth flow in browser
277
-# Connection is established automatically
278
-```
279
-</CodeGroup>
280
-
281
-### 3. **Tool Execution**
282
-
283
-<CodeGroup>
284
-```typescript TypeScript
285
-// Execute tools on behalf of the user
286
-const result = await composio.tools.execute('GITHUB_CREATE_ISSUE', {
287
- userId: user.id,
288
- arguments: {
289
- owner: 'myorg',
290
- repo: 'myrepo',
291
- title: 'Bug Report',
292
- body: 'Description of the bug...',
293
- },
294
-});
295
-```
296
-
297
-```python Python
298
-# Execute tools on behalf of the user
299
-result = await composio.tools.execute('GITHUB_CREATE_ISSUE',
300
- user_id=user.id,
301
- arguments={
302
- 'owner': 'myorg',
303
- 'repo': 'myrepo',
304
- 'title': 'Bug Report',
305
- 'body': 'Description of the bug...'
306
- }
307
-)
308
-```
309
-</CodeGroup>
310
-
311
-### 4. **AI Integration**
312
-
313
-<CodeGroup>
314
-```typescript TypeScript
315
-// Use tools with AI models
316
-const tools = await composio.tools.get(user.id, {
317
- toolkits: ['github', 'slack'],
318
-});
319
-
320
-const completion = await openai.chat.completions.create({
321
- model: 'gpt-4',
322
- messages: [{ role: 'user', content: 'Create a GitHub issue and notify the team on Slack' }],
323
- tools: tools, // Composio tools formatted for OpenAI
324
-});
325
-```
326
-
327
-```python Python
328
-# Use tools with AI models
329
-tools = await composio.tools.get(user.id,
330
- toolkits=['github', 'slack']
331
-)
332
-
333
-completion = await openai.chat.completions.create(
334
- model='gpt-4',
335
- messages=[{'role': 'user', 'content': 'Create a GitHub issue and notify the team on Slack'}],
336
- tools=tools # Composio tools formatted for OpenAI
337
-)
338
-```
339
-</CodeGroup>
340
-
341
-## Key Patterns and Best Practices
342
-
343
-### 1. **User-Centric Design**
344
-
345
-<CodeGroup>
346
-```typescript TypeScript
347
-// ✅ Always scope operations to specific users
348
-const userTools = await composio.tools.get(userId, { toolkits: ['github'] });
349
-
350
-// ❌ Don't use 'default' in production
351
-const defaultTools = await composio.tools.get('default', { toolkits: ['github'] });
352
-```
353
-
354
-```python Python
355
-# ✅ Always scope operations to specific users
356
-user_tools = await composio.tools.get(user_id, toolkits=['github'])
357
-
358
-# ❌ Don't use 'default' in production
359
-default_tools = await composio.tools.get('default', toolkits=['github'])
360
-```
361
-</CodeGroup>
362
-
363
-### 2. **Error Handling**
364
-
365
-<CodeGroup>
366
-```typescript TypeScript
367
-try {
368
- const result = await composio.tools.execute('GITHUB_GET_REPO', {
369
- userId: user.id,
370
- arguments: { owner: 'composio', repo: 'sdk' },
371
- });
372
-
373
- if (result.successful) {
374
- // Handle success
375
- } else {
376
- // Handle tool-level errors
377
- console.error('Tool error:', result.error);
378
- }
379
-} catch (error) {
380
- // Handle SDK-level errors
381
- console.error('SDK error:', error.message);
382
-}
383
-```
384
-
385
-```python Python
386
-try:
387
- result = await composio.tools.execute('GITHUB_GET_REPO',
388
- user_id=user.id,
389
- arguments={'owner': 'composio', 'repo': 'sdk'}
390
- )
391
-
392
- if result.successful:
393
- # Handle success
394
- pass
395
- else:
396
- # Handle tool-level errors
397
- print('Tool error:', result.error)
398
-except Exception as error:
399
- # Handle SDK-level errors
400
- print('SDK error:', str(error))
401
-```
402
-</CodeGroup>
403
-
404
-### 3. **Connection Management**
405
-
406
-<CodeGroup>
407
-```typescript TypeScript
408
-// Check if user has required connections
409
-const accounts = await composio.connectedAccounts.list({
410
- userIds: [userId],
411
- toolkitSlugs: ['github'],
412
-});
413
-
414
-if (accounts.items.length === 0) {
415
- // Prompt user to connect GitHub
416
- const connection = await composio.toolkits.authorize(userId, 'github');
417
- // Redirect to connection.redirectUrl
418
-}
419
-```
420
-
421
-```python Python
422
-# Check if user has required connections
423
-accounts = await composio.connected_accounts.list(
424
- user_ids=[user_id],
425
- toolkit_slugs=['github']
426
-)
427
-
428
-if len(accounts.items) == 0:
429
- # Prompt user to connect GitHub
430
- connection = await composio.toolkits.authorize(user_id, 'github')
431
- # Redirect to connection.redirect_url
432
-```
433
-</CodeGroup>
434
-
435
-## Advanced Concepts
436
-
437
-### Custom Tools
438
-
439
-Create your own tools for services not yet supported:
440
-
441
-<CodeGroup>
442
-```typescript TypeScript
443
-const customTool = await composio.tools.createCustomTool({
444
- slug: 'MY_CUSTOM_TOOL',
445
- name: 'My Custom Tool',
446
- description: 'Does something specific',
447
- inputParameters: z.object({
448
- // Define the input parameters for the tool
449
- param1: z.string().describe('The first parameter'),
450
- param2: z.string().describe('The second parameter'),
451
- }),
452
- execute: async params => {
453
- // Your custom logic
454
- return { data: {}, successful: true, error: null };
455
- },
456
-});
457
-```
458
-
459
-```python Python
460
-custom_tool = await composio.tools.create_custom_tool(
461
- slug='MY_CUSTOM_TOOL',
462
- name='My Custom Tool',
463
- description='Does something specific',
464
- input_parameters=z.object({
465
- # Define the input parameters for the tool
466
- 'param1': z.string().describe('The first parameter'),
467
- 'param2': z.string().describe('The second parameter')
468
- }),
469
- execute=lambda params: {
470
- # Your custom logic
471
- 'data': {},
472
- 'successful': True,
473
- 'error': None
474
- }
475
-)
476
-```
477
-</CodeGroup>
478
-
479
-### MCP (Model Control Protocol)
480
-
481
-Expose tools to AI models through a standardized protocol:
482
-
483
-<CodeGroup>
484
-```typescript TypeScript
485
-const mcpServer = await composio.mcp.create('my-server', [
486
- {
487
- toolkit: 'github',
488
- authConfigId: 'auth_123',
489
- allowedTools: ['GITHUB_GET_REPO', 'GITHUB_CREATE_ISSUE'],
490
- },
491
-]);
492
-```
493
-
494
-```python Python
495
-mcp_server = await composio.mcp.create('my-server', [
496
- {
497
- 'toolkit': 'github',
498
- 'auth_config_id': 'auth_123',
499
- 'allowed_tools': ['GITHUB_GET_REPO', 'GITHUB_CREATE_ISSUE']
500
- }
501
-])
502
-```
503
-</CodeGroup>
504
-
505
-### Triggers
506
-
507
-React to real-time events from external services:
508
-
509
-<CodeGroup>
510
-```typescript TypeScript
511
-composio.triggers.subscribe(
512
- event => {
513
- console.log('New email received:', event.payload);
514
- },
515
- {
516
- toolkits: ['gmail'],
517
- triggerSlug: ['GMAIL_NEW_EMAIL'],
518
- }
519
-);
520
-```
521
-
522
-```python Python
523
-def handle_event(event):
524
- print('New email received:', event.payload)
525
-
526
-composio.triggers.subscribe(
527
- handle_event,
528
- toolkits=['gmail'],
529
- trigger_slug=['GMAIL_NEW_EMAIL']
530
-)
531
-```
532
-</CodeGroup>
533
-
534
-## Quick Reference
535
-
536
-| Concept | Purpose | Example |
537
-| --------------------- | ------------------- | ------------------- |
538
-| **User ID** | Identity & security | `'user_123'` |
539
-| **Tool** | Specific action | `'GITHUB_GET_REPO'` |
540
-| **Toolkit** | Service collection | `'github'` |
541
-| **Connected Account** | User authorization | OAuth to GitHub |
542
-| **Auth Config** | Auth template | GitHub OAuth app |
543
-| **Provider** | AI integration | OpenAI, LangChain |
544
-
545
-## Common Questions
546
-
547
-**Q: Can one user have multiple connected accounts for the same service?**
548
-A: Yes, but it requires explicitly allowing multiple connections when creating them.
549
-
550
-**Q: Do I need to store authentication tokens?**
551
-A: No, Composio manages all tokens securely. You only work with Connected Account IDs.
552
-
553
-**Q: Can I use tools without user authentication?**
554
-A: Some tools (like HackerNews) don't require authentication, but most do.
555
-
556
-**Q: How do I know which tools require authentication?**
557
-A: Tools that require authentication will throw an error if no connected account is provided.
558
-
559
-
560
-**💡 Remember**: These concepts work together to provide a secure, scalable, and flexible way to integrate external services into your applications. Start with the basics and gradually explore advanced features as your needs grow.
fern/pages/src/core-concepts/tools-and-toolkits.mdx
deleted
-767
@@ -1,767 +0,0 @@
1
----
2
-title: Tools and Toolkits
3
-subtitle: Understanding the tools and toolkits of Composio
4
-image: 'https://og.composio.dev/api/og?title=Tools%20and%20Toolkits' # image for socials
5
-keywords: ''
6
-hide-nav-links: false
7
----
8
-
9
-Tools and Toolkits form the core functionality of Composio, enabling your applications to interact with external services. Understanding the distinction between these concepts and how to use them effectively is essential for building robust integrations.
10
-
11
-## Understanding the Hierarchy
12
-
13
-### Tools: Individual Actions
14
-
15
-A **Tool** represents a single, specific action that can be performed with an external service. Each tool has:
16
-
17
-- **Unique Slug**: A standardized identifier (e.g., `GITHUB_GET_REPO`)
18
-- **Input Parameters**: The data required to execute the tool
19
-- **Output Schema**: The structure of data returned
20
-- **Authentication Requirements**: Whether user authorization is needed
21
-
22
-<CodeGroup>
23
-```python Python
24
-# Example: Getting repository information
25
-result = composio.tools.execute('GITHUB_GET_REPO',
26
- user_id='user_123',
27
- arguments={
28
- 'owner': 'composiohq',
29
- 'repo': 'composio'
30
- }
31
-)
32
-
33
-# The tool returns structured data
34
-
35
-print(result.data.name) // "sdk"
36
-print(result.data.description) // Repository description
37
-print(result.data.stargazers_count) // Number of stars
38
-
39
-````
40
-
41
-```typescript TypeScript
42
-// Example: Getting repository information
43
-const result = await composio.tools.execute('GITHUB_GET_REPO', {
44
- userId: 'user_123',
45
- arguments: {
46
- owner: 'composiohq',
47
- repo: 'composio'
48
- }
49
-});
50
-
51
-// The tool returns structured data
52
-console.log(result.data.name); // "sdk"
53
-console.log(result.data.description); // Repository description
54
-console.log(result.data.stargazers_count); // Number of stars
55
-````
56
-
57
-</CodeGroup>
58
-
59
-### Toolkits: Service/App Collections
60
-
61
-A **Toolkit** is a collection of related tools that work with the same external service. For example:
62
-
63
-- **GitHub Toolkit**: Contains tools for repositories, issues, pull requests, users, organizations
64
-- **Gmail Toolkit**: Contains tools for reading, sending, searching emails
65
-- **Slack Toolkit**: Contains tools for messaging, channels, user management
66
-
67
-<CodeGroup>
68
-```python Python
69
-# Get all tools from the GitHub toolkit
70
-github_tools = composio.tools.get('user_123',
71
- toolkits=['github']
72
-)
73
-
74
-print(f"GitHub toolkit contains {len(github_tools)} tools")
75
-
76
-# Outputs: GitHub toolkit contains 45+ tools
77
-
78
-````
79
-
80
-```typescript TypeScript
81
-// Get all tools from the GitHub toolkit
82
-const githubTools = await composio.tools.get('user_123', {
83
- toolkits: ['github']
84
-});
85
-
86
-console.log(`GitHub toolkit contains ${githubTools.length} tools`);
87
-// Outputs: GitHub toolkit contains 45+ tools
88
-````
89
-
90
-</CodeGroup>
91
-
92
-## Tool Anatomy
93
-
94
-### Tool Structure
95
-
96
-Every tool follows a consistent structure:
97
-
98
-<CodeGroup>
99
-```json JSON
100
-{
101
- "slug": "GITHUB_GET_REPO",
102
- "name": "Get Repository",
103
- "description": "Retrieve information about a specific GitHub repository",
104
- "inputParameters": {
105
- "type": "object",
106
- "properties": {
107
- "owner": {
108
- "type": "string",
109
- "description": "Repository owner username or organization name"
110
- },
111
- "repo": {
112
- "type": "string",
113
- "description": "Repository name"
114
- }
115
- },
116
- "required": ["owner", "repo"]
117
- },
118
- "outputParameters": {
119
- "type": "object",
120
- "properties": {
121
- "name": { "type": "string" },
122
- "description": { "type": "string" },
123
- "stargazers_count": { "type": "integer" },
124
- "html_url": { "type": "string" }
125
- }
126
- }
127
-}
128
-```
129
-</CodeGroup>
130
-
131
-### Tool Categories
132
-
133
-Tools can be categorized by their authentication requirements:
134
-
135
-**Public Tools** - No authentication required:
136
-
137
-<CodeGroup>
138
-```python Python
139
-# HackerNews tools work without user authentication
140
-user = await composio.tools.execute('HACKERNEWS_GET_USER',
141
- user_id='default',
142
- arguments={'user_id': 'pg'}
143
-)
144
-```
145
-
146
-```typescript TypeScript
147
-// HackerNews tools work without user authentication
148
-const user = await composio.tools.execute('HACKERNEWS_GET_USER', {
149
- userId: 'default',
150
- arguments: { userId: 'pg' },
151
-});
152
-```
153
-
154
-</CodeGroup>
155
-
156
-**Authenticated Tools** - Require user authorization:
157
-
158
-<CodeGroup>
159
-```python Python
160
-# GitHub tools require connected account
161
-repos = await composio.tools.execute('GITHUB_LIST_REPOS',
162
- user_id='user_123',
163
- connected_account_id='ca_github_abc123',
164
- arguments={'per_page': 10}
165
-)
166
-```
167
-
168
-```typescript TypeScript
169
-// GitHub tools require connected account
170
-const repos = await composio.tools.execute('GITHUB_LIST_REPOS', {
171
- userId: 'user_123',
172
- connectedAccountId: 'ca_github_abc123',
173
- arguments: { per_page: 10 },
174
-});
175
-```
176
-
177
-</CodeGroup>
178
-
179
-## Working with Tools
180
-
181
-### Discovering Available Tools
182
-
183
-**List tools by Toolkit:**
184
-
185
-<CodeGroup>
186
-
187
-```python Python
188
-# Get tools from specific toolkits
189
-tools = await composio.tools.get('user_123',
190
- toolkits=['github', 'gmail']
191
-)
192
-```
193
-
194
-```typescript TypeScript
195
-// Get tools from specific toolkits
196
-const tools = await composio.tools.get('user_123', {
197
- toolkits: ['github', 'gmail'],
198
-});
199
-```
200
-
201
-</CodeGroup>
202
-
203
-**Search for Tools:**
204
-
205
-<CodeGroup>
206
-
207
-```python Python
208
-# Search tools by name or description
209
-search_results = composio.tools.get('user_123',
210
- search='repository',
211
- limit=10
212
-)
213
-```
214
-
215
-```typescript TypeScript
216
-// Search tools by name or description
217
-const searchResults = await composio.tools.get('user_123', {
218
- search: 'repository',
219
- limit: 10,
220
-});
221
-```
222
-
223
-</CodeGroup>
224
-
225
-**Get Specific Tools:**
226
-
227
-<CodeGroup>
228
-
229
-```python Python
230
-# Get specific tools by their slugs
231
-specific_tools = await composio.tools.get('user_123',
232
- tools=['GITHUB_GET_REPO', 'GITHUB_CREATE_ISSUE', 'GMAIL_SEND_EMAIL']
233
-)
234
-```
235
-
236
-```typescript TypeScript
237
-// Get specific tools by their slugs
238
-const specificTools = await composio.tools.get('user_123', {
239
- tools: ['GITHUB_GET_REPO', 'GITHUB_CREATE_ISSUE', 'GMAIL_SEND_EMAIL'],
240
-});
241
-```
242
-
243
-</CodeGroup>
244
-
245
-### Tool Execution Patterns
246
-
247
-**Basic Execution:**
248
-
249
-<CodeGroup>
250
-
251
-```python Python
252
-try:
253
- result = await composio.tools.execute('GITHUB_GET_REPO',
254
- user_id='user_123',
255
- arguments={
256
- 'owner': 'composio',
257
- 'repo': 'sdk'
258
- }
259
- )
260
-
261
- if result.successful:
262
- print('Repository data:', result.data)
263
- else:
264
- print('Tool execution failed:', result.error)
265
-except Exception as error:
266
- print('SDK error:', str(error))
267
-```
268
-
269
-```typescript TypeScript
270
-try {
271
- const result = await composio.tools.execute('GITHUB_GET_REPO', {
272
- userId: 'user_123',
273
- arguments: {
274
- owner: 'composio',
275
- repo: 'sdk',
276
- },
277
- });
278
-
279
- if (result.successful) {
280
- console.log('Repository data:', result.data);
281
- } else {
282
- console.error('Tool execution failed:', result.error);
283
- }
284
-} catch (error) {
285
- console.error('SDK error:', error.message);
286
-}
287
-```
288
-
289
-</CodeGroup>
290
-
291
-**With Connected Account:**
292
-
293
-<CodeGroup>
294
-```python Python
295
-# For tools requiring authentication
296
-result = composio.tools.execute('GITHUB_CREATE_ISSUE',
297
- user_id='user_123',
298
- connected_account_id='ca_abc123',
299
- arguments={
300
- 'owner': 'myorg',
301
- 'repo': 'myrepo',
302
- 'title': 'Bug Report',
303
- 'body': 'Description of the issue...'
304
- }
305
-)
306
-```
307
-
308
-```typescript TypeScript
309
-// For tools requiring authentication
310
-const result = await composio.tools.execute('GITHUB_CREATE_ISSUE', {
311
- userId: 'user_123',
312
- connectedAccountId: 'ca_abc123',
313
- arguments: {
314
- owner: 'myorg',
315
- repo: 'myrepo',
316
- title: 'Bug Report',
317
- body: 'Description of the issue...',
318
- },
319
-});
320
-```
321
-
322
-</CodeGroup>
323
-
324
-## Toolkit Authentication Patterns
325
-
326
-### OAuth2 Toolkits
327
-
328
-Most modern services use OAuth2 for secure authentication:
329
-
330
-<CodeGroup>
331
-```python Python
332
-# Initiate OAuth flow
333
-connection_request = await composio.toolkits.authorize('user_123', 'github')
334
-
335
-# User visits connection_request.redirect_url to authorize
336
-
337
-# After authorization, get the connected account
338
-
339
-connected_account = await composio.connected_accounts.wait_for_connection(
340
-connection_request.id
341
-)
342
-
343
-# Use the connected account with toolkit tools
344
-
345
-result = await composio.tools.execute('GITHUB_GET_REPO',
346
-user_id='user_123',
347
-connected_account_id=connected_account.id,
348
-arguments={'owner': 'composio', 'repo': 'sdk'}
349
-)
350
-
351
-````
352
-```typescript TypeScript
353
-// Initiate OAuth flow
354
-const connectionRequest = await composio.toolkits.authorize('user_123', 'github');
355
-
356
-// User visits connectionRequest.redirectUrl to authorize
357
-// After authorization, get the connected account
358
-const connectedAccount = await composio.connectedAccounts.waitForConnection(
359
-connectionRequest.id
360
-);
361
-
362
-// Use the connected account with toolkit tools
363
-const result = await composio.tools.execute('GITHUB_GET_REPO', {
364
-userId: 'user_123',
365
-connectedAccountId: connectedAccount.id,
366
-arguments: { owner: 'composio', repo: 'sdk' }
367
-});
368
-
369
-````
370
-
371
-</CodeGroup>
372
-
373
-### API Key Toolkits
374
-
375
-Some services use API keys for authentication:
376
-
377
-```typescript TypeScript
378
-// Connect using API key
379
-const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'auth_config_id', {
380
- config: AuthScheme.ApiKey({
381
- api_key: 'user_provided_api_key',
382
- }),
383
-});
384
-```
385
-
386
-<CodeGroup>
387
-
388
-```python Python
389
-# Connect using API key
390
-connection_request = await composio.connected_accounts.initiate(
391
- 'user_123',
392
- 'auth_config_id',
393
- config=AuthScheme.api_key(
394
- api_key='user_provided_api_key'
395
- )
396
-)
397
-```
398
-
399
-```typescript TypeScript
400
-// Connect using API key
401
-const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'auth_config_id', {
402
- config: AuthScheme.ApiKey({
403
- api_key: 'user_provided_api_key',
404
- }),
405
-});
406
-```
407
-
408
-</CodeGroup>
409
-
410
-### No Authentication Required
411
-
412
-Some toolkits provide public data without authentication:
413
-
414
-<CodeGroup>
415
-
416
-```python
417
-# Public tools work without connected accounts
418
-result = await composio.tools.execute('HACKERNEWS_GET_USER',
419
- user_id='default',
420
- arguments={'user_id': 'pg'}
421
-)
422
-```
423
-
424
-```typescript TypeScript
425
-// Public tools work without connected accounts
426
-const result = await composio.tools.execute('HACKERNEWS_GET_USER', {
427
- userId: 'default',
428
- arguments: { userId: 'pg' },
429
-});
430
-```
431
-
432
-</CodeGroup>
433
-
434
-## Advanced Tool Features
435
-
436
-### Tool Parameters and Validation
437
-
438
-Tools automatically validate input parameters:
439
-
440
-<CodeGroup>
441
-
442
-```python Python
443
-# This will fail validation
444
-try:
445
- await composio.tools.execute('GITHUB_GET_REPO',
446
- user_id='user_123',
447
- arguments={
448
- 'owner': 'composio'
449
- // Missing required 'repo' parameter
450
- }
451
- )
452
-except Exception as error:
453
- print('Validation error:', str(error))
454
- // Error: Missing required parameter 'repo'
455
-```
456
-
457
-```typescript TypeScript
458
-// This will fail validation
459
-try {
460
- await composio.tools.execute('GITHUB_GET_REPO', {
461
- userId: 'user_123',
462
- arguments: {
463
- owner: 'composio',
464
- // Missing required 'repo' parameter
465
- },
466
- });
467
-} catch (error) {
468
- console.error('Validation error:', error.message);
469
- // Error: Missing required parameter 'repo'
470
-}
471
-```
472
-
473
-</CodeGroup>
474
-
475
-### File Handling
476
-
477
-Some tools support file operations:
478
-
479
-<CodeGroup>
480
-
481
-```python Python
482
-# Tools with file upload capability
483
-result = await composio.tools.execute('GOOGLE_DRIVE_UPLOAD_FILE',
484
- user_id='user_123',
485
- arguments={
486
- 'file_to_upload': '/path/to/local/file.pdf' // SDK handles upload automatically
487
- }
488
-)
489
-
490
-# Tools that return files
491
-file_result = await composio.tools.execute('GOOGLE_DRIVE_DOWNLOAD_FILE',
492
- user_id='user_123',
493
- arguments={'file_id': 'file_id'}
494
-)
495
-
496
-# SDK automatically downloads file to local path
497
-print('Downloaded to:', file_result.data.file.uri)
498
-```
499
-```typescript TypeScript
500
-// Tools with file upload capability
501
-const result = await composio.tools.execute('GOOGLE_DRIVE_UPLOAD_FILE', {
502
- userId: 'user_123',
503
- arguments: {
504
- file_to_upload: '/path/to/local/file.pdf', // SDK handles upload automatically
505
- }
506
-});
507
-
508
-// Tools that return files
509
-const fileResult = await composio.tools.execute('GOOGLE_DRIVE_DOWNLOAD_FILE', {
510
-userId: 'user_123',
511
-arguments: { file_id: 'file_id' }
512
-});
513
-
514
-// SDK automatically downloads file to local path
515
-console.log('Downloaded to:', fileResult.data.file.uri);
516
-
517
-```
518
-
519
-</CodeGroup>
520
-
521
-### Error Handling Patterns
522
-
523
-Different types of errors require different handling approaches:
524
-
525
-
526
-<CodeGroup>
527
-```python Python
528
-async def execute_tool_safely(tool_slug: str, params: dict):
529
- try:
530
- result = await composio.tools.execute(tool_slug, **params)
531
-
532
- if result.successful:
533
- return result.data
534
- else:
535
- # Tool-level error (e.g., API rate limit, invalid parameters)
536
- raise ToolExecutionError(result.error)
537
- except ComposioToolNotFoundError:
538
- # Tool doesn't exist
539
- print('Tool not found:', tool_slug)
540
- raise
541
- except ComposioConnectedAccountNotFoundError:
542
- # User hasn't connected the required account
543
- print('Account not connected for toolkit')
544
- raise
545
- except Exception as error:
546
- # Other SDK errors
547
- print('Unexpected error:', str(error))
548
- raise
549
-```
550
-
551
-```typescript TypeScript
552
-async function executeToolSafely(toolSlug: string, params: Record<string, any>) {
553
- try {
554
- const result = await composio.tools.execute(toolSlug, params);
555
-
556
- if (result.successful) {
557
- return result.data;
558
- } else {
559
- // Tool-level error (e.g., API rate limit, invalid parameters)
560
- throw new ToolExecutionError(result.error);
561
- }
562
- } catch (error) {
563
- if (error instanceof ComposioToolNotFoundError) {
564
- // Tool doesn't exist
565
- console.error('Tool not found:', toolSlug);
566
- } else if (error instanceof ComposioConnectedAccountNotFoundError) {
567
- // User hasn't connected the required account
568
- console.error('Account not connected for toolkit');
569
- } else {
570
- // Other SDK errors
571
- console.error('Unexpected error:', error);
572
- }
573
- throw error;
574
- }
575
-}
576
-```
577
-
578
-</CodeGroup>
579
-
580
-## Tool Discovery and Documentation
581
-
582
-### Exploring Toolkit Capabilities
583
-
584
-<CodeGroup>
585
-
586
-```python Python
587
-# Get toolkit information
588
-toolkit = await composio.toolkits.get('github')
589
-print(f"{toolkit.name} has {toolkit.meta.tools_count} tools")
590
-
591
-# List all tools in a toolkit
592
-tools = await composio.tools.get('user_123',
593
- toolkits=['github']
594
-)
595
-
596
-for tool in tools:
597
- print(f"{tool.function.name}: {tool.function.description}")
598
-```
599
-```typescript TypeScript
600
-// Get toolkit information
601
-const toolkit = await composio.toolkits.get('github');
602
-console.log(`${toolkit.name} has ${toolkit.meta.toolsCount} tools`);
603
-
604
-// List all tools in a toolkit
605
-const tools = await composio.tools.get('user_123', {
606
-toolkits: ['github']
607
-});
608
-
609
-tools.forEach(tool => {
610
-console.log(`${tool.function.name}: ${tool.function.description}`);
611
-});
612
-
613
-```
614
-
615
-</CodeGroup>
616
-
617
-### Understanding Tool Requirements
618
-
619
-<CodeGroup>
620
-
621
-```python Python
622
-# Get detailed tool information
623
-tool = await composio.tools.get_raw_composio_tool_by_slug('GITHUB_GET_REPO')
624
-print('Required parameters:', tool.input_parameters.required)
625
-print('All parameters:', list(tool.input_parameters.properties.keys()))
626
-```
627
-```typescript TypeScript
628
-// Get detailed tool information
629
-const tool = await composio.tools.getRawComposioToolBySlug('GITHUB_GET_REPO');
630
-console.log('Required parameters:', tool.inputParameters.required);
631
-console.log('All parameters:', Object.keys(tool.inputParameters.properties));
632
-```
633
-
634
-</CodeGroup>
635
-
636
-## Integration with AI Providers
637
-
638
-Tools are automatically formatted for different AI providers:
639
-
640
-### OpenAI Integration
641
-
642
-<CodeGroup>
643
-```python Python
644
-from openai import OpenAI
645
-
646
-openai = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
647
-tools = await composio.tools.get('user_123',
648
- toolkits=['github']
649
-)
650
-
651
-completion = await openai.chat.completions.create(
652
- model='gpt-4',
653
- messages=[
654
- {'role': 'user', 'content': 'Get information about the composio/sdk repository'}
655
- ],
656
- tools=tools # Tools are pre-formatted for OpenAI
657
-)
658
-```
659
-```typescript TypeScript
660
-import OpenAI from 'openai';
661
-
662
-const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
663
-const tools = await composio.tools.get('user_123', {
664
-toolkits: ['github']
665
-});
666
-
667
-const completion = await openai.chat.completions.create({
668
-model: 'gpt-4',
669
-messages: [
670
-{ role: 'user', content: 'Get information about the composio/sdk repository' }
671
-],
672
-tools: tools // Tools are pre-formatted for OpenAI
673
-});
674
-
675
-```
676
-
677
-</CodeGroup>
678
-
679
-### LangChain Integration
680
-
681
-<CodeGroup>
682
-```python Python
683
-from composio.providers.langchain import LangChainProvider
684
-
685
-langchain_composio = Composio(
686
- provider=LangChainProvider()
687
-)
688
-
689
-tools = await langchain_composio.tools.get('user_123',
690
- toolkits=['github']
691
-)
692
-
693
-# Tools are formatted as LangChain tools
694
-agent = tools.create_executor(model='gpt-4')
695
-```
696
-```typescript TypeScript
697
-import { LangChainProvider } from '@composio/langchain';
698
-
699
-const langchainComposio = new Composio({
700
-provider: new LangChainProvider()
701
-});
702
-
703
-const tools = await langchainComposio.tools.get('user_123', {
704
-toolkits: ['github']
705
-});
706
-
707
-// Tools are formatted as LangChain tools
708
-const agent = tools.createExecutor({ model: 'gpt-4' });
709
-
710
-```
711
-</CodeGroup>
712
-
713
-## Best Practices
714
-
715
-### Tool Selection
716
-
717
-- **Be Specific**: Request only the tools you need rather than entire toolkits
718
-- **Use Search**: Leverage search functionality to find relevant tools
719
-- **Check Requirements**: Verify authentication requirements before using tools
720
-
721
-### Error Handling
722
-
723
-- **Check Success**: Always verify `result.successful` before using data
724
-- **Handle Missing Connections**: Gracefully handle cases where users haven't connected accounts
725
-- **Validate Inputs**: Ensure required parameters are provided
726
-
727
-### Performance
728
-
729
-- **Batch Operations**: Group related tool executions when possible
730
-- **Cache Results**: Store frequently accessed data to reduce API calls
731
-- **Rate Limiting**: Be aware of external service rate limits
732
-
733
-### Security
734
-
735
-- **User Context**: Always execute tools in the correct user context
736
-- **Parameter Validation**: Validate user inputs before passing to tools
737
-- **Error Information**: Be careful not to expose sensitive error details to end users
738
-
739
-## Troubleshooting Common Issues
740
-
741
-### Authentication Errors
742
-
743
-```javascript
744
-// Check if user has connected the required toolkit
745
-const accounts = await composio.connectedAccounts.list({
746
- userIds: ['user_123'],
747
- toolkitSlugs: ['github'],
748
-});
749
-
750
-if (accounts.items.length === 0) {
751
- // User needs to connect GitHub
752
- const connection = await composio.toolkits.authorize('user_123', 'github');
753
-}
754
-```
755
-
756
-### Parameter Validation Errors
757
-
758
-```javascript
759
-// Get tool schema to understand required parameters
760
-const tool = await composio.tools.getRawComposioToolBySlug('GITHUB_GET_REPO');
761
-console.log('Required parameters:', tool.inputParameters.required);
762
-console.log('Parameter schemas:', tool.inputParameters.properties);
763
-```
764
-
765
----
766
-
767
-Understanding tools and toolkits is fundamental to building effective integrations with Composio. These concepts provide the building blocks for connecting your applications to the external services your users need.
fern/pages/src/core-concepts/triggers.mdx
deleted
-234
@@ -1,234 +0,0 @@
1
----
2
-title: Triggers
3
-subtitle: Understanding the triggers in Composio
4
-image: 'https://og.composio.dev/api/og?title=Triggers' # image for socials
5
-keywords: ''
6
-hide-nav-links: false
7
----
8
-
9
-Triggers enable your applications to respond to real-time events from external services. Instead of polling for changes, triggers deliver events instantly when they occur.
10
-
11
-## What Are Triggers?
12
-
13
-A **Trigger** is a real-time event notification from an external service. When something happens in a connected service (like a new email, GitHub issue, or Slack message), Composio delivers that event to your application.
14
-
15
-<CodeGroup>
16
-
17
-```python
18
-# Create a trigger for new GitHub issues
19
-trigger = await composio.triggers.create(
20
- user_id='user_123',
21
- trigger_slug='GITHUB_ISSUE_CREATED',
22
- trigger_config={
23
- 'repository': 'composiohq/composio'
24
- }
25
-)
26
-```
27
-```typescript
28
-// Create a trigger for new GitHub issues
29
-const trigger = await composio.triggers.create(
30
- 'user_123',
31
- 'GITHUB_ISSUE_CREATED',
32
- {
33
- triggerConfig: {
34
- repository: 'composiohq/composio'
35
- }
36
- }
37
-);
38
-```
39
-
40
-</CodeGroup>
41
-
42
-## How Triggers Work
43
-
44
-1. **Create**: Set up a trigger for specific events
45
-2. **Connect**: User authorizes the external service
46
-3. **Monitor**: Composio watches for events in real-time
47
-4. **Deliver**: Events are sent to your application via webhooks or SDK
48
-
49
-## Development vs Production
50
-
51
-### Development: SDK Subscription
52
-For testing and development, subscribe to events in your code:
53
-
54
-<CodeGroup>
55
-
56
-
57
-```python
58
-# Development only - not for production
59
-def handle_event(trigger_data):
60
- print(f"Event: {trigger_data.trigger_slug}")
61
- print(f"Data: {trigger_data.payload}")
62
-
63
-composio.triggers.subscribe(
64
- callback=handle_event,
65
- filters={'user_id': 'user_123'}
66
-)
67
-```
68
-```typescript
69
-// Development only - not for production
70
-composio.triggers.subscribe((triggerData) => {
71
- console.log(`Event: ${triggerData.triggerSlug}`);
72
- console.log(`Data: ${triggerData.payload}`);
73
-}, {
74
- userId: 'user_123'
75
-});
76
-```
77
-</CodeGroup>
78
-
79
-### Production: Webhook Endpoints
80
-For production, use webhook endpoints to receive events:
81
-
82
-<CodeGroup>
83
-```python Python
84
-# Production webhook endpoint
85
-@app.route('/webhooks/composio', methods=['POST'])
86
-def handle_webhook():
87
- trigger_data = request.json
88
-
89
- # Process the event
90
- process_event(trigger_data)
91
-
92
- return jsonify({'status': 'success'}), 200
93
-```
94
-
95
-```typescript TypeScript
96
-// Production webhook endpoint
97
-app.post('/webhooks/composio', (req, res) => {
98
- const triggerData = req.body;
99
-
100
- // Process the event
101
- processEvent(triggerData);
102
-
103
- res.status(200).json({ status: 'success' });
104
-});
105
-```
106
-</CodeGroup>
107
-
108
-## Event Structure
109
-
110
-All trigger events follow a consistent format:
111
-
112
-<CodeGroup>
113
-```python Python
114
-# Trigger event structure
115
-{
116
- 'id': 'trigger_instance_id',
117
- 'trigger_slug': 'GITHUB_ISSUE_CREATED',
118
- 'toolkit_slug': 'github',
119
- 'user_id': 'user_123',
120
- 'payload': {
121
- # Event-specific data
122
- 'title': 'Bug Report',
123
- 'number': 42,
124
- 'author': 'username'
125
- },
126
- 'metadata': {
127
- 'connected_account': {
128
- 'id': 'ca_abc123',
129
- 'status': 'ACTIVE'
130
- }
131
- }
132
-}
133
-```
134
-
135
-```typescript TypeScript
136
-// Trigger event structure
137
-interface TriggerEvent {
138
- id: string; // Trigger instance ID
139
- triggerSlug: string; // Event type
140
- toolkitSlug: string; // Service name
141
- userId: string; // User ID
142
- payload: { // Event data
143
- title: string;
144
- number: number;
145
- author: string;
146
- };
147
- metadata: {
148
- connectedAccount: {
149
- id: string; // Connected account ID
150
- status: string; // Connection status
151
- };
152
- };
153
-}
154
-```
155
-</CodeGroup>
156
-
157
-## Managing Triggers
158
-
159
-### List Active Triggers
160
-<CodeGroup>
161
-
162
-
163
-```python
164
-# Get all active triggers
165
-triggers = await composio.triggers.list_active()
166
-
167
-# Filter by user or toolkit
168
-user_triggers = await composio.triggers.list_active(
169
- filters={'user_ids': ['user_123']}
170
-)
171
-```
172
-```typescript
173
-// Get all active triggers
174
-const triggers = await composio.triggers.listActive();
175
-
176
-// Filter by user or toolkit
177
-const userTriggers = await composio.triggers.listActive({
178
- connectedAccountIds: ['ca_123']
179
-});
180
-```
181
-</CodeGroup>
182
-
183
-### Enable/Disable Triggers
184
-<CodeGroup>
185
-
186
-
187
-```python
188
-# Temporarily disable a trigger
189
-await composio.triggers.disable('trigger_id')
190
-
191
-# Re-enable when needed
192
-await composio.triggers.enable('trigger_id')
193
-```
194
-```typescript
195
-// Temporarily disable a trigger
196
-await composio.triggers.disable('trigger_id');
197
-
198
-// Re-enable when needed
199
-await composio.triggers.enable('trigger_id');
200
-```
201
-</CodeGroup>
202
-
203
-## Key Differences: Development vs Production
204
-
205
-| Aspect | Development (SDK) | Production (Webhooks) |
206
-|--------|------------------|----------------------|
207
-| **Connection** | Persistent WebSocket | HTTP requests |
208
-| **Scalability** | Single instance | Horizontally scalable |
209
-| **Reliability** | Can disconnect | Built-in retries |
210
-| **Deployment** | Not recommended | Production-ready |
211
-
212
-## Best Practices
213
-
214
-### For Development
215
-- Use `triggers.subscribe()` for quick testing
216
-- Monitor connection status during development
217
-- Handle events synchronously for debugging
218
-
219
-### For Production
220
-- Always use webhook endpoints
221
-- Implement signature verification for security
222
-- Handle duplicate events (idempotency)
223
-- Use proper HTTP status codes (200 for success)
224
-- Implement retry logic for failed processing
225
-
226
-### General Guidelines
227
-- Filter events to reduce unnecessary processing
228
-- Monitor trigger health and connection status
229
-- Handle connection failures gracefully
230
-- Log events for debugging and monitoring
231
-
232
----
233
-
234
-Triggers enable reactive applications that respond immediately to external events, creating more efficient and responsive integrations.
\ No newline at end of file
fern/pages/src/core-concepts/user-ids.mdx
deleted
-832
@@ -1,832 +0,0 @@
1
----
2
-title: User IDs - The Security Foundation
3
-subtitle: Understanding the security foundation of Composio
4
-image: 'https://og.composio.dev/api/og?title=User%20IDs' # image for socials
5
-keywords: ''
6
-hide-nav-links: true
7
----
8
-User IDs are the **core foundation** of accessing and executing tools in Composio. Every tool execution, connection authorization, and account management operation requires a `userId` parameter that identifies which user's context the operation should be performed in.
9
-
10
-## Why User IDs Are Critical
11
-
12
-User IDs provide the fundamental security layer that ensures:
13
-
14
-- **Data Isolation**: Users can only access their own connected accounts and data
15
-- **Security Boundaries**: No unauthorized access to other users' external services
16
-- **Multi-Tenancy**: Support for applications with multiple users
17
-- **Compliance**: Meet data privacy and security requirements
18
-- **Audit Trail**: Track which user performed which actions
19
-
20
-<CodeGroup>
21
-```python Python
22
-# ✅ Each user operates in their own secure context
23
-user_a_repos = composio.tools.execute('GITHUB_LIST_REPOS',
24
- user_id='user_a', # User A's GitHub repositories
25
- arguments={}
26
-)
27
-
28
-user_b_repos = composio.tools.execute('GITHUB_LIST_REPOS',
29
- user_id='user_b', # User B's GitHub repositories
30
- arguments={}
31
-)
32
-
33
-# User A cannot see User B's repositories, and vice versa
34
-```
35
-
36
-```typescript TypeScript
37
-// ✅ Each user operates in their own secure context
38
-const userARepos = await composio.tools.execute('GITHUB_LIST_REPOS', {
39
- userId: 'user_a', // User A's GitHub repositories
40
- arguments: {}
41
-});
42
-
43
-const userBRepos = await composio.tools.execute('GITHUB_LIST_REPOS', {
44
- userId: 'user_b', // User B's GitHub repositories
45
- arguments: {}
46
-});
47
-
48
-// User A cannot see User B's repositories, and vice versa
49
-```
50
-</CodeGroup>
51
-
52
-## Choosing the Right User ID
53
-
54
-### ✅ **Recommended: Database Primary Key**
55
-
56
-The best practice is to use your application's existing user identifier:
57
-
58
-<CodeGroup>
59
-```python Python
60
-# Use your database user ID
61
-user_id = user.id # e.g., "550e8400-e29b-41d4-a716-446655440000"
62
-user_id = user.uuid # e.g., UUID from your user table
63
-user_id = user.primary_key # Any unique, stable identifier
64
-
65
-tools = await composio.tools.get(user_id,
66
- toolkits=['github']
67
-)
68
-```
69
-
70
-```typescript TypeScript
71
-// Use your database user ID
72
-const userId = user.id; // e.g., "550e8400-e29b-41d4-a716-446655440000"
73
-const userId = user.uuid; // e.g., UUID from your user table
74
-const userId = user.primaryKey; // Any unique, stable identifier
75
-
76
-const tools = await composio.tools.get(userId, {
77
- toolkits: ['github']
78
-});
79
-```
80
-</CodeGroup>
81
-
82
-**Why Database IDs Are Best:**
83
-- **Unique**: Guaranteed uniqueness in your system
84
-- **Stable**: Won't change over time
85
-- **Consistent**: Already used throughout your application
86
-- **Secure**: Not guessable or enumerable
87
-
88
-### ✅ **Acceptable: Unique Username/Identifier**
89
-
90
-If you don't have database IDs, use unique, stable identifiers:
91
-
92
-<CodeGroup>
93
-```python Python
94
-user_id = user.username # e.g., "john_doe_123"
95
-user_id = user.external_id # e.g., "auth0|507f1f77bcf86cd799439011"
96
-user_id = f"tenant_{tenant_id}_user_{user_index}" # Custom format
97
-```
98
-
99
-```typescript TypeScript
100
-const userId = user.username; // e.g., "john_doe_123"
101
-const userId = user.externalId; // e.g., "auth0|507f1f77bcf86cd799439011"
102
-const userId = `tenant_${tenantId}_user_${userIndex}`; // Custom format
103
-```
104
-</CodeGroup>
105
-
106
-### ⚠️ **Avoid: Email Addresses**
107
-
108
-While functional, email addresses can change and cause issues:
109
-
110
-<CodeGroup>
111
-```python Python
112
-# Not recommended - emails can change
113
-user_id = user.email # e.g., "user@example.com"
114
-
115
-# Better: Use a stable ID even if you display the email
116
-user_id = user.id # Your stable user ID
117
-display_name = user.email # For display purposes only
118
-```
119
-
120
-```typescript TypeScript
121
-// Not recommended - emails can change
122
-const userId = user.email; // e.g., "user@example.com"
123
-
124
-// Better: Use a stable ID even if you display the email
125
-const userId = user.id; // Your stable user ID
126
-const displayName = user.email; // For display purposes only
127
-```
128
-</CodeGroup>
129
-
130
-### ❌ **Never Use: Sensitive or Guessable Data**
131
-
132
-<CodeGroup>
133
-```python Python
134
-# ❌ DON'T use sensitive information
135
-user_id = user.ssn # Social Security Number
136
-user_id = user.credit_card_number # Financial data
137
-
138
-# ❌ DON'T use easily guessable patterns
139
-user_id = "user1" # Sequential numbers
140
-user_id = "admin" # Common names
141
-```
142
-
143
-```typescript TypeScript
144
-// ❌ DON'T use sensitive information
145
-const userId = user.ssn; // Social Security Number
146
-const userId = user.creditCardNumber; // Financial data
147
-
148
-// ❌ DON'T use easily guessable patterns
149
-const userId = "user1"; // Sequential numbers
150
-const userId = "admin"; // Common names
151
-```
152
-</CodeGroup>
153
-
154
-## Organization-Based Applications
155
-
156
-For applications where users belong to organizations and apps are connected at the **organization level**, use the **organization ID** as the `userId`:
157
-
158
-### When to Use Organization IDs
159
-
160
-Use organization IDs when:
161
-- **Team/Organization tools**: Slack, Microsoft Teams, project management tools
162
-- **Enterprise applications**: IT administrators connect apps for the whole organization
163
-- **Shared resources**: Multiple users need access to the same connected accounts
164
-- **Role-based access**: Permissions are managed at the organization level
165
-
166
-### Implementation Pattern
167
-
168
-<CodeGroup>
169
-```python Python
170
-# Organization-based approach
171
-user_id = organization.id # e.g., "org_550e8400-e29b-41d4-a716-446655440000"
172
-
173
-# All users in the organization share the same connected accounts
174
-tools = await composio.tools.get(user_id,
175
- toolkits=['slack', 'github']
176
-)
177
-
178
-# Execute tools in the organization context
179
-result = await composio.tools.execute('SLACK_SEND_MESSAGE',
180
- user_id=user_id, # Organization ID, not individual user ID
181
- arguments={
182
- 'channel': '#general',
183
- 'text': 'Hello from the team!'
184
- }
185
-)
186
-```
187
-
188
-```typescript TypeScript
189
-// Organization-based approach
190
-const userId = organization.id; // e.g., "org_550e8400-e29b-41d4-a716-446655440000"
191
-
192
-// All users in the organization share the same connected accounts
193
-const tools = await composio.tools.get(userId, {
194
- toolkits: ['slack', 'github']
195
-});
196
-
197
-// Execute tools in the organization context
198
-const result = await composio.tools.execute('SLACK_SEND_MESSAGE', {
199
- userId: userId, // Organization ID, not individual user ID
200
- arguments: {
201
- channel: '#general',
202
- text: 'Hello from the team!'
203
- }
204
-});
205
-```
206
-</CodeGroup>
207
-
208
-### Complete Organization Example
209
-
210
-<CodeGroup>
211
-```python Python
212
-from composio import Composio
213
-
214
-composio = Composio(
215
- api_key=os.environ.get('COMPOSIO_API_KEY')
216
-)
217
-
218
-# 1. Admin connects Slack for the entire organization
219
-async def connect_organization_to_slack(organization_id: str, admin_user_id: str):
220
- # Use organization ID as user_id in Composio
221
- connection_request = await composio.toolkits.authorize(organization_id, 'slack')
222
-
223
- # Store the connection request for the admin to complete
224
- await store_connection_request(organization_id, admin_user_id, connection_request)
225
-
226
- return connection_request.redirect_url
227
-
228
-# 2. Any user in the organization can use the connected tools
229
-async def send_slack_message(organization_id: str, channel: str, message: str):
230
- return await composio.tools.execute('SLACK_SEND_MESSAGE',
231
- user_id=organization_id, # Organization ID, not individual user ID
232
- arguments={
233
- 'channel': channel,
234
- 'text': message
235
- }
236
- )
237
-
238
-# 3. Check if organization has required connections
239
-async def get_organization_tools(organization_id: str):
240
- return await composio.tools.get(organization_id,
241
- toolkits=['slack', 'github', 'jira']
242
- )
243
-
244
-# Usage in your API endpoint
245
-@app.post('/api/slack/message')
246
-async def send_message():
247
- channel = request.json['channel']
248
- message = request.json['message']
249
- organization_id = request.user.organization_id # Get from your auth system
250
-
251
- # Verify user has permission to send messages for this organization
252
- if not await user_can_send_messages(request.user.id, organization_id):
253
- return jsonify({'error': 'Insufficient permissions'}), 403
254
-
255
- try:
256
- result = await send_slack_message(organization_id, channel, message)
257
- return jsonify(result.data)
258
- except Exception as error:
259
- return jsonify({'error': 'Failed to send message'}), 500
260
-```
261
-
262
-```typescript TypeScript
263
-import { Composio } from '@composio/core';
264
-
265
-const composio = new Composio({
266
- apiKey: process.env.COMPOSIO_API_KEY
267
-});
268
-
269
-// 1. Admin connects Slack for the entire organization
270
-async function connectOrganizationToSlack(organizationId: string, adminUserId: string) {
271
- // Use organization ID as userId in Composio
272
- const connectionRequest = await composio.toolkits.authorize(organizationId, 'slack');
273
-
274
- // Store the connection request for the admin to complete
275
- await storeConnectionRequest(organizationId, adminUserId, connectionRequest);
276
-
277
- return connectionRequest.redirectUrl;
278
-}
279
-
280
-// 2. Any user in the organization can use the connected tools
281
-async function sendSlackMessage(organizationId: string, channel: string, message: string) {
282
- return await composio.tools.execute('SLACK_SEND_MESSAGE', {
283
- userId: organizationId, // Organization ID, not individual user ID
284
- arguments: {
285
- channel: channel,
286
- text: message
287
- }
288
- });
289
-}
290
-
291
-// 3. Check if organization has required connections
292
-async function getOrganizationTools(organizationId: string) {
293
- return await composio.tools.get(organizationId, {
294
- toolkits: ['slack', 'github', 'jira']
295
- });
296
-}
297
-
298
-// Usage in your API endpoint
299
-app.post('/api/slack/message', async (req, res) => {
300
- const { channel, message } = req.body;
301
- const organizationId = req.user.organizationId; // Get from your auth system
302
-
303
- // Verify user has permission to send messages for this organization
304
- if (!(await userCanSendMessages(req.user.id, organizationId))) {
305
- return res.status(403).json({ error: 'Insufficient permissions' });
306
- }
307
-
308
- try {
309
- const result = await sendSlackMessage(organizationId, channel, message);
310
- res.json(result.data);
311
- } catch (error) {
312
- res.status(500).json({ error: 'Failed to send message' });
313
- }
314
-});
315
-```
316
-</CodeGroup>
317
-
318
-## 🚨 The `default` User ID
319
-
320
-The `default` userId refers to the default account of your Composio project and should **only be used for**:
321
-
322
-- **Testing and development** environments
323
-- **Single-user applications** where external users don't connect their own accounts
324
-- **Internal tools** where all operations are performed by your system
325
-- **Learning and experimentation**
326
-
327
-### When `default` is Appropriate
328
-
329
-<CodeGroup>
330
-```python Python
331
-# ✅ Good uses for 'default'
332
-# 1. Development and testing
333
-if os.environ.get('NODE_ENV') == 'development':
334
- tools = await composio.tools.get('default', toolkits=['github'])
335
-
336
-# 2. Single-user applications
337
-single_user_app = await composio.tools.execute('HACKERNEWS_GET_USER',
338
- user_id='default',
339
- arguments={'user_id': 'pg'}
340
-)
341
-
342
-# 3. Internal automation scripts
343
-internal_script = await composio.tools.execute('GITHUB_CREATE_ISSUE',
344
- user_id='default',
345
- arguments={} # internal tool usage
346
-)
347
-```
348
-
349
-```typescript TypeScript
350
-// ✅ Good uses for 'default'
351
-// 1. Development and testing
352
-if (process.env.NODE_ENV === 'development') {
353
- const tools = await composio.tools.get('default', { toolkits: ['github'] });
354
-}
355
-
356
-// 2. Single-user applications
357
-const singleUserApp = await composio.tools.execute('HACKERNEWS_GET_USER', {
358
- userId: 'default',
359
- arguments: { userId: 'pg' }
360
-});
361
-
362
-// 3. Internal automation scripts
363
-const internalScript = await composio.tools.execute('GITHUB_CREATE_ISSUE', {
364
- userId: 'default',
365
- arguments: { /* internal tool usage */ }
366
-});
367
-```
368
-</CodeGroup>
369
-
370
-### When NOT to Use `default`
371
-
372
-<CodeGroup>
373
-```python Python
374
-# ❌ NEVER use 'default' in production multi-user apps
375
-@app.post('/api/github/repos')
376
-async def list_repos():
377
- # This would expose other users' data!
378
- repos = await composio.tools.execute('GITHUB_LIST_REPOS',
379
- user_id='default', # ❌ Wrong! Use request.user.id
380
- arguments={}
381
- )
382
-
383
-# ❌ Don't use 'default' for user-specific operations
384
-user_email = await composio.tools.execute('GMAIL_SEND_EMAIL',
385
- user_id='default', # ❌ Wrong! This could send from wrong account
386
- arguments={
387
- 'to': 'user@example.com',
388
- 'subject': 'Personal message'
389
- }
390
-)
391
-```
392
-
393
-```typescript TypeScript
394
-// ❌ NEVER use 'default' in production multi-user apps
395
-app.post('/api/github/repos', async (req, res) => {
396
- // This would expose other users' data!
397
- const repos = await composio.tools.execute('GITHUB_LIST_REPOS', {
398
- userId: 'default', // ❌ Wrong! Use req.user.id
399
- arguments: {}
400
- });
401
-});
402
-
403
-// ❌ Don't use 'default' for user-specific operations
404
-const userEmail = await composio.tools.execute('GMAIL_SEND_EMAIL', {
405
- userId: 'default', // ❌ Wrong! This could send from wrong account
406
- arguments: {
407
- to: 'user@example.com',
408
- subject: 'Personal message'
409
- }
410
-});
411
-```
412
-</CodeGroup>
413
-
414
-## Security Best Practices
415
-
416
-### 1. **Always Validate User IDs**
417
-
418
-<CodeGroup>
419
-```python Python
420
-# ✅ Validate user IDs before using them
421
-def validate_user_id(user_id: str, authenticated_user: Any) -> str:
422
- # Ensure the user can only access their own data
423
- if user_id != authenticated_user.id:
424
- raise ValueError('Unauthorized: Cannot access other user data')
425
- return user_id
426
-
427
-@app.post('/api/tools/execute')
428
-async def execute_tool():
429
- user_id = validate_user_id(request.json['user_id'], request.user)
430
-```
431
-
432
-```typescript TypeScript
433
-// ✅ Validate user IDs before using them
434
-function validateUserId(userId: string, authenticatedUser: any) {
435
- // Ensure the user can only access their own data
436
- if (userId !== authenticatedUser.id) {
437
- throw new Error('Unauthorized: Cannot access other user data');
438
- }
439
- return userId;
440
-}
441
-
442
-app.post('/api/tools/execute', async (req, res) => {
443
- const userId = validateUserId(req.body.userId, req.user);
444
- // ... proceed with execution
445
-});
446
-```
447
-</CodeGroup>
448
-
449
-### 2. **Integrate with Your Auth System**
450
-
451
-<CodeGroup>
452
-```python Python
453
-# ✅ Integrate with your existing auth
454
-def authenticate_user(request):
455
- token = request.headers.get('authorization')
456
- user = verify_jwt(token)
457
-
458
- if not user:
459
- return jsonify({'error': 'Unauthorized'}), 401
460
-
461
- request.user = user
462
- return None
463
-
464
-@app.use('/api/composio')
465
-def auth_middleware():
466
- return authenticate_user(request)
467
-
468
-@app.post('/api/composio/execute')
469
-async def execute_tool():
470
- # request.user is guaranteed to be authenticated
471
- result = await composio.tools.execute(request.json['tool_slug'],
472
- user_id=request.user.id, # Use authenticated user's ID
473
- arguments=request.json['arguments']
474
- )
475
-
476
- return jsonify(result)
477
-```
478
-
479
-```typescript TypeScript
480
-// ✅ Integrate with your existing auth
481
-const authenticateUser = async (req, res, next) => {
482
- const token = req.headers.authorization;
483
- const user = await verifyJWT(token);
484
-
485
- if (!user) {
486
- return res.status(401).json({ error: 'Unauthorized' });
487
- }
488
-
489
- req.user = user;
490
- next();
491
-};
492
-
493
-app.use('/api/composio', authenticateUser);
494
-
495
-app.post('/api/composio/execute', async (req, res) => {
496
- // req.user is guaranteed to be authenticated
497
- const result = await composio.tools.execute(req.body.toolSlug, {
498
- userId: req.user.id, // Use authenticated user's ID
499
- arguments: req.body.arguments
500
- });
501
-
502
- res.json(result);
503
-});
504
-```
505
-</CodeGroup>
506
-
507
-### 3. **Never Expose User IDs in Client Code**
508
-
509
-<CodeGroup>
510
-```python Python
511
-# ❌ Don't expose user IDs to the client
512
-client_config = {
513
- 'user_id': user.id, # ❌ Exposed to client
514
- 'api_key': 'composio-key' # ❌ Never expose API keys
515
-}
516
-
517
-# ✅ Keep user IDs on the server
518
-@app.post('/api/user/tools')
519
-async def get_user_tools():
520
- # User ID is determined server-side from authentication
521
- tools = await composio.tools.get(request.user.id, request.json['filters'])
522
- return jsonify(tools)
523
-```
524
-
525
-```typescript TypeScript
526
-// ❌ Don't expose user IDs to the client
527
-const clientConfig = {
528
- userId: user.id, // ❌ Exposed to client
529
- apiKey: 'composio-key' // ❌ Never expose API keys
530
-};
531
-
532
-// ✅ Keep user IDs on the server
533
-app.post('/api/user/tools', async (req, res) => {
534
- // User ID is determined server-side from authentication
535
- const tools = await composio.tools.get(req.user.id, req.body.filters);
536
- res.json(tools);
537
-});
538
-```
539
-</CodeGroup>
540
-
541
-## Implementation Examples
542
-
543
-### Express.js Application
544
-
545
-<CodeGroup>
546
-```python Python
547
-from flask import Flask, request, jsonify
548
-from composio import Composio
549
-
550
-app = Flask(__name__)
551
-composio = Composio(api_key=os.environ.get('COMPOSIO_API_KEY'))
552
-
553
-# Middleware to ensure user authentication
554
-def require_auth():
555
- if not request.user:
556
- return jsonify({'error': 'Authentication required'}), 401
557
- return None
558
-
559
-# Get user's available tools
560
-@app.route('/api/tools', methods=['GET'])
561
-@require_auth
562
-async def get_tools():
563
- try:
564
- tools = await composio.tools.get(request.user.id,
565
- toolkits=request.args.get('toolkits', '').split(',') if request.args.get('toolkits') else []
566
- )
567
- return jsonify(tools)
568
- except Exception as error:
569
- return jsonify({'error': str(error)}), 500
570
-
571
-# Execute tool for user
572
-@app.route('/api/tools/execute', methods=['POST'])
573
-@require_auth
574
-async def execute_tool():
575
- try:
576
- result = await composio.tools.execute(request.json['tool_slug'],
577
- user_id=request.user.id, # Always use authenticated user's ID
578
- arguments=request.json['arguments'],
579
- connected_account_id=request.json.get('connected_account_id')
580
- )
581
-
582
- return jsonify(result)
583
- except Exception as error:
584
- return jsonify({'error': str(error)}), 500
585
-```
586
-
587
-```typescript TypeScript
588
-import express from 'express';
589
-import { Composio } from '@composio/core';
590
-
591
-const app = express();
592
-const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
593
-
594
-// Middleware to ensure user authentication
595
-const requireAuth = (req, res, next) => {
596
- if (!req.user) {
597
- return res.status(401).json({ error: 'Authentication required' });
598
- }
599
- next();
600
-};
601
-
602
-// Get user's available tools
603
-app.get('/api/tools', requireAuth, async (req, res) => {
604
- try {
605
- const tools = await composio.tools.get(req.user.id, {
606
- toolkits: req.query.toolkits?.split(',') || []
607
- });
608
- res.json(tools);
609
- } catch (error) {
610
- res.status(500).json({ error: error.message });
611
- }
612
-});
613
-
614
-// Execute tool for user
615
-app.post('/api/tools/execute', requireAuth, async (req, res) => {
616
- try {
617
- const result = await composio.tools.execute(req.body.toolSlug, {
618
- userId: req.user.id, // Always use authenticated user's ID
619
- arguments: req.body.arguments,
620
- connectedAccountId: req.body.connectedAccountId
621
- });
622
-
623
- res.json(result);
624
- } catch (error) {
625
- res.status(500).json({ error: error.message });
626
- }
627
-});
628
-```
629
-</CodeGroup>
630
-
631
-### Next.js API Routes
632
-
633
-<CodeGroup>
634
-```python Python
635
-# pages/api/composio/tools.py
636
-from fastapi import FastAPI, Depends, HTTPException
637
-from composio import Composio
638
-from auth import get_server_session
639
-
640
-app = FastAPI()
641
-composio = Composio(api_key=os.environ.get('COMPOSIO_API_KEY'))
642
-
643
-async def get_session(request):
644
- session = await get_server_session(request)
645
- if not session or not session.user:
646
- raise HTTPException(status_code=401, detail='Unauthorized')
647
- return session
648
-
649
-@app.get('/api/composio/tools')
650
-async def handle_get(request, session = Depends(get_session)):
651
- try:
652
- tools = await composio.tools.get(session.user.id,
653
- toolkits=request.query_params.get('toolkits', '').split(',') if request.query_params.get('toolkits') else []
654
- )
655
- return tools
656
- except Exception as error:
657
- raise HTTPException(status_code=500, detail=str(error))
658
-
659
-@app.post('/api/composio/tools')
660
-async def handle_post(request, session = Depends(get_session)):
661
- try:
662
- result = await composio.tools.execute(request.json['tool_slug'],
663
- user_id=session.user.id, # Use session user ID
664
- arguments=request.json['arguments']
665
- )
666
- return result
667
- except Exception as error:
668
- raise HTTPException(status_code=500, detail=str(error))
669
-```
670
-
671
-```typescript TypeScript
672
-// pages/api/composio/tools.ts
673
-import { Composio } from '@composio/core';
674
-import { getServerSession } from 'next-auth';
675
-
676
-const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
677
-
678
-export default async function handler(req, res) {
679
- // Get authenticated user from NextAuth
680
- const session = await getServerSession(req, res);
681
-
682
- if (!session?.user) {
683
- return res.status(401).json({ error: 'Unauthorized' });
684
- }
685
-
686
- if (req.method === 'GET') {
687
- try {
688
- const tools = await composio.tools.get(session.user.id, {
689
- toolkits: req.query.toolkits?.split(',') || []
690
- });
691
- res.json(tools);
692
- } catch (error) {
693
- res.status(500).json({ error: error.message });
694
- }
695
- }
696
-
697
- if (req.method === 'POST') {
698
- try {
699
- const result = await composio.tools.execute(req.body.toolSlug, {
700
- userId: session.user.id, // Use session user ID
701
- arguments: req.body.arguments
702
- });
703
- res.json(result);
704
- } catch (error) {
705
- res.status(500).json({ error: error.message });
706
- }
707
- }
708
-}
709
-```
710
-</CodeGroup>
711
-
712
-## Common Mistakes and Solutions
713
-
714
-### Mistake 1: Using `default` in Production
715
-
716
-<CodeGroup>
717
-```python Python
718
-# ❌ Wrong - using default in production
719
-result = await composio.tools.execute('GMAIL_SEND_EMAIL',
720
- user_id='default',
721
- arguments={'to': 'user@example.com', 'subject': 'Test'}
722
-)
723
-
724
-# ✅ Correct - use actual user ID
725
-result = await composio.tools.execute('GMAIL_SEND_EMAIL',
726
- user_id=request.user.id,
727
- arguments={'to': 'user@example.com', 'subject': 'Test'}
728
-)
729
-```
730
-
731
-```typescript TypeScript
732
-// ❌ Wrong - using default in production
733
-const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
734
- userId: 'default',
735
- arguments: { to: 'user@example.com', subject: 'Test' }
736
-});
737
-
738
-// ✅ Correct - use actual user ID
739
-const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
740
- userId: req.user.id,
741
- arguments: { to: 'user@example.com', subject: 'Test' }
742
-});
743
-```
744
-</CodeGroup>
745
-
746
-### Mistake 2: Trusting Client-Provided User IDs
747
-
748
-<CodeGroup>
749
-```python Python
750
-# ❌ Wrong - trusting client data
751
-@app.post('/api/execute')
752
-async def execute():
753
- result = await composio.tools.execute(request.json['tool_slug'],
754
- user_id=request.json['user_id'], # ❌ Client could provide any user ID!
755
- arguments=request.json['arguments']
756
- )
757
-
758
-# ✅ Correct - use server-side authentication
759
-@app.post('/api/execute')
760
-@require_auth
761
-async def execute():
762
- result = await composio.tools.execute(request.json['tool_slug'],
763
- user_id=request.user.id, # ✅ From authenticated session
764
- arguments=request.json['arguments']
765
- )
766
-```
767
-
768
-```typescript TypeScript
769
-// ❌ Wrong - trusting client data
770
-app.post('/api/execute', (req, res) => {
771
- const result = await composio.tools.execute(req.body.toolSlug, {
772
- userId: req.body.userId, // ❌ Client could provide any user ID!
773
- arguments: req.body.arguments
774
- });
775
-});
776
-
777
-// ✅ Correct - use server-side authentication
778
-app.post('/api/execute', requireAuth, (req, res) => {
779
- const result = await composio.tools.execute(req.body.toolSlug, {
780
- userId: req.user.id, // ✅ From authenticated session
781
- arguments: req.body.arguments
782
- });
783
-});
784
-```
785
-</CodeGroup>
786
-
787
-### Mistake 3: Inconsistent User ID Format
788
-
789
-<CodeGroup>
790
-```python Python
791
-# ❌ Wrong - mixing different formats
792
-user_id1 = user.email # "user@example.com"
793
-user_id2 = user.id # "12345"
794
-user_id3 = user.username # "john_doe"
795
-
796
-# ✅ Correct - consistent format throughout app
797
-user_id = user.id # Always use the same property
798
-```
799
-
800
-```typescript TypeScript
801
-// ❌ Wrong - mixing different formats
802
-const userId1 = user.email; // "user@example.com"
803
-const userId2 = user.id; // "12345"
804
-const userId3 = user.username; // "john_doe"
805
-
806
-// ✅ Correct - consistent format throughout app
807
-const userId = user.id; // Always use the same property
808
-```
809
-</CodeGroup>
810
-
811
-## User ID Patterns Summary
812
-
813
-| Pattern | Use Case | Example | Security Level |
814
-|---------|----------|---------|----------------|
815
-| Database UUID | Production apps | `550e8400-e29b-41d4-a716-446655440000` | ✅ High |
816
-| Username | Simple apps | `john_doe_123` | ✅ Medium |
817
-| Organization ID | Enterprise | `org_acme_corp` | ✅ High |
818
-| Email | Not recommended | `user@example.com` | ⚠️ Medium |
819
-| `default` | Testing only | `default` | ❌ Low |
820
-
821
-## Key Takeaways
822
-
823
-1. **User IDs are the foundation** of Composio's security model
824
-2. **Use your database primary keys** for best security and consistency
825
-3. **Never use `default` in production** multi-user applications
826
-4. **Always validate user IDs** against your authentication system
827
-5. **Organization IDs** are perfect for enterprise/team applications
828
-6. **Keep user IDs server-side** and never expose them to clients
829
-
830
----
831
-
832
-**🔐 Remember**: User IDs are your security boundary. Get this right, and everything else becomes much easier and more secure.
\ No newline at end of file
fern/pages/src/get-started/core-concepts.mdx
deleted
-565
@@ -1,565 +0,0 @@
1
----
2
-title: Core Concepts
3
-subtitle: Overview of the core concepts of Composio
4
-image: 'https://og.composio.dev/api/og?title=Core%20Concepts' # image for socials
5
-keywords: ''
6
-hide-nav-links: false
7
----
8
-
9
-Understanding Composio's core concepts is essential for building robust applications. This guide explains the fundamental building blocks and how they work together to provide seamless integration with external services.
10
-
11
-## Essential Concepts
12
-
13
-### 1. **User IDs** - The Foundation
14
-
15
-User IDs are the cornerstone of Composio's security model. Every operation requires a User ID to ensure proper data isolation. You can use the default user ID `default` for public APIs, or create a user ID for each user in your application.
16
-
17
-<CodeGroup>
18
-```python Python
19
-# ✅ Each user has their own isolated context
20
-user_a_tools = await composio.tools.get('user_a', toolkits=['github'])
21
-user_b_tools = await composio.tools.get('user_b', toolkits=['github'])
22
-```
23
-
24
-```typescript TypeScript
25
-// ✅ Each user has their own isolated context
26
-const userATools = await composio.tools.get('user_a', { toolkits: ['github'] });
27
-const userBTools = await composio.tools.get('user_b', { toolkits: ['github'] });
28
-```
29
-</CodeGroup>
30
-
31
-**Why User IDs Matter:**
32
-
33
-- **Security**: Prevents users from accessing each other's data
34
-- **Isolation**: Each user's connected accounts are separate
35
-- **Scaling**: Supports multi-tenant applications
36
-- **Compliance**: Meets data privacy requirements
37
-
38
-[**→ Learn more about User IDs**](./user-ids.md)
39
-
40
----
41
-
42
-### 2. **Tools** - Individual Actions
43
-
44
-Tools are specific actions you can perform, like "Get GitHub Repository" or "Send Email". Each tool has defined inputs and outputs.
45
-
46
-<CodeGroup>
47
-```python Python
48
-# A tool execution
49
-result = await composio.tools.execute('GITHUB_GET_REPO',
50
- user_id='user_123',
51
- arguments={
52
- 'owner': 'composio',
53
- 'repo': 'sdk'
54
- }
55
-)
56
-```
57
-
58
-```typescript TypeScript
59
-// A tool execution
60
-const result = await composio.tools.execute('GITHUB_GET_REPO', {
61
- userId: 'user_123',
62
- arguments: {
63
- owner: 'composio',
64
- repo: 'sdk',
65
- },
66
-});
67
-```
68
-</CodeGroup>
69
-
70
-**Tool Properties:**
71
-
72
-- **Slug**: Unique identifier (e.g., `GITHUB_GET_REPO`)
73
-- **Input Parameters**: What data the tool needs
74
-- **Output**: What data the tool returns
75
-- **Authentication**: Whether the tool requires user authorization
76
-
77
----
78
-
79
-### 3. **Toolkits** - Collections of Tools
80
-
81
-Toolkits group related tools from the same service. For example, the GitHub toolkit contains tools for repositories, issues, pull requests, and more.
82
-
83
-<CodeGroup>
84
-```python Python
85
-# Get all tools from the GitHub toolkit
86
-github_tools = await composio.tools.get('user_123',
87
- toolkits=['github']
88
-)
89
-
90
-# Available toolkits include: gmail, slack, notion, hubspot, salesforce, etc.
91
-```
92
-
93
-```typescript TypeScript
94
-// Get all tools from GitHub toolkit
95
-const githubTools = await composio.tools.get('user_123', {
96
- toolkits: ['github'],
97
-});
98
-
99
-// Available toolkits include: gmail, slack, notion, hubspot, salesforce, etc.
100
-```
101
-</CodeGroup>
102
-
103
-**Popular Toolkits:**
104
-
105
-- **GitHub**: Repository management, issues, PRs
106
-- **Gmail**: Email sending, reading, searching
107
-- **Slack**: Messaging, channels, user management
108
-- **Google Calendar**: Event management, scheduling
109
-- **Notion**: Database operations, page creation
110
-
111
-[**→ Explore Tools & Toolkits**](./tools-and-toolkits.md)
112
-
113
----
114
-
115
-### 4. **Connected Accounts** - User Authorizations
116
-
117
-Connected Accounts represent a user's authorized connection to an external service. Users must authorize access before tools can act on their behalf.
118
-
119
-<CodeGroup>
120
-```python Python
121
-# User authorizes GitHub access
122
-connection_request = await composio.connected_accounts.initiate('user_123', 'ac_authconfig_id')
123
-
124
-# After user completes OAuth flow
125
-connected_account = await composio.connected_accounts.wait_for_connection(connection_request.id)
126
-
127
-# Now tools can access user's GitHub data
128
-repos = await composio.tools.execute('GITHUB_LIST_REPOS',
129
- user_id='user_123',
130
- connected_account_id=connected_account.id
131
-)
132
-```
133
-
134
-```typescript TypeScript
135
-// User authorizes GitHub access
136
-const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'ac_authconfig_id');
137
-
138
-// After user completes OAuth flow
139
-const connectedAccount = await composio.connectedAccounts.waitForConnection(connectionRequest.id);
140
-
141
-// Now tools can access user's GitHub data
142
-const repos = await composio.tools.execute('GITHUB_LIST_REPOS', {
143
- userId: 'user_123',
144
- connectedAccountId: connectedAccount.id,
145
-});
146
-```
147
-</CodeGroup>
148
-
149
-**Connection Types:**
150
-
151
-- **OAuth2**: Most common (GitHub, Google, Slack)
152
-- **API Keys**: For services like OpenAI, Anthropic
153
-- **Basic Auth**: Username/password authentication
154
-- **Custom**: Service-specific authentication methods
155
-
156
-[**→ Learn about Connected Accounts**](./connected-accounts.md)
157
-
158
----
159
-
160
-### 5. **Auth Configs** - Authentication Templates
161
-
162
-Auth Configs define how authentication works for each toolkit. They specify the authentication method and required credentials.
163
-
164
-<CodeGroup>
165
-```python Python
166
-# Create a custom auth config for GitHub
167
-auth_config = await composio.auth_configs.create('github', {
168
- 'type': 'use_composio_managed_auth',
169
- 'name': 'My GitHub Integration'
170
-})
171
-```
172
-
173
-```typescript TypeScript
174
-// Create a custom auth config for GitHub
175
-const authConfig = await composio.authConfigs.create('github', {
176
- type: 'use_composio_managed_auth',
177
- name: 'My GitHub Integration',
178
-});
179
-```
180
-</CodeGroup>
181
-
182
-**Auth Config Types:**
183
-
184
-- **Composio Managed**: Composio handles OAuth apps and credentials
185
-- **User Credentials**: Users provide their own API keys/credentials
186
-- **Custom Auth**: Custom authentication flows
187
-- **No Auth**: For public APIs that don't require authentication
188
-
189
-[**→ Understanding Auth Configs**](./auth-configs.md)
190
-
191
----
192
-
193
-### 6. **Providers** - AI Platform Integration
194
-
195
-Providers adapt Composio tools for different AI platforms, handling the formatting and execution patterns each platform expects.
196
-
197
-<CodeGroup>
198
-```python Python
199
-from composio.providers.openai import OpenAIProvider
200
-from composio.providers.langchain import LangChainProvider
201
-
202
-# OpenAI Provider (non-agentic)
203
-openai_composio = Composio(
204
- provider=OpenAIProvider()
205
-)
206
-
207
-# LangChain Provider (agentic)
208
-langchain_composio = Composio(
209
- provider=LangChainProvider()
210
-)
211
-```
212
-
213
-```typescript TypeScript
214
-import { OpenAIProvider } from '@composio/openai';
215
-import { LangChainProvider } from '@composio/langchain';
216
-
217
-// OpenAI Provider (non-agentic)
218
-const openaiComposio = new Composio({
219
- provider: new OpenAIProvider(),
220
-});
221
-
222
-// LangChain Provider (agentic)
223
-const langchainComposio = new Composio({
224
- provider: new LangChainProvider(),
225
-});
226
-```
227
-</CodeGroup>
228
-
229
-**Provider Types:**
230
-
231
-- **Non-Agentic**: Format tools for external use (OpenAI, Anthropic, Google)
232
-- **Agentic**: Control tool execution internally (LangChain, Vercel AI)
233
-
234
-[**→ Learn about Providers**](./providers.md)
235
-
236
-## How It All Works Together
237
-
238
-Here's how these concepts work together in a typical application:
239
-
240
-### 1. **Setup Phase**
241
-
242
-<CodeGroup>
243
-```typescript TypeScript
244
-// Initialize with your preferred provider
245
-const composio = new Composio({
246
- apiKey: process.env.COMPOSIO_API_KEY,
247
- provider: new OpenAIProvider(),
248
-});
249
-```
250
-
251
-```python Python
252
-# Initialize with your preferred provider
253
-composio = Composio(
254
- api_key=os.environ.get('COMPOSIO_API_KEY'),
255
- provider=OpenAIProvider()
256
-)
257
-```
258
-</CodeGroup>
259
-
260
-### 2. **User Onboarding**
261
-
262
-<CodeGroup>
263
-```typescript TypeScript
264
-// When a user wants to connect GitHub
265
-const connectionRequest = await composio.connectedAccounts.initiate(
266
- user.id, // Your user's ID
267
- 'ac_123322' // Auth config ID to connect
268
-);
269
-
270
-// User completes OAuth flow in browser
271
-// Connection is established automatically
272
-```
273
-
274
-```python Python
275
-# When a user wants to connect GitHub
276
-connection_request = await composio.connected_accounts.initiate(
277
- user.id, # Your user's ID
278
- 'ac_123322' # Auth config ID to connect
279
-)
280
-
281
-# User completes OAuth flow in browser
282
-# Connection is established automatically
283
-```
284
-</CodeGroup>
285
-
286
-### 3. **Tool Execution**
287
-
288
-<CodeGroup>
289
-```typescript TypeScript
290
-// Execute tools on behalf of the user
291
-const result = await composio.tools.execute('GITHUB_CREATE_ISSUE', {
292
- userId: user.id,
293
- arguments: {
294
- owner: 'myorg',
295
- repo: 'myrepo',
296
- title: 'Bug Report',
297
- body: 'Description of the bug...',
298
- },
299
-});
300
-```
301
-
302
-```python Python
303
-# Execute tools on behalf of the user
304
-result = await composio.tools.execute('GITHUB_CREATE_ISSUE',
305
- user_id=user.id,
306
- arguments={
307
- 'owner': 'myorg',
308
- 'repo': 'myrepo',
309
- 'title': 'Bug Report',
310
- 'body': 'Description of the bug...'
311
- }
312
-)
313
-```
314
-</CodeGroup>
315
-
316
-### 4. **AI Integration**
317
-
318
-<CodeGroup>
319
-```typescript TypeScript
320
-// Use tools with AI models
321
-const tools = await composio.tools.get(user.id, {
322
- toolkits: ['github', 'slack'],
323
-});
324
-
325
-const completion = await openai.chat.completions.create({
326
- model: 'gpt-4',
327
- messages: [{ role: 'user', content: 'Create a GitHub issue and notify the team on Slack' }],
328
- tools: tools, // Composio tools formatted for OpenAI
329
-});
330
-```
331
-
332
-```python Python
333
-# Use tools with AI models
334
-tools = await composio.tools.get(user.id,
335
- toolkits=['github', 'slack']
336
-)
337
-
338
-completion = await openai.chat.completions.create(
339
- model='gpt-4',
340
- messages=[{'role': 'user', 'content': 'Create a GitHub issue and notify the team on Slack'}],
341
- tools=tools # Composio tools formatted for OpenAI
342
-)
343
-```
344
-</CodeGroup>
345
-
346
-## Key Patterns and Best Practices
347
-
348
-### 1. **User-Centric Design**
349
-
350
-<CodeGroup>
351
-```typescript TypeScript
352
-// ✅ Always scope operations to specific users
353
-const userTools = await composio.tools.get(userId, { toolkits: ['github'] });
354
-
355
-// ❌ Don't use 'default' in production
356
-const defaultTools = await composio.tools.get('default', { toolkits: ['github'] });
357
-```
358
-
359
-```python Python
360
-# ✅ Always scope operations to specific users
361
-user_tools = await composio.tools.get(user_id, toolkits=['github'])
362
-
363
-# ❌ Don't use 'default' in production
364
-default_tools = await composio.tools.get('default', toolkits=['github'])
365
-```
366
-</CodeGroup>
367
-
368
-### 2. **Error Handling**
369
-
370
-<CodeGroup>
371
-```typescript TypeScript
372
-try {
373
- const result = await composio.tools.execute('GITHUB_GET_REPO', {
374
- userId: user.id,
375
- arguments: { owner: 'composio', repo: 'sdk' },
376
- });
377
-
378
- if (result.successful) {
379
- // Handle success
380
- } else {
381
- // Handle tool-level errors
382
- console.error('Tool error:', result.error);
383
- }
384
-} catch (error) {
385
- // Handle SDK-level errors
386
- console.error('SDK error:', error.message);
387
-}
388
-```
389
-
390
-```python Python
391
-try:
392
- result = await composio.tools.execute('GITHUB_GET_REPO',
393
- user_id=user.id,
394
- arguments={'owner': 'composio', 'repo': 'sdk'}
395
- )
396
-
397
- if result.successful:
398
- # Handle success
399
- pass
400
- else:
401
- # Handle tool-level errors
402
- print('Tool error:', result.error)
403
-except Exception as error:
404
- # Handle SDK-level errors
405
- print('SDK error:', str(error))
406
-```
407
-</CodeGroup>
408
-
409
-### 3. **Connection Management**
410
-
411
-<CodeGroup>
412
-```typescript TypeScript
413
-// Check if user has required connections
414
-const accounts = await composio.connectedAccounts.list({
415
- userIds: [userId],
416
- toolkitSlugs: ['github'],
417
-});
418
-
419
-if (accounts.items.length === 0) {
420
- // Prompt user to connect GitHub
421
- const connection = await composio.toolkits.authorize(userId, 'github');
422
- // Redirect to connection.redirectUrl
423
-}
424
-```
425
-
426
-```python Python
427
-# Check if user has required connections
428
-accounts = await composio.connected_accounts.list(
429
- user_ids=[user_id],
430
- toolkit_slugs=['github']
431
-)
432
-
433
-if len(accounts.items) == 0:
434
- # Prompt user to connect GitHub
435
- connection = await composio.toolkits.authorize(user_id, 'github')
436
- # Redirect to connection.redirect_url
437
-```
438
-</CodeGroup>
439
-
440
-## Advanced Concepts
441
-
442
-### Custom Tools
443
-
444
-Create your own tools for services not yet supported:
445
-
446
-<CodeGroup>
447
-```typescript TypeScript
448
-const customTool = await composio.tools.createCustomTool({
449
- slug: 'MY_CUSTOM_TOOL',
450
- name: 'My Custom Tool',
451
- description: 'Does something specific',
452
- inputParameters: z.object({
453
- // Define the input parameters for the tool
454
- param1: z.string().describe('The first parameter'),
455
- param2: z.string().describe('The second parameter'),
456
- }),
457
- execute: async params => {
458
- // Your custom logic
459
- return { data: {}, successful: true, error: null };
460
- },
461
-});
462
-```
463
-
464
-```python Python
465
-custom_tool = await composio.tools.create_custom_tool(
466
- slug='MY_CUSTOM_TOOL',
467
- name='My Custom Tool',
468
- description='Does something specific',
469
- input_parameters=z.object({
470
- # Define the input parameters for the tool
471
- 'param1': z.string().describe('The first parameter'),
472
- 'param2': z.string().describe('The second parameter')
473
- }),
474
- execute=lambda params: {
475
- # Your custom logic
476
- 'data': {},
477
- 'successful': True,
478
- 'error': None
479
- }
480
-)
481
-```
482
-</CodeGroup>
483
-
484
-### MCP (Model Control Protocol)
485
-
486
-Expose tools to AI models through a standardized protocol:
487
-
488
-<CodeGroup>
489
-```typescript TypeScript
490
-const mcpServer = await composio.mcp.create('my-server', [
491
- {
492
- toolkit: 'github',
493
- authConfigId: 'auth_123',
494
- allowedTools: ['GITHUB_GET_REPO', 'GITHUB_CREATE_ISSUE'],
495
- },
496
-]);
497
-```
498
-
499
-```python Python
500
-mcp_server = await composio.mcp.create('my-server', [
501
- {
502
- 'toolkit': 'github',
503
- 'auth_config_id': 'auth_123',
504
- 'allowed_tools': ['GITHUB_GET_REPO', 'GITHUB_CREATE_ISSUE']
505
- }
506
-])
507
-```
508
-</CodeGroup>
509
-
510
-### Triggers
511
-
512
-React to real-time events from external services:
513
-
514
-<CodeGroup>
515
-```typescript TypeScript
516
-composio.triggers.subscribe(
517
- event => {
518
- console.log('New email received:', event.payload);
519
- },
520
- {
521
- toolkits: ['gmail'],
522
- triggerSlug: ['GMAIL_NEW_EMAIL'],
523
- }
524
-);
525
-```
526
-
527
-```python Python
528
-def handle_event(event):
529
- print('New email received:', event.payload)
530
-
531
-composio.triggers.subscribe(
532
- handle_event,
533
- toolkits=['gmail'],
534
- trigger_slug=['GMAIL_NEW_EMAIL']
535
-)
536
-```
537
-</CodeGroup>
538
-
539
-## Quick Reference
540
-
541
-| Concept | Purpose | Example |
542
-| --------------------- | ------------------- | ------------------- |
543
-| **User ID** | Identity & security | `'user_123'` |
544
-| **Tool** | Specific action | `'GITHUB_GET_REPO'` |
545
-| **Toolkit** | Service collection | `'github'` |
546
-| **Connected Account** | User authorization | OAuth to GitHub |
547
-| **Auth Config** | Auth template | GitHub OAuth app |
548
-| **Provider** | AI integration | OpenAI, LangChain |
549
-
550
-## Common Questions
551
-
552
-**Q: Can one user have multiple connected accounts for the same service?**
553
-A: Yes, but it requires explicitly allowing multiple connections when creating them.
554
-
555
-**Q: Do I need to store authentication tokens?**
556
-A: No, Composio manages all tokens securely. You only work with Connected Account IDs.
557
-
558
-**Q: Can I use tools without user authentication?**
559
-A: Some tools (like HackerNews) don't require authentication, but most do.
560
-
561
-**Q: How do I know which tools require authentication?**
562
-A: Tools that require authentication will throw an error if no connected account is provided.
563
-
564
-
565
-**💡 Remember**: These concepts work together to provide a secure, scalable, and flexible way to integrate external services into your applications. Start with the basics and gradually explore advanced features as your needs grow.