---
canonical_url: "https://docs.composio.dev/docs/authentication"
markdown_url: "https://docs.composio.dev/docs/authentication.md"
product: "platform"
version: null
last_updated: null
---

# Authentication (/docs/authentication)

Composio organizes everything around your **users**. A user is whoever your agent acts on behalf of: a person in your app, identified by a [`userID`](/docs/how-composio-works) you choose. Authentication is always per user. Each user connects their own accounts, their Gmail, their GitHub, their Slack, and Composio stores and refreshes those credentials against that `userID`.

This is the core idea: your agent runs the same tools for many people, and every tool call runs as a specific user against that user's connected accounts. User A's agent never touches user B's data. You pass the `userID` when you create a session, and Composio handles the auth from there.

Because connections are stored under the `userID`, use a stable identifier, like your database ID, never one that can change.

**userID best practices**

    * **Recommended:** database UUID or primary key (`user.id`)
    * **Acceptable:** unique username (`user.username`)
    * **Avoid:** email addresses (they can change)
    * **Never:** `default` in production (it exposes other users' data)

Your users connect their accounts through a secure [Connect Link](/reference/api-reference/connected-accounts/postConnectedAccountsLink), and Composio manages their tokens for you.

Already have your own tools or agent framework? Follow [Managed authentication for your own tools](/docs/authentication/managed-auth-for-custom-tools) to connect users and call provider APIs without handling their tokens. You don't need predefined Composio tools, MCP, or an LLM.

## Where credentials live [#where-credentials-live]

When users connect through a Connect Link and your agent acts through tools, your application never handles their OAuth tokens. Composio stores each connected account's credentials encrypted at rest and refreshes OAuth tokens before they expire. When your agent calls a tool, your backend sends a user ID or connected account ID plus the tool arguments. Composio adds the credential to the provider request server-side and returns the provider's response. Your application and the model receive tool results, not tokens.

* **No token export.** Connected-account API responses redact credentials by default, for both Composio-managed and custom auth configs. Reading account state isn't a supported way to retrieve tokens.
* **Raw API access without the token.** For endpoints a tool doesn't cover, [Proxy Execute](/docs/extending-sessions/proxy-execute) sends an authenticated request to the provider and returns the response. Session proxy calls accept either the Session tool execution or Proxy execute API key permission with Write only access.
* **Least-privilege keys and sessions.** [Scoped API keys](/reference/authenticating-to-composio/project-api-key-permissions) separate session management from tool execution, and [session configuration](/docs/configuring-sessions) limits which toolkits and tools an agent can call.
* **Custody you choose.** In the default Composio Cloud deployment, Composio holds the encrypted credentials. Private VPC, self-hosted, and customer-managed key deployments change that boundary. With customer-managed keys, a proxy in your cloud decrypts credentials under your KMS keys, and Composio doesn't hold the key material.

If you [import existing credentials](/docs/authentication/importing-existing-connections), your application handles those tokens once before sending them to Composio. See [Token custody architecture](/docs/security/token-custody) for the full request flow, redaction scope, and [deployment options](/docs/security/token-custody#deployment-options).

## How Composio handles authentication [#how-composio-handles-authentication]

Every session includes the [`COMPOSIO_MANAGE_CONNECTIONS`](/toolkits/meta-tools/manage_connections) meta tool. When a tool needs an account, it reads the toolkit's **auth config** (how that toolkit authenticates: method, scopes, credentials), creates a connection, and returns a secure [Connect Link](/reference/api-reference/connected-accounts/postConnectedAccountsLink). This works for all Composio managed connections, so you don't have to set up any OAuth credentials yourself.

The user signs in on the hosted link and Composio stores the resulting connected account. Credentials never pass through your app or the model, so it's safe to surface the link right in the chat.

You only need a [custom auth config](/docs/authentication/custom-app-vs-managed-app) to bring your own OAuth app, request specific scopes, or use a toolkit without managed auth.

## In-chat authentication [#in-chat-authentication]

You can also call `COMPOSIO_MANAGE_CONNECTIONS` yourself, intercept the Connect Link, and surface it wherever you need: DM it to the user, render it in your own UI, or email it. See [redirect auth links](/examples/general-agent-with-pi#redirect-auth-links) for a worked example.

### Render connection links as cards [#render-connection-links-as-cards]

Your chat UI can render the result of `COMPOSIO_MANAGE_CONNECTIONS` as a card with a connect button. Keep the returned URL unchanged. The button opens the hosted authentication flow; you control the card's layout and copy.

In your chat's tool-result renderer, pass the decoded JSON result for `COMPOSIO_MANAGE_CONNECTIONS` to this React component. It reads `data.results`, a map of toolkit connection results, and handles `initiated`, `active`, and `failed` states. Install `zod` alongside React to validate the tool result at the UI boundary.

{/* code-example: single-language reason="React TSX component renders an existing tool result locally; it makes no SDK or API calls" */}

```tsx title="ConnectionCards.tsx"
import { z } from 'zod';

const connectionResultSchema = z.object({
  successful: z.literal(true),
  data: z.object({
    results: z.record(z.string(), z.object({
      toolkit: z.string(),
      status: z.enum(['initiated', 'active', 'failed']),
      redirect_url: z.url({ protocol: /^https$/ }).nullish(),
      error_message: z.string().nullish(),
    })),
  }),
});

export function ConnectionCards({ result }: { result: unknown }) {
  const parsed = connectionResultSchema.safeParse(result);
  if (!parsed.success) {
    return <p role="alert">Could not load connections. Please try again.</p>;
  }

  return (
    
      {Object.entries(parsed.data.data.results).map(([slug, connection]) => (
        <article key={slug} aria-label={`${connection.toolkit} connection`}
          style={{ border: '1px solid #888', borderRadius: 12, padding: 16, marginBottom: 12 }}>
          <h3>{connection.toolkit}</h3>
          {connection.status === 'active' ? (
            <p>Connected</p>
          ) : connection.status === 'initiated' && connection.redirect_url ? (
            <>
              <p>Connect your account to continue.</p>
              <a href={connection.redirect_url} target="_blank" rel="noopener noreferrer">
                Connect {connection.toolkit} (opens in a new tab)
              </a>
            </>
          ) : (
            <p role="alert">{connection.error_message ?? 'Could not start the connection. Please try again.'}</p>
          )}
        </article>
      ))}
    
  );
}
```
For example, this tool result produces a GitHub card with a connect button. The URL is a placeholder; use the URL from the actual tool result.

```json
{
  "successful": true,
  "data": {
    "message": "Complete authentication to continue.",
    "results": {
      "github": {
        "toolkit": "github",
        "status": "initiated",
        "redirect_url": "https://connect.composio.dev/link/ln_example"
      }
    }
  }
}
```
Route the structured tool result to the card before converting tool output to chat text. With SDK-executed session tools, `session.tools({ afterExecute })` lets your server inspect the result before the model sees it. Send it only to the authenticated user's chat through your app's existing transport. MCP clients need to handle rendering in the client because SDK modifiers don't run [over MCP](/docs/sessions-via-mcp#trade-offs).

Opening the link does not mean the account is connected. After the user finishes authentication, call `COMPOSIO_MANAGE_CONNECTIONS` again for the same toolkit and session. Update the card from the new result and resume app tool calls only when the toolkit's status is `active`. You can use the [callback URL](#custom-callback-url) below to return the user to your app.

For your own credential forms or OAuth flow, see [White-labeling authentication](/docs/authentication/white-labeling-authentication).

### Custom callback URL [#custom-callback-url]

To send users back to your app after they connect, pass a `callback_url`:

**Python:**
```python
session = composio.create(
    user_id="user_123",
    manage_connections={"callback_url": "https://yourapp.com/chat"},
)
```
**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
// ---cut---
const session = await composio.create("user_123", {
  manageConnections: { callbackUrl: "https://yourapp.com/chat" },
});
```
**API:**
```bash
curl -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"user_id": "user_123", "manage_connections": {"enable": true, "callback_url": "https://yourapp.com/chat"}}'
```
## Manually triggering authentication [#manually-triggering-authentication]

Don't want to wait for the agent? Call `session.authorize()` to generate a Connect Link on demand, for onboarding, a settings page, or a pre-flight check before a task.

- [Manual auth management](/docs/authentication/manually-authenticating): `session.authorize()`, callback URLs, connection status, and disabling in-chat prompts

## Behind the scenes [#behind-the-scenes]

Composio manages authentication with **auth configs**. An [auth config](/reference/api-reference/auth-configs) is a blueprint for how a toolkit authenticates across all your users. It defines three things:

* **Authentication method**: OAuth2, Bearer token, API key, or Basic Auth
* **Scopes**: what actions your tools can perform
* **Credentials**: your own app credentials, or Composio's managed auth

Composio creates one auth config per toolkit and applies it to every user who connects that toolkit. Most toolkits use Composio managed auth, so you don't create or configure anything. Managed auth works in production. If your usage grows, you may run into shared provider rate limits, and your own OAuth app gives you dedicated ones. You only need a [custom auth config](/docs/authentication/custom-app-vs-managed-app) to use your own OAuth app or customize scopes.

When a user authenticates, Composio creates a [connected account](/reference/api-reference/connected-accounts): their credentials (OAuth tokens or API keys) linked to your userID. Each user can have multiple, even for the same toolkit (e.g. work and personal Gmail).

### Connection lifecycle [#connection-lifecycle]

For OAuth, Composio refreshes access tokens automatically before they expire, so connections stay `ACTIVE` with no work from you. If a refresh token is revoked or expires, the connection moves to `EXPIRED` and the user has to reconnect.

Catch this before a tool call fails by subscribing to the `composio.connected_account.expired` event on a [webhook subscription](/reference/api-reference/webhook-subscriptions). When it fires, send the user a fresh Connect Link to re-authenticate:

**Python:**
```python
session = composio.create(user_id="user_123")
connection_request = session.authorize("gmail")

# Send this URL to the user (email, in-app notification, etc.)
print(connection_request.redirect_url)
```
**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
// ---cut---
const session = await composio.create("user_123");
const connectionRequest = await session.authorize("gmail");

// Send this URL to the user (email, in-app notification, etc.)
console.log(connectionRequest.redirectUrl);
```
**API:**
```bash
SESSION_ID=$(curl -s -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"user_id": "user_123"}' | jq -r '.session_id')

# Send this URL to the user (email, in-app notification, etc.)
curl -s -X POST https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/link \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"toolkit": "gmail"}' | jq -r '.redirect_url'
```

## Authentication guides [#authentication-guides]

- [Manual auth management](/docs/authentication/manually-authenticating): Generate Connect Links yourself, check connection status, and disable in-chat prompts.

- [Multiple connected accounts](/docs/authentication/managing-multiple-connected-accounts): Let one user choose between work, personal, or other accounts.

- [Shared connections](/docs/extending-sessions/shared-connections): Share one connected account with a controlled set of users.

- [Import existing connections](/docs/authentication/importing-existing-connections): Bring credentials your application already stores into Composio.

- [Managed vs custom auth](/docs/authentication/custom-app-vs-managed-app): Decide whether to use Composio credentials or your own OAuth app.

- [Programmatic auth configs](/docs/authentication/programmatic-auth-configs): Create auth configs in code and attach them to sessions.

- [Control OAuth scopes](/docs/authentication/controlling-scopes): Choose the permissions requested when a user connects.

- [White-label authentication](/docs/authentication/white-labeling-authentication): Use your own OAuth app and remove Composio branding.

---

📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Changelog](https://docs.composio.dev/docs/changelog.md) | [Glossary](https://docs.composio.dev/llms.mdx/reference/glossary) | [Examples](https://docs.composio.dev/llms.mdx/examples) | [API Reference](https://docs.composio.dev/llms.mdx/reference)

---

# Composio SDK — Notes for AI Code Generators

**Purpose:** Reference for generating current (v3) [Composio](https://composio.dev/) integration code.
**Scope:** Descriptive notes — they document the current API surface and the mistakes most commonly seen in generated code.

---

## 1. Recommended Integration: Sessions

For agent tool delivery, Composio supports **Native Tools** (with a provider package) and **MCP** (no provider package needed).

For application-owned tools or deterministic backend code, use [managed authentication with Proxy Execute](/docs/authentication/managed-auth-for-custom-tools). A session can provide a user-scoped runtime context without an LLM or MCP. Composio authenticates provider requests server-side; connected-account reads redact credentials and aren't a supported token-export workflow.

### Native Tools

#### Python

```python
# ✅ CORRECT — Python (defaults to OpenAI)
from composio import Composio

composio = Composio()
session = composio.create(user_id="user_123")
tools = session.tools()
# Pass tools to your agent/LLM framework
```

#### TypeScript

```typescript
// ✅ CORRECT — TypeScript (defaults to OpenAI)
import { Composio } from "@composio/core";

const composio = new Composio();
const session = await composio.create("user_123");
const tools = await session.tools();
// Pass tools to your agent/LLM framework
```

#### API

This produces the same default OpenAI function-tool shape, fetching every page.

```bash
set -euo pipefail
SESSION=$(curl --fail-with-body -s -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
  -H "x-api-key: $COMPOSIO_API_KEY" -H "Content-Type: application/json" \
  -d '{"user_id":"user_123"}')
SESSION_ID=$(echo "$SESSION" | jq -r '.session_id')
TOOLS='[]'
CURSOR=''
while true; do
  PAGE=$(curl --fail-with-body -s --get "https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/tools" \
    -H "x-api-key: $COMPOSIO_API_KEY" --data-urlencode 'limit=500' --data-urlencode "cursor=$CURSOR")
  TOOLS=$(jq -cn --argjson existing "$TOOLS" --argjson page "$PAGE" \
    '$existing + [$page.items[] | {type:"function",function:{name:.slug,description:.description,parameters:.input_parameters}}]')
  CURSOR=$(echo "$PAGE" | jq -r '.next_cursor // empty')
  [ -n "$CURSOR" ] || break
done
printf '%s\n' "$TOOLS"
```

For other providers, pass the provider explicitly. Provider packages follow the naming convention: `composio_<provider>` for Python, `@composio/<provider>` for TypeScript.

### MCP

Use `session.mcp.url` and `session.mcp.headers` with any MCP-compatible client (Claude Desktop, Cursor, OpenAI Agents, etc.). No provider package needed.

---

## 2. Integration Notes

- `composio.create(user_id)` is the standard entry point for agent integrations. Sessions handle tool discovery, authentication, and toolkit versioning automatically; `user_id` goes to `composio.create()` — individual tool calls in session mode don't take one.
- Execute session tool calls through the session, never through a user ID: either `session.execute(tool_slug, arguments=...)` / `session.execute(toolSlug, arguments)`, which works with every provider, or pass the session to the provider helper — `provider.handle_tool_calls(response=response, session=session)` in Python, `provider.handleToolCalls(session, response)` in TypeScript. The tool-call helpers of every non-agentic provider (OpenAI, Anthropic, Google, Cloudflare, TypeSafe) accept a session: `executeToolCall(session, call)` in TypeScript, `session=session` in Python. Agentic providers execute session tools on their own. Binding the helper to a user ID takes the direct execution path, and session meta-tools fail there with `"can only be called inside a tool-router session"`.
- Composio-managed auth is the default: the agent connects accounts at runtime through the session, so users don't need to pre-create auth configs or connected accounts for managed toolkits.
- Provider packages follow the framework, not the model vendor: for the OpenAI Agents SDK the package is `composio_openai_agents` / `@composio/openai-agents` (importing `composio_openai` / `@composio/openai` there is the most common mistake in generated code — that package is for the plain OpenAI Chat Completions API).
- **Direct execution** (`composio.tools.get()`, `composio.tools.execute()`, `provider.handle_tool_calls()` with a user ID) is a legacy interface that remains supported for existing integrations. Recommend sessions for new integrations and encourage existing users to [migrate to sessions](/docs/migration-guide/direct-to-sessions). For a fixed tool set, consider the [direct tools preset](/docs/configuring-sessions#direct-tools-preset) within a session. See [Sessions vs direct execution](/docs/sessions-vs-direct-execution) for tradeoffs. Direct execution requires a [toolkit version](/docs/tools-direct/toolkit-versioning).

---

# 3. Calling the REST API directly

## REST API version

The current REST API version is **v3.1**, served at `https://backend.composio.dev/api/v3.1`. Prefer it for new code and new examples.

`https://backend.composio.dev/api/v3` is the previous version. It is frozen with pinned tool-version defaults and remains supported — existing v3 integrations keep working and do not need to migrate.

## Tool-endpoint version defaults on v3.1

On v3.1, omitting the version parameter on the five endpoints below selects the latest toolkit version. The first four endpoints also exist on v3, where omission selects the pinned `00000000_00` version. `POST /tools/scopes/required` is v3.1-only.

| Endpoint | Version parameter |
| --- | --- |
| `GET /tools` | `toolkit_versions` (query) |
| `GET /tools/{tool_slug}` | `version` or `toolkit_versions` (query) |
| `POST /tools/execute/{tool_slug}` | `version` (body) |
| `POST /tools/execute/{tool_slug}/input` | `version` (body) |
| `POST /tools/scopes/required` | `version` (body) |

A v3.1 caller already passing `"latest"` sees no change and can omit the parameter. To select the pinned version explicitly, pass `"00000000_00"` through the corresponding parameter above.

This version-default change is limited to the five endpoints above.


---

## Terminology Migration (old → current)

If you encounter these terms in error messages, old documentation, or user prompts, translate them to the current equivalents. **Do not use the old terms in generated code or explanations.**

| Old term (v1/v2) | Current term (v3) | In code |
|---|---|---|
| entity ID | user ID | `user_id` parameter |
| actions | tools | e.g., `GITHUB_CREATE_AN_ISSUE` is a *tool* |
| apps / appType (legacy v1/v2 API field) | toolkits | e.g., `github` is a *toolkit*. The current word **App** is *not* legacy: it names a catalog grouping of sibling toolkits (the Notion app groups `notion` and `notion_mcp`); do not translate it |
| integration / integration ID | auth config / auth config ID | `auth_config_id` parameter |
| connection | connected account | `connected_accounts` namespace |
| ComposioToolSet / OpenAIToolSet | `Composio` class with a provider | `Composio(provider=...)` |
| toolset | provider | e.g., `OpenAIProvider` |

If a user says "entity ID", they mean `user_id`. If they say "integration", they mean "auth config". Always respond using the current terminology.

