---
canonical_url: "https://docs.composio.dev/examples/restrict-gmail-domain"
markdown_url: "https://docs.composio.dev/examples/restrict-gmail-domain.md"
product: "platform"
version: null
last_updated: null
---

# Restrict Gmail connections to an email domain (/examples/restrict-gmail-domain)

Accept a Gmail connection only when its mailbox address belongs to your allowed domain. This example connects an account, checks its address on the server, and prepares agent tools only after approval.

The check runs **after Google authentication**. It doesn't restrict Google's account picker or prove Google Workspace membership. For an organization-membership policy, follow [Google's guidance on the validated `hd` claim](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).

## Set up the project [#set-up-the-project]

Use Python 3.12 or Node.js 24.17 or newer. Install in a new project, using a virtual environment for Python:

**Python:**

**uv:**

```bash
uv add composio
```

**pip:**

```bash
pip install composio
```

**TypeScript:**

**npm:**

```bash
npm install @composio/core zod
```

**pnpm:**

```bash
pnpm add @composio/core zod
```

**bun:**

```bash
bun add @composio/core zod
```

**yarn:**

```bash
yarn add @composio/core zod
```

Set a [Composio project key](https://dashboard.composio.dev/~/project/settings/api-keys?utm_source=docs\&utm_medium=content\&utm_campaign=examples-restrict-gmail-domain) and a fresh application user ID for this demo:

```bash
export COMPOSIO_API_KEY="your-composio-api-key"
export COMPOSIO_USER_ID="domain-check-demo"
```

In your application, derive the user ID from your authenticated session. Keep the API key and this code on the server. If you use a scoped project key, enable [Proxy execute](/reference/authenticating-to-composio/project-api-key-permissions).

The script calls Gmail's [`users.getProfile`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users/getProfile) endpoint with `me`, which selects the authenticated mailbox. It reads the returned `emailAddress`. The endpoint requires a Gmail scope such as `https://www.googleapis.com/auth/gmail.readonly`; `openid` and `email` alone don't grant this access. Ensure your Gmail auth config requests `gmail.readonly` if the agent will also read messages. See [Controlling scopes](/docs/authentication/controlling-scopes) to configure scopes and reconnect after changing them.

## Connect and check the account [#connect-and-check-the-account]

Replace `example.com` in the script with your allowed domain. Run the script, open the printed Connect Link, and complete authentication within five minutes. The script polls its own connection request, so it doesn't need an HTTP callback handler.

**Python:**

Save as `restrict_gmail.py`:

```python title="restrict_gmail.py"
import os
from email.headerregistry import Address

from composio import Composio

ALLOWED_DOMAIN = "example.com"

def approved_email(data):
    email = data["emailAddress"]
    address = Address(addr_spec=email)
    if (
        not address.username
        or address.addr_spec != email
        or address.domain.lower() != ALLOWED_DOMAIN.lower()
    ):
        raise ValueError("Mailbox address is not allowed")
    return email

composio = Composio()
user_id = os.environ["COMPOSIO_USER_ID"]
onboarding = composio.create(
    user_id=user_id,
    toolkits=["gmail"],
    manage_connections=False,
    sandbox={"enable": False},
)
request = onboarding.authorize("gmail")
print(f"Connect Gmail: {request.redirect_url}", flush=True)

try:
    account = request.wait_for_connection(timeout=300)  # Python uses seconds.
    response = composio.tools.proxy(
        endpoint="https://gmail.googleapis.com/gmail/v1/users/me/profile",
        method="GET",
        connected_account_id=account.id,
    )
    if response["status"] != 200:
        raise RuntimeError("Gmail profile request failed")
    email = approved_email(response["data"])
except Exception:
    # Also reject missing identity, insufficient scopes, and timeouts.
    composio.connected_accounts.disable(request.id)
    raise SystemExit(
        f"Connection disabled. Rerun and connect a Gmail account at {ALLOWED_DOMAIN}. "
        "If you used that domain, check the Gmail scopes and try again."
    ) from None

session = composio.create(
    user_id=user_id,
    toolkits=["gmail"],
    connected_accounts={"gmail": [account.id]},
    manage_connections=False,
    sandbox={"enable": False},
)
tools = session.tools()
print(f"Connected as {email}. Agent tools are ready for this account.")
```
```bash
python restrict_gmail.py
```
**TypeScript:**

Save as `restrict-gmail.ts`:

```typescript title="restrict-gmail.ts"
import { Composio } from '@composio/core';
import { z } from 'zod';

const ALLOWED_DOMAIN = 'example.com';
const gmailProfile = z.object({ emailAddress: z.string().email() });

function approvedEmail(data: unknown) {
  const { emailAddress } = gmailProfile.parse(data);
  const domain = emailAddress.split('@')[1].toLowerCase();
  if (domain !== ALLOWED_DOMAIN.toLowerCase()) {
    throw new Error('Mailbox address is not allowed');
  }
  return emailAddress;
}

const userId = process.env.COMPOSIO_USER_ID;
if (!userId) throw new Error('Set COMPOSIO_USER_ID');
const composio = new Composio();
const onboarding = await composio.create(userId, {
  toolkits: ['gmail'],
  manageConnections: false,
  sandbox: { enable: false },
});
const request = await onboarding.authorize('gmail');
console.log(`Connect Gmail: ${request.redirectUrl}`);

let email: string;
try {
  const account = await request.waitForConnection(300_000); // TypeScript uses milliseconds.
  const response = await composio.tools.proxyExecute({
    endpoint: 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
    method: 'GET',
    connectedAccountId: account.id,
  });
  if (response.status !== 200) {
    throw new Error('Gmail profile request failed');
  }
  email = approvedEmail(response.data);
} catch {
  // Also reject missing identity, insufficient scopes, and timeouts.
  await composio.connectedAccounts.disable(request.id);
  throw new Error(
    `Connection disabled. Rerun and connect a Gmail account at ${ALLOWED_DOMAIN}. ` +
    'If you used that domain, check the Gmail scopes and try again.',
  );
}

const session = await composio.create(userId, {
  toolkits: ['gmail'],
  connectedAccounts: { gmail: [request.id] },
  manageConnections: false,
  sandbox: { enable: false },
});
const tools = await session.tools();
console.log(`Connected as ${email}. Agent tools are ready for this account.`);
```
```bash
node restrict-gmail.ts
```

For an approved account, the script prints `Connected as alice@example.com. Agent tools are ready for this account.` Pass the returned `tools` to your [agent framework](/docs/providers) using this approved session. The default SDK provider returns OpenAI-compatible tools; configure your framework's provider when constructing `Composio` if needed.

For a rejected account, the script disables the connection and exits before creating the agent session. If disabling fails, the script stops with that error and still doesn't create the agent session. Resolve the failure before retrying. Disabling a connection blocks Composio tool execution; it doesn't revoke Google's OAuth grant.

## Keep the check in the execution path [#keep-the-check-in-the-execution-path]

The onboarding session never supplies tools to an agent. The second session selects the approved account explicitly and disables in-chat connection management, so the agent can't connect another account through that session. Don't expose the onboarding session to clients or reuse other sessions that can select unchecked accounts. Apply the same validation whenever you accept a new or replacement connection.

The domain comparison ignores case and requires an exact match. `alice@EXAMPLE.COM` passes; `alice@gmail.com`, `alice@sub.example.com`, and `alice@notexample.com` don't. Missing or malformed profile data and failed profile requests also prevent approval. An alias such as `work-gmail` or the account's `displayName` isn't the input to this decision.

To display identity without a domain policy, see [Identify the connected account](/docs/authentication/manually-authenticating#identify-the-connected-account). For session account selection, see [Managing multiple connected accounts](/docs/authentication/managing-multiple-connected-accounts#selecting-a-specific-account-for-a-session).

---

📚 **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

Composio supports two integration modes: **Native Tools** (with a provider package) and **MCP** (no provider package needed).

### Native Tools

```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
// ✅ 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
```

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_ISSUE` is a *tool* |
| apps / appType | toolkits | e.g., `github` is a *toolkit* |
| 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.

