Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Add Authentication documentation section
Sushmithamallesh4f2f8e61d55f
diff --git a/fumadocs/content/docs/connected-accounts.mdx b/fumadocs/content/docs/connected-accounts.mdxnew file mode 100644index 000000000..909817fba--- /dev/null+++ b/fumadocs/content/docs/connected-accounts.mdx@@ -0,0 +1,299 @@+---+title: Connected Accounts+description: Manage and monitor user connections to toolkits+---++Connected accounts are authenticated connections between your users and toolkits. After users authenticate (see [Authenticating tools](/docs/authenticating-tools)), you can manage these accounts throughout their lifecycle.++Composio automatically handles token refresh and credential management. This guide covers manual operations: listing, retrieving, refreshing, enabling, disabling, and deleting accounts.++## List accounts++Retrieve all connected accounts with optional filters:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# List all accounts for a user+accounts = composio.connected_accounts.list(+ user_ids=[user_id]+)++# Filter by status+active_accounts = composio.connected_accounts.list(+ user_ids=[user_id],+ statuses=["ACTIVE"]+)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// List all accounts for a user+const accounts = await composio.connectedAccounts.list({+ userIds: [userId]+});++// Filter by status+const activeAccounts = await composio.connectedAccounts.list({+ userIds: [userId],+ statuses: ['ACTIVE']+});+```+ </Tab>+</Tabs>++## Get account details++Retrieve a connected account by ID:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+account = composio.connected_accounts.get(connected_account_id)++print(f"Status: {account.status}")+print(f"Toolkit: {account.toolkit.slug}")+```+ </Tab>+ <Tab value="TypeScript">+```typescript+const account = await composio.connectedAccounts.get(connectedAccountId);++console.log('Status:', account.status);+console.log('Toolkit:', account.toolkit.slug);+```+ </Tab>+</Tabs>++### Get account credentials++Get account credentials for use with your own tools:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Get the connected account's authentication state+if account.state:+ # The state contains the auth scheme and credentials+ auth_scheme = account.state.auth_scheme+ credentials = account.state.val++ print(f"Auth scheme: {auth_scheme}")+ print(f"Credentials: {credentials}")+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// Get the connected account's authentication state+if (account.state) {+ // The state contains the auth scheme and credentials+ const authScheme = account.state.authScheme;+ const credentials = account.state.val;++ console.log('Auth scheme:', authScheme);+ console.log('Credentials:', credentials);+}+```+ </Tab>+</Tabs>++<Callout type="warn">+If credentials return as `REDACTED` instead of actual values, the **Mask Connected Account Secrets** setting is enabled on your account. This setting redacts all sensitive credential data (tokens, secrets, API keys) for security purposes.++To view actual credentials, navigate to **Settings → Project Settings → Project Configuration** and disable "Mask Connected Account Secrets".+</Callout>++## Refresh credentials++Manually refresh credentials for a connected account:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+try:+ refreshed = composio.connected_accounts.refresh(connected_account_id)+ print(f"Redirect URL: {refreshed.redirect_url}")++ # Wait for the connection to be established+ composio.connected_accounts.wait_for_connection(refreshed.id)+except Exception as e:+ print(f"Failed to refresh tokens: {e}")+```+ </Tab>+ <Tab value="TypeScript">+```typescript+try {+ const refreshed = await composio.connectedAccounts.refresh(connectedAccountId);+ console.log('Redirect URL:', refreshed.redirect_url);++ // Wait for the connection to be established+ await composio.connectedAccounts.waitForConnection(refreshed.id);+} catch (error) {+ console.error('Failed to refresh tokens:', error);+}+```+ </Tab>+</Tabs>++## Enable and disable accounts++Change account status without deleting. Set to INACTIVE to pause access, or ACTIVE to restore. Useful for:+- Pausing access during subscription lapses+- Temporary disconnection++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Disable an account+disabled = composio.connected_accounts.disable(connected_account_id)+print(f"Account disabled status: {disabled.success}")++# Re-enable when needed+enabled = composio.connected_accounts.enable(connected_account_id)+print(f"Account enabled status: {enabled.success}")+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// Disable an account+const disabled = await composio.connectedAccounts.disable(connectedAccountId);+console.log('Account disabled status:', disabled.success);++// Re-enable when needed+const enabled = await composio.connectedAccounts.enable(connectedAccountId);+console.log('Account enabled status:', enabled.success);+```+ </Tab>+</Tabs>++<Callout type="warn">+INACTIVE accounts cannot execute tools. Tool execution will fail until the status is changed.+</Callout>++## Delete accounts++Permanently remove a connected account and revoke all credentials:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Delete a connected account+composio.connected_accounts.delete(connected_account_id)+print("Account deleted successfully")+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// Delete a connected account+await composio.connectedAccounts.delete(connectedAccountId);+console.log('Account deleted successfully');+```+ </Tab>+</Tabs>++<Callout type="warn">+Deletion is permanent. Users must re-authenticate to reconnect.+</Callout>++## Multiple accounts++Users can connect multiple accounts for the same toolkit (e.g., personal and work Gmail).++<Callout type="info">+Use `link()` for creating accounts, as it provides hosted authentication and allows multiple accounts by default. See [Connect Link authentication](/docs/authenticating-tools#hosted-authentication-connect-link).+</Callout>++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# First account+try:+ first_account = composio.connected_accounts.initiate(+ user_id=user_id,+ auth_config_id=auth_config_id+ )+ print(f"First account redirect URL: {first_account.redirect_url}")+ connected_first_account = first_account.wait_for_connection()+ print(f"First account status: {connected_first_account.status}")+except Exception as e:+ print(f"Error initiating first account: {e}")++# Second account - must explicitly allow multiple+try:+ second_account = composio.connected_accounts.initiate(+ user_id=user_id,+ auth_config_id=auth_config_id,+ allow_multiple=True # Required for additional accounts+ )+ print(f"Second account redirect URL: {second_account.redirect_url}")+ connected_second_account = second_account.wait_for_connection()+ print(f"Second account status: {connected_second_account.status}")+except Exception as e:+ print(f"Error initiating second account: {e}")+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// First account+try {+ const firstAccount = await composio.connectedAccounts.initiate(+ userId,+ authConfigId+ );+ console.log('First account redirect URL:', firstAccount.redirectUrl);+ const connectedFirstAccount = await firstAccount.waitForConnection();+ console.log('First account status:', connectedFirstAccount.status);+} catch (error) {+ console.error('Error initiating first account:', error);+}++// Second account - must explicitly allow multiple+try {+ const secondAccount = await composio.connectedAccounts.initiate(+ userId,+ authConfigId,+ {+ allowMultiple: true // Required for additional accounts+ }+ );+ console.log('Second account redirect URL:', secondAccount.redirectUrl);+ const connectedSecondAccount = await secondAccount.waitForConnection();+ console.log('Second account status:', connectedSecondAccount.status);+} catch (error) {+ console.error('Error initiating second account:', error);+}+```+ </Tab>+</Tabs>++### Execute with a specific account++When you have multiple accounts, specify which one to use with `connected_account_id`:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Execute tool with a specific connected account+result = composio.tools.execute(+ "GMAIL_GET_PROFILE",+ user_id=user_id,+ connected_account_id=connected_account_id, # Specify which account to use+ version="20251111_00",+ arguments={}+)+print(f"Tool executed: {result}")+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// Execute tool with a specific connected account+const result = await composio.tools.execute('GMAIL_GET_PROFILE', {+ userId: userId,+ connectedAccountId: connectedAccountId, // Specify which account to use+ version: '20251111_00',+ arguments: {}+});+console.log('Tool executed:', result);+```+ </Tab>+</Tabs>diff --git a/fumadocs/content/docs/custom-auth-configs.mdx b/fumadocs/content/docs/custom-auth-configs.mdxnew file mode 100644index 000000000..f79024845--- /dev/null+++ b/fumadocs/content/docs/custom-auth-configs.mdx@@ -0,0 +1,246 @@+---+title: Custom Auth Configs+description: Customize auth configs for any toolkit+---++Many toolkits support a level of customization for the auth config, specifically OAuth applications.++This guide will walk you through the process of customizing the auth config for toolkits where you can configure your own developer app.++## Creating a custom auth config++To create a custom auth config, click **Create Auth Config** in your dashboard, then navigate to **Authentication management** → **Manage authentication with custom credentials**.++You'll need to customize the auth config when you want to use different values than the defaults - such as your own subdomain, base URL, client ID, client secret, etc.++<Tabs items={['Example: PostHog', 'Example: Hubspot']}>+ <Tab value="Example: PostHog">+You may change the subdomain for the PostHog toolkit to match your own instance.++<Figure src="/images/custom-auth-posthog.png" alt="PostHog Auth Config Settings" caption="PostHog Auth Config Settings" size="sm" />+ </Tab>+ <Tab value="Example: Hubspot">+For Hubspot you may customize everything here. For each auth scheme there is a different set of fields.++If you choose to use your own developer app for the OAuth2 scheme, you will have to provide the client ID and client secret.++<Figure src="/images/custom-auth-hubspot.png" alt="Hubspot Auth Config Settings" caption="Hubspot Auth Config Settings" size="sm" />+ </Tab>+</Tabs>++Toolkits that support OAuth2 allow using your own developer app. This is the recommended approach for most cases.++<Callout type="info" title="Use your own developer app!">+We recommend using your own developer app for the OAuth2 scheme as it is more suited for production usage with many users and more granular control over scopes.++However, getting OAuth approvals takes time, so Composio provides a default developer app!+</Callout>++## OAuth2 Auth Configs++<Steps>+<Step>+### Generate the OAuth Client ID and Client Secret++To set up a custom OAuth config, you'll need the OAuth Client ID and Client Secret.++You can generate the client ID and client secret from your provider's OAuth configuration page.++Examples for Google and GitHub:++<Tabs items={['Google', 'GitHub']}>+ <Tab value="Google">+<Figure src="/images/google-oauth-config.png" alt="Google OAuth Configuration" caption="Google OAuth Configuration" size="sm" />+ </Tab>+ <Tab value="GitHub">+<Figure src="/images/github-oauth-config.png" alt="GitHub OAuth Configuration" caption="GitHub OAuth Configuration" size="sm" />+ </Tab>+</Tabs>+</Step>++<Step>+### Set the Authorized Redirect URI++When creating your OAuth app, make sure to configure the Authorized Redirect URI to point to the Composio callback URL below:++```+https://backend.composio.dev/api/v3/toolkits/auth/callback+```+</Step>++<Step>+### Create the auth config++Once you have the OAuth credentials, you can add them to the auth config in the dashboard.++1. Select the OAuth2 scheme.+2. Select the scopes to request from users. Default scopes are pre-filled for most apps.+3. Add the OAuth client ID and client secret for your developer app. Keep the redirect URL as is for now!+4. Click Create!++<Figure src="/images/integration-step-3-0.png" alt="Auth Config Settings" caption="Auth Config Settings" size="sm" />+</Step>+</Steps>++This auth config is now ready to be used in your application!++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Create a new connected account+connection_request = composio.connected_accounts.initiate(+ user_id="user_id",+ auth_config_id="ac_1234",+)+print(connection_request)++# Wait for the connection to be established+connected_account = connection_request.wait_for_connection()+print(connected_account)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+const connReq = await composio.connectedAccounts.initiate(userId, "ac_1234");++console.log(connReq.redirectUrl);++const connection = await composio.connectedAccounts.waitForConnection(+ connReq.id+);++console.log(connection);+```+ </Tab>+</Tabs>++### White-labeling the OAuth Consent Screen++By default the users will see an OAuth screen like the one below:++<Figure src="/images/oauth-branding.png" alt="Composio's Domain in OAuth Consent Screen" caption="Composio's Domain in OAuth Consent Screen" size="sm" />++The OAuth redirect URL is surfaced in some OAuth providers' consent screens. This may cause confusion for some users as that URL is not of the same domain as the application.++To remediate this:++<Steps>+<Step>+### Set the Authorized Redirect URI++Specify the Authorized Redirect URI to your own domain in the OAuth configuration.+For example:+```+https://yourdomain.com/api/composio-redirect+```+</Step>++<Step>+### Create a redirect logic++Create a redirect logic, either through your DNS or in your application to redirect that endpoint to `https://backend.composio.dev/api/v3/toolkits/auth/callback`++**Example: API Route for OAuth Redirect**++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+from fastapi import FastAPI+from fastapi.responses import RedirectResponse++from composio import Composio++# Create a FastAPI app+app = FastAPI()++# Create a Composio client+composio = Composio()++[email protected]("/authorize/{toolkit}")+def authorize_app(toolkit: str):+ # retrieve the user id from your app+ user_id = "<user_id>"++ # retrieve the auth config id from your app+ auth_config_id = "<auth_config_id>"++ # initiate the connection request+ connection_request = composio.connected_accounts.initiate(+ user_id=user_id,+ auth_config_id=auth_config_id,+ )+ return RedirectResponse(url=connection_request.redirect_url)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+import type { NextApiRequest, NextApiResponse } from 'next';++export default function handler(req: NextApiRequest, res: NextApiResponse) {+ // The target Composio endpoint that handles OAuth callbacks+ const composioEndpoint = 'https://backend.composio.dev/api/v3/toolkits/auth/callback';++ // Extract and preserve all query parameters+ const queryParams = new URLSearchParams();+ Object.entries(req.query).forEach(([key, value]) => {+ if (typeof value === 'string') {+ queryParams.append(key, value);+ }+ });++ // Redirect to Composio with all query parameters intact+ const redirectUrl = `${composioEndpoint}?${queryParams.toString()}`;+ res.redirect(302, redirectUrl);+}+```+ </Tab>+</Tabs>+</Step>++<Step>+### Create the auth config++Specify your custom redirect URI in the auth config settings!++<Figure src="/images/custom-redirect-uri.png" alt="Auth Config Settings" caption="Auth Config Settings" size="sm" />+</Step>+</Steps>++With this setup, you can use `https://yourdomain.com/api/composio-redirect` as your OAuth redirect URI, which will create a better user experience by keeping users on your domain during the OAuth flow.++<Accordions>+<Accordion title="How does this work?">++The custom OAuth config allows you to use your own domain in the OAuth consent screen instead of Composio's domain. Here's the core difference:++```mermaid+flowchart TD+ A[Your App initiates OAuth] --> B[User redirected to OAuth Provider]+ B --> C{Redirect URI Configuration}++ C -->|Direct Setup| D[Provider redirects to<br/>backend.composio.dev]+ C -->|Custom Domain| E[Provider redirects to<br/>yourdomain.com/api/composio-redirect]++ E --> F[Your endpoint forwards to<br/>backend.composio.dev]++ D --> G[Composio exchanges code for token]+ F --> G++ G --> H[Connection established]++ style E fill:#e1f5fe+ style F fill:#e1f5fe+ style C fill:#fff3e0+```++**Key Benefits:**++- **Custom Domain**: Users see your domain in OAuth consent screens, not Composio's+- **Same Security**: Your domain just forwards the OAuth callback - no token handling+- **Better UX**: Maintains brand consistency throughout the auth flow++The custom redirect endpoint is a simple passthrough that preserves all OAuth parameters while keeping users on your domain.++</Accordion>+</Accordions>diff --git a/fumadocs/content/docs/custom-auth-params.mdx b/fumadocs/content/docs/custom-auth-params.mdxnew file mode 100644index 000000000..5ba5be703--- /dev/null+++ b/fumadocs/content/docs/custom-auth-params.mdx@@ -0,0 +1,131 @@+---+title: Custom Auth Parameters+description: Inject custom credentials in headers or parameters+---++In cases where Composio is not being used for managing the auth but only for the tools, it is possible to use the `beforeExecute` hook to inject custom auth headers or parameters for a toolkit.++## Setup and Initialization++First, initialize the Composio SDK with your API key:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+from composio import Composio++composio = Composio()+```+ </Tab>+ <Tab value="TypeScript">+```typescript+import { Composio } from "@composio/core";++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});+```+ </Tab>+</Tabs>++## Creating the Auth Modifier Function++Define a function that modifies authentication parameters for specific toolkits. This function checks the toolkit name and adds custom authentication headers when needed.++<Card title="This is a Before Execute Modifier!" href="/docs/modify-tool-behavior/before-execution-modifiers">+Before Execute Modifiers are a way to modify the parameters of a tool before it is executed. In this case, they are useful for adding custom authentication headers or parameters to a tool.+</Card>++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+from composio import before_execute+from composio.types import ToolExecuteParams+++@before_execute(toolkits=["NOTION"])+def add_custom_auth(+ tool: str,+ toolkit: str,+ params: ToolExecuteParams,+) -> ToolExecuteParams:+ if params["custom_auth_params"] is None:+ params["custom_auth_params"] = {"parameters": []}++ params["custom_auth_params"]["parameters"].append(+ {+ "name": "x-api-key",+ "value": os.getenv("NOTION_API_KEY"),+ "in": "header",+ }+ )+ return params+```+ </Tab>+ <Tab value="TypeScript">+```typescript+const authModifier = (toolSlug: string, toolkitSlug: string, params: any) => {+ // Add authentication parameters for specific toolkits+ if (toolkitSlug === "NOTION") {+ if (!params.customAuthParams) {+ params.customAuthParams = {};+ }++ if (!params.customAuthParams.parameters) {+ params.customAuthParams.parameters = [];+ }++ // Add an API key to the headers+ params.customAuthParams.parameters.push({+ in: "header",+ name: "X-API-Key",+ value: process.env.CUSTOM_API_KEY,+ });+ }+ return params;+};+```+ </Tab>+</Tabs>++## Executing Tools with Custom Auth++Execute the tool using the custom authentication modifier. The `beforeExecute` hook allows you to modify parameters before the tool runs.++Following is an example of how to execute a tool with a custom authentication modifier for Completion Providers.++For Agentic Providers, read about [Modifying tool inputs](/docs/modify-tool-behavior/before-execution-modifiers).++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+result = composio.tools.execute(+ slug="NOTION_GET_DATABASE_ITEMS",+ user_id="default",+ arguments={},+ modifiers=[+ add_custom_auth,+ ],+)+print(result)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+const result = await composio.tools.execute(+ "NOTION_GET_DATABASE_ITEMS",+ {+ userId: "sid",+ arguments: {+ database_id: "1234567890",+ },+ },+ {+ beforeExecute: authModifier,+ }+);++console.log(JSON.stringify(result, null, 2));+```+ </Tab>+</Tabs>diff --git a/fumadocs/content/docs/meta.json b/fumadocs/content/docs/meta.jsonindex 533eed04f..fff7db9b6 100644--- a/fumadocs/content/docs/meta.json+++ b/fumadocs/content/docs/meta.json@@ -11,6 +11,12 @@"using-triggers","modify-tool-behavior","custom-tools",- "toolkit-versioning"+ "toolkit-versioning",+ "---Authentication---",+ "custom-auth-configs",+ "programmatic-auth-configs",+ "custom-auth-params",+ "connected-accounts",+ "user-management"]}diff --git a/fumadocs/content/docs/programmatic-auth-configs.mdx b/fumadocs/content/docs/programmatic-auth-configs.mdxnew file mode 100644index 000000000..ae1c4fe83--- /dev/null+++ b/fumadocs/content/docs/programmatic-auth-configs.mdx@@ -0,0 +1,239 @@+---+title: Programmatic Auth Configs+description: Create auth configs programmatically+---++Auth configs are created once and reused many times. However, when managing multiple toolkits, you may want to create auth configs programmatically.++- When creating and destroying auth configs multiple times in your app's lifecycle.+- When creating auth configs for your users' users.++## OAuth2 based apps++### Using Composio Default Auth++Since OAuth2 is the most common authentication type for applications, Composio provides managed auth for most OAuth2 based applications. This is to speed up development and prototyping. This means you don't have to provide your own OAuth credentials.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+from composio import Composio++composio = Composio()++# Use composio managed auth+auth_config = composio.auth_configs.create(+ toolkit="github",+ options={+ "type": "use_composio_managed_auth",+ },+)+print(auth_config)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+import { Composio } from "@composio/core";++const composio = new Composio();++const authConfig = await composio.authConfigs.create("GITHUB", {+ name: "GitHub",+ type: "use_composio_managed_auth",+});++console.log(authConfig);+```+ </Tab>+</Tabs>++The returned `auth_config_id` should be stored securely in your database for future use to be created and destroyed multiple times.++You can also provide your own authentication details. The required `credentials` and `authScheme` depend on the auth type.++### Using your own OAuth2 credentials++Setting up and using your own OAuth2 credentials is the recommended way when going to production or expecting high usage.++In this example, we're using our own OAuth2 client ID and secret to create the auth config for Notion.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Use custom auth+auth_config = composio.auth_configs.create(+ toolkit="notion",+ options={+ "name": "Notion Auth",+ "type": "use_custom_auth",+ "auth_scheme": "OAUTH2",+ "credentials": {+ "client_id": "1234567890",+ "client_secret": "1234567890",+ "oauth_redirect_uri": "https://backend.composio.dev/api/v3/toolkits/auth/callback",+ },+ },+)+print(auth_config)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+const authConfig = await composio.authConfigs.create("NOTION", {+ name: "Notion",+ type: "use_custom_auth",+ credentials: {+ client_id: "1234567890",+ client_secret: "1234567890",+ oauth_redirect_uri: "https://backend.composio.dev/api/v3/toolkits/auth/callback",+ },+ authScheme: "OAUTH2",+});++console.log(authConfig);+```+ </Tab>+</Tabs>++<Callout type="info">+You can specify a custom redirect URI by including the `oauth_redirect_uri` parameter in the credentials object. If not provided, Composio uses the default redirect URI.+</Callout>++**Specifying the authorized redirect URI**++The process of setting up your own OAuth2 credentials usually involves generating a client ID and secret and specifying the **authorized redirect URI** in the OAuth configuration.++<Callout type="info">+The **authorized redirect URI** is the URI that captures the OAuth code that is returned to the app.+</Callout>++While doing so, you must ensure to set the **authorized redirect URI** in the OAuth configuration to:++```+https://backend.composio.dev/api/v3/toolkits/auth/callback+```++<Tabs items={['GitHub', 'Google']}>+ <Tab value="GitHub">+<Figure src="/images/github-callback.png" alt="Developer settings for GitHub OAuth2 app" caption="Redirect URI for GitHub" size="sm" />+ </Tab>+ <Tab value="Google">+<Figure src="/images/google-callback.png" alt="Developer settings for Google OAuth2 app" caption="Redirect URI for Google" size="sm" />+ </Tab>+</Tabs>++### Specifying scopes++Composio requests a set of appropriate default OAuth2 scopes for each toolkit wherever possible. However, you can override or modify these scopes by passing a `scopes` field to the `credentials` object.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+from composio import Composio++composio = Composio()++response = composio.auth_configs.create(+ toolkit="HUBSPOT",+ options={+ "name": "HubspotConfig",+ "authScheme": "OAUTH2",+ "type": "use_composio_managed_auth",+ "credentials": {+ "scopes": "sales-email-read,tickets"+ }+ }+)++print(response.id)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+import { Composio } from "@composio/core";++const composio = new Composio();++const authConfig = await composio.authConfigs.create("HUBSPOT", {+ name: "HubspotConfig",+ type: "use_composio_managed_auth",+ credentials: {+ scopes: "sales-email-read,tickets",+ },+});++console.log(authConfig);+```+ </Tab>+</Tabs>++## Other auth types++Composio supports many applications that use different authentication types like API keys, Bearer tokens, JWT and even no authentication at all.++Generating the auth config for other auth types only has minor differences:+- `use_custom_auth` is used instead of `use_composio_managed_auth`+- The `credentials` field is used to pass the authentication details+- The `authScheme` field is used to specify the auth type++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Use custom auth+auth_config = composio.auth_configs.create(+ toolkit="perplexityai",+ options={+ "type": "use_custom_auth",+ "auth_scheme": "API_KEY",+ "credentials": {}+ },+)+print(auth_config)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+const authConfig = await composio.authConfigs.create('PERPLEXITYAI', {+ name: 'Perplexity AI',+ type: 'use_custom_auth',+ credentials: {},+ authScheme: 'API_KEY',+});++console.log(authConfig);+```+ </Tab>+</Tabs>++## Programmatically inspecting fields++In cases where you need to dynamically discover the exact field names and handle different auth schemes programmatically, you can inspect the auth config details first.++This works for all auth types.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+required_fields = composio.toolkits.get_auth_config_creation_fields(+ toolkit="NOTION",+ auth_scheme="OAUTH2",+ required_only=True,+)+print(required_fields)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+const toolkits = await composio.toolkits.get("NOTION");++// Extract field names from authConfigDetails+const authFields = await composio.toolkits.getAuthConfigCreationFields('NOTION', 'OAUTH2', {+ requiredOnly: true,+});++console.log("Required auth config fields:", authFields);+```+ </Tab>+</Tabs>++Then inspect the required fields and specify them in the `credentials` object.diff --git a/fumadocs/content/docs/user-management.mdx b/fumadocs/content/docs/user-management.mdxnew file mode 100644index 000000000..b93f76d79--- /dev/null+++ b/fumadocs/content/docs/user-management.mdx@@ -0,0 +1,324 @@+---+title: User Management+description: Manage users and their connected accounts+---++## What are User IDs?++User IDs determine whose connected accounts and data you're accessing in Composio. Every tool execution, connection authorization, and account operation requires a `userId` parameter that identifies which context to use.++User IDs act as containers that group connected accounts together across toolkits. Depending on your application, you can use User IDs to represent an individual user, a team, or an entire organization.++## Quick Decision Guide++**How do users access connected accounts in your app?**++- **Each user connects their own personal accounts?**+ Use User IDs+ *Use your database UUID or primary key (e.g., `user.id`)*+ *Example: Users connect their personal Gmail, GitHub*++- **Teams share the same connected accounts?**+ Use Organization IDs+ *Use your organization UUID or primary key (e.g., `organization.id`)*+ *Example: Company Slack workspace*++## Patterns++### User IDs (Individual Accounts)++In production applications with multiple users, where each user connects and manages their own accounts.++**Choosing User IDs:**++- Recommended: Database UUID or primary key (`user.id`)+- Acceptable: Unique username (`user.username`)+- Avoid: Email addresses (emails can change)++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Use your database's user ID (UUID, primary key, etc.)+user_id = user.id; # e.g., "550e8400-e29b-41d4-a716-446655440000"++tools = composio.tools.get(+ user_id=user_id,+ toolkits=["GITHUB"],+)++result = composio.tools.execute(+ "GITHUB_GET_REPO",+ user_id=user_id,+ arguments={+ "owner": 'example',+ "repo": 'repo'+ }+)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// Use your database's user ID (UUID, primary key, etc.)+const userId = user.id; // e.g., "550e8400-e29b-41d4-a716-446655440000"++const tools = await composio.tools.get(userId, {+ toolkits: ['github'],+});++const result = await composio.tools.execute('GITHUB_GET_REPO', {+ userId: userId,+ arguments: { owner: 'example', repo: 'repo' },+});+```+ </Tab>+</Tabs>++<Callout type="warn">+Never use 'default' as a User ID in production with users. This could expose other users' data.+</Callout>++### Organization IDs (Team Accounts)++For applications where teams share connections - one admin connects accounts, all team members use them.++**When to use:**+- Team tools: Slack, Microsoft Teams, Jira+- Shared accounts: [email protected], company GitHub org+- Enterprise apps: IT manages connections for all employees++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Use the organization ID as userId+user_id = organization.id # e.g., "org_550e8400"++# All users in the organization share the same connected accounts+tools = composio.tools.get(+ user_id=user_id,+ toolkits=["SLACK"],+)++# Execute tools in the organization context+result = composio.tools.execute(+ "SLACK_SEND_MESSAGE",+ user_id=user_id,+ arguments={+ "channel": '#general',+ "text": 'Hello from the team!'+ }+)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// Use the organization ID as userId+const userId = organization.id; // e.g., "org_550e8400"++// All users in the organization share the same connected accounts+const tools = await composio.tools.get(userId, {+ toolkits: ['slack'],+});++// Execute tools in the organization context+const result = await composio.tools.execute('SLACK_SEND_MESSAGE', {+ userId: userId,+ arguments: {+ channel: '#general',+ text: 'Hello from the team!',+ },+});+```+ </Tab>+</Tabs>++## Multiple Connected Accounts++A single User ID can have multiple connected accounts for the same toolkit. For example, a user might connect both their personal and work Gmail accounts.++**Key concepts:**+- Each connected account gets a unique Connected Account ID+- Multiple accounts can exist under the same User ID for any toolkit+- You can specify which account to use when executing tools++**Account selection:**+- **Explicit:** Specify the Connected Account ID to target a specific account+- **Default:** If no Connected Account ID is provided, the most recently connected account is used++## Examples++### Organization-Based Application++In B2B applications, typically an admin connects accounts once and all team members share access. Here's a complete implementation:++**Key concepts:**+- Admin performs the OAuth connection using organization ID+- All team members execute tools using the same organization ID+- Permission checks ensure users can only access their organization's connections++```typescript+import { Composio } from '@composio/core';+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});++// 1. Admin connects Slack for the entire organization+async function connectOrganizationToSlack(organizationId: string, adminUserId: string) {+ // Use organization ID as userId in Composio+ const connectionRequest = await composio.toolkits.authorize(organizationId, 'slack');++ // Store the connection request for the admin to complete+ await storeConnectionRequest(organizationId, adminUserId, connectionRequest);++ return connectionRequest.redirectUrl;+}++// 2. Any user in the organization can use the connected tools+async function sendSlackMessage(organizationId: string, channel: string, message: string) {+ return await composio.tools.execute('SLACK_SEND_MESSAGE', {+ userId: organizationId, // organization ID, not individual user ID+ arguments: {+ channel: channel,+ text: message,+ },+ });+}++// 3. Check if organization has required connections+async function getOrganizationTools(organizationId: string) {+ return await composio.tools.get(organizationId, {+ toolkits: ['slack', 'github', 'jira'],+ });+}++// Usage in your API endpoint+app.post('/api/slack/message', async (req, res) => {+ const { channel, message } = req.body;+ const organizationId = req.user.organizationId; // Get from your auth system++ // Verify user has permission to send messages for this organization+ if (!(await userCanSendMessages(req.user.id, organizationId))) {+ return res.status(403).json({ error: 'Insufficient permissions' });+ }++ try {+ const result = await sendSlackMessage(organizationId, channel, message);+ res.json(result.data);+ } catch (error) {+ res.status(500).json({ error: 'Failed to send message' });+ }+});+```++### Multi-User Application++In B2C applications, each user connects and manages their own accounts. Every user goes through their own OAuth flow and their data remains completely isolated.++**Key concepts:**+- Each user authorizes their own accounts using their unique user ID+- Connections are isolated - users can only access their own connected accounts+- No permission checks needed since users only access their own data++```typescript+import { Composio } from '@composio/core';+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});++// 1. User initiates GitHub connection+async function connectUserToGitHub(userId: string) {+ const connectionRequest = await composio.toolkits.authorize(userId, 'github');+ return connectionRequest.redirectUrl;+}++// 2. Get user's connected GitHub tools+async function getUserGitHubTools(userId: string) {+ return await composio.tools.get(userId, {+ toolkits: ['github'],+ });+}++// 3. Execute tool for specific user+async function getUserRepos(userId: string) {+ return await composio.tools.execute('GITHUB_LIST_REPOS', {+ userId: userId,+ arguments: {+ per_page: 10,+ },+ });+}++// Usage in your API endpoint+app.get('/api/github/repos', async (req, res) => {+ const userId = req.user.id; // Get from your auth system++ try {+ const repos = await getUserRepos(userId);+ res.json(repos.data);+ } catch (error) {+ res.status(500).json({ error: 'Failed to fetch repos' });+ }+});+```++**Data isolation**: Composio ensures each userId's connections and data are completely separate. User A can never access User B's repositories.++### Hybrid Pattern++Many applications need both personal and team resources. Users might connect their personal Gmail while sharing the company Slack workspace.++**Common scenarios:**+- Personal calendars + shared project management+- Individual GitHub accounts + organization repositories++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+ <Tab value="Python">+```python+# Wrong: Using individual user ID for org-connected tool+user_tools = composio.tools.get(+ user_id="user_123", # Individual user ID+ toolkits=["slack"] # Fails - Slack is connected at org level+)++# Correct: Match the ID type to how the tool was connected+user_personal_tools = composio.tools.get(+ user_id="user_123", # Individual user ID+ toolkits=["gmail"] # User's personal Gmail+)++org_shared_tools = composio.tools.get(+ user_id="org_123", # Organization ID+ toolkits=["slack", "jira"] # Organization's shared tools+)+```+ </Tab>+ <Tab value="TypeScript">+```typescript+// Wrong: Using individual user ID for org-connected tool+const userTools = await composio.tools.get(req.user.id, {+ toolkits: ['slack'], // Fails - Slack is connected at org level+});++// Correct: Match the ID type to how the tool was connected+const userPersonalTools = await composio.tools.get(req.user.id, {+ toolkits: ['gmail'], // User's personal Gmail+});++const orgSharedTools = await composio.tools.get(req.user.organizationId, {+ toolkits: ['slack', 'jira'], // Organization's shared tools+});+```+ </Tab>+</Tabs>++Remember: The userId must match how the account was connected. If admin connected Slack with org ID, all members must use org ID to access it.++## Best Practices++**Your responsibilities:**+- Pass the correct User ID for each user+- Verify user permissions before executing organization tools+- Never use 'default' in production with multiple users+- Keep User IDs consistent across your application and Composio+- Use stable identifiers that won't change over time++**Data isolation:** Composio ensures complete isolation between User IDs. Users cannot access another ID's connections or data.diff --git a/fumadocs/public/images/custom-auth-hubspot.png b/fumadocs/public/images/custom-auth-hubspot.pngnew file mode 100644index 000000000..8b8f6fd18Binary files /dev/null and b/fumadocs/public/images/custom-auth-hubspot.png differdiff --git a/fumadocs/public/images/custom-auth-posthog.png b/fumadocs/public/images/custom-auth-posthog.pngnew file mode 100644index 000000000..57c58cb75Binary files /dev/null and b/fumadocs/public/images/custom-auth-posthog.png differdiff --git a/fumadocs/public/images/custom-redirect-uri.png b/fumadocs/public/images/custom-redirect-uri.pngnew file mode 100644index 000000000..9bc418115Binary files /dev/null and b/fumadocs/public/images/custom-redirect-uri.png differdiff --git a/fumadocs/public/images/github-callback.png b/fumadocs/public/images/github-callback.pngnew file mode 100644index 000000000..4d4e22f3cBinary files /dev/null and b/fumadocs/public/images/github-callback.png differdiff --git a/fumadocs/public/images/github-oauth-config.png b/fumadocs/public/images/github-oauth-config.pngnew file mode 100644index 000000000..c3c4305a1Binary files /dev/null and b/fumadocs/public/images/github-oauth-config.png differdiff --git a/fumadocs/public/images/google-callback.png b/fumadocs/public/images/google-callback.pngnew file mode 100644index 000000000..a762db506Binary files /dev/null and b/fumadocs/public/images/google-callback.png differdiff --git a/fumadocs/public/images/google-oauth-config.png b/fumadocs/public/images/google-oauth-config.pngnew file mode 100644index 000000000..cf61aa1c1Binary files /dev/null and b/fumadocs/public/images/google-oauth-config.png differdiff --git a/fumadocs/public/images/integration-step-3-0.png b/fumadocs/public/images/integration-step-3-0.pngnew file mode 100644index 000000000..b389a3c43Binary files /dev/null and b/fumadocs/public/images/integration-step-3-0.png differdiff --git a/fumadocs/public/images/oauth-branding.png b/fumadocs/public/images/oauth-branding.pngnew file mode 100644index 000000000..8b056ed9bBinary files /dev/null and b/fumadocs/public/images/oauth-branding.png differ