> ## Documentation Index
> Fetch the complete documentation index at: https://composio-preview.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Manual auth management

> Authenticate and manage user connections to toolkits outside of chat

Manual authentication lets you connect users to toolkits outside the chat flow. Reach for it when you want to:

* Pre-authenticate users before they start chatting.
* Build a custom connections UI in your app.

## Authorize a toolkit

Call `session.authorize()` to generate a [Connect Link](https://composio-preview.mintlify.site/docs/tools-direct/authenticating-tools.md#hosted-authentication-connect-link) URL, redirect the user, and wait for them to finish:

> [tab] Python
>
> ```python theme={null}
> session = composio.create(user_id="user_123")
>
> connection_request = session.authorize("gmail")
>
> print(connection_request.redirect_url)
> # https://connect.composio.dev/link/ln_abc123
>
> connected_account = connection_request.wait_for_connection(60)
> print(f"Connected: {connected_account.id}")
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio({ apiKey: 'your_api_key' });
> const session = await composio.create("user_123");
>
> const connectionRequest = await session.authorize("gmail");
>
> console.log(connectionRequest.redirectUrl);
> // https://connect.composio.dev/link/ln_abc123
>
> const connectedAccount = await connectionRequest.waitForConnection(60000);
> console.log(`Connected: ${connectedAccount.id}`);
> ```

> [tab] API
>
> ```bash theme={null}
> 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')
>
> CONNECTION=$(curl --fail-with-body -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"}')
> echo "$CONNECTION" | jq -r '.redirect_url'
> CONNECTED_ACCOUNT_ID=$(echo "$CONNECTION" | jq -r '.connected_account_id')
>
> # Open the printed link. Wait at most 60 seconds for authorization.
> DEADLINE=$((SECONDS + 60))
> while true; do
>   ACCOUNT=$(curl --fail-with-body -s https://backend.composio.dev/api/v3.1/connected_accounts/$CONNECTED_ACCOUNT_ID \
>     -H "x-api-key: $COMPOSIO_API_KEY") || exit 1
>   STATUS=$(echo "$ACCOUNT" | jq -r '.status')
>   case "$STATUS" in
>     ACTIVE) echo "$ACCOUNT" | jq -r '.id'; break ;;
>     FAILED|EXPIRED|INACTIVE|REVOKED) echo "Connection ended: $STATUS" >&2; exit 1 ;;
>   esac
>   if [ "$SECONDS" -ge "$DEADLINE" ]; then
>     echo "Timed out waiting for authorization" >&2
>     exit 1
>   fi
>   sleep 1
> done
> ```

Redirect the user to the `redirectUrl`. After they authenticate, they'll return to your callback URL. The connection request polls until the user completes authentication (default timeout: 60 seconds).

> [!NOTE]
>
> If the user closes the Connect Link without completing auth, the connection remains in `INITIATED` status until it expires.

## Reusing an active connection

In TypeScript, call `session.ensureConnected("gmail")` to reuse the session's active connection. If none exists, it starts an authorization flow and waits for the connection to become active. The optional `timeout` sets how long to wait in milliseconds (default: `60000`).

The result includes `toolkit`, `wasConnected`, and `connectedAccount`. `wasConnected` is `true` when an active connection already exists. Toolkits that don't require authentication also return `wasConnected: true`, with no `connectedAccount`.

Use `session.authorize()` and `waitForConnection()` when you need to display or redirect to the Connect Link. `ensureConnected()` waits internally and doesn't return the redirect URL. Calling `authorize()` always starts a new authorization flow, even if an active connection exists.

## Redirecting users after authentication

Pass a `callbackUrl` to control where users land after authenticating. You can include query parameters to carry context through the flow, for example to identify which `userID` or session triggered the connection.

> [tab] Python
>
> ```python theme={null}
> connection_request = session.authorize(
>     "gmail",
>     callback_url="https://your-app.com/callback?user_id=user_123&source=onboarding"
> )
>
> print(connection_request.redirect_url)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio({ apiKey: 'your_api_key' });
> const session = await composio.create("user_123");
> const connectionRequest = await session.authorize("gmail", {
>   callbackUrl: "https://your-app.com/callback?user_id=user_123&source=onboarding",
> });
>
> console.log(connectionRequest.redirectUrl);
> ```

> [tab] API
>
> ```bash theme={null}
> # SESSION_ID is the session_id returned when you created the session
> curl -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", "callback_url": "https://your-app.com/callback?user_id=user_123&source=onboarding"}'
> ```

After authentication, Composio redirects the user to your callback URL with the following parameters appended, while preserving your existing ones:

| Parameter | Description |
| - | - |
| `status` | `success` or `failed` |
| `connected_account_id` | The ID of the newly created connected account |

```text theme={null}
https://your-app.com/callback?user_id=user_123&source=onboarding&status=success&connected_account_id=ca_abc123
```

## Identify the connected account

After authentication, use the account returned by `wait_for_connection()` or `waitForConnection()` to identify which provider account connected. If you use a callback instead, verify its `connected_account_id` against the connection attempt stored on your server and the signed-in application user before retrieving it. Callback query parameters alone aren't proof of ownership.

These identifiers serve different purposes:

| Value | Meaning |
| - | - |
| Application user ID | Your application's user, such as `user_123`. This doesn't identify their Gmail or GitHub account. |
| Connected account ID | One connection in Composio, such as `ca_abc123`. Use it to select the account for a profile request. |
| Alias | A label you assign, such as `work-gmail`. It doesn't prove which account connected. |
| Provider identity | The email address, username, or ID returned by the provider for the authenticated account. |

For a "Connected as…" label, read `state.val.displayName` when available. For additional profile fields, get the toolkit's current-user endpoint and call it through Composio's [authenticated proxy](https://composio-preview.mintlify.site/reference/api-reference/tools/postToolsExecuteProxy.md) with the same connected account ID:

> [tab] Python
>
> ```python theme={null}
> from typing import Literal, cast
>
> # Continue after connected_account = connection_request.wait_for_connection().
> account_id = connected_account.id
> state = connected_account.model_dump().get("state") or {}
> display_name = state.get("val", {}).get("displayName")
> print(f"Connected as {display_name}" if display_name else "Account connected")
>
> toolkit = composio.toolkits.get(connected_account.toolkit.slug)
> endpoint = toolkit.get_current_user_endpoint
> method = toolkit.get_current_user_endpoint_method
> if not endpoint or method not in ("GET", "POST", "PUT", "PATCH", "DELETE"):
>     raise ValueError("This toolkit doesn't publish a supported current-user endpoint")
> # The membership check validates the value; cast records that narrowing for mypy.
>
> response = composio.tools.proxy(
>     endpoint=endpoint,
>     method=cast(Literal["GET", "POST", "PUT", "PATCH", "DELETE"], method),
>     connected_account_id=account_id,
> )
> if response.status != 200:
>     raise RuntimeError("Could not retrieve the connected account's profile")
> profile = response.data  # Parse the fields documented by this provider.
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio();
> declare const connectedAccount: Awaited<ReturnType<typeof composio.connectedAccounts.get>>;
> import { z } from 'zod';
>
> // Continue after connectedAccount = await connectionRequest.waitForConnection().
> const accountId = connectedAccount.id;
> const label = z.object({ displayName: z.string().optional() })
>   .safeParse(connectedAccount.state?.val ?? {});
> const displayName = label.success ? label.data.displayName : undefined;
> console.log(displayName ? `Connected as ${displayName}` : 'Account connected');
>
> const toolkit = await composio.toolkits.get(connectedAccount.toolkit.slug);
> if (!toolkit.getCurrentUserEndpoint) {
>   throw new Error("This toolkit doesn't publish a current-user endpoint");
> }
> const method = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
>   .parse(toolkit.getCurrentUserEndpointMethod);
> const response = await composio.tools.proxyExecute({
>   endpoint: toolkit.getCurrentUserEndpoint,
>   method,
>   connectedAccountId: accountId,
> });
> if (response.status !== 200) {
>   throw new Error("Could not retrieve the connected account's profile");
> }
> const profile = z.record(z.string(), z.unknown()).parse(response.data);
> // Validate the provider-specific fields before using them in your application.
> ```

> [tab] API
>
> ```bash theme={null}
> # CONNECTED_ACCOUNT_ID is the connected_account_id returned by the link request
> ACCOUNT=$(curl -s -X GET https://backend.composio.dev/api/v3.1/connected_accounts/$CONNECTED_ACCOUNT_ID \
>   -H "x-api-key: $COMPOSIO_API_KEY")
> echo "$ACCOUNT" | jq -r '.state.val.displayName // "Account connected"'
> TOOLKIT_SLUG=$(echo "$ACCOUNT" | jq -r '.toolkit.slug')
>
> TOOLKIT=$(curl -s -X GET https://backend.composio.dev/api/v3.1/toolkits/$TOOLKIT_SLUG \
>   -H "x-api-key: $COMPOSIO_API_KEY")
> ENDPOINT=$(echo "$TOOLKIT" | jq -r '.get_current_user_endpoint')
> METHOD=$(echo "$TOOLKIT" | jq -r '.get_current_user_endpoint_method')
>
> # Response has status and data; parse the fields documented by this provider
> curl -X POST https://backend.composio.dev/api/v3.1/tools/execute/proxy \
>   -H "x-api-key: $COMPOSIO_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{"endpoint": "'"$ENDPOINT"'", "method": "'"$METHOD"'", "connected_account_id": "'"$CONNECTED_ACCOUNT_ID"'"}'
> ```

Toolkit metadata describes where to request a profile; it doesn't contain the account owner's details. Endpoint availability, required scopes, and response fields vary by provider. If the metadata is absent, use a documented profile endpoint or tool for that provider. A GitHub username or display label isn't a verified email address.

For an application policy, validate the provider's response before giving an agent access to the account. Follow [Restrict Gmail connections to an email domain](https://composio-preview.mintlify.site/examples/restrict-gmail-domain.md) for a complete example that checks the mailbox address and disables rejected connections. Return only the fields your UI needs, not the account's authentication state.

## Check connection status

Use `session.toolkits()` to see all toolkits in the session and their connection status:

> [tab] Python
>
> ```python theme={null}
> toolkits = session.toolkits()
>
> for toolkit in toolkits.items:
>     connection = toolkit.connection
>     if connection and connection.is_active and connection.connected_account:
>         status = connection.connected_account.id
>     else:
>         status = "Not connected"
>     print(f"{toolkit.name}: {status}")
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio({ apiKey: 'your_api_key' });
> const session = await composio.create("user_123");
> const toolkits = await session.toolkits();
>
> toolkits.items.forEach((toolkit) => {
>   console.log(`${toolkit.name}: ${toolkit.connection?.isActive ? toolkit.connection.connectedAccount?.id : "Not connected"}`);
> });
> ```

> [tab] API
>
> ```bash theme={null}
> # SESSION_ID is the session_id returned when you created the session
> curl -s -X GET https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/toolkits \
>   -H "x-api-key: $COMPOSIO_API_KEY" \
>   | jq -r '.items[] | "\(.name): \(if .connected_account.status == "ACTIVE" then .connected_account.id else "Not connected" end)"'
> ```

## Disabling in-chat auth

By default, sessions include the `COMPOSIO_MANAGE_CONNECTIONS` meta-tool that prompts users to authenticate during chat. To turn it off and handle auth entirely in your own UI, set `manage_connections` to `False`:

> [tab] Python
>
> ```python theme={null}
> session = composio.create(
>     user_id="user_123",
>     manage_connections=False,
> )
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio({ apiKey: 'your_api_key' });
> const session = await composio.create("user_123", {
>   manageConnections: false,
> });
> ```

> [tab] API
>
> ```bash theme={null}
> 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": false}}'
> ```

## Putting it together

A common pattern is to verify all required connections before starting the agent:

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio(api_key="your-api-key")
>
> required_toolkits = ["gmail", "github"]
>
> session = composio.create(
>     user_id="user_123",
>     manage_connections=False,  # Disable in-chat auth prompts
> )
>
> toolkits = session.toolkits()
>
> connected = {t.slug for t in toolkits.items if t.connection is not None and t.connection.is_active}
> pending = [slug for slug in required_toolkits if slug not in connected]
>
> print(f"Connected: {connected}")
> print(f"Pending: {pending}")
>
> for slug in pending:
>     connection_request = session.authorize(slug)
>     print(f"Connect {slug}: {connection_request.redirect_url}")
>     connection_request.wait_for_connection()
>
> print("All toolkits connected!")
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from "@composio/core";
>
> const composio = new Composio({ apiKey: "your-api-key" });
>
> const requiredToolkits = ["gmail", "github"];
>
> const session = await composio.create("user_123", {
>   manageConnections: false, // Disable in-chat auth prompts
> });
>
> const toolkits = await session.toolkits();
>
> const connected = toolkits.items
>   .filter((t) => t.connection?.isActive)
>   .map((t) => t.slug);
>
> const pending = requiredToolkits.filter((slug) => !connected.includes(slug));
>
> console.log("Connected:", connected);
> console.log("Pending:", pending);
>
> for (const slug of pending) {
>   const connectionRequest = await session.authorize(slug);
>   console.log(`Connect ${slug}: ${connectionRequest.redirectUrl}`);
>   await connectionRequest.waitForConnection();
> }
>
> console.log("All toolkits connected!");
> ```

> [tab] API
>
> ```bash theme={null}
> 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", "manage_connections": {"enable": false}}' | jq -r '.session_id')
>
> # Required toolkits without an active connection
> PENDING=$(curl -s -X GET "https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/toolkits?toolkits=gmail,github" \
>   -H "x-api-key: $COMPOSIO_API_KEY" \
>   | jq -r '.items[] | select(.connected_account.status != "ACTIVE") | .slug')
>
> for SLUG in $PENDING; do
>   # Send the user to redirect_url, then poll GET /connected_accounts/{connected_account_id} until ACTIVE
>   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": "'"$SLUG"'"}' | jq -r --arg slug "$SLUG" '"Connect \($slug): \(.redirect_url)"'
> done
> ```

## Next

> [card] [Managing multiple connected accounts](https://composio-preview.mintlify.site/docs/authentication/managing-multiple-connected-accounts.md)
>
> Let a user connect work and personal accounts for the same toolkit, then pick which one runs
