# Toucan AI Documentation

{% hint style="info" icon="messages" %}
**Embed engaging AI-powered analytics** into your product, website, customer portal or internal tool, with all the production-ready workflows built in.

**Toucan AI lets your users explore data through a conversational interface**, instantly turning questions into visualizations, dashboards and insights they can act on.
{% endhint %}

***

#### ✨ What you can do with Toucan

* Embed conversational experiences seamlessly into your app, website, customer portal or internal tool
* Build and embed dashboards, read-only or self-service, with AI or manual configuration
* Create and manage business metrics to create alignment and govern AI-generated content
* Control access with fine-grained permissions
* Customize the experience to match your product

***

#### 👉 Start building with Toucan AI

**Launch your free trial and ship your first embedded conversational experience in minutes.**

* No credit card required
* Setup in minutes
* Cancel anytime

<a href="https://toucanai.cloud/auth/sign-up" class="button primary">Start free trial</a>

***

#### 🚀 Get started

{% content-ref url="/pages/b7KCGB4tdJeeLoX3FVPW" %}
[Embed a chat](/getting-started/quick-start/embed-a-chat)
{% endcontent-ref %}

{% content-ref url="/pages/Yfnlk9RGEsQR7c6RzAg9" %}
[Embed a dashboard](/getting-started/quick-start/embed-a-dashboard)
{% endcontent-ref %}

<figure><img src="/files/DVLtV5av6NMLJreMp9Lf" alt=""><figcaption></figcaption></figure>


# Getting started

### Welcome to Toucan AI!

{% hint style="info" %}
**Target Audience:** Non technical users & Developers
{% endhint %}

Toucan AI is an analytics platform designed to embed data visualizations and conversational AI directly into software products.

***

### The Documentation Promise

This documentation provides the technical and conceptual framework to:

* Understand platform capabilities and limitations.
* Build and embed self-service analytics end-to-end.
* Deploy to production without ongoing Toucan support.

***

### Quick Start Path

To reach first value quickly, follow the Golden Path:

1. **Core Concepts:** Understand the Toucan mental model.
2. **Build:** Connect data and create your first chart.
3. **Embed:** Integrate the visualization into your application via Web Component.


# What Is Toucan AI?

{% hint style="info" %}
**Target Audience:** Non technical users & Developers
{% endhint %}

### TL;DR

A platform for embedding analytics and conversational dashboards into software products using AI-assisted or manual workflows.

***

### Core Capabilities

* **Data Connectivity:** Supports SQL databases and data warehouses.
* **Semantic Layer:** Define metrics, dimensions, and relationships for consistent data logic.
* **Visualization:** Generate charts using natural language (AI-assisted) or manual configuration.
* **Integration:** Embed via web components, SDKs, or iframes.
* **Security:** Built-in row-level security (RLS) and role-based access control (RBAC).
* **Deployment:** Available as SaaS or self-hosted via Helm/Docker.

***

### When to Use Toucan AI

Choose Toucan AI to:

* Embed analytics into a product with minimal development effort.
* Provide end-users with self-service data exploration.
* Maintain centralized control over data access and compliance.

***

### Boundaries

Toucan AI is not:

* A general-purpose BI tool for internal business reporting.
* A data warehouse or ETL (Extract, Transform, Load) platform.
* A standalone "AI add-on" for external legacy dashboards.


# Glossary

{% hint style="info" %}
**Target Audience:** Developers & Non technical users
{% endhint %}

### TL;DR

Exhaustive definitions of the building blocks, security protocols, and data structures within the Toucan.ai ecosystem.

***

### 1. Identity & Governance

* **Organization**: A secure group of users with shared access to databases, content, and permissions.
* **Workspace**: The collaborative environment within an organization where analytics content is managed.
* **Admin**: User role with full access to all features, including user and data management.
* **Maker**: User role that can create and modify charts and dashboards but cannot manage organization settings.
* **Explorer**: Read-only access to shared content; can interact with filters but cannot create content.

***

### 2. Embedding & Security

* **API Key**: A secret credential issued by Toucan.ai required to sign and generate tokens server-side.
* **Token**: A server-side generated credential used for authenticating embedded visualizations.
* **Attributes**: Custom metadata (e.g., department, customer ID) included in a token to enforce row-level security.
* **Distinct Id**: A unique identifier within a token that scopes analytics and permissions to a specific user session.
* **Row-Level Security (RLS)**: Attribute-based rules that restrict data access at the row level, automatically enforced in every query.

{% hint style="danger" %}
**Critical Security Requirement:** API Keys are secret credentials. They must be used server-side only and never exposed in client-side code.
{% endhint %}

***

### 3. Data

* **Database**: The external storage where raw data lives (SQL databases or data warehouses).
* **Table**: Structured data within a database consisting of records (rows) and attributes (columns).

***

### 4. Content & Creation

* **Chart**: A visual representation of data built from datasets and semantic definitions.
* **Dashboard**: A collection of charts and filters organized to answer specific business questions.
* **Filter**: A component that refines dashboard data by applying criteria to one or more charts.
* **AI-Assisted Creation**: The use of natural language to generate charts and queries based on the semantic layer.
* **Manual Creation**: Direct configuration of charts and dashboards for full control over metrics and layout.
* **Embedded Analytics**: Integration of analytics features directly into a host application.
* **Internal Analytics**: The use of the Toucan.ai interface for internal team data exploration.

***

### 5. General Settings

* **Variable**: A dynamic placeholder defined once and reused across configuration settings (e.g., database connections). At runtime, Toucan AI resolves the variable to inject context-specific values, such as customer or environment details.


# Credits & Usage

Toucan AI uses a credit-based system. Credits are consumed each time a user sends a message or triggers an AI action. Your plan includes a monthly credit allowance that resets each billing cycle.

#### **How credits work**

Each interaction deducts credits from your account's balance. The cost depends on the type and complexity of the request:

| Interaction                           | Indicative credit cost |
| ------------------------------------- | ---------------------- |
| Single question (standard)            | \~50 credits           |
| Single question (complex, multi-step) | Up to 100 credits      |
| Self-service dashboard creation       | \~950 credits          |
| Metadata enrichment                   | \~120 credits          |

Your monthly credit allowance depends on your plan:

| Plan  | Credits/month |
| ----- | ------------- |
| Start | 50,000        |
| Grow  | 100,000       |

At standard usage, 50,000 credits covers approximately **1,000 questions** — or a mix of questions and dashboard configurations.

{% hint style="info" %}
Credit costs are indicative and may vary depending on request complexity.
{% endhint %}

#### **Monitor your usage**

You can check your remaining credits at any time from **Settings → Usage**. The dashboard shows credits used and remaining for the current billing period.

<details>

<summary><strong>FAQ</strong></summary>

**When do my credits reset?** Credits reset every month on your billing renewal date.

**What happens if I run out of credits?** AI interactions will be paused until your credits reset. Contact your account manager if you need to increase your allowance.

**Why did a request cost more than expected?** Credit costs are indicative. Complex or multi-step requests may consume more credits depending on the amount of processing involved.

</details>


# Welcome to Toucan AI

### Your First Steps

#### First Login Experience

After signing in, you’ll land on your organization’s dashboard.\
The interface is tailored to your organization and your user role, so you see exactly what matters to you.

***

#### UI Overview

* The left sidebar gives you quick access to key sections: **Library**, **Chat**, **Databases**, and **Settings**.
* The main area displays your recent visualizations—dashboards and charts at a glance.
* Use the **“Add a visualization”** button to start building a new chart or dashboard.
* The search bar at the top lets you describe what you want to create in natural language—let AI do the heavy lifting.

<figure><img src="/files/7Px3OkcAElXwBOqaps9l" alt="Toucan AI Home"><figcaption></figcaption></figure>

***

#### Navigation Basics

* Switch between Library, Chat, and Databases using the sidebar.
* View and manage your recent visualizations right from the main dashboard.
* Access organization and account settings from the lower section of the sidebar.

***

#### Where to Start

1. **Connect your data sources** in the Databases section.<br>

   <figure><img src="/files/NEvqa3sCYjdpnkTAd5go" alt="Add a database"><figcaption></figcaption></figure>
2. Use the **Library** to view, create, and organize charts and dashboards.<br>

   <figure><img src="/files/GGE9VfqVMhFnXIIrSQs6" alt="Toucan AI Library"><figcaption></figcaption></figure>
3. Create new visualizations by clicking **“Add a visualization”** or using the search bar.<br>

   <figure><img src="/files/Gl2E1wz62gtf4KngN3ha" alt="Create a chart"><figcaption></figcaption></figure>
4. Manage organization settings and user roles from the **Settings** menu.<br>

   <figure><img src="/files/tcUXeDGTIKpkDvNGk8Nf" alt="Toucan AI Settings"><figcaption></figcaption></figure>

***

### Summary

On your first login, you’re guided to set up your organization.\
The UI is designed for easy navigation between data, charts, dashboards, and embedding options.\
Start by connecting your data, then use AI or manual tools to build and embed analytics features—quickly and efficiently.


# Quick start


# Subscribe to Toucan AI

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### Goal

Establish a Toucan AI account and create an organization to manage databases, dashboards, and permissions.

***

### Prerequisites

* Access to a Toucan AI signup page for cloud or self-hosted instances.
* A valid email address for account verification.

***

### Steps

#### 1. Create Your Account

* Navigate to the Toucan AI signup page.
* Enter your name and email address.
* Define a password.
* Click the verification link sent to your email inbox.

<figure><img src="/files/ANWWqvCQMwNnxUBCXzOn" alt="Create an account"><figcaption></figcaption></figure>

{% hint style="warning" %}
**Constraint**: An account is mandatory to access analytics features and manage organizational settings.
{% endhint %}

#### 2. Initialize Your First Organization

* Enter a name for your organization when prompted.
* Access the settings menu to modify the organization slug or URL.
* Invite team members from the organization settings panel.

<figure><img src="/files/V46t8JLF4ssttp17BCiU" alt="Team Settings"><figcaption></figcaption></figure>

{% hint style="info" %}
**Technical Note**: All databases, charts, dashboards, and user roles are scoped to the organization.
{% endhint %}

***

### Conclusion

You now have a verified account and an active organization. You may now proceed to connect data sources and define your semantic layer.

**Suggested** **Next Steps**: [How-to: Add a database](/build/data-connections/how-to/add-a-database)


# Embed a chat

{% hint style="info" %}
**Target Audience**: Non technical users & Developers
{% endhint %}

### Goal

Configure and embed a self-service chat experience into your application, allowing users to explore data using natural language.

***

### Prerequisites

* A [Toucan AI account](/getting-started/quick-start/subscribe-to-toucan) and active organization.
* Credentials for a supported SQL database (e.g., PostgreSQL).
* A code editor or environment for testing HTML/web components (e.g., Codepen).

***

### Steps

#### 1: Create an API Key

* Navigate to your Account settings page by clicking on your profile icon in the bottom left corner, then go to the **API Keys** section.
* Create a new **API Key**. Copy it and store it securely.

This key will be used on your backend server to securely generate authentication tokens for your embedded application.

<figure><img src="/files/rjrsP8YNo3k5Lyeak5Ze" alt="API Key"><figcaption></figcaption></figure>

{% hint style="danger" %}
**Security Alert**: This is a secret key. Never expose it in client-side code (HTML, JavaScript). Use it only on your secure backend server.
{% endhint %}

#### 2: Implement a user attribute model

(Optional) Define the attributes that will contextually personalize the experience for your users.

{% hint style="danger" %}
The user model will define user access to data (see "Define Row-Level Security (RLS)").
{% endhint %}

**Register User Attributes**

* Navigate to **Settings > Embed & access**.
* In the **Token Attributes** section, click **Add an attribute**.
* Define the traits you need (e.g., name: `region`, type: `String`). These must match the keys you will send in your user tokens.

<figure><img src="/files/WDVsCHWupWBU7RmTtkAB" alt="Token Attributes"><figcaption></figcaption></figure>

#### 3: Connect to a database

* Navigate to the **Database** tab from the Home Page.
* Click **Add a Database** and select a connector.
* Input connection details including Host, Username, Password, and Database name.
* Click **Test Connection**, then click **Connect**.

{% hint style="info" %}
**Example:** Connect to your HR database containing employee data, including a **location** column with values like Tokyo, Paris, etc.
{% endhint %}

**How-To**: [Add a database](/build/data-connections/how-to/add-a-database)

<figure><img src="/files/NEvqa3sCYjdpnkTAd5go" alt=""><figcaption></figcaption></figure>

#### 4: Complete Metadata Information

* Review existing table and column descriptions for accuracy.
* **(Optional)**: Click the **Analyze** button to trigger an AI scan of the database.
  * The AI generates descriptions for tables and columns based on the scanned data.
  * AI identifies specific column types, such as location data, to prepare them for visualization.
  * Review and modify the AI-generated descriptions to ensure they provide correct context for the dashboard.
* Ensure all critical columns are described plainly to improve future AI prompt results.

**How-To**: [Analyze your database with AI](/build/analyze-your-database-with-ai/how-to/analyze-your-database-with-ai)

<figure><img src="/files/pchipWr66RkQE1pXwl7u" alt="Analyze Your Database"><figcaption></figcaption></figure>

#### 5: Define Row-Level Security (RLS)

Secure your data so users only see what they are authorized to access.

1. Go to the **Database** tab and select a table.
2. In the **Access rules** section, map a **User Attribute** to a specific **dataset field** (a column of the table).
   * *Example*: Map the `user.region` attribute to the `sales_region` column.

This ensures that the AI automatically applies a filter (e.g., `WHERE sales_region = "North"`) based on the user attribute.

**How-To**: [Apply RLS to your database](https://github.com/ToucanToco/toucan-ai/blob/main/docs/permissions-and-row-level-security/how-to/apply-rls-to-your-database.md)

#### 6: Configure a chat

In the menu, go to the [chat page](https://toucanai.cloud/chat), and click "Embed" in the top right corner, then copy the snippet provided.

When configuring your embed, you can choose between two experiences:

* **AI chat only:** embed only the conversational interface.
* **AI chat + dashboard**: embed the chat with a personal dashboard for each user. The dashboard is linked to the provided `auth-token` .

<figure><img src="/files/V226FBDinjoQVxv9T6Fo" alt=""><figcaption></figcaption></figure>

As you can see, there is a placeholder for the auth token in this snippet (`auth-token="your-auth-token"`).

You can also personalize the chat experience with attributes such as:

* `welcome-message`: the first message displayed to users when the chat opens.
* `prompt-placeholder`: the placeholder text shown in the input field before the user starts typing.
* `data-theme`: optional setting to switch between `light` and `dark`.

Below is an example of what an embedded chat looks like when displayed with its associated dashboard.

<figure><img src="/files/kSS0Cv9DUWVXBitfrrFj" alt=""><figcaption><p>AI chat + dashboard embed (dashboard hidden)<br>Click the button at the top of the chat to show the dashboard.</p></figcaption></figure>

<figure><img src="/files/Wtdj4DSG26Mqc8xSw2eX" alt=""><figcaption><p>AI chat + dashboard embed (dashboard visible)</p></figcaption></figure>

{% hint style="info" %}
The *AI chat + dashboard* option is available on the Grow pricing plan.
{% endhint %}

#### 7: Get an auth token

{% hint style="info" %}
You can customize the way the AI assistant will behave thanks to "AI context clues" within the token, where you can define the tone of voice, company context, etc.
{% endhint %}

For testing and configuration, you can generate a temporary token directly from the Toucan AI interface.

* Navigate to **Settings > Embed & access**.
* Scroll down to the **Token Generation Sandbox** section.
* Paste your **API Key**.
* Under **User Attributes**, configure the values for any custom attributes as well as the `aiContextClues` for this token.
* Click **Generate Token** and copy the resulting string.

<figure><img src="/files/BYOnZf5WPbVMZVuzYTXY" alt="Token generation sandbox"><figcaption></figcaption></figure>

{% hint style="info" %}
**Production Note**: For a live application, your backend server would generate these tokens dynamically via the API to securely authenticate your users and apply the correct security filters.
{% endhint %}

#### 8: Configure CORS and embed the chat

Before your embed can render, you must authorize the domain where it will be hosted.

* In the **Embed & access** settings, locate the **Authorized Origins** section.
* Add the URL of your application or development environment (e.g., `https://codepen.io`) and click Save.
* Go to your application's code and paste the snippet you retrieved in Step 6.
* Replace `your-auth-token` with the token you generated in the previous step.

Example result in codepen:

<figure><img src="/files/Ty7PrYs63dY8N4qacWtS" alt="Codepen embedded chat"><figcaption></figcaption></figure>

***

### Conclusion

You have successfully configured and embedded a self-service chat. Your users can now ask questions and receive data-driven answers secured by your RLS and CLS policies.


# Embed a dashboard

{% hint style="info" %}
**Target Audience**: Non technical users & Developers
{% endhint %}

### Goal

Create and embed a functional dashboard into an application using AI-assisted workflows.

For each step, you will find more information in the dedicated practical guide (**How-To** sections).

***

### Prerequisites

* A [Toucan AI account](/getting-started/quick-start/subscribe-to-toucan) and active organization.
* Credentials for a supported SQL database (e.g., PostgreSQL).
* A code editor or environment for testing HTML/web components (e.g., CodePen).

***

### Steps

#### 1: Create an API Key

* Navigate to your Account settings page by clicking on your profile icon in the bottom left corner, then go to the **API Keys** section.
* Create a new **API Key**. Copy it and store it securely.

This key will be used on your backend server to securely generate authentication tokens for your embedded application.

<figure><img src="/files/rjrsP8YNo3k5Lyeak5Ze" alt="API Key"><figcaption></figcaption></figure>

{% hint style="danger" %}
**Security Alert**: This is a secret key. Never expose it in client-side code (HTML, JavaScript). Use it only on your secure backend server.
{% endhint %}

#### 2: Implement a user attribute model

(Optional) Define the attributes that will contextually personalize the experience for your users.

{% hint style="danger" %}
The user model will define user access to data (see "Define Row-Level Security (RLS)").
{% endhint %}

**Register User Attributes**

* Navigate to **Settings > Embed & access**.
* In the **Token Attributes** section, click **Add an attribute**.
* Define the traits you need (e.g., name: `region`, type: `String`). These must match the keys you will send in your user tokens.

<figure><img src="/files/WDVsCHWupWBU7RmTtkAB" alt="Token Attributes"><figcaption></figcaption></figure>

#### 3: Connect to a Database

* Navigate to the **Database** tab from the Home Page.
* Click **Add a Database** and select a connector.
* Input connection details including Host, Username, Password, and Database name.
* Click **Test Connection**, then click **Connect**.

{% hint style="info" %}
**Example:** Connect to your HR database containing employee data, including a **location** column with values like Tokyo, Paris, etc.
{% endhint %}

**How-To**: [Add a database](/build/data-connections/how-to/add-a-database)

<figure><img src="/files/NEvqa3sCYjdpnkTAd5go" alt=""><figcaption></figcaption></figure>

#### 4: Complete Metadata Information

* Review existing table and column descriptions for accuracy.
* **(Optional)**: Click the **Analyze** button to trigger an AI scan of the database.
  * The AI generates descriptions for tables and columns based on the scanned data.
  * AI identifies specific column types, such as location data, to prepare them for visualization.
  * Review and modify the AI-generated descriptions to ensure they provide correct context for the dashboard.
* Ensure all critical columns are described plainly to improve future AI prompt results.

**How-To**: [Analyze your database with AI](/build/analyze-your-database-with-ai/how-to/analyze-your-database-with-ai)

<figure><img src="/files/pchipWr66RkQE1pXwl7u" alt="Analyze Your Database"><figcaption></figcaption></figure>

#### 5: Define Row-Level Security (RLS)

Secure your data so users only see what they are authorized to access.

1. Go to the **Database** tab and select a table.
2. In the **Access rules** section, map a **User Attribute** to a specific **dataset field** (a column of the table).
   * *Example*: Map the `user.region` attribute to the `sales_region` column.

This ensures that the AI automatically applies a filter (e.g., `WHERE sales_region = "North"`) based on the user attribute.

**How-To**: [Apply RLS to your database](https://github.com/ToucanToco/toucan-ai/blob/main/docs/permissions-and-row-level-security/how-to/apply-rls-to-your-database.md)

#### 6: Create a Dashboard with AI

* Open the **Library** menu and locate the conversational prompt interface.
* Enter a natural language prompt.
* Review the AI-generated charts and modify filters or layouts as required.

{% hint style="info" %}
**Example:** The AI creates a dashboard that tracks employee contract types and locations (e.g., Tokyo, Paris).
{% endhint %}

**How-To**: [Create a dashboard with AI](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai)

<figure><img src="/files/iP0LbHrJv0zNnirmCJaS" alt="Dashboard Creation"><figcaption></figcaption></figure>

#### 7: Get an auth token

{% hint style="info" %}
You can customize the way the AI assistant will behave thanks to "AI context clues" within the token, where you can define the tone of voice, company context, etc.
{% endhint %}

For testing and configuration, you can generate a temporary token directly from the Toucan AI interface.

* Navigate to **Settings > Embed & access**.
* Scroll down to the **Token Generation Sandbox** section.
* Paste your **API Key**.
* Under **User Attributes**, configure the values for any custom attributes as well as the `aiContextClues` for this token.
* Click **Generate Token** and copy the resulting string.

<figure><img src="/files/BYOnZf5WPbVMZVuzYTXY" alt="Token generation sandbox"><figcaption></figcaption></figure>

{% hint style="info" %}
**Production Note**: For a live application, your backend server would generate these tokens dynamically via the API to securely authenticate your users and apply the correct security filters.
{% endhint %}

#### 8: Configure CORS and embed the dashboard

Before your embed can render, you must authorize the domain where it will be hosted.

* In the **Embed & access** settings, locate the **Authorized Origins** section.
* Add the URL of your application or development environment (e.g., `https://codepen.io`) and click Save.
* Go back to your dashboard
* Select **Embed** from the dashboard menu (three-dot icon).

<figure><img src="/files/2yHxYIny9jw4dDPodNAY" alt="Embed Settings"><figcaption></figcaption></figure>

* Copy the `<tc-dashboard/>` web component code.
* Paste the code into your application's HTML.
* Replace the `Auth-Token` placeholder with your generated token.

Once the token has been copied into the web component, this is what it looks like (here on codepen.io, for example).

<figure><img src="/files/UVao7Xuw0csPbJnmDSah" alt="Dashboard on CodePen"><figcaption></figcaption></figure>

**How-To**: [Embed a dashboard](/embed/embedding-overview/how-to/embed-a-dashboard)

***

### Conclusion

The dashboard is now connected to live data and embedded within the host application. To move to production, implement a server-side endpoint to generate tokens dynamically for authenticated users.


# Embed a self-service dashboard editor

{% hint style="info" %}
**Target Audience**: Non technical users & Developers
{% endhint %}

### Goal

Configure and embed a self-service dashboard editor into your application so end users can create their own dashboards from scratch.

Each dashboard is personal to the authenticated user and linked to the provided `auth-token`.

What this enables:

* End users create dashboards without leaving your app
* Dashboard ownership is scoped per user token

***

### Prerequisites

* A [Toucan AI account](/getting-started/quick-start/subscribe-to-toucan) and active organization.
* Credentials for a supported SQL database (e.g., PostgreSQL).
* A code editor or environment for testing HTML/web components (e.g., CodePen).

{% hint style="info" %}
This feature is currently configured through code integration (documentation snippet), not through the Toucan AI interface.
{% endhint %}

***

### Steps

#### 1: Create an API Key

* Navigate to your Account settings page by clicking on your profile icon in the bottom left corner, then go to the **API Keys** section.
* Create a new **API Key**. Copy it and store it securely.

This key will be used on your backend server to securely generate authentication tokens for your embedded application.

<figure><img src="/files/rjrsP8YNo3k5Lyeak5Ze" alt="API Key"><figcaption></figcaption></figure>

{% hint style="danger" %}
**Security Alert**: This is a secret key. Never expose it in client-side code (HTML, JavaScript). Use it only on your secure backend server.
{% endhint %}

#### 2: Implement a user attribute model

(Optional) Define the attributes that will contextually personalize the experience for your users.

{% hint style="danger" %}
The user model will define user access to data (see "Define Row-Level Security (RLS)").
{% endhint %}

**Register User Attributes**

* Navigate to **Settings > Embed & access**.
* In the **Token Attributes** section, click **Add an attribute**.
* Define the traits you need (e.g., name: `region`, type: `String`). These must match the keys you will send in your user tokens.

<figure><img src="/files/WDVsCHWupWBU7RmTtkAB" alt="Token Attributes"><figcaption></figcaption></figure>

#### 3: Connect to a Database

* Navigate to the **Database** tab from the Home Page.
* Click **Add a Database** and select a connector.
* Input connection details including Host, Username, Password, and Database name.
* Click **Test Connection**, then click **Connect**.

{% hint style="info" %}
**Example:** Connect to your HR database containing employee data, including a **location** column with values like Tokyo, Paris, etc.
{% endhint %}

**How-To**: [Add a database](/build/data-connections/how-to/add-a-database)

<figure><img src="/files/NEvqa3sCYjdpnkTAd5go" alt=""><figcaption></figcaption></figure>

#### 4: Complete Metadata Information

* Review existing table and column descriptions for accuracy.
* **(Optional)**: Click the **Analyze** button to trigger an AI scan of the database.
  * The AI generates descriptions for tables and columns based on the scanned data.
  * AI identifies specific column types, such as location data, to prepare them for visualization.
  * Review and modify the AI-generated descriptions to ensure they provide correct context for the dashboard.
* Ensure all critical columns are described plainly to improve future AI prompt results.

**How-To**: [Analyze your database with AI](/build/analyze-your-database-with-ai/how-to/analyze-your-database-with-ai)

<figure><img src="/files/pchipWr66RkQE1pXwl7u" alt="Analyze Your Database"><figcaption></figcaption></figure>

#### 5: Define Row-Level Security (RLS)

Secure your data so users only see what they are authorized to access.

1. Go to the **Database** tab and select a table.
2. In the **Access rules** section, map a **User Attribute** to a specific **dataset field** (a column of the table).
   * *Example*: Map the `user.region` attribute to the `sales_region` column.

This ensures that the AI automatically applies a filter (e.g., `WHERE sales_region = "North"`) based on the user attribute.

**How-To**: [Apply RLS to your database](https://github.com/ToucanToco/toucan-ai/blob/main/docs/permissions-and-row-level-security/how-to/apply-rls-to-your-database.md)

#### 6: **Behavior and user scope**

* The embedded editor lets users create dashboards from scratch.
* Each user only accesses their own dashboard workspace.
* A different `auth-token` results in a different personal dashboard context.

#### 7: Get an auth token

{% hint style="info" %}
You can customize the way the AI assistant will behave thanks to "AI context clues" within the token, where you can define the tone of voice, company context, etc.
{% endhint %}

For testing and configuration, you can generate a temporary token directly from the Toucan AI interface.

* Navigate to **Settings > Embed & access**.
* Scroll down to the **Token Generation Sandbox** section.
* Paste your **API Key**.
* Under **User Attributes**, configure the values for any custom attributes as well as the `aiContextClues` for this token.
* Click **Generate Token** and copy the resulting string.

<figure><img src="/files/BYOnZf5WPbVMZVuzYTXY" alt="Token generation sandbox"><figcaption></figcaption></figure>

{% hint style="info" %}
**Production Note**: For a live application, your backend server would generate these tokens dynamically via the API to securely authenticate your users and apply the correct security filters.
{% endhint %}

#### 8: Configure CORS and embed the dashboard editor

Before your embed can render, you must authorize the domain where it will be hosted.

* In the **Embed & access** settings, locate the **Authorized Origins** section.
* Add the URL of your application or development environment (e.g., `https://codepen.io`) and click Save.
* Copy the `<tc-self-service-dashboard/>` web component code:

```html
<script type="module" src="https://toucanai.cloud/embed/embed.js"></script>

<tc-self-service-dashboard
  server-url="https://toucanai.cloud/api"
  auth-token="your-auth-token"
  data-theme="light">
</tc-self-service-dashboard>
```

* Paste the code into your application's HTML.
* Replace the `Auth-Token` placeholder with your generated token.

Once the token has been copied into the web component, this is what it looks like (here on codepen.io, for example).

<figure><img src="/files/aeC3HLrdCR60Mnw7alGa" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The *AI chat + dashboard* option is available on the Grow pricing plan.
{% endhint %}

***

### Conclusion

You have successfully embedded a self-service dashboard editor.\
Your end users can now create and manage their own personal dashboards directly in your application, with each dashboard securely tied to the user’s authentication token.


# Build

Goal: Explain how users model data and create analytics content.


# Data connections


# Data Readiness requirements

### TL;DR

Toucan AI relies on semantic metadata to power accurate chart generation and Natural Language Queries. Before connecting, your data must be structured to eliminate ambiguity, as the platform performs read-only operations and cannot "clean" your source data.

### When to read this

Review these requirements before or during the Build phase to confirm your database is prepared for AI analysis.

### Data Preparation Standards

#### **1. Structural Logic: The "Single Grain" Rule**

The AI engine requires a clearly defined granularity for every table.

* Requirement: Each table should represent a single level of detail (e.g., one row per transaction).
* Constraint: Do not include "Total" or "Sub-total" rows within the same table as individual records.
* Why: AI agents use simple aggregations; mixed grains result in double-counting and massive errors in dashboards.

#### **2. Naming Conventions: Natural Language Mapping**

Toucan AI uses column names and display names to interpret user prompts and map chart axes.

* Requirement: Use declarative, nouns for table names and human-readable column names, reveiw the display names for columns
* Constraint: Avoid cryptic abbreviations or "computer-speak."
  * ❌ `rev_ext_tax` ->✅ `revenue_excluding_tax`
  * ❌ `ts_crtd` ->✅ `created_at_timestamp`

#### **3. Type Integrity**

Field type inference is based on sampled values.

* Metrics: Must be strictly numeric (float/int). Remove currency symbols or "N/A" strings from cells.
* Dates: Use [ISO 8601 / RFC3339](https://www.rfc-editor.org/rfc/rfc3339.html) format (`YYYY-MM-DD`) to avoid regional formatting errors.
* Categories: Use standardized strings or enums to prevent the AI from seeing "USA" and "United States" as two different entities.

### Summary

| **Feature**      | **Requirement**              | **Purpose**                                  |
| ---------------- | ---------------------------- | -------------------------------------------- |
| **Table Names**  | Use nouns (e.g., `orders`)   | Identifies entities for AI                   |
| **Column Names** | Human-readable, no codes     | <p>Enables Natural Language Query</p><p></p> |
| **Data Types**   | Cast and Clean (Strict Type) | Correct field-type inference                 |
| **Logic**        | Atomic grain (no sub-totals) | Prevents calculation errors                  |

#### Constraints

* **Read-Only**: Toucan AI never writes to your database; all cleaning must be done at the source.
* **Sampling**: Inference is based on schema structure and sampled values, not a full data audit.
* **Manual review**: All AI-generated metadata is editable and must be validated before production.


# Supported databases

{% hint style="info" %}
**Target Audience:** Non technical users & Developers
{% endhint %}

### TL;DR

Toucan.ai connects to external PostgreSQL, MySQL, Google BigQuery, ClickHouse, Snowflake, and Oracle instances for read-only data extraction.

***

### When to use it

Use this page to identify supported data sources and the network requirements for establishing a secure connection to your infrastructure.

***

### Core Functionality

Database Connections enable Toucan.ai to read data from source systems. The platform performs the following actions:

* Discovers schemas and tables.
* Previews raw data.
* Analyzes metadata using AI.
* Powers charts, dashboards, and embedded analytics.

{% hint style="warning" %}
**Constraint**: Toucan.ai only performs read operations and does not write to the connected database.
{% endhint %}

***

### Prerequisites

Before creating a database connection, ensure the following are available:

* Access to an active Toucan.ai organization.
* Valid credentials for the source database.
* Network visibility between Toucan.ai and the database.

***

### Supported Connectors

The following database and warehouse connectors are currently available:

* **PostgreSQL**.
* **Google BigQuery**.
* **MySQL**.
* **ClickHouse**.
* **Snowflake**.
* **Oracle**.

***

### Security & Network Configuration

* **Access Model**: Use a read-only database user to prevent unauthorized data modification.
* **Network Allow-Listing**: You must allow-list Toucan.ai static IP addresses in your firewall or security group settings.
* **Cloud Static IP (EU)**: `51.15.216.216`.

***

### Constraints

* **Write Operations**: Write access is not supported.
* **Firewalls**: Connection attempts will fail if network restrictions are not handled on the database side.
* **Authentication**: Every connector requires specific authentication formats (e.g., credentials vs. JSON keys).
* **Oracle specifics**: Service-name connection (`host`, `port`, `user`, `password`, `service_name`) via the Oracle 23 ODBC driver. An optional **schema (owner)** selects which schema's tables to expose — in Oracle [a schema is a database user and shares the same name as the user](https://docs.oracle.com/en/database/oracle/oracle-database/19/admqs/managing-schema-objects.html), so it defaults to the connecting user; set it to read tables owned by another schema (e.g. a read-only account). When TLS is required, add a **wallet ZIP** (max 500 KB; files at the archive root or in one folder). Non-TLS instances do not need a wallet. Individual file upload, oversized ZIPs, and nested archive layouts are not supported.


# Connection concepts and credentials security


# How-to

* [Add a database](/build/data-connections/how-to/add-a-database)
* [Connect a Snowflake database](https://github.com/ToucanToco/toucan-ai/blob/main/docs/build/data-connections/how-to/connect-a-snowflake-database.md)


# Add a database

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### Goal

Connect a PostgreSQL, MySQL, ClickHouse, Snowflake, Oracle, or Google BigQuery database/warehouse to Toucan.ai to enable metadata analysis and chart creation.

***

### Prerequisites

* A verified [Toucan.ai account](/getting-started/quick-start/subscribe-to-toucan).
* An active organization.
* Valid credentials/connection details depending on the selected connector:
  * PostgreSQL/MySQL: Host, Database Name, Username, Password, Port, and SSL settings.
  * ClickHouse: Host, Username, Password (optional), Port, and TLS setting.
  * Snowflake: Account, User, Private Key (PEM), Warehouse, Database, and optional Role/Schema/Passphrase.
  * Oracle: Host, Port, User, Password, and Service Name, plus an optional Schema owner (plus a TLS wallet ZIP when your database requires TLS).
  * BigQuery: A Google service account credentials JSON file.
* Network access granted to Toucan.ai static IPs (see [Supported Databases](/build/data-connections/supported-databases)).

***

### Steps

#### 1. Navigate to the Database Section

* Click the **Database** tab from the Toucan.ai home page.
* View the list of currently connected databases.

#### 2. Initialize the Connection

* Click the **Add a database** button in the top-right corner.
* Select a connector from the available list (**PostgreSQL**, **Google BigQuery**, **MySQL**, **ClickHouse**, **Snowflake**, **Oracle**).

<figure><img src="/files/NEvqa3sCYjdpnkTAd5go" alt="Add a database"><figcaption></figcaption></figure>

#### 3. Input Connection Details

* Enter a **Name** to identify the connection internally.
* Then provide the details required by your connector:

**PostgreSQL**

* **Host** address (e.g., `database.mycompany.com`)
* **Port** (default: `5432`)
* **Database** name (e.g., `analytics`)
* **Username** and **Password**
* **SSL** toggle based on your security requirements

<figure><img src="/files/CNMMOvzRtAgOvQg4Pcw7" alt="Add a PostgreSQL database"><figcaption></figcaption></figure>

**BigQuery**

* Upload your Google service account credentials **JSON** file (credentials format depends on your service account)
* The form will load fields such as `project_id`, `client_email`, and the private key from the JSON

> If you need to review or edit values, you can open **View raw credentials** (collapsible section) inside the form.

**MySQL**

* **Host** address
* **Port** (default: `3306`)
* **User** and **Password**
* **Charset**
* **Database** name
* **SSL Mode**
* If **SSL Mode** is enabled, fill in **SSL CA**, **SSL Cert**, and **SSL Key**.

**ClickHouse**

* **Host** address (for example `hostname.clickhouse.cloud`)
* **Port** (default: `9000`)
* **User**
* **Password** (optional, depending on your ClickHouse setup)
* **TLS** toggle

**Snowflake**

* **Account** (for example `xy12345.us-east-1`)
* **User**
* **Warehouse** (for example `COMPUTE_WH`)
* **Database**
* **Schema** (optional)
* **Role** (optional)
* **Private key (PEM)**
* **Private key passphrase** (optional)

**Oracle**

* **Host** address (e.g. `db.example.com`, or your cloud provider’s hostname)
* **Port** (default `1521`; TLS setups often use a different port—use the value from your provider)
* **User**
* **Password**
* **Service name** (e.g. `ORCL` or the service name from your connection details)
* **Schema (owner)** (optional) — the schema that owns the tables to expose. In Oracle, [a schema is a database user and shares the same name as the user](https://docs.oracle.com/en/database/oracle/oracle-database/19/admqs/managing-schema-objects.html), so this defaults to the connecting user. Set it when the login account reads tables owned by a different schema (e.g. a read-only account granted `SELECT` on another owner's tables); otherwise no tables are found.
* **TLS wallet (ZIP)** — only when your database requires TLS; upload the wallet archive as provided by your vendor (do not unzip it first)
* **Server certificate DN**, this optional field is displayed after you upload your TLS wallet and allow to verify the identity of a Oracle server during TLS connexion by indicating the Distinguished Name (DN) awaited in the server certificate. This option is required if you use a custom certificate or if you want to use a full DN matching

{% hint style="info" %}
**Oracle TLS wallet**: For managed Oracle databases that require TLS, download the wallet from your provider’s console (e.g. Autonomous Database → **Database connection** → download wallet), then upload that ZIP in the form. Toucan.ai accepts ZIP files up to 500 KB with wallet files at the archive root or in a single folder.

Not supported: pasting files individually, archives larger than 500 KB, deeply nested folder layouts, or relying on `tnsnames.ora` instead of filling **Host**, **Port**, and **Service name** in the form.
{% endhint %}

#### 4. Validate and Save

* Click **Test Connection** to verify that the credentials and network settings are valid.
* Wait for the success notification.
* Click **Connect** to save the configuration to your organization.

<figure><img src="/files/XedmV8OvbyEFHpqySdRB" alt="HR Database"><figcaption></figcaption></figure>

{% hint style="warning" %}
**Constraint**: If the test fails, verify that Toucan.ai IP(s) are allow-listed in your firewall. The UI will display an IP under **IP Whitelist**, and Toucan.ai also publishes the static IP `51.15.216.216` in its documentation.
{% endhint %}

***

### Conclusion

The database is now connected and visible in your organization's database list. You may proceed to analyze the data with AI to generate metadata descriptions.

**Suggested** **Next Steps**: [How-to: Analyse your database with AI](/build/analyze-your-database-with-ai/how-to/analyze-your-database-with-ai)


# Connect a Snowflake database


# Metadata


# AI analysis overview

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### TL;DR

Toucan.ai uses AI analysis to enrich connected databases with semantic metadata, which is required for accurate chart generation and security configuration.

***

### When to use this

Use this page to understand how metadata affects the platform's AI reasoning and when to initiate the analysis process.

***

### Purpose of AI Analysis

The Analyze feature adds a semantic layer to raw data. This process is a required step for the following workflows:

* **Natural Language Queries**: Enriches tables and columns so the AI can interpret user prompts.
* **Dashboard Generation**: Improves the selection of relevant charts based on data types.
* **Security Preparation**: Prepares column structures for Row-Level Security (RLS) mapping by inferring data types, which determines the available comparison operators
* **User Clarity**: Replaces raw database names with human-readable display names.

***

### Core Functionality

When the Analyze feature is triggered, Toucan.ai performs the following automated actions on a selected schema:

{% hint style="info" %}
**Selection Phase**

Before automated actions begin, the platform triggers a selection modal. This allows users to target specific subsets of data rather than analyzing the entire connection, optimizing processing time and relevance
{% endhint %}

| Component   | Automated Action                                                                                |
| ----------- | ----------------------------------------------------------------------------------------------- |
| **Tables**  | Generates a description summarizing the table's content (e.g., "Provides regional sales data"). |
| **Columns** | Infers a semantic field type: Category, Text, Date, or Metric.                                  |
| **Naming**  | Creates a display name for use in the UI.                                                       |
| **Context** | Generates a short explanation for what each specific column represents.                         |

{% hint style="info" %}
**Note**: All AI-generated metadata remains editable. Manual refinement is required for ambiguous columns to ensure visualization accuracy.
{% endhint %}

{% hint style="info" %}
**Refresh schema:** If your database structure changes (e.g., added tables or modified columns), use the Refresh Schema button. This triggers a re-scan of your metadata, ensuring Toucan-AI reflects the most current architecture and maintains query accuracy.
{% endhint %}

***

### Usage Requirements

* **Timing**: Initiate analysis immediately after connecting a new database or whenever the underlying schema changes.
* **Prerequisite**: Analysis must be completed before configuring RLS or creating AI-powered dashboards.
* **Persona**: This feature is designed for Product Managers and Data Analysts preparing data for end-users.

***

### Limitations

* **Sample-Based**: Inference is based on schema structure and sampled values; it is not an exhaustive data audit.
* **Scope**: Multiple schemas and tables can be selected for analysis within a single operation via the selection modal.
* **Manual Review**: Toucan.ai assumes users will validate generated metadata before production use.


# How-to


# Analyze your database with AI

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### Goal

Enrich a database schema with semantic metadata to improve the quality of AI-powered queries and visualizations.

***

### Prerequisites

* A [connected and active database](/build/data-connections/how-to/add-a-database) (e.g., PostgreSQL or Google BigQuery).

***

### Steps

#### **1.** Access the Database Schema

* Navigate to the **Databases** section.
* Select the specific database for analysis.
* View the list of identified tables and their current structure.

#### 2. Execute AI Analysis

* Click the **Analyze** button in the top-right corner of the database view
* **Select Schemas & Tables**: In the "Select schemas to analyze" modal, use the checkboxes to choose the specific schemas and tables you wish to enrich.
  * Click the **Analyze** button within the modal to launch the enrichment process.
* **Monitor Progress**: Monitor the loading bar as Toucan.ai samples the selected data.
* **Verification**: Wait for the "Enriched" status to appear on the tables before proceeding.

<figure><img src="/files/pchipWr66RkQE1pXwl7u" alt="Analyze Database"><figcaption></figcaption></figure>

#### 3. Review and Refine

* Select a table to view its Structure tab.
* Verify that the Semantic Field Type is accurate.
* Modify Display Names or Descriptions to provide better context for natural language prompts.

#### 4. Validate Data and Security

* Use the Preview tab to inspect a limited sample of the data records.
* Access the Access Rules (Row-Level Security) tab to map user attributes to specific table columns:
  * Define Logical Rules: Beyond simple mapping, you can now use operators to create complex access logic (e.g., `Department` contains `Sales`).
  * Multi-Condition Logic: Use the + AND or + OR buttons to group conditions for a single table.
  * Attribute Mapping: RLS operations compare Dataset Fields against User Attributes (provided via your authentication token).

***

#### Constraints

* **Ambiguity**: Field type inference may be incorrect for columns with generic naming or data.
* **Schema Evolution**: You must re-run the analysis if the underlying database structure changes.
* **Preview Limits**: The Preview tab is for validation only and is not intended for reporting.

***

### Conclusion

The database now contains the semantic context necessary for the AI assistant to interpret user prompts. You may now proceed to create charts in the Library or finalize security rules in the Govern phase.

**Suggested Next Step**: [How-to: Create a dashboard with AI](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai)


# Copy of Analyze your database with AI

Analyzing your data with AI is a core part of how Toucan AI helps you move from raw data to actionable insights, faster.

### Objective

In this tutorial, we will show you how to analyze your connected database using AI to enrich the context of future prompts and generate more relevant charts and dashboards.

***

### Prerequisites

You must have already [connected a database](https://toucan-toco.gitbook.io/toucan-ai/build/data-connections/supported-databases) (see the first tutorial on how to add a database).

***

### Steps

#### 1. Access Your Database

* Once your database is connected, go to the **Databases** section and click on the database you want to analyze from the list.

#### 2. Explore the Database Schema

* Once you're inside the database, you will be able to see its schema and the various tables it contains.
* On the left side of the screen, you will see a list of tables in the database, *such as HR data, sales data, video game data, or climate data for instance.*

#### 3. View the Table Structure

* On the right side of the screen, the structure of the database is displayed.
* You will see column names, display names in the dashboard, data types, and an option to manually set data types using a dropdown. You can also add descriptions for each column.

#### 4. Use AI to Analyze the Database

* Toucan AI is intelligent enough to understand your data structure. To enrich the database context automatically, click on the **Analyze** button in the top-right corner.
* Once clicked, a loading bar will appear, and after a few seconds, all tables will be analyzed. You will see the table descriptions and column descriptions being automatically completed.

<figure><img src="/files/Pul9KLR4ZBPAl6T9f8zS" alt="Analyze Database"><figcaption></figcaption></figure>

#### 5. Review and Adjust the Descriptions

* AI will detect field types and try to interpret them. For example, if a field was marked as a string, but it contains dates, Toucan AI will recognize it as a date type based on the data inside that column.
* These descriptions can be manually adjusted to improve the context and provide better insights for future visualizations. It's crucial to refine these descriptions to ensure highly relevant charts and dashboards are generated.

#### 6. Add More Context Manually

* *Although this is not yet a full **semantic layer**, it is coming soon in Toucan AI. You can continue to fine-tune the database context by adding detailed and precise descriptions for each table and column.*

<figure><img src="/files/APqL3gefCLaxEDMXTCk6" alt="Database Metadata"><figcaption></figcaption></figure>

#### 7. Preview Your Data and Apply Security

* Alongside the table structure, you will also see two additional buttons:
  * **Preview**: Clicking this will show a preview of your data.
  * **RLS (Row Level Security)**: This feature will be discussed in later tutorials, as it allows you to apply data security at a granular level.

***

### Conclusion

Congratulations! You have successfully analyzed your database with AI, which will help you create more relevant charts and dashboards in future steps.

**Suggested** **Next Steps**: discover [how-to create a chart with AI](https://toucan-toco.gitbook.io/toucan-ai/build/charts/how-to/create-a-chart-with-ai)!


# Semantic Layer


# What the Semantic Layer is?


# Metrics, dimensions and relationships


# Why does metadata matter?


# How-to


# Complete metadata information


# Variable management

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### TL;DR

Define reusable variables to replace static configuration values, enabling dynamic and multi-tenant setups.

***

### When to use this

Use this feature to manage multiple clients or environments where connection parameters (e.g., database hosts) change based on user context.

***

### Core Functionality

Variable Management enables the creation of dynamic configurations across the platform.

* **Centralization**: Define variables in one location for reuse in multiple configuration screens.
* **Dynamic Injection**: Replace static text or integers with variables that resolve at runtime.
* **Context-Awareness**: Supports multi-tenant architectures by injecting user-specific values into configurations.

***

### Prerequisites

* Access to the **Settings** menu within a Toucan.ai organization.
* For User Attribute variables: A backend system capable of generating tokens with custom attributes.

***

### Variable Types and Properties

Toucan AI supports one main type of variable:

* **User Attributes**: These variables map directly to values stored in the authentication token. They are typically used for client-specific database routing or security scoping.

Variables are managed via a table in the **Settings** > **Variables** section.

| Property          | Description                                                  |
| ----------------- | ------------------------------------------------------------ |
| **Name**          | The unique identifier used to reference the variable.        |
| **Type**          | The data format: Text, Integer, Boolean, Float, or Datetime. |
| **Default Value** | An optional value used during testing and development.       |

{% hint style="warning" %}
**Access rules Integration**\
User Attributes defined here are the primary source for access rules comparison values. For date-based filtering (e.g., `created_at > last_login`), ensure the User Attribute is explicitly typed as `Datetime` to enable comparison operators
{% endhint %}

***

### Implementation: Database Connections

Variables can be applied to specific fields during the database connection process.

* **Selector Toggle**: Supported fields allow a choice between a static value and a variable.
* **Type Matching**: Toucan.ai filters the variable list to show only types compatible with the selected field.
* **Resolution**: During a **Test Connection**, the platform resolves the variable using the default value or token attribute to validate the link.

***

### Default value&#x20;

The default value enables the definition of a preset value for testing purposes, applicable only within the platform.

#### Awaited formats for default values&#x20;

to setup a default value, use the json format&#x20;

* String: Wrapped in double quotes (e.g., `"example"`).
* Integer: A whole number without quotes (e.g., `42`).
* Float: A fractional number using a decimal point (e.g., `3.14`).
* Boolean: Lowercase `true` or `false` without quotes.
* Date: Passed as a String following the ISO 8601 standard (e.g., `"2025-02-13T12:53:45Z"`).
* List (Array): An ordered collection of any of the above types, enclosed in square brackets `[]`.

***

### Constraints

* **Type Strictness**: Lists must contain values of a single, uniform type.
* **Security**: Encryption for variable fields is not available in the current version.
* **Visibility**: Variables are only selectable in fields specifically designed to support dynamic injection.


# Security & Governance

* [Row-Level Security (RLS) operators](/build/security-and-governance/row-level-security-rls-operators)
* [Column-Level Security (CLS)](/build/security-and-governance/column-level-security-cls)


# Row-Level Security (RLS) operators

{% hint style="info" %}
**Target Audience**: Non technical users & Developers
{% endhint %}

#### TL;DR

Define granular data access by using logical operators (e.g., `contains`, `greater than`) to map User Attributes to Dataset Fields, moving beyond simple 1:1 equality.

***

#### When to use it

Use RLS operators when you need to implement complex multi-tenant security patterns, such as:

* **Hierarchical Access**: Allowing a user to see all data where a field `contains` their department name.
* **Numerical Thresholds**: Restricting data based on `greater than` or `less than` values (e.g., seniority levels or budget limits).
* **Temporal Filtering**: Limiting access to records `sooner than` or `later than` a specific date attribute.
* **Existence Checks**: Filtering rows based on whether a specific user attribute `is set` or `is not set`.

***

#### Core Functionality

The RLS engine applies security filters to SQL queries at runtime. It supports:

* **Dynamic Injection**: Resolving User Attributes from authentication tokens to filter rows.
* **Logic Grouping**: Using `AND` and `OR` blocks to wrap multiple rules for a single table.
* **Context-Aware UI**: Automatically hiding or disabling input fields for unary operators (e.g., `is set`) that only require one operand.

***

#### Prerequisites

* **Connected Database**: An active PostgreSQL or Google BigQuery connection.
* **User Attributes**: A backend system capable of generating tokens with custom attributes for comparison.

***

#### Types and Properties

Operators are automatically filtered based on the data type of the selected column and user attribute.

**Operator Availability by Type**

| **Data Type**    | **Available Operators**                                                                                                                                                                      |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| String           | `is equal to`, `is different from`, `is set`, `is not set`, `is in`, `is not in`                                                                                                             |
| Integer, Numeric | `is equal to`, `is different from`, `is set`, `is not set`, `is greater than`, `is greater than or equal to`, `is less than`, `is less than or equal to`, `is in (list)`, `is not in (list)` |
| Boolean          | `is equal to`, `is different from`, `is set`, `is not set`, `is in (list)`, `is not in (list)`                                                                                               |
| Date             | `is equal to`, `is different from`, `is set`, `is not set`, `is sooner than`, `is later than`, `is in (list)`, `is not in (list)`                                                            |

***

#### Where to use it

RLS operators are configured within the **Databases** section of the platform:

1. Navigate to a specific table in your schema.
2. Select the **Access Rules** tab.
3. Click on the rule block to select the **Dataset field**, the **Operator**, and the **User attribute**.

***

#### Constraints

* **Type Matching**: You can only refer to a date field using a User Attribute explicitly typed as a Date.
* **List Uniformity**: Operators using "in (list)" must contain values of a single, uniform type
* **No Regex Support**: Regular expressions are excluded from RLS configurations to prevent security vulnerabilities.
* **Read-Only**: RLS only impacts data extraction; Toucan.ai never writes back to the source database.

***

#### Related

For column visibility rules, see [Column-Level Security (CLS)](/build/security-and-governance/column-level-security-cls). RLS and CLS are configured together on the **Access Rules** tab and both apply at query time.


# Column-Level Security (CLS)

{% hint style="info" %}
**Target Audience**: Non technical users & Developers
{% endhint %}

#### TL;DR

Control which columns a user can see by grouping columns into sections and applying include or exclude rules based on User Attributes from authentication tokens.

***

#### When to use it

Use CLS when you need to restrict column visibility without duplicating dashboards or charts, such as:

* **PII protection**: Hiding personal identifiers (e.g., email, phone) from most users.
* **Compensation data**: Exposing salary or bonus columns only to HR or finance roles.
* **Admin-only fields**: Showing internal metadata columns only when a role attribute matches a privileged value.
* **Compliance**: Enforcing least-privilege access at the column level alongside row filters.

***

#### Core Functionality

The CLS engine evaluates column visibility at query time and injects a `select` step so only authorized columns are returned. It supports:

* **Column sections**: Group specific columns and assign an include or exclude effect.
* **Catch-all column section**: Covers every column not claimed by another sections, including columns added to the table later.
* **Conditional rules**: Apply an effect only when a User Attribute satisfies a condition (e.g., `role is equal to HR`).
* **Logic grouping**: Combine conditions with `AND` and `OR` blocks within a section.
* **Runtime enforcement**: Applies to charts, AI answers, and access-rule previews.

Unlike RLS, CLS conditions compare a **User Attribute** (left operand) against a **literal value** (right operand), not a dataset field.

***

#### Prerequisites

* **Connected Database**: An active connection.
* **User Attributes**: Custom attributes defined in **Settings > Embed & access / User Model**(scalar types only: String, Boolean, Integer, Numeric, Date).

***

#### Policy model

Since policies are usually shared among columns, we regrouped them by sections. Each section lists columns, an effect (`included` or `excluded`), and optional conditions.

There's an automatic section listed last, the **catch-all section**, to target all remaining columns and those that'll be added in the future. Like other sections, it also applies an effect (`all` = include, `none` = exclude).

When you add a column to a section, it'll be removed from the section it was in. When removing a column, it'll flow back to the catch-all section, so all columns are always explicitely covered.

When you add conditions to a section, it switches to an **included if…** form: conditions are always evaluated inclusively for simplicity.

***

#### Types and Properties

Operators are filtered based on the **User Attribute** type selected in the condition.

**Operator availability by attribute type**

| **Attribute type** | **Available operators**                                                                                                                                |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| String             | `is equal to`, `is different from`, `is in`, `is not in`                                                                                               |
| Boolean            | `is equal to`, `is different from`, `is in`, `is not in`                                                                                               |
| Integer, Numeric   | `is equal to`, `is different from`, `is greater than`, `is greater than or equal to`, `is less than`, `is less than or equal to`, `is in`, `is not in` |
| Date               | `is after`, `is before`, `is in`, `is not in`                                                                                                          |

***

#### Where to use it

CLS is configured within the **Databases** section of the platform:

1. Navigate to a specific table in your schema.
2. Select the **Access Rules** tab.
3. In the column-level section (above row-level rules), configure the catch-all or add **column sections**.
4. For each section, select columns, set the effect, and optionally add conditions on User Attributes.

***

#### Constraints

* **Scalar attributes only**: Array and date-range token attributes cannot be used in CLS conditions.
* **No existence operators**: Unlike RLS, CLS does not support `is set` or `is not set`.
* **Chart subsets**: CLS applies to the columns requested by a chart; rules only affect columns present in the query.
* **Read-Only**: CLS only impacts data extraction; Toucan.ai never writes back to the source database.

***

#### Relationship with RLS

RLS and CLS are complementary and both apply at query time:

1. **RLS** filters which **rows** a user can access (dataset field vs. User Attribute).
2. **CLS** filters which **columns** are returned (User Attribute vs. literal value).

Configure both on the same **Access Rules** tab. For a step-by-step setup guide, see [Apply CLS to your database](/embed/permissions-and-row-level-security/how-to/apply-cls-to-your-database).

For RLS operator details, see [Row-Level Security (RLS) operators](/build/security-and-governance/row-level-security-rls-operators).


# Charts


# Chart concepts


# Chart types

Chart types — overview, shared editor settings, and links to each chart type reference in Toucan AI.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring visualizations in the Library.
{% endhint %}

## Overview

Toucan AI supports several chart types in the **Library** manual editor. Each type has its own dimension, measure, and display options. Use the pages below when you refine a chart after AI creation or build one from scratch in **Manual Edit** mode.

## Prerequisites

* A [connected and active database](/build/data-connections/how-to/add-a-database).
* A **Data** source (database and query) selected in the chart editor.

## Chart type reference index

| Page                                                             | Use case                                  |
| ---------------------------------------------------------------- | ----------------------------------------- |
| [Bar chart](/build/charts/chart-types/bar-chart)                 | Compare categories or rankings            |
| [Stacked bar chart](/build/charts/chart-types/stacked-bar-chart) | Part-to-whole breakdown within categories |
| [Line chart](/build/charts/chart-types/line-chart)               | Trends over time or by category           |
| [Circular chart](/build/charts/chart-types/circular-chart)       | Share of a whole (pie / donut)            |
| [Heatmap chart](/build/charts/chart-types/heatmap-chart)         | Two dimensions with cell intensity        |
| [Value](/build/charts/chart-types/value)                         | Single KPI with optional variation        |
| [Table](/build/charts/chart-types/table)                         | Tabular data with column-level formatting |

## Shared chart-level settings

All chart types share these fields at the top of the manual editor:

| Option        | Description                                           |
| ------------- | ----------------------------------------------------- |
| **Title**     | Name shown in the Library and embeds.                 |
| **Narrative** | Optional explanation for end users.                   |
| **Data**      | Database and query that supply columns for the chart. |

## Shared measure options

Where a chart uses a **metric** column (Bars, Line, Value, etc.), you can usually set:

* **Aggregation** (Sum, Average, Count rows, etc.). Options depend on column type.
* **Format number** — decimals, percent, currency, and **Unit** for numeric columns.

See each chart page above for the exact fields available.

**Suggested next steps**

* [Create a chart](/build/charts/how-to/create-a-chart)
* [Create a chart with AI](/build/charts/how-to/create-a-chart-with-ai)
* [Customize a chart manually](/build/charts/how-to/customize-a-chart-manually)


# Bar chart

Configure a bar chart in Toucan AI to compare categories or rankings.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring charts in the Library.
{% endhint %}

<figure><img src="/files/oj2YmVZsKFgT5TdgzlUN" alt="Bar chart example"><figcaption></figcaption></figure>

## Overview

A bar chart compares a **measure** across **categories**. Each bar’s length reflects **Bar height**; categories come from **Bar category** (vertical: horizontal axis; horizontal: category axis for rankings).

* **Dimension:** **Bar category** plus optional **Orientation** (vertical or horizontal).
* **Measure:** **Bar height** — one query column, with optional **Aggregation**.
* **Optional:** **Group bars** for side-by-side bars, or a **Line** overlay (vertical orientation only).

In the **Library**, enable **Manual Edit**, set **Type** to **Bars**, and map columns under **Data**.

Shared fields (**Title**, **Narrative**, **Data**) are in [Chart types](/build/charts/chart-types#shared-chart-level-settings).

## When to use it

**Good fit**

* Compare values across categories (sales by region, headcount by team).
* Show **rankings** with horizontal bars and optional **Show rank**.
* Combine bars with a second metric as a **line** (vertical only).

**Prefer another chart**

* Trend over time → [Line chart](/build/charts/chart-types/line-chart).
* Part-to-whole within each category → [Stacked bar chart](/build/charts/chart-types/stacked-bar-chart).
* Share of a total (few slices) → [Circular chart](/build/charts/chart-types/circular-chart).
* One big number → [Value](/build/charts/chart-types/value).

**Examples:** top products by revenue, department headcount, monthly sales with a target line.

**Common setups**

* **Vertical bars:** default orientation, **Bar category** + **Bar height**.
* **Ranking:** **Horizontal** + **Show rank** under *More dimension options*.
* **Grouped bars:** **Group bars** under *More dimension options*.
* **Bar + line:** vertical orientation, **Line Y-Axis** in the **Line** section.

## Configuration options

Open the chart in the **Library**, turn on **Manual Edit**, select **Data**, then set **Type** to **Bars**. Panels: **Dimension**, **Measure**, and **Line** (vertical only). Advanced fields: *More dimension options* / *More measure options*.

Prerequisites: [connected database](/build/data-connections/how-to/add-a-database), Manual Edit ([how-to](/build/charts/how-to/customize-a-chart-manually)).

### Dimension

| Option               | How it works                                                                                                    |
| -------------------- | --------------------------------------------------------------------------------------------------------------- |
| **Orientation**      | **Vertical** (default) or **Horizontal**. Horizontal hides the **Line** section.                                |
| **Bar category**     | Category axis (X when vertical, Y when horizontal).                                                             |
| **Date granularity** | When **Bar category** is a date: **Year**, **Quarter**, **Month**, **Week**, or **Day**.                        |
| **Date format**      | How date labels appear on the category axis.                                                                    |
| **Order bars**       | *More dimension options.* Sort by a column, ascending or descending.                                            |
| **Group bars**       | *More dimension options.* Side-by-side bars per category value.                                                 |
| **Show all labels**  | Only shown when **Orientation** is **Vertical**. *More dimension options.* Label under each bar.                |
| **Show rank**        | Only shown when **Orientation** is **Horizontal**. *More dimension options.* Rank numbers on the category axis. |

### Measure

| Option                       | How it works                                                                                            |
| ---------------------------- | ------------------------------------------------------------------------------------------------------- |
| **Bar height**               | Column for bar length. Often numeric; use **Aggregation** (e.g. Count rows) otherwise.                  |
| **Aggregation**              | Reduces rows before plotting (see below).                                                               |
| **Format number**            | Shown when the measure is numeric (after aggregation). Standard, Percent, Currency, decimals, **Unit**. |
| **Show value on bar**        | *More measure options.* Values on bars (on by default).                                                 |
| **Automatic y-axis scaling** | *More measure options.* On by default; off for **Min** / **Max**.                                       |
| **Exclude 0 values**         | *More measure options.* Removes rows where the measure is **0**, **null**, or empty.                    |

### Line (vertical orientation only)

| Option                              | How it works                                                  |
| ----------------------------------- | ------------------------------------------------------------- |
| **Line Y-Axis**                     | Second metric as a line. Clear the column to remove the line. |
| **Aggregation**                     | Shown after **Line Y-Axis** is selected.                      |
| **Show value on line**              | Values on line points.                                        |
| **Unify scales for bars and lines** | On by default: bars and line share one scale.                 |

**Aggregations on Bar height and Line Y-Axis**

| Aggregation                 | Typical column types |
| --------------------------- | -------------------- |
| Sum, Cumulated sum, Average | Integer, float       |
| Minimum, Maximum            | Integer, float, date |
| Count rows, Count distinct  | All types            |
| Standard deviation          | Integer, float       |

The AI assistant can pre-fill these fields; use **Manual Edit** to adjust.

**Suggested next steps:** [Chart types](/build/charts/chart-types) · [Line chart](/build/charts/chart-types/line-chart) · [Customize a chart manually](/build/charts/how-to/customize-a-chart-manually) · [Create a chart with AI](/build/charts/how-to/create-a-chart-with-ai)


# Stacked bar chart

Configure a stacked bar chart in Toucan AI to show part-to-whole breakdowns.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring charts in the Library.
{% endhint %}

<figure><img src="/files/3ccr40bwfX2REP3UCHqe" alt="Stacked bar chart example"><figcaption></figcaption></figure>

## Overview

A stacked bar chart shows how a **total** splits into **segments** within each category. **Bar category** defines each bar; **Bar segment** defines stack layers; **Bar height** sets segment size.

* **Dimension:** **Bar category** and **Orientation** (vertical or horizontal).
* **Measure:** **Bar segment** (required) and **Bar height** with optional **Aggregation**.

In the **Library**, enable **Manual Edit**, set **Type** to **Stacked bars**, and map columns under **Data**.

Shared fields (**Title**, **Narrative**, **Data**) are in [Chart types](/build/charts/chart-types#shared-chart-level-settings).

## When to use it

**Good fit**

* Part-to-whole within each category (revenue by month split by product line).
* Compare segment mix across teams, regions, or periods.
* Survey or funnel answers stacked per question.

**Prefer another chart**

* Side-by-side category comparison → [Bar chart](/build/charts/chart-types/bar-chart).
* Trend over time → [Line chart](/build/charts/chart-types/line-chart).
* Few slices as % of one total → [Circular chart](/build/charts/chart-types/circular-chart).
* Raw row listing → [Table](/build/charts/chart-types/table).

**Examples:** revenue by month and product line, headcount by team and contract type.

{% hint style="warning" %}
Limit **Bar segment** to a modest number of categories so stacks stay readable.
{% endhint %}

**Common setups**

* **Vertical stacks:** **Bar category** + **Bar segment** + **Bar height** (e.g. Sum).
* **Over time:** date **Bar category** + **Date granularity** + segment column.
* **Horizontal:** set **Orientation** to **Horizontal**, then same fields.

## Configuration options

Open the chart in the **Library**, turn on **Manual Edit**, select **Data**, then set **Type** to **Stacked bars**. Panels: **Dimension** and **Measure** (*More dimension options* / *More measure options*).

Prerequisites: [connected database](/build/data-connections/how-to/add-a-database), Manual Edit ([how-to](/build/charts/how-to/customize-a-chart-manually)).

### Dimension

| Option               | How it works                                                                                               |
| -------------------- | ---------------------------------------------------------------------------------------------------------- |
| **Orientation**      | **Vertical** (default) or **Horizontal** stacked layout.                                                   |
| **Bar category**     | Column for each bar (category or time axis).                                                               |
| **Date granularity** | Only shown when **Bar category** is a date column. **Year**, **Quarter**, **Month**, **Week**, or **Day**. |
| **Date format**      | How date labels appear on the category axis.                                                               |
| **Order bars**       | *More dimension options.* Sort by a column, ascending or descending.                                       |
| **Show all labels**  | *More dimension options.* Label under each bar.                                                            |

### Measure

| Option                       | How it works                                                           |
| ---------------------------- | ---------------------------------------------------------------------- |
| **Bar segment**              | Column whose values become stack segments (e.g. status, product type). |
| **Bar height**               | Column for segment size. Often numeric; use **Aggregation** as needed. |
| **Aggregation**              | On **Bar height** after the column is selected.                        |
| **Format number**            | Shown when **Bar height** is numeric (after aggregation).              |
| **Show value on bar**        | *More measure options.* Values on segments (on by default).            |
| **Automatic y-axis scaling** | *More measure options.* On by default; off for **Min** / **Max**.      |

**Aggregations on Bar height**

| Aggregation                 | Typical column types |
| --------------------------- | -------------------- |
| Sum, Cumulated sum, Average | Integer, float       |
| Minimum, Maximum            | Integer, float, date |
| Count rows, Count distinct  | All types            |
| Standard deviation          | Integer, float       |

The AI assistant can pre-fill these fields; use **Manual Edit** to adjust.

**Suggested next steps:** [Chart types](/build/charts/chart-types) · [Bar chart](/build/charts/chart-types/bar-chart) · [Customize a chart manually](/build/charts/how-to/customize-a-chart-manually) · [Create a chart with AI](/build/charts/how-to/create-a-chart-with-ai)


# Line chart

Configure a line chart in Toucan AI to visualize trends and evolutions over time or categories.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring charts in the Library.
{% endhint %}

<figure><img src="/files/AewJeGZ71j7XYrqREuvp" alt="Line chart example"><figcaption></figcaption></figure>

## Overview

A line chart shows how a **measure** evolves along a **dimension** on the horizontal axis.

* **Dimension (X-Axis):** one column — often a date, or categories such as region or product.
* **Measure (Line Y-Axis):** one column from your query, with an optional **Aggregation** (Sum, Count rows, etc.). Usually a numeric metric; counts (Count rows, Count distinct) work on any column type.

You can split the chart into several lines with **Categorize by line** (one line per category value). In the **Library**, enable **Manual Edit**, set **Type** to **Line**, and map columns from your query under **Data**.

Shared fields (**Title**, **Narrative**, **Data**) are documented in [Chart types](/build/charts/chart-types#shared-chart-level-settings).

## When to use it

**Good fit**

* Show a **trend over time** (revenue by month, headcount by year).
* Compare **a few series** on the same timeline (e.g. two or three regions).
* Track a KPI that changes across ordered categories (quarters, stages).

**Prefer another chart**

* Side-by-side category comparison or ranking → [Bar chart](/build/charts/chart-types/bar-chart).
* Part-to-whole → [Stacked bar chart](/build/charts/chart-types/stacked-bar-chart) or [Circular chart](/build/charts/chart-types/circular-chart).
* A single KPI number → [Value](/build/charts/chart-types/value).

**Examples:** revenue over time, headcount by department on a shared timeline, events counted per month.

{% hint style="warning" %}
With **Categorize by line**, keep few categories (about **three lines or fewer**) so the chart stays readable.
{% endhint %}

**Common setups**

* **Time series:** date on **X-Axis** + **Date granularity** + **Line Y-Axis** with aggregation.
* **Multi-line:** same as above + **Categorize by line** (e.g. region).
* **Counts over time:** date on **X-Axis** + **Count rows** or **Count distinct** on **Line Y-Axis**.

## Configuration options

Open the chart in the **Library**, turn on **Manual Edit**, select **Data** (database + query), then set **Type** to **Line**. Options match the editor panels **Dimension** and **Measure**; advanced fields are under *More dimension options* and *More measure options*.

Prerequisites: [connected database](/build/data-connections/how-to/add-a-database), Manual Edit enabled ([how-to](/build/charts/how-to/customize-a-chart-manually)).

### Dimension

| Option                 | How it works                                                                                          |
| ---------------------- | ----------------------------------------------------------------------------------------------------- |
| **X-Axis**             | Horizontal axis (date, product, region, etc.).                                                        |
| **Date granularity**   | When **X-Axis** is a date: **Year**, **Quarter**, **Month**, **Week**, or **Day**.                    |
| **Date format**        | How date labels appear on the axis.                                                                   |
| **Order data**         | *More dimension options.* Sort by a column, ascending or descending.                                  |
| **Categorize by line** | *More dimension options.* One line per distinct value in the column.                                  |
| **Show all labels**    | *More dimension options.* Label under each X point; when off, labels may be thinned to avoid overlap. |

### Measure

| Option                       | How it works                                                                                                             |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| **Line Y-Axis**              | Column plotted on the vertical axis. Often numeric; use **Aggregation** (e.g. Count rows) for non-numeric columns.       |
| **Aggregation**              | Reduces rows before plotting.                                                                                            |
| **Format number**            | Shown when the measure is numeric (after aggregation). Style (Standard, Percent, Currency), decimals, optional **Unit**. |
| **Show value on line**       | *More measure options.* Values above each point.                                                                         |
| **Automatic y-axis scaling** | *More measure options.* On by default; off to set **Min** / **Max**.                                                     |
| **Exclude 0 values**         | *More measure options.* Removes rows where the measure is **0**, **null**, or empty (same as the UI label).              |

**Aggregations on Line Y-Axis**

| Aggregation                 | Typical column types |
| --------------------------- | -------------------- |
| Sum, Cumulated sum, Average | Integer, float       |
| Minimum, Maximum            | Integer, float, date |
| Count rows, Count distinct  | All types            |
| Standard deviation          | Integer, float       |

The AI assistant can pre-fill these fields when you create a chart with AI; use **Manual Edit** to adjust them.


# Value

Configure a Value visualization in Toucan AI to highlight a single KPI with optional variation.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring charts in the Library.
{% endhint %}

<figure><img src="/files/CP1TJOm215Z3209iBFXN" alt="Value chart example"><figcaption></figcaption></figure>

## Overview

**Value** displays one main **KPI** in large type. An optional **Variation** metric can show change versus another period or segment (for example growth or a comparison value).

* **Value:** the primary column, with optional **Aggregation** and **Format number**.
* **Variation:** optional second column under *More options*, with its own aggregation and formatting.

There is no dimension axis — the editor shows **Value** at the top, then *More options* for **Variation**. In the **Library**, enable **Manual Edit**, set **Type** to **Value**, and map columns under **Data**.

Shared fields (**Title**, **Narrative**, **Data**) are in [Chart types](/build/charts/chart-types#shared-chart-level-settings).

## When to use it

**Good fit**

* One headline number (total revenue, active users, open tickets).
* A KPI with a **comparison** (vs last month, vs target) via **Variation**.
* Dashboard tiles where a chart would be too busy.

**Prefer another chart**

* Trend over time → [Line chart](/build/charts/chart-types/line-chart).
* Compare many categories → [Bar chart](/build/charts/chart-types/bar-chart).
* Row-by-row detail → [Table](/build/charts/chart-types/table).
* Share of a whole → [Circular chart](/build/charts/chart-types/circular-chart).

**Examples:** total revenue this quarter, active users with month-over-month variation, average deal size vs last quarter.

**Common setups**

* **Single KPI:** **Value** + **Aggregation** (e.g. Sum, Count distinct) + **Format number**.
* **KPI + comparison:** configure **Value**, then **Variation** under *More options*.

## Configuration options

Open the chart in the **Library**, turn on **Manual Edit**, select **Data**, then set **Type** to **Value**.

Prerequisites: [connected database](/build/data-connections/how-to/add-a-database), Manual Edit ([how-to](/build/charts/how-to/customize-a-chart-manually)).

### Value

| Option            | How it works                                                                                                   |
| ----------------- | -------------------------------------------------------------------------------------------------------------- |
| **Value**         | Main KPI column. Often numeric; use **Aggregation** (e.g. Count rows) for other column types.                  |
| **Aggregation**   | Reduces rows before display (see below).                                                                       |
| **Format number** | Shown when the value is numeric (after aggregation). Standard, Percent, Currency, decimals, optional **Unit**. |

### More options

| Option        | How it works                                                                                                                           |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| **Variation** | Optional comparison column. Clear the selection to remove variation. Same **Aggregation** and **Format number** behavior as **Value**. |

**Aggregations on Value and Variation**

| Available                      | Not available in the editor |
| ------------------------------ | --------------------------- |
| Sum, Average, Minimum, Maximum | Cumulated sum               |
| Count rows, Count distinct     | Standard deviation          |

Availability still depends on the selected column type (same rules as other charts).

The AI assistant can pre-fill **Value** and **Variation**; use **Manual Edit** to adjust aggregation and formatting.

**Suggested next steps:** [Chart types](/build/charts/chart-types) · [Customize a chart manually](/build/charts/how-to/customize-a-chart-manually) · [Create a chart with AI](/build/charts/how-to/create-a-chart-with-ai)


# Circular chart

Configure a circular (pie or donut) chart in Toucan AI to show proportions of a whole.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring charts in the Library.
{% endhint %}

<figure><img src="/files/x1ySOlJHWmWL65iEQRAu" alt="Circular chart example"><figcaption></figcaption></figure>

## Overview

A circular chart shows how a **measure** is split across **labels** (slices). Each slice is one value of the dimension; slice size comes from **Value**.

* **Dimension:** **Label** — the column that defines each slice.
* **Measure:** **Value** — one query column, with optional **Aggregation**.

In the **Library**, enable **Manual Edit**, set **Type** to **Circular**, and map columns under **Data**.

Shared fields (**Title**, **Narrative**, **Data**) are in [Chart types](/build/charts/chart-types#shared-chart-level-settings).

## When to use it

**Good fit**

* Shares of a **limited** number of categories (market share, budget mix).
* Proportions that sum to a meaningful whole.
* Quick comparison of a few segments.

**Prefer another chart**

* Many categories or precise comparison → [Bar chart](/build/charts/chart-types/bar-chart).
* Trend over time → [Line chart](/build/charts/chart-types/line-chart).
* Part-to-whole **per** category (stacked) → [Stacked bar chart](/build/charts/chart-types/stacked-bar-chart).
* One KPI → [Value](/build/charts/chart-types/value).

**Examples:** market share by region, tickets by priority, budget by department.

{% hint style="warning" %}
Keep the number of slices small so labels stay readable.
{% endhint %}

**Common setups**

* **Share of total:** **Label** (category) + **Value** with **Sum** or **Count rows**.
* **Time slices:** date **Label** + **Date granularity** + **Value**.

## Configuration options

Open the chart in the **Library**, turn on **Manual Edit**, select **Data**, then set **Type** to **Circular**. Panels: **Dimension** and **Measure**.

Prerequisites: [connected database](/build/data-connections/how-to/add-a-database), Manual Edit ([how-to](/build/charts/how-to/customize-a-chart-manually)).

### Dimension

| Option               | How it works                                                                                        |
| -------------------- | --------------------------------------------------------------------------------------------------- |
| **Label**            | Column for each slice (category, region, etc.).                                                     |
| **Date granularity** | Only shown when **Label** is a date column. **Year**, **Quarter**, **Month**, **Week**, or **Day**. |
| **Date format**      | Only shown when **Label** is a date column. How dates appear in slice labels.                       |

### Measure

| Option            | How it works                                                                                            |
| ----------------- | ------------------------------------------------------------------------------------------------------- |
| **Value**         | Column for slice size. Often numeric; use **Aggregation** (e.g. Count rows) otherwise.                  |
| **Aggregation**   | Reduces rows before plotting (see below).                                                               |
| **Format number** | Shown when the measure is numeric (after aggregation). Standard, Percent, Currency, decimals, **Unit**. |

The AI assistant can pre-fill **Label** and **Value**; use **Manual Edit** to adjust.


# Heatmap chart

Configure a heatmap in Toucan AI to compare two dimensions with cell intensity.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring charts in the Library.
{% endhint %}

<figure><img src="/files/0PgUcG0PaKc3SOEowF7L" alt="Heatmap example"><figcaption></figcaption></figure>

## Overview

A heatmap shows a **primary cell value** for each pair of categories: one on **Columns (X-Axis)** and one on **Rows (Y-Axis)**. Color intensity reflects the metric. You can add a **secondary cell value** per cell.

* **Dimension:** **Columns (X-Axis)**.
* **Measure:** **Rows (Y-Axis)**, **Primary cell value**, and optional **Secondary cell value**.

In the **Library**, enable **Manual Edit**, set **Type** to **Heatmap**, and map columns under **Data**.

Shared fields (**Title**, **Narrative**, **Data**) are in [Chart types](/build/charts/chart-types#shared-chart-level-settings).

## When to use it

**Good fit**

* Compare a metric across **two categorical dimensions** (region × product, day × hour).
* Spot patterns or hotspots in a grid.
* Show a main metric plus a second number per cell.

**Prefer another chart**

* One dimension + trend → [Line chart](/build/charts/chart-types/line-chart).
* Category comparison without a grid → [Bar chart](/build/charts/chart-types/bar-chart).
* Detailed row-level data → [Table](/build/charts/chart-types/table).

**Examples:** activity by weekday and hour, sales by region and category, errors by service and severity.

**Common setups**

* **Two categories:** **Columns (X-Axis)** + **Rows (Y-Axis)** + **Primary cell value** (e.g. Sum).
* **Two metrics per cell:** enable **Add secondary cell value** and set **Secondary cell value**.

## Configuration options

Open the chart in the **Library**, turn on **Manual Edit**, select **Data**, then set **Type** to **Heatmap**. Panel **Dimension** holds the X axis; panel **Measure** holds rows, primary value, and *More measure options*.

Prerequisites: [connected database](/build/data-connections/how-to/add-a-database), Manual Edit ([how-to](/build/charts/how-to/customize-a-chart-manually)).

### Dimension

| Option               | How it works                                                                                                   |
| -------------------- | -------------------------------------------------------------------------------------------------------------- |
| **Columns (X-Axis)** | Horizontal categories.                                                                                         |
| **Date granularity** | Only shown when **Columns (X-Axis)** is a date column. **Year**, **Quarter**, **Month**, **Week**, or **Day**. |
| **Date format**      | Only shown when **Columns (X-Axis)** is a date column. How dates appear on the X axis.                         |

### Measure

| Option                   | How it works                                                                                                               |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| **Rows (Y-Axis)**        | Vertical categories (shown in the Measure panel).                                                                          |
| **Date granularity**     | Only shown when **Rows (Y-Axis)** is a date column. **Year**, **Quarter**, **Month**, **Week**, or **Day**.                |
| **Date format**          | Only shown when **Rows (Y-Axis)** is a date column. How dates appear on the Y axis.                                        |
| **Primary cell value**   | Metric driving cell color. Often numeric; use **Aggregation** as needed.                                                   |
| **Aggregation**          | On **Primary cell value** after the column is selected.                                                                    |
| **Format number**        | Shown when the primary value is numeric (after aggregation).                                                               |
| **Secondary cell value** | *More measure options.* Shown when the secondary metric toggle is enabled. Same aggregation/format options as the primary. |

The AI assistant can pre-fill axes and metrics; use **Manual Edit** to adjust.


# Table

Configure a table in Toucan AI with column display and formatting.

{% hint style="info" %}
**Target Audience**: Non-technical users and builders configuring charts in the Library.
{% endhint %}

<figure><img src="/files/xPiS3iOKCy5pmQbi2RAz" alt="Table chart example"><figcaption></figcaption></figure>

## Overview

A **table** lists query **rows and columns** in the Library or embeds. You choose which columns to show, how headers and values are formatted, and table behavior (pagination, totals, row styling).

Unlike bar or line charts, there is no separate dimension/measure mapping — configuration is per **column** and per **table** settings.

In the **Library**, enable **Manual Edit**, set **Type** to **Table**, and select **Data**. One block appears per query column under **Display columns**.

Shared fields (**Title**, **Narrative**, **Data**) are in [Chart types](/build/charts/chart-types#shared-chart-level-settings).

## When to use it

**Good fit**

* Detailed listings (employees, orders, transactions).
* Exact values where charts would hide precision.
* Paginated logs or directories on a dashboard.

**Prefer another chart**

* Trends or comparisons → [Line chart](/build/charts/chart-types/line-chart) or [Bar chart](/build/charts/chart-types/bar-chart).
* Two-dimensional intensity grid → [Heatmap chart](/build/charts/chart-types/heatmap-chart).
* Single KPI → [Value](/build/charts/chart-types/value).

**Examples:** employee directory with formatted dates, product catalog with tag-style status, paginated transaction log.

**Common setups**

* **Listing:** show/hide columns (eye icon), set **Label** and formats, set **Rows per page**.
* **Status tags:** **Style** → **Tag** on a text column.
* **Footer totals:** **Show totals in last row** under *More table options*.

## Configuration options

Open the chart in the **Library**, turn on **Manual Edit**, select **Data**, then set **Type** to **Table**. The column list updates when the query changes.

Prerequisites: [connected database](/build/data-connections/how-to/add-a-database), Manual Edit ([how-to](/build/charts/how-to/customize-a-chart-manually)).

### Column

| Option              | How it works                                                                                     |
| ------------------- | ------------------------------------------------------------------------------------------------ |
| **Display columns** | One row per query column. **Eye** icon: show or hide in the table.                               |
| **Label**           | Header text (expand column accordion).                                                           |
| **Style**           | **Tag** for tag-style cell rendering.                                                            |
| **Format date**     | On date columns. Preset date display.                                                            |
| **Format number**   | On numeric columns. Standard, Percent, Currency (with **Currency display**), decimals, **Unit**. |

### Table

| Option                      | How it works                                                    |
| --------------------------- | --------------------------------------------------------------- |
| **Rows per page**           | Rows per page, **1–150** (default **5**).                       |
| **Show totals in last row** | *More table options.* Totals for numeric columns in the footer. |
| **Alternate row color**     | *More table options.* Alternating row backgrounds.              |

The AI assistant can propose visible columns and formatting; use **Manual Edit** to refine.

**Suggested next steps:** [Chart types](/build/charts/chart-types) · [Customize a chart manually](/build/charts/how-to/customize-a-chart-manually) · [Create a chart with AI](/build/charts/how-to/create-a-chart-with-ai)


# AI-generated VS manual editing


# How-to


# Create a chart

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### Goal

Define the data structure and visual representation of a chart using AI-assisted or manual workflows.

***

### **Prerequisites**

* A [connected and active database](/build/data-connections/how-to/add-a-database).
* A clear idea of the chart you want to create (e.g., employee counts by contract type)

***

### **Steps**

#### 1. Access the Chart Creator

* Navigate to the **Library** tab from the home page.
* Click **Add a visualization** in the top-right corner.
* Select **Add a chart**.

#### 2. Choose a Creation Method

Toucan.ai provides two methods for chart creation. Choose the method that matches your requirement:

**Method A: AI-Assisted Creation**

* **Input Prompt**: Type a natural language request into the conversational interface (e.g., "Show me the number of employees by contract type").
* **Generate**: Press Enter to let the AI analyze the database and propose a visualization.
* **Review**: Inspect the generated chart, summary, and suggested metrics.

<figure><img src="/files/rtzxt8cbXNQetmUzCsq4" alt="AI Chart Creation"><figcaption></figcaption></figure>

**Method B: Manual Creation**

* **Enable Manual Mode**: Toggle the **Manual Edition** switch to exit the AI interface.
* **Select Data Source**: Choose the specific database and table for the chart.
* **Configure Dimensions and Metrics**: Manually assign qualitative attributes (Dimensions) and quantitative values (Metrics).
* **Define Visualization** Type: Select a chart format (e.g., bar, line, pie) and adjust orientation.

<figure><img src="/files/ikhA5Bb3Su3w8r1CfSQv" alt=""><figcaption></figcaption></figure>

#### 3. Refine and Save

* **Add Metadata**: Enter a factual title and narrative context for end-users.
* **Format Data**: Set precision, units, and number formatting.
* **Finalize**: The chart is saved automatically and is now available in the Library.

***

### **Conclusion**

The chart is successfully created and stored in the organization's Library. You can now incorporate this visualization into a dashboard or apply Row-Level Security (RLS) rules.

**Suggested Next Step:** [How-to: Create a dashboard with AI](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai)


# Create a chart with AI

Creating charts with AI in Toucan AI lets you move from data to insight in seconds—no manual setup required.

### Objective

In this tutorial, you will learn how to create a chart using AI in Toucan AI. You will interact with the AI to automatically generate a chart based on your data.

***

### Prerequisites

* A [connected database](https://toucan-toco.gitbook.io/toucan-ai/build/data-connections/how-to/add-a-database) (as seen in the previous tutorials).
* A clear idea of the chart you want to create, *such as employee counts by contract type.*

***

### Steps

#### 1. Access the "Library" Tab

* From the home page of Toucan AI, click on the **Library** tab.
* In the top-right corner, click on the **Add Visualization** button.

#### 2. Choose the "Add Chart" Option

* Click on **Add Chart** to start creating a new chart.
* This will open the AI-powered conversational interface where you can interact with the AI to generate a chart.

#### 3. Enter Your Prompt for AI

* In the conversational interface, type a relevant prompt.
  * *For example, you could type **"Show me the number of employees by contract type"** if you have HR Data for instance.*
* Once you send the prompt, Toucan AI will start analyzing your connected database and propose a chart based on the model.

#### 4. Review the AI-Generated Chart

* The chart will appear on the right side of the screen. The AI will also provide a brief summary of the proposed chart along with insights and steps to understand the data transformation process.
* You should verify the suggested metrics and dimensions to ensure they match your needs.

<figure><img src="/files/iP0LbHrJv0zNnirmCJaS" alt="AI-Generated Chart"><figcaption></figcaption></figure>

***

### Conclusion

Congratulations! You've successfully created your first chart using AI in Toucan AI. You can now refine, adjust, and save it to use in your dashboards.

**Suggested Next Steps**: [create a dashboard with AI](https://toucan-toco.gitbook.io/toucan-ai/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai)!


# Customize a chart manually

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### Goal

Modify the technical configuration and visual appearance of a chart through the manual editor.

***

### Prerequisites

* A [connected and active database](/build/data-connections/how-to/add-a-database).
* An existing [chart created with AI](/build/charts/how-to/create-a-chart-with-ai) or manually that you wish to customize in the **Library.**

***

### Steps

#### 1. Access the Chart Library

* Navigate to the **Library** tab from the main menu.
* Select an existing chart from the list to open the visualization.

#### 2. Enable Manual Edit Mode

* Click the **Manual Edit** switch to exit the AI conversational interface.
* Access the manual configuration panels for data and design.

<figure><img src="/files/ikhA5Bb3Su3w8r1CfSQv" alt="Manual Edit Mode"><figcaption></figcaption></figure>

#### 3. Configure Title and Narrative

* Input a factual title for the chart.
* Provide a narrative description to explain the data significance to end-users.

#### 4. Adjust Data and Dimensions

* **Data Steps**: Review and modify the data processing steps generated by the AI.
* **Dimensions**: Assign qualitative attributes to the chart axes (e.g., Department, Region).
* **Measures**: Assign quantitative values to be visualized (e.g., Revenue, Headcount).

#### 5. Modify Chart Type and Layout

* Select a visual format, such as bar, line, or pie charts.
* Adjust the chart orientation between horizontal and vertical layouts.
* Select specific subtypes, such as switching from a stacked bar to a regular bar chart.

#### 6. Refine Data Presentation

* **Precision**: Set the number of decimal places or round values.
* **Formatting**: Apply units (e.g., %, $) and define number styles.
* **Preview**: View the updated chart in the editor to validate the visual output.

#### 7. Save Changes

* Verify that the status indicates the chart is saved.
* The updated chart is now available for placement in dashboards.

***

### Conclusion

The chart is manually refined and saved to the organization Library. You may now integrate this visualization into a dashboard or apply Row-Level Security (RLS).

**Suggested Next Step:** [How-to: Create a dashboard with AI](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai)


# Configure a chart with dimensions and metrics

Configure charts with dimensions and metric expressions in the semantic manual editor.

{% hint style="info" %}
**Target Audience**: Makers using the semantic chart editor.
{% endhint %}

### Goal

Configure a chart manually using **dimensions** (what you slice by) and **metrics** (what you measure), instead of assigning plain column names to chart axes.

***

### Prerequisites

* A [connected and active database](/build/data-connections/how-to/add-a-database).

***

### Key concepts

| Term               | Role                                                                                                                         |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| **Dimension**      | A qualitative or time axis — a category column, or a date column with a granularity (year, month, day, …).                   |
| **Metric**         | A quantitative measure, defined by an **expression** such as `SUM(amount)` or `SUM(revenue) / COUNT_DISTINCT(customer_id)`.  |
| **Derived metric** | A metric whose expression references **other metrics by name** instead of columns, e.g. `` `male count` / `female count` ``. |
| **Data source**    | The database table (and optional **joins** to other tables) that dimensions and metrics draw columns from.                   |
| **Ordering**       | How result rows are sorted and optionally limited.                                                                           |

Dimensions reference a concrete **table column**. Metrics reference columns only inside their **expression**; every column must sit inside an aggregation (`SUM`, `AVG`, `COUNT`, …).

For field-level details on metric filters, normalization, time comparison, helper metrics, and chart slots, see the [Semantic chart reference](/references/semantic-chart-reference).

***

### Steps

#### 1. Open the manual semantic editor

The editor knows whether a chart is semantic, so two possibilities: a. Open a semantic chart from the **Library**; we provided a few examples. b. Create a new chart: it will be semantic chart.

Then switch to **Manual**.

#### 2. Choose the data source

* Under **Data**, pick the database and source table.
* Optionally add **joins** to bring in columns from related tables. Joined tables expand the column list available to dimensions and metrics.
* Data steps remain available for pre-processing the source table when needed.
* Data steps are used to transform the data upfront: filter rows, rename columns, or create derived columns, to prepare the output schema consumed by the semantic editor.
* When you use **data steps**, the semantic editor exposes the columns produced by the pipeline (including columns you create/rename in the steps). They become selectable for your **dimensions** and **metric expressions**.

#### 3. Pick a chart type

* Select the visual type (bar, line, table, value, …). Each type exposes its own dimension and metric slots — for example, a bar chart has **Bar category**, optional **Series**, and **Bar height**.

#### 4. Configure dimensions

* Open a **Dimension** block and set a **Label** (shown to end-users).
* Pick the backing **Column** from the grouped table/column picker.
* For **date** columns, choose a **Granularity** (year, quarter, month, week, day).
* Optional dimensions (e.g. **Series** on a bar chart) can be toggled on with the header switch; turning them off removes them from the saved config.
* Column selection: dimensions are bound to a specific table column via the picker, so they don't rely on “bare” column names to resolve ambiguity after `joins`.

#### 5. Configure metrics

Each metric has two definition modes:

* **Basic** — pick one column and one aggregation (`Sum`, `Average`, `Count`, …). Equivalent to writing `SUM(column_name)`.
* **Expression** — write a free-form formula combining aggregations and arithmetic.

Supported aggregations: `SUM`, `AVG`, `MIN`, `MAX`, `COUNT`, `COUNT_DISTINCT`.

You may use quotes `"` or backticks \`\`\` to delimit a column name with spaces or special characters.

If you want the full semantic reference for `where`, `having`, `timeShift`, formatting, and hidden helper metrics, see [Semantic chart reference](/references/semantic-chart-reference).

#### Legacy vs Expression (calculations)

* **Legacy** (NonSemantic): advanced calculations typically require multiple **data steps** to produce intermediate columns (numerator/denominator, derived amounts, etc.), and then measure those columns.
* **Expression (semantic)**: you can combine multiple aggregations and math operations directly inside the metric.

Ratio example:

* Legacy: prepare intermediate columns via `data steps`, then build the metric.
* Expression: `SUM(revenue) / COUNT_DISTINCT(order_id)`

Literal example:

* Expression: `SUM(revenue) + 100`
* Legacy: for this kind of calculation (addition, division, etc.), you would use **data steps** to create one or more intermediate columns, and then measure the result.

{% hint style="warning" %} **Expression rules**

* Every **column** reference must appear inside an aggregation: a bare column (`amount`) is invalid; use `SUM(amount)`. (A bare reference to another **metric** by name is allowed — that's how derived metrics work; see below.)
* Nested aggregations are not supported: for example `AVG(SUM(amount))` is rejected.
* Columns sharing the same name across multiple joined tables cannot be picked in Basic; use distinct column names (or rename in `data steps`). In Expression, if needed, use quoted identifiers for names containing spaces/special characters (e.g. `SUM("unit price")`). {% endhint %}

**Expression examples:**

```
SUM(revenue)
SUM(quantity * unit_price)
SUM(revenue) / COUNT_DISTINCT(order_id)
```

#### Literals and math operators (Expression)

The **Expression** field supports:

* Numeric literals: `42`, `3.14`, `0`
* Binary operators: `+`, `-`, `*`, `/`, `%`
* Unary negation: `-SUM(loss)`
* Parentheses for grouping: `(SUM(a) + SUM(b)) / COUNT(*)`

Examples:

```
(SUM(revenue) + 10) / COUNT_DISTINCT(customer_id)
SUM(revenue) - SUM(discount)
```

#### Deriving metrics (referencing other metrics)

An expression can reference **another metric by its name** instead of a column. This lets you build a metric out of other metrics — for example a ratio of two counts:

```
male count          → COUNT(account_id)        (filtered to gender = Male)
female count        → COUNT(account_id)        (filtered to gender = Female)
male to female ratio → `male count` / `female count`
```

Use quotes or backticks around the metric name when it contains spaces (e.g. `` `male count` ``). Each referenced metric is computed per the chart's dimensions and the results are combined, so the derived metric is evaluated at the same grain as the rest of the chart.

This makes every metric one of two kinds:

* **Simple metric** — its expression uses only columns and aggregations (`COUNT(account_id)`, `SUM(amount) / 2`). It can use the full set of options (filter, having, share-of-total, time comparison).
* **Derived metric** — its expression uses only references to other metrics plus numbers and operators (`` `male count` / `female count` ``). It can carry a **having** filter on its computed value, but **not** a row filter (`where`), share-of-total, or time comparison.

{% hint style="warning" %} **Derivation rules**

* A single expression is **either** simple **or** derived — you cannot mix a metric reference with a raw aggregation (e.g. `` `helper` + SUM(amount) `` is rejected).
* A metric referenced by another metric may carry a row **filter**, but not share-of-total, having, or time comparison.
* References must not form a **cycle** (A → B → A), and a name cannot be used by both a metric and a table column. {% endhint %}

#### Column selection in metrics

* **Basic**: column picker + aggregation. If a column has the same name in multiple joined tables, Basic selection may be disabled to avoid ambiguity.
* **Expression**: you reference columns via identifiers inside the formula. For names containing spaces or special characters, use quoted identifiers, e.g. `SUM("unit price")` or `SUM(\`unit price\`)\`.

Switching between Basic and Expression preserves separate drafts, so you do not lose your work when exploring both modes.

#### 6. Set ordering (optional)

* Enable **Ordering** to sort results by any configured dimension or metric.
* Add one or more sort predicates, drag to reorder priority, and optionally set a row **limit**.

#### 7. Preview and save

* The chart preview updates as you edit.
* Incomplete required fields are highlighted; fix them before publishing.
* Save when the status badge shows the chart is persisted.

***

### Chart-type cheat sheet

| Chart type      | Typical dimensions            | Typical metrics                                   |
| --------------- | ----------------------------- | ------------------------------------------------- |
| **Bar**         | Bar category; optional series | Bar height; optional line overlay (vertical bars) |
| **Stacked bar** | Category; stack series        | Stack value                                       |
| **Line**        | X axis; optional series       | Line value                                        |
| **Circular**    | Slice label                   | Slice value                                       |
| **Heatmap**     | X axis; Y axis                | Cell value                                        |
| **Value**       | —                             | Main value; optional comparison                   |
| **Table**       | One dimension per column      | One metric per column                             |

***

### Conclusion

The chart is configured with explicit dimensions and metric expressions. The semantic layer executes the config against your tables and joins.

**Suggested next steps:** [Semantic chart reference](/references/semantic-chart-reference) or [Add filters to a dashboard](/build/dashboards-and-layouts/how-to/add-filters-to-a-dashboard)


# Dashboards & Layouts


# Dashboard structure


# Layout rules


# Filters and interactions


# How-to


# Create a dashboard with AI

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### Goal

Create a dashboard containing multiple visualizations and synchronized filters for data interaction.

***

### Prerequisites

* A [connected and active database](/build/data-connections/how-to/add-a-database).
* [Existing charts](/build/charts/how-to/create-a-chart) in the **Library** or a clear intent for AI-generated charts.

***

### Steps

#### 1. Initialize the Dashboard Interface

* Navigate to the **Library** tab.
* **Option A (AI Prompt)**: Type a natural language request in the input box (e.g., "Create a dashboard to track employee contracts and gender") and press Enter.
* **Option B (Manual Start)**: Click **Add a visualization** and select **Add a dashboard**.

#### 2. Add Visualizations

* **Generate with AI**: Type a prompt in the conversational interface to create a new chart directly within the dashboard.
* **Add Existing**: Click **Add existing chart** to select visualizations previously saved in the **Library**.
* **Organize**: Arrange the charts within the dashboard layout by dragging components into position.

<figure><img src="/files/iP0LbHrJv0zNnirmCJaS" alt="Dashboard Creation"><figcaption></figcaption></figure>

#### 3. Configure Interactive Filters

* Click the Add Filter button in the top-right corner.
* Select a filter type (e.g., Multi-select).
* Enter a factual name for the filter (e.g., "Department").

#### 4. Link Filters to Charts

* Click the **Link icon** on the specific filter component.
* Select the chart you want the filter to control.
* Choose the specific database column to map to the filter (e.g., `team_name`).
* Repeat this process for all charts that must respond to the filter.
* Click on the **Close button** to finalize the mapping.

<figure><img src="/files/QTktGKQxQWwpRLrE2FSO" alt="Add a filter"><figcaption></figcaption></figure>

#### 5. Save the Dashboard

* Verify the dashboard configuration and chart interactivity.
* Ensure the status indicates the dashboard is saved to the workspace.

***

### Conclusion

The dashboard is created with the selected visualizations and synchronized filters. You may now proceed to configure embedding settings or apply Row-Level Security (RLS) to the source tables.

**Suggested Next Steps**: [How-to: Embed a dashboard](/embed/embedding-overview/how-to/embed-a-dashboard)


# Add filters to a dashboard

{% hint style="info" %}
**Target Audience**: Non technical users
{% endhint %}

### Goal

Implement filter components and map them to specific database columns across one or more dashboard charts.

***

### Prerequisites

* An [existing dashboard](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai) with at least one chart.
* [Charts added to your dashboard](/build/charts/how-to/create-a-chart) that you want to filter.
* Identified data columns in the connected database to serve as filter criteria (e.g., `date`, `region`, `status`).

***

### Steps

#### 1. Open the Dashboard Editor

* Navigate to the **Library** tab from the Toucan.ai home page.
* Select the target dashboard to enter the editing interface.

#### 2. Initialize a Filter Component

* Click the **Add Filte**r button in the top-right corner.
* Select a filter type based on the data requirement:
  * **Dropdown**: Restricts selection to a single value.
  * **Multi-select**: Enables selection of multiple values from a list.
  * **Date Range**: Enables selection of a start and end point for date data.

<figure><img src="/files/5RzI46tCiliCHQJ0dAkS" alt="Filter Types"><figcaption></figcaption></figure>

#### 3. Configure Filter Properties

* Input a factual **Name** for the filter (e.g., "Contract Type").
* This name serves as the label visible to end-users in the dashboard.

#### 4. Link Filter to Charts

* Click the **Link Filter** icon (link symbol) located next to the filter name.
* Click on the specific charts that must respond to this filter.
* For each linked chart, select the database column that matches the filter criteria (e.g., map the "Contract Type" filter to the `contract_type` column).
* Repeat this mapping for every chart in the dashboard that shares the relevant data.

<figure><img src="/files/HM1DjvYibShvQpuqAUCA" alt="Apply Filter"><figcaption></figcaption></figure>

#### 5. Save and Validate

* Click the **Close** button to finalize the filter configuration.
* Select different values in the new filter to verify that the linked charts update correctly.

***

### Conclusion

The dashboard now includes interactive filters synchronized across the selected charts. Users can now refine the visualized data based on the defined dimensions.

**Suggested Next Steps**: [How-to: Embed a dashboard](/embed/embedding-overview/how-to/embed-a-dashboard)


# Embed

Goal: Enable customer-facing analytics and self-service embedding.


# Embedding overview


# Embedded analytics concepts

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### TL;DR

Integrate Toucan AI visualizations and conversational assistants directly into host applications to provide contextual data exploration.

***

### When to use this

Use this page to understand the architectural relationship between your application and Toucan AI, specifically regarding security, branding, and component delivery.

***

#### **Definition of Embedded Analytics**

Embedded analytics is the integration of dashboards, charts, and AI assistants into external software, SaaS platforms, or internal tools. This model provides data insights within the user's primary workflow, removing the requirement to access a standalone business intelligence (BI) tool.

***

### **Core Architectural Concepts**

Toucan AI utilizes a "separation of concerns" architecture. The host application manages user identity and context, while Toucan AI manages data visualization and AI-driven logic.

* **Web Components**: Toucan AI provides embeddable web components compatible with React, Vue, and vanilla JavaScript for front-end integration.
* **Security Model**: Access is managed through API keys and tokens to enforce authentication and Row-Level Security (RLS).
* **White-Labeling**: Components can be styled to match the host application's branding to maintain a uniform user experience.
* **Conversational Interactivity**: End-users can interact with embedded elements through filtering or by using the AI assistant to generate charts via natural language.

***

### Implementation Use Cases

Embedding Toucan AI is utilized in environments requiring secure, multi-tenant data delivery:

* **SaaS Platforms**: Providing customer-facing analytics dashboards as a product feature.
* **Internal Tools**: Surfacing operational data within corporate portals.
* **Self-Service Portals**: Enabling users to ask data questions through an embedded AI assistant.

***

### Benefits for Developers

* **Reduced Engineering Effort**: Integrate advanced analytics and LLM-powered features without building custom visualization engines.
* **Data Governance**: Maintain centralized control over data access and security permissions across all embedded instances.
* **Contextual Access**: Deliver data at the point of action, reducing context switching for the end-user.

***

### Constraints

* **Authentication Requirement**: Every embedded session requires a valid token to ensure data security.
* **Network Visibility**: The host application must have connectivity to Toucan AI services to render components.


# Typical architectures

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### TL;DR

Toucan AI supports multiple integration patterns, ranging from direct client-side web components to backend-driven API workflows.

***

### When to use this

Use this page to select the integration model that aligns with your application's security requirements and existing infrastructure.

***

### Integration Patterns

**1. Client-Side Embedding (Web Components)**

This pattern involves loading Toucan AI components directly into the application's frontend.

* **Workflow**: The host application generates a secure token on its server and passes it to the `<tc-dashboard>` or `<tc-ai-assistant>` web components.
* **Best for**: SaaS products requiring fast deployment and high interactivity with minimal backend modifications.
* **Benefits**: Supports responsive design, full interactivity, and user-specific Row-Level Security (RLS).

**2. Backend-Driven Embedding (API Integration)**

In this model, the backend manages the communication with the Toucan AI API.

* **Workflow**: The application backend requests tokens and manages access permissions before the frontend renders the analytics components.
* **Best for**: Applications with complex multi-tenancy, advanced data governance, or legacy system requirements.
* **Benefits**: Provides maximum control over data flow and allows for custom business logic during the authentication phase.

**3. Hybrid Approach**

This architecture combines client-side components with backend API orchestration.

* **Workflow**: Uses web components for user interactivity while utilizing backend API calls for tasks like audit logging or dynamic token attribute generation.
* **Best for**: Enterprise products requiring deep integration with internal security and logging systems.

***

### Implementation Considerations

* **Token Generation**: Tokens must be generated on the server side to protect API keys and prevent unauthorized access.
* **Row-Level Security (RLS)**: Use token attributes to map user context to specific data rows, ensuring multi-tenant isolation.
* **Branding**: Apply custom CSS and themes to embedded components to match the host application's visual identity.
* **Deployment Options**: Toucan AI is available via SaaS or can be self-hosted using Docker and Helm charts.

***

### Example Architecture Diagram

<figure><img src="/files/uQzuUsu7WMvcQ6Kamu1u" alt="Architecture Diagram"><figcaption></figcaption></figure>

***

### Summary Table

| Architecture       | Primary Advantage                           | Typical Persona                |
| ------------------ | ------------------------------------------- | ------------------------------ |
| **Client-Side**    | Speed of implementation and responsiveness. | Frontend Developers.           |
| **Backend-Driven** | High security and data flow control.        | Full-Stack/Backend Developers. |
| **Hybrid**         | Flexibility and deep system integration.    | Enterprise Architects.         |


# Security boundaries

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### TL;DR

Toucan AI utilizes a multi-layered security model combining server-side token generation, row-level security (RLS), and origin restrictions to protect embedded data.

***

### When to use this

Use this page to understand the division of security responsibilities between your application and Toucan AI, and to implement best practices for multi-tenant data isolation.

***

### Key Security Principles

Toucan AI follows a "security-by-design" approach to ensure that data access remains controlled and compliant.

* **Separation of Concerns**: Your application manages user identity and authentication. Toucan AI processes data and rendering requests only when presented with a valid, authorized token.
* **Token-Based Access Control**: Every embedded component requires a signed token that defines the user or tenant identity, object-level access permissions, and token expiration.
* **Row-Level Security (RLS)**: Fine-grained access is enforced by mapping attributes within the authentication token (e.g., `user_id`, `region`) to specific database columns.
* **API Key Management**: API keys must remain on the server side to authorize token requests. Exposing keys in client-side code is a security risk.
* **Origin Restrictions**: Security settings allow you to specify authorized domains (origins) where Toucan AI components are permitted to render.
* **Data Residency**: Deployment options include SaaS or self-hosted (Docker/Helm) to accommodate varying compliance and residency requirements.

***

### Security Responsibilities

The following table outlines the division of tasks between your infrastructure and the Toucan AI platform.

| Responsibility              |   Your App / Backend  |     Toucan AI Platform    |
| --------------------------- | :-------------------: | :-----------------------: |
| **User authentication**     |           ✅           |             —             |
| **Token generation**        |           ✅           |             —             |
| **API key storage**         |           ✅           |             —             |
| **Data access control**     | ✅ (Define attributes) | ✅ (Enforce at query time) |
| **Data storage**            |           —           |  ✅ (In SaaS deployments)  |
| **Visualization rendering** |           —           |             ✅             |
| **Row-level security**      |    ✅ (Define logic)   |     ✅ (Enforce logic)     |

***

### Best Practices

* **Server-Side Signing**: Always generate and sign authentication tokens on your backend to prevent client-side tampering.
* **Token Lifespan**: Use short-lived tokens and implement a rotation strategy for API keys.
* **RLS Mandatory**: Apply row-level security as a default for all multi-tenant or sensitive data use cases.
* **Domain Whitelisting**: Strictly restrict allowed origins to your trusted production and development domains.
* **Audit Logs**: Periodically review token scopes and access logs to ensure compliance with internal security policies.


# How-to


# Embed a dashboard

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### Goal

Render a specific Toucan AI dashboard within an external web page using a `<tc-dashboard>` web component.

***

### Prerequisites

* A [dashboard created](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai) and saved in the Library.
* A [valid authentication token](/embed/authentication/how-to/authentication-and-tokens).
* Access to your application's source code or a web-based code editor (e.g., CodePen).

***

### Steps

#### 1. Locate the dashboard

* Navigate to the **Library** tab of Toucan AI.
* In the page click on **Dashboards**.
* Select the specific dashboard you intend to embed.

#### 2. Retrieve the embed code

* Click the **three dots** icon in the top-right corner of the dashboard view.
* Select **Embed** from the dropdown menu.
* Copy the provided HTML snippet containing the web component (e.g., `<tc-dashboard ...></tc-dashboard>`).

#### 3. Implement in your application

* Open your code editor and paste the copied snippet into your HTML file.

#### 4. Authorize the component

* Initially, the component may display a "Failed to load dashboard" error; this indicates that no valid token is present.
* Locate the `auth-token` attribute within the pasted tag.
* Replace the placeholder text with your valid authentication token.

{% hint style="info" %}
**Note**: In a production environment, the `auth-token` must be dynamically injected via a variable received from your backend's API call to Toucan AI.
{% endhint %}

#### 5. Verify the integration

* Save your changes and refresh the application.
* Confirm that the dashboard renders correctly and that interactive elements are functional.

<figure><img src="/files/UVao7Xuw0csPbJnmDSah" alt=""><figcaption></figcaption></figure>

***

### Conclusion

The dashboard is now successfully embedded and authorized. From here, you can apply custom CSS to match your application's branding or implement Row-Level Security (RLS) to restrict data access based on user attributes.

**Suggested Next Steps**: [How-to: Configure Row-level Security (RLS)](/embed/permissions-and-row-level-security/how-to/apply-rls-to-your-database)


# Embed an AI Chat

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### Goal

Embed a self-service AI chat from Toucan AI into a host application to enable conversational analytics.

***

### Prerequisites

* At least one [connected and active database](/build/data-connections/how-to/add-a-database).
* A [valid API key](/embed/authentication/how-to/generate-an-api-key) for token generation.
* (Recommended): [Enriched metadata](/build/analyze-your-database-with-ai/how-to/analyze-your-database-with-ai) to improve the AI assistant's accuracy.
* (Recommended): [Row-Level Security (RLS) configured](/embed/permissions-and-row-level-security/how-to/apply-rls-to-your-database) for multi-tenant data isolation.

***

### Steps

#### 1. Prepare the data layer

* Execute an AI analysis on your datasets to generate semantic metadata.
* Review column descriptions and metric definitions to ensure the AI assistant has sufficient context.
* High-quality metadata directly improves the relevance of natural language answers.

#### 2. Configure security and RLS

* Define required token attributes (e.g., `customer_id` or `region`).
* Map these attributes to specific dataset columns using the RLS interface.
* Validate the configuration with different attribute values to confirm data isolation.

#### 3. Generate an authentication token

* Generate a token including all necessary user attributes.
* Set an appropriate expiration time for the session.
* Ensure the token scope includes permission for the AI assistant capability.

#### 4. Retrieve the embed code

* Locate the embed snippet in your admin panel or use the following standard web component format:

```html
<script type="module" src="https://toucanai.cloud/embed/embed.js"></script>
<link rel="stylesheet" href="https://toucanai.cloud/embed/embed.css" />

<tc-ai-assistant
  auth-token="YOUR_AUTH_TOKEN"
  server-url="https://toucanai.cloud/api"
  data-theme="light"
></tc-ai-assistant>
```

#### 5. Integrate and test

* Paste the embed code into your application's HTML.
* Replace `YOUR_AUTH_TOKEN` with a dynamic variable from your backend.
* Load your application and submit a test prompt (e.g., "How many hires last quarter?") to verify the connection.

<figure><img src="/files/N7je2tTfv7FdrMlQY1zx" alt="Embed AI Chat"><figcaption></figcaption></figure>

***

#### Multi-tenant Example: HR SaaS

In a multi-tenant environment, the integration follows this logic to ensure data privacy:

| Step            | Configuration                                                          |
| --------------- | ---------------------------------------------------------------------- |
| **Attribute**   | `customer_id` defined in the token.                                    |
| **RLS Mapping** | Token `customer_id` maps to database `customer_id` column.             |
| **User Query**  | "How many hires last quarter?".                                        |
| **Execution**   | The query is automatically filtered by `customer_id` before execution. |
| **Result**      | The user only sees data belonging to their specific organization.      |

***

### Conclusion

The AI assistant is now embedded and respects the security boundaries defined by your authentication tokens. Users can perform ad-hoc analysis through natural language while Toucan AI handles the underlying query generation and data visualization.


# Integrate Toucan into your own AI chat

{% hint style="info" %}
**Target Audience**: Developers building a custom AI chat experience.
{% endhint %}

### Goal

Extend an AI chat you already own with Toucan's data-aware assistant. Your host LLM stays in charge of the conversation; when the user asks a data question, it calls a single Toucan tool and renders the response inline.

This is the alternative to [Embed an AI Chat](/embed/embedding-overview/how-to/embed-an-ai-chat): instead of dropping a Toucan-branded chat into your product, you keep your own chat UI and brand and add Toucan as a capability behind it.

***

### How it works

Toucan exposes an [MCP](https://modelcontextprotocol.io) endpoint at `https://toucanai.cloud/api/mcp`. Your backend connects to it like any other MCP server, attaches the discovered tools to your LLM call, and the model decides when to invoke them.

```
┌──────────────┐  user msg   ┌─────────────────┐
│  Your chat   │ ──────────► │  Your backend   │
│   (UI)       │ ◄────────── │  + your LLM     │
└──────────────┘  envelope   └────────┬────────┘
                                      │  MCP
                                      ▼
                             ┌─────────────────┐
                             │   Toucan MCP    │
                             │ (orchestrator,  │
                             │ query, charts)  │
                             └─────────────────┘
```

Tool results are self-contained JSON envelopes with an `answer` field (markdown the LLM relays verbatim) and a `visualizations` array (chart payloads your UI renders with the `<tc-result-renderer>` web component). No Toucan auth token is required on the browser side — visualizations carry their own data.

***

### Prerequisites

* At least one [connected and active database](/build/data-connections/how-to/add-a-database).
* A [valid API key](/embed/authentication/how-to/generate-an-api-key) for token generation.
* (Recommended): [Enriched metadata](/build/analyze-your-database-with-ai/how-to/analyze-your-database-with-ai) to improve the AI assistant's accuracy.
* (Recommended): [Row-Level Security (RLS) configured](/embed/permissions-and-row-level-security/how-to/apply-rls-to-your-database) for multi-tenant data isolation.
* An LLM SDK on your backend that speaks MCP. The examples below use the [Vercel AI SDK](https://ai-sdk.dev/) (`@ai-sdk/mcp`), but any MCP-capable client works.

***

### Steps

#### 1. Generate a Toucan embed token on your backend

The MCP endpoint is authenticated with the same embed tokens you use for dashboard or chat embedding. Mint a token server-side, scoped to the end user's attributes so RLS applies to every query the assistant runs. How you cache it (per request, per session, per browser tab) is up to your auth model — just keep it server-side.

See [Generate a token via API](/embed/authentication/how-to/generate-a-token-via-api) for the full token-generation flow.

#### 2. Connect to the Toucan MCP endpoint

From your chat backend (typically the route that proxies to your LLM), open an MCP session, then pull the tools list **and** the `tool-usage` prompt that ships the system-prompt addendum your LLM needs to relay Toucan's `answer` verbatim:

```ts
import { createMCPClient } from "@ai-sdk/mcp";

const client = await createMCPClient({
  transport: {
    type: "http",
    url: "https://toucanai.cloud/api/mcp",
    headers: { Authorization: `Bearer ${embedToken}` },
  },
});

const [tools, toolUsage] = await Promise.all([
  client.tools(),
  client.experimental_getPrompt({ name: "tool-usage" }),
]);
const systemAddendum = toolUsage.messages
  .map((m) => (m.content.type === "text" ? m.content.text : ""))
  .join(" ");
// Remember to call client.close() when the request finishes.
```

Both the tool list and the prompt are discovered at runtime via MCP, so any new capabilities or guidance Toucan ships will surface to your LLM automatically without code changes on your side.

#### 3. Attach the tool to your LLM call

Pass the tools to your existing chat completion and append `systemAddendum` to your own system prompt. The addendum tells the model to forward Toucan's natural-language `answer` instead of paraphrasing it; without it the model tends to summarize.

```ts
import { streamText } from "ai";

const result = streamText({
  model: yourModel,
  system: `${YOUR_SYSTEM_PROMPT} ${systemAddendum}`,
  messages,
  tools,
  onFinish: () => client.close(),
  onError:  () => client.close(),
});
```

#### 4. Render visualizations in your UI

Load the Toucan embed script once in your app's root layout so the `<tc-result-renderer>` custom element registers itself globally:

```html
<script type="module" src="https://toucanai.cloud/embed/embed.js"></script>
```

That single script tag is the only browser-side dependency.

Then, in your message-rendering loop, find the Toucan tool result, parse its text content as JSON, and assign each `visualization` to a `<tc-result-renderer>`. The renderer takes its input via the `payload` DOM property (not an attribute), so you assign it programmatically once the element is in the DOM.

Add a small helper to recognise a Toucan envelope by its `schema` field, so any other tools you've attached pass through untouched. The current wire-format tag is `"toucan-mcp-v1"`; new major versions will publish a new tag and this page will be updated.

```js
function parseToucanEnvelope(text) {
  try {
    const parsed = JSON.parse(text);
    if (parsed?.schema === "toucan-mcp-v1") return parsed;
  } catch {}
  return null;
}
```

**Vanilla JS / any framework**

```js
function renderToucanResult(toolResult, container) {
  const envelope = parseToucanEnvelope(toolResult.content?.[0]?.text);
  if (!envelope) return; // not a Toucan tool result: ignore
  for (const viz of envelope.visualizations) {
    const el = document.createElement("tc-result-renderer");
    el.style.cssText = "display: block; height: 360px";
    el.payload = viz;
    container.appendChild(el);
  }
}
```

**React example**

```tsx
// In your message-part loop, alongside your text branch:
if (part.type.startsWith("tool-") || part.type === "dynamic-tool") {
  const envelope = parseToucanEnvelope(part.output?.[0]?.text);
  if (!envelope) return null; // not a Toucan tool result: ignore
  return envelope.visualizations.map((viz, i) => (
    <tc-result-renderer
      key={i}
      ref={(el) => { if (el) el.payload = viz; }}
      style={{ display: "block", height: 360 }}
    />
  ));
}
```

Each visualization payload includes both the chart configuration and its data rows, so no further Toucan API calls or auth tokens are needed in the browser.

#### 5. Test

Send a non-data message ("hi") and verify your existing chat behaves as before. Then ask a data question ("Top 5 customers by revenue this quarter") and verify the answer streams in along with one or more rendered charts underneath.

***

### Response envelope reference

Every Toucan tool result is a single text content block whose text is JSON of the following shape. You don't need to import this type — it's reproduced here for reference; just `JSON.parse` the text and read the fields.

```ts
type ToucanMCPEnvelope = {
  schema: "toucan-mcp-v1";
  answer: string;                  // markdown — surface verbatim
  visualizations: Visualization[]; // empty when no chart was produced
  threadId: string;                // pass back on follow-up questions to retain context
};

type Visualization =
  | { type: "chart"; title: string; narrative?: string; config: ...; data: Row[] }
  | { type: "error"; title?: string; message: string }
  | { type: "text";  text: string };
```

The `schema` field is the version tag; renderers should branch on it and ignore unknown `type` values rather than throwing, so the contract stays forward-compatible.

***

### Current scope and limits

* **Conversational memory via `threadId`**. Every envelope includes a `threadId`. Pass it back in the next `ask_toucan_assistant` call to continue the same conversation thread — the assistant will remember previous queries and charts. Omit it (or start fresh) to begin a new thread. The host LLM decides when to thread vs. start fresh; the `tool-usage` system-prompt addendum (step 2) already instructs it how. Threads are ephemeral: they expire after a period of inactivity.
* **Browser does not need a Toucan token**. Only your backend authenticates; visualizations are self-contained.
* **RLS still applies**. Every query the assistant runs is scoped to the attributes you put on the embed token in step 1.
* **in-progress notifications**. Our tools pushes notifications as MCP `notifications/progress` message. Make sure your library handle them, and wire them into your existing status indicator, to see Toucan's real progress.

***

### Conclusion

Your chat now answers data questions through Toucan without leaving the host UI. Users keep your branding and conversational experience while gaining self-service analytics over your governed data layer.


# Authentication


# Authentication models

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### TL;DR

Toucan AI utilizes server-side token generation to authorize user access and enforce data isolation for embedded components.

***

### When to use this

Use this page to understand the technical workflow for securing embedded dashboards and the AI assistant, ensuring each user only accesses authorized data.

***

### Purpose of Authentication

Authentication establishes a secure link between the host application and Toucan AI. It serves two primary functions:

* **Access Control**: Verifies that a user is authorized to view specific dashboards, charts, or the AI assistant.
* **Data Scoping**: Enables Row-Level Security (RLS) and multi-tenant isolation by passing user context from the host application to Toucan AI.

***

### Token-Based Authentication

This is the standard model for production environments. It relies on a secure handshake between your backend and the Toucan AI API.

**Technical Workflow**

1. **Identity Verification**: Your application authenticates the user through your existing system (e.g., SSO, OAuth, or JWT).
2. **Token Generation**: Your backend requests a signed session token from Toucan AI using a secure API key. This token encodes the user identity and custom attributes like `organization_id` or `region`.
3. **Frontend Delivery**: The backend passes this token to the frontend, where it is injected into the `<tc-dashboard>` or `<tc-ai-assistant>` web component.
4. **Validation**: Toucan AI validates the token signature and enforces the associated RLS rules during data execution.

**Use Case Suitability**

* **Multi-tenant SaaS**: Essential for isolating customer data within shared database schemas.
* **Production Environments**: Required for any scenario where API keys must be protected from client-side exposure.
* **Dynamic Scoping**: Best for applications where data access changes frequently based on user roles or departments.

<figure><img src="/files/KvEYoib3jOZmV6a4A2K9" alt="Authentication Flow"><figcaption></figcaption></figure>

***

### Security Best Practices

* **Server-Side Execution**: Always generate and sign tokens on your backend; never expose API keys or signing secrets in client-side code.
* **Token Expiration**: Implement short-lived tokens to minimize the impact of potential session compromise.
* **Credential Rotation**: Regularly rotate API keys within the Toucan AI settings to maintain platform security.
* **Minimalist Attributes**: Include only the specific attributes required for access control and RLS to maintain efficient token payloads.


# Copy of Authentication models

Embedding analytics securely means choosing the right authentication model for your product and users. Toucan AI supports flexible authentication approaches to fit a variety of integration scenarios, from simple SaaS products to complex, multi-tenant platforms.

### Why Authentication Matters

Authentication ensures that only authorized users can access embedded dashboards, charts, and AI assistants. It also enables fine-grained control over what data each user can see, supporting row-level security, multi-tenancy, and compliance requirements.

***

### Supported Authentication Models

#### 1. Token-Based Authentication (Recommended)

**How it works:**

* Your backend authenticates the user (via your own auth system: SSO, OAuth, JWT, etc.).
* Your backend generates a signed token (using your Toucan AI API key) that encodes the user’s identity, permissions, and any custom attributes (e.g., organization, department, region).
* The token is passed to the embedded Toucan AI component in the frontend.
* Toucan AI validates the token and enforces access control and row-level security.

**Best for:**

* Most production use cases
* Multi-tenant SaaS platforms
* Scenarios requiring row-level security or user-specific data

**Benefits:**

* Secure: API keys and signing logic stay server-side
* Flexible: Supports custom attributes and fine-grained access
* Scalable: Works with any authentication provider

***

#### 2. API Key Authentication (For Testing & Development)

**How it works:**

* You use your Toucan AI API key directly to generate tokens in a sandbox or development environment.
* API keys should never be exposed in client-side code or production environments.

**Best for:**

* Local development
* Testing embedding and integration flows

**Benefits:**

* Quick setup for prototyping
* Not recommended for production

***

#### 3. Single Sign-On (SSO) Integration

**How it works:**

* Your application handles SSO (e.g., SAML, OAuth, OpenID Connect) for user authentication.
* After authentication, your backend generates a Toucan AI token for the user session.
* The rest of the flow is identical to token-based authentication.

**Best for:**

* Enterprise deployments
* Organizations with centralized identity providers

***

### How to Choose

* For most use cases: Use token-based authentication, generated server-side after your own user authentication.
* For internal tools or demos: API key authentication is acceptable, but never expose keys in production.
* For enterprise SSO: Integrate your SSO provider and generate tokens after successful login.

***

### Example Flow

<figure><img src="/files/Ie6KaBBHgQYLEkm9qJeM" alt="Authentication Flow"><figcaption></figcaption></figure>

***

### Best Practices

* Always generate and sign tokens server-side.
* Never expose API keys or signing secrets in client-side code.
* Use short-lived tokens and rotate API keys regularly.
* Include only necessary attributes in tokens for access control and row-level security.

***

### Summary

Toucan AI’s authentication models are designed to be secure, flexible, and easy to integrate—so you can deliver embedded analytics with confidence.


# Token-based access

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### TL;DR

Toucan AI uses signed authentication tokens to define granular user permissions and session lifespan without exposing backend credentials.

***

### When to use this

Use this page to configure the `permissions` object during token generation to control specific user actions, such as editing dashboards or querying the AI assistant.

***

### Fine-grained permissions

The authentication token includes a `permissions` object that determines the available actions for the embedded user. This model allows for precision control at the resource level.

#### Permission levels

| Permission     | Description                                                            |
| -------------- | ---------------------------------------------------------------------- |
| **can\_view**  | Grants read-only access to the specified resource.                     |
| **can\_edit**  | Grants full access to view, create, update, and delete the resource.   |
| **can\_query** | Specifically enables the use of the AI assistant for data exploration. |

#### Permission models by resource

| Model         | Available Permissions  | Description                                                     |
| ------------- | ---------------------- | --------------------------------------------------------------- |
| **dashboard** | `can_view`, `can_edit` | Controls the ability to view or manage dashboards.              |
| **chart**     | `can_view`, `can_edit` | Controls the ability to view or manage individual charts.       |
| **database**  | `can_view`, `can_edit` | Controls access to data source configurations within Toucan AI. |
| **ai**        | `can_query`            | Grants permission to use the AI assistant.                      |

{% hint style="warning" %}
**Note**: Database permissions control the management of connection settings and table metadata within Toucan AI; they do not grant direct write access to your source database.
{% endhint %}

***

### Implementation examples

To generate a token with specific permissions, perform an HTTP POST request to the `/embed/generate-token` endpoint.

Your request must include:

* The `x-api-key` header with your API key
* The `Content-Type: application/json` header
* A JSON body containing the `user` and `permissions` objects

**Example request body:**

```json
{
  "user": {
    "distinctId": "user-123",
    "role": "explorer"
  },
  "permissions": {
    "dashboard": "can_edit",
    "chart": "can_edit"
  }
}
```

**1. View-only access**

Restricts users to reading data without the ability to modify visualizations.

```json
{
  "user": {
    "distinctId": "user-123",
    "role": "explorer"
  },
  "permissions": {
    "dashboard": "can_view",
    "chart": "can_view"
  }
}
```

**2. Full edit access**

Allows users to create and modify both dashboards and charts.

```json
{
  "user": {
    "distinctId": "user-123",
    "role": "explorer"
  },
  "permissions": {
    "dashboard": "can_edit",
    "chart": "can_edit"
  }
}
```

**3. AI-enabled exploration**

Allows users to view dashboards and perform ad-hoc queries via the AI assistant.

```json
{
  "user": {
    "distinctId": "user-123",
    "role": "explorer"
  },
  "permissions": {
    "dashboard": "can_view",
    "ai": "can_query"
  }
}
```

***

### Constraints and defaults

* **Default Fallback**: If no `permissions` object is provided, Toucan AI defaults to `can_view` for dashboards, charts, and databases, with no AI access (`❌`).
* **Permission Overrides**: Explicit token permissions override default role behavior. For example, a user with an "explorer" role can be granted `can_edit` access through the token.
* **Security**: Tokens must be generated and signed server-side. API keys must never be exposed in client-side code.


# User identity propagation

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### TL;DR

Securely transmit user identity and contextual attributes from your application to Toucan AI via signed tokens to enable data isolation and personalized analytics.

***

### When to use this

Use this page to configure how your backend communicates a user's unique ID and access attributes (such as region or department) to Toucan AI for Row-Level Security (RLS) enforcement.

***

### Definition of identity propagation

User identity propagation is the process of transferring an authenticated user's identity and specific metadata from your host application to Toucan AI. This transfer occurs within the encrypted payload of the embed token.

#### **Core objectives**

* **Data Isolation**: Ensures Row-Level Security (RLS) restricts users to only the records they are authorized to view.
* **Compliance and Auditing**: Attributes every query and action to a specific user for monitoring and reporting purposes.
* **Contextual Experience**: Enables the dashboard or the AI assistant to provide personalized data filtered for the user's specific context.

***

### Technical workflow

The propagation follows a secure four-step sequence between your application and Toucan AI.

1. **Host Authentication**: Your backend verifies the user's identity using your internal system (e.g., SSO or OAuth).
2. **Token Payload Construction**: Your backend requests a Toucan AI token and includes a `user` object containing specific identity fields:
   * `distinctId` (Required): A unique, stable identifier for the user.
   * `role`: The user's specific role within Toucan AI (e.g., explorer, maker).
   * `attributes` (Optional): Custom key-value pairs (e.g., `customerId`, `region`) used to drive RLS logic.
3. **Frontend Transfer**: The backend delivers the signed token to the frontend, where it is injected into the `<tc-dashboard>` or `<tc-ai-assistant>` component.
4. **Verification and Enforcement**: Toucan AI validates the token signature and enforces data filters based on the provided attributes.

**Example token payload**

```json
{
  "user": {
    "distinctId": "user-123",
    "role": "explorer",
    "attributes": {
      "department": "finance",
      "region": "EMEA"
    }
  }
}
```

***

### Implementation best practices

* **Stable Identifiers**: Use your application's internal primary key as the `distinctId` to ensure consistent tracking.
* **Minimalist Attributes**: Only include the attributes strictly necessary for RLS or personalization to minimize token size.
* **Server-Side Security**: Tokens must be generated and signed on the server to prevent users from modifying their own attributes or permissions.
* **Data Privacy**: Do not include sensitive information in the token payload unless it is functionally required for access control.

***

### Summary table: propagation results

| Feature           | Outcome of propagation                                          |
| ----------------- | --------------------------------------------------------------- |
| **Multi-tenancy** | Users from different organizations only see their own data.     |
| **Security**      | Requests are tied to a specific identity and cannot be spoofed. |
| **Auditability**  | All actions can be traced to the `distinctId` provided.         |


# How-to


# Generate an API key

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### Goal

Obtain an API key to securely authenticate server-side requests to Toucan AI.

***

### Prerequisites

* A [Toucan AI account](/getting-started/quick-start/subscribe-to-toucan) with active access.
* Permissions to modify user profile and security settings.

***

### Steps

#### 1. Open security settings

* Locate the user profile icon (containing your initials) in the bottom-left corner of the Toucan AI interface.
* Click the icon and select the **Account settings** from the navigation menu.

#### 2. Navigate to API keys

* Scroll to the **API Keys** section.
* This area displays existing keys and allows for the creation of new credentials.

#### 3. Generate the key

* Click the **Create API Key** button.
* Toucan AI will generate and display a new unique string.

#### 4. Secure the credential

* Copy the key immediately and save it in a secure environment, such as a password manager or your application’s environment variables (`.env`).

{% hint style="danger" %}
**Security Alert**: Never expose this key in client-side code, public repositories, or frontend scripts, as it grants administrative access to generate session tokens.
{% endhint %}

<figure><img src="/files/rjrsP8YNo3k5Lyeak5Ze" alt="API Keys"><figcaption></figcaption></figure>

***

#### API key functionality

The API key acts as a master credential for the following backend operations:

* **Token Generation**: Requesting signed session tokens for embedded dashboards and the AI assistant.
* **Access Control**: Defining user permissions and roles within the generated tokens.
* **Data Filtering**: Passing attributes for Row-Level Security (RLS) enforcement.

***

### Conclusion

The API key is now active and stored for backend use. This credential serves as the foundation for authenticating your users and delivering personalized analytics experiences.

**Suggested Next Step**: [How-to: Generate a token](/embed/authentication/how-to/authentication-and-tokens)


# Generate a token

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### Goal

Generate a temporary authentication token to authorize an embedded dashboard or the AI assistant in a development environment.

***

### Prerequisites

* A [Toucan AI account](/getting-started/quick-start/subscribe-to-toucan) with active access.
* A [valid API key](/embed/authentication/how-to/generate-an-api-key).
* Access to the platform's security and embed settings.

***

### Steps

#### 1. Access embed settings

* Click on the **Settings** button in the main menu.
* Select the **Embed & access** tab to access the token management interface.

#### 2. Configure authorized origins

* Navigate to the **Authorized Origins** section.
* Define the specific URLs (domains) where Toucan AI components are permitted to render.
* Toucan AI will reject requests and tokens used on domains not listed in this section.

#### 3. Define token attributes

* Review the **Token Attributes** section to see default identity fields like `distinctId` and `role`.
* Add any custom attributes (e.g., `location`, `department`) required to test Row-Level Security (RLS) filters.

#### 4. Generate a sandbox token

* Scroll to the **Token Generation Sandbox** section.
* Paste your API key into the designated field.
* Click **Generate Token** to create a signed credential.
* **Validity**: By default, sandbox tokens remain valid for **1 hour**.

<figure><img src="/files/PL3c3vo1IkdcaRs4FUNP" alt="Token Generation"><figcaption></figcaption></figure>

#### 5. Verify and inspect

* Copy the generated token for use in your embed code.
* **Token Introspection**: If you need to verify the payload, use the **Token Introspection** section to view the encoded attributes and expiration timestamp.

***

#### Token functionality

The generated token facilitates the following during an embedded session:

* **Secure Handshake**: Authenticates the component without exposing your master API key.
* **Data Scoping**: Automatically applies RLS rules based on the attributes contained in the token payload.

***

### Conclusion

You have generated a temporary token for testing purposes. While this sandbox token is suitable for development, production environments require your backend to generate these tokens dynamically via the API.

**Suggested Next Step**: [How-to: Embed a dashboard](/embed/embedding-overview/how-to/embed-a-dashboard) or [How-to: Configure Row-Level Security (RLS)](/embed/permissions-and-row-level-security/how-to/apply-rls-to-your-database)


# Generate a sandbox token

Sandbox tokens in Toucan AI let you test and validate your embedded analytics in a safe, controlled environment—before rolling out to production.

### Objective

In this tutorial, you will learn how to generate a sandbox token in Toucan AI. Sandbox tokens allow you to test embedding your visualizations and dashboards in a controlled environment before using them in production.

***

### Prerequisites

* A Toucan AI [account](https://toucan-toco.gitbook.io/toucan-ai/getting-started/subscribe-to-toucan).
* An [API key](https://toucan-toco.gitbook.io/toucan-ai/embed/authentication) (as seen in the previous tutorial on [how to generate a sandbox API key](https://toucan-toco.gitbook.io/toucan-ai/embed/authentication/how-to/generate-an-api-key)).

***

### Steps

#### 1. Access the Settings Menu

* From the main interface, click on the **Settings** button in the menu.

#### 2. Navigate to the Embed Tab

* In the **Settings** menu, click on the **Embed** tab to access token generation settings.

#### 3. Find the Token Generation Sandbox Section

* Scroll down to the **Token Generation Sandbox** section within the **Embed** tab.
* This section allows you to generate tokens specifically for testing and embedding purposes.

#### 4. Paste Your API Key

* In the **Token Generation Sandbox**, you will see a field to paste your **API key**.
* Copy your API key (generated in the previous tutorial) and paste it into this field.

#### 5. Generate the Token

* If needed, complete **Custom Attributes** to test your Row Level Security
* After pasting the API key, click the **Generate Token** button.
* A sandbox token will be generated and displayed on the screen. This token is valid for a limited time (1 hour by default) and can be used to test embedding visualizations or dashboards.

<figure><img src="/files/PL3c3vo1IkdcaRs4FUNP" alt="Token Generation"><figcaption></figcaption></figure>

#### 6. Copy and Store the Token

* **Copy the token** to use it for embedding dashboards and testing your integrations.
* Store the token securely in your password manager for future use.

***

### Conclusion

Congratulations! You have successfully generated a sandbox token in Toucan AI. This token can now be used to test embedding dashboards and charts within your application in a safe environment before going live in production.

**Suggested Next Steps:** [Token Introspection](https://toucan-toco.gitbook.io/toucan-ai/embed/authentication/how-to/token-introspection)!


# Generate a token via API

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### Goal

Implement a server-to-server POST request to the Toucan AI `/generate-token` endpoint to retrieve a signed access token.

***

### Prerequisites

* A [Toucan AI account](/getting-started/quick-start/subscribe-to-toucan) with an active instance.
* A [valid API key](/embed/authentication/how-to/generate-an-api-key) with permissions to generate tokens.
* Knowledge of your instance's base URL (SaaS or self-hosted).

***

### Steps

#### 1. Secure your environment

* Obtain your API key from the **User Settings** in Toucan AI.
* Store the API key in a secure server-side environment variable or secret manager.

{% hint style="danger" %}
**Security Alert**: This request must remain server-side. Exposing the API key or token generation logic in the frontend allows users to bypass security filters and access unauthorized datasets.
{% endhint %}

#### 2. Call the `/generate-token` endpoint

Make a POST request to the relevant URL for your deployment:

* Cloud (SaaS): `https://toucanai.cloud/embed/generate-token`

**HTTP request example**

```http
POST /embed/generate-token HTTP/1.1
Host: toucanai.cloud
x-api-key: <YOUR_API_KEY>
Content-Type: application/json

{
  "user": {
    "distinctId": "user-123",
    "role": "explorer",
    "attributes": {}
  }
}
```

**Request body parameters**

| Parameter           | Type   | Required | Description                                              |
| ------------------- | ------ | -------- | -------------------------------------------------------- |
| **user**            | object | ✅        | Contains the identity and role of the target user.       |
| **user.distinctId** | string | ✅        | A unique identifier used for tracking and auditing logs. |
| **user.role**       | string | ✅        | The user's role (currently "explorer").                  |
| **user.attributes** | object | ✅        | Custom metadata for the user (e.g., RLS, custom traits). |

#### 3. Process the response

On success, the API returns the token and its expiration duration:

```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresIn": "1h"
}
```

* Extract the `token` string and pass it to your frontend for use in the `<tc-dashboard>` or `<tc-ai-assistant>` components.

***

#### Security best practices

* **Server-side only**: Never call this endpoint from client-side code.
* **Protect credentials**: Use environment variables to handle API keys; do not hardcode them in your source files.
* **Short lifespans**: Use the token immediately for the session, as it is designed to expire.

***

### Conclusion

Programmatic token generation ensures that every user in your application receives a secure, unique session authorized by your backend. This workflow is the standard for production-grade embedded analytics.

**Suggested Next Step**: [How-to: Embed a dashboard](/embed/embedding-overview/how-to/embed-a-dashboard) or [How-to: Configure Row-Level Security (RLS)](/embed/permissions-and-row-level-security/how-to/apply-rls-to-your-database)


# Introspect a token

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### Goal

Decode a signed Toucan AI token to inspect its internal payload and verify its validity.

***

### Prerequisites

* A [Toucan AI account](/getting-started/quick-start/subscribe-to-toucan) with active access.
* A previously [generated token](/embed/authentication/how-to/authentication-and-tokens) (sandbox or production).

***

### Steps

#### 1. Access the Embed settings

* Click on the **Settings** button in the main navigation menu.
* Select the **Embed & access** tab to view the integration and security configurations.

#### 2. Locate the introspection tool

* Scroll to the **Token Introspection** section.
* This interface is designed to parse and display the metadata of any Toucan AI authentication token.

#### 3. Input and decode the token

* Copy the token string you wish to examine.
* Paste the string into the **JWT Token** field.
* Click the **Introspect Token** button to trigger the decoding process.

#### 4. Review token metadata

The tool will display the following decoded parameters:

* **User Information**: Includes the `distinctId` and the assigned `role`.
* **Custom Attributes**: Displays all key-value pairs used for Row-Level Security (e.g., `department: "finance"`).
* **Permissions**: Lists granular access rights like `can_view`, `can_edit`, or `can_query`.
* **Expiration**: Shows the exact timestamp when the token will become invalid.

#### 5. Validate results

* Verify that the attributes match the intended user context.
* If the data is incorrect or the status indicates the token has expired, generate a new credential via the sandbox or API.

<figure><img src="/files/q4iuwOWIikiTEyNgIQNx" alt="Token Introspection"><figcaption></figcaption></figure>

***

### Conclusion

Token introspection provides a non-destructive way to audit user identity propagation and permission scoping. Ensuring token accuracy at this stage prevents unauthorized access or "Failed to load" errors in the embedded environment.

**Suggested Next Step**: [How-to: Embed a dashboard](/embed/embedding-overview/how-to/embed-a-dashboard) or [How-to: Configure Row-Level Security (RLS)](/embed/permissions-and-row-level-security/how-to/apply-rls-to-your-database)


# Permissions & Row-Level Security


# Permission level overview

{% hint style="info" %}
**Target Audience**: Non technical users & Developers
{% endhint %}

### TL;DR

Toucan AI utilizes a layered security framework—combining roles, granular permissions, and Row-Level Security (RLS)—to regulate access to assets and specific data rows.

***

### When to use this

Use this page to understand how Toucan AI evaluates user authorization across organizations, datasets, and dashboards before rendering data.

***

### Key Security Concepts

Toucan AI provides a multi-tenant security architecture that enforces access control at different functional levels.

* **Roles**: Define a user's default access level across the organization (e.g., admin, editor, viewer).
* **Permissions**: Specific action-based rights associated with roles, such as the ability to view, edit, or manage resources.
* **Row-Level Security (RLS)**: A dynamic filtering mechanism that ensures users only access specific rows within a dataset based on their unique attributes.
* **Scopes**: The boundary where permissions are applied, ranging from entire organizations to individual datasets or dashboards.

***

### The Permission Evaluation Process

When a user initiates a request, Toucan AI validates authorization through a sequential check:

1. **Organization-level**: Verifies membership and general resource access within the organization.
2. **Dataset-level**: Determines if the user is authorized to query the underlying data source or specific tables.
3. **Dashboard-level**: Validates whether the user can view or modify the specific visualization layout.
4. **Row-level**: Injects dynamic SQL filters into the query based on user attributes (e.g., department, region) to restrict data output.

***

### Implementation Example: Role and RLS Integration

Consider a single "Sales" dashboard accessed by two different users:

| User Role         | Security Configuration                   | Data Visibility                                                   |
| ----------------- | ---------------------------------------- | ----------------------------------------------------------------- |
| **Sales Manager** | High-level Role                          | Authorized to view data across all regions.                       |
| **Sales Rep**     | Role + RLS Attribute (`region: 'North'`) | Restricted to viewing only data rows where the region is 'North'. |

***

### Practical Benefits

* **Data Isolation**: Safely distribute analytics to different teams or external customers within a single dashboard.
* **Compliance**: Maintain strict adherence to privacy requirements by preventing unauthorized data exposure.
* **Access Precision**: Provide users with the exact functional rights required for their specific tasks.


# Dataset-Level VS Row-Level Security

{% hint style="info" %}
**Target Audience**: Non technical users & Developers
{% endhint %}

### TL;DR

Toucan AI utilizes dataset-level security to restrict access to entire data sources and Row-Level Security (RLS) to filter specific records within a shared dataset.

***

### When to use this

Use this page to determine the appropriate security layer for isolating data between different departments, teams, or external tenants.

***

### Dataset-level security

Dataset-level security defines which users or roles are authorized to access a specific data source in its entirety.

* **Definition**: This layer restricts access to the complete dataset; users without permission cannot query or visualize any part of the source.
* **How it works**: Permissions are assigned at the dataset object level. Unauthorized users are unable to view the dataset within the Toucan AI interface.
* **Use case**: Separating sensitive data by department, such as ensuring HR datasets remain private from the general Sales team.
* **Example**: A "Finance" dataset is configured so it is only visible to the Finance group; no other users can interact with its metadata or values.

***

### Row-Level Security (RLS)

RLS provides a granular filtering mechanism that allows multiple users to access the same dataset while only viewing records relevant to them.

* **Definition**: This layer filters data rows within a dataset based on dynamic user attributes.
* **How it works**: Toucan AI injects filtering policies into the query at execution time, utilizing attributes passed in the authentication token.
* **Use case**: Multi-tenant environments where all sales representatives use a single "Global Sales" dashboard but are restricted to their specific regional data.
* **Example**: In a "Customer Orders" dataset, an employee with the attribute `region: France` only sees French orders, while a manager with broader attributes may see all regions.

***

### Comparison and selection

| Feature          | Dataset-Level Security                    | Row-level Security (RLS)                                      |
| ---------------- | ----------------------------------------- | ------------------------------------------------------------- |
| **Scope**        | Entire dataset or data source.            | Individual rows within a dataset.                             |
| **Visibility**   | Dataset is hidden if unauthorized.        | Dataset is visible, but content is filtered.                  |
| **Management**   | Assigned to specific roles or teams.      | Driven by dynamic user attributes (e.g., `department`, `ID`). |
| **Primary Goal** | Strict boundaries between business units. | Personalized, multi-tenant data isolation.                    |

***

### Implementation best practices

* **Layered Security**: Start with dataset-level restrictions for broad access control, then apply RLS for fine-grained filtering.
* **Single Source of Truth**: Use RLS to avoid duplicating datasets or dashboards for different user groups.
* **Validation**: Test security policies with various user attribute combinations to ensure compliance and correct data isolation.


# How-to


# Apply RLS to your database

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### Goal

Establish a secure mapping between dynamic user attributes and dataset fields to filter data at query time.

***

### Prerequisites

* A [connected database](/build/data-connections/how-to/add-a-database) containing columns suitable for filtering (e.g., `region`, `team_id`, `department`).
* An [existing dashboard](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai) or [chart](/build/charts/how-to/create-a-chart) to validate the filtering logic.
* A [valid API key](/embed/authentication/how-to/generate-an-api-key) to generate test tokens in the sandbox.

***

### Steps

#### 1. Verify dataset compatibility

* Navigate to the **Databases** tab and select the target **Database** and **Table**.
* Click **Preview** to confirm the presence of the column intended for filtering (e.g., a `location` column containing values like "Paris" or "Tokyo").

#### 2. Define custom token attributes

* Navigate to the **Settings** tab and select the **Embed & access** section.
* Locate the **Token Attributes** menu under **Custom Attributes**.
* Click **Add an attribute**.
* Input a factual **name** (e.g., `location`) and select the **data type** (e.g., `String`).
* Click **Save changes** to register the attribute for use in authentication tokens.

<figure><img src="/files/NDQc2pN1FwznNT5A7bju" alt="Custom attributes"><figcaption></figcaption></figure>

#### 3. Map attributes to database columns

* Return to the **Databases** section and select your **Database** and **Table**.
* Click the **Access rules** tab to configure security policies.
* Under the section "Then, for a row to be included...", use the rule builder to define your filter.
* In the **Select dataset field** dropdown, choose the column in your database you want to filter (e.g., `location_name`).
* Ensure the operator is set to **must be equal** to.
* In the **Select token attribute** dropdown, select the custom attribute created in Step 2 (e.g., `location`).

<figure><img src="/files/KfAG5jvLOCBGLy7q128o" alt="RLS settings"><figcaption></figcaption></figure>

#### 4. Enable and save RLS

* Click Save to activate the security policy.
* Verify that the RLS enabled blue tag appears next to the table name.
* You may repeat this mapping for additional tables that require the same security logic.

#### 5. Validate the RLS policy

* Within the table view, click **Preview with Token** in the top right corner.
* Enter a test value for your custom attribute (e.g., `Paris`) and click **Generate Preview**.
* Confirm that the displayed data rows are strictly limited to the value provided.

<figure><img src="/files/KH3plypehcA98WhUjDCn" alt="Preview RLS"><figcaption></figcaption></figure>

#### 6. Generate a test token and embed

* Navigate to **Settings > Embed & access** and scroll to the **Token Generation Sandbox**.
* Enter your **API Key** and assign a value to your custom attribute (e.g., `location` = `Paris`).
* Click **Generate Token**.
* Use this token in your embedded component (e.g., `<tc-dashboard auth-token="YOUR_TOKEN">`) to confirm the filtered view in your host application.

***

### Conclusion

The database now enforces Row-Level Security based on the identity context passed via authentication tokens. This ensures data isolation in multi-tenant environments without the need for multiple dashboards.

To restrict which columns users can see on the same table, see [Apply CLS to your database](/embed/permissions-and-row-level-security/how-to/apply-cls-to-your-database).


# Apply CLS to your database

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

### Goal

Restrict which columns users can see based on identity context passed via authentication tokens — without creating separate dashboards per role.

***

### Prerequisites

* A [connected database](/build/data-connections/how-to/add-a-database) containing columns you want to protect (e.g., `salary`, `email`, `seller`).
* An [existing dashboard](/build/dashboards-and-layouts/how-to/create-a-dashboard-with-ai) or [chart](/build/charts/how-to/create-a-chart) that uses the target table.
* A [valid API key](/embed/authentication/how-to/generate-an-api-key) to generate test tokens in the sandbox.

***

### Steps

#### 1. Verify sensitive columns

* Navigate to the **Databases** tab and select the target **Database** and **Table**.
* Click **Preview** to confirm the columns you want to restrict (e.g., a `salary` column or a `seller` identifier).

#### 2. Define custom token attributes

* Navigate to the **Settings** tab and select the **Embed & access** / **User Model** section.
* Locate the **Token Attributes** menu under **Custom Attributes**.
* Click **Add an attribute**.
* Input a factual **name** (e.g., `role`) and select the **data type** (e.g., `String`).
* Click **Save changes** to register the attribute for use in authentication tokens.

#### 3. Configure column-level rules

* Return to the **Databases** section and select your **Database** and **Table**.
* Click the **Access rules** tab.
* In the column-level section at the top of the page:
  * **Empty state**: choose `all` (every column visible) or `none` (no column visible) as the default catch-all.
  * Click **Add column section** to create a section for sensitive columns.
  * Select the columns to protect (e.g., `salary`).
  * Click **Add condition** and define when those columns should be visible — for example: *included if \[role] is equal to \[HR]*.
  * The catch-all section at the bottom covers all other columns (and any columns added to the table later).

#### 4. Enable and save CLS

* Click **Save** to activate the security policy.
* Verify that the CLS enabled indicator appears next to the table name.
* You may repeat this configuration for additional tables that require the same column-level logic.

#### 5. Validate the CLS policy

* Within the table view, click **Preview access rules** in the top right corner.
* Enter a test value for your custom attribute (e.g., `role` = `HR`) and click **Generate preview**.
* Confirm that sensitive columns appear only when the condition is satisfied.
* Change the attribute value (e.g., `role` = `Sales`) and regenerate the preview to confirm those columns are hidden.

#### 6. Generate a test token and embed

* Navigate to **Settings > Embed & access** and scroll to the **Token Generation Sandbox**.
* Enter your **API Key** and assign a value to your custom attribute (e.g., `role` = `HR`).
* Click **Generate Token**.
* Use this token in your embedded component (e.g., `<tc-dashboard auth-token="YOUR_TOKEN">`) to confirm the column-scoped view in your host application.

***

### Conclusion

The database now enforces Column-Level Security based on the identity context passed via authentication tokens. Combine CLS with [Row-Level Security (RLS)](/embed/permissions-and-row-level-security/how-to/apply-rls-to-your-database) on the same table for full row-and-column isolation in multi-tenant environments.

For operator details and policy semantics, see [Column-Level Security (CLS)](/build/security-and-governance/column-level-security-cls).


# Embedding methods


# Web Component embedding

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

### TL;DR

Toucan AI utilizes a standards-based web component to enable framework-agnostic embedding of analytics through a custom HTML element.

***

### When to use this

Choose this method to maintain a portable analytics layer that works across any web stack—including React, Vue, Angular, or plain HTML—without requiring a dedicated SDK or complex build dependencies.

***

### Functional Overview

The web component is a self-contained unit of code that wraps Toucan AI visualizations into a custom HTML tag. This approach leverages native browser technologies to ensure that dashboards and charts render consistently regardless of the host application's underlying framework.

```html
<script type="module" src="https://toucanai.cloud/embed/embed.js"></script>
<tc-dashboard
    dashboard-id="your-dashboard-id"
    auth-token="your-embed-token"
    server-url="https://toucanai.cloud/api"
    data-theme="light"
    style="width: 100%; height: 600px;"
></tc-dashboard>
```

***

### Core Attributes

The behavior and content of the web component are controlled through declarative HTML attributes:

| Attribute                   | Required | Description                                                    |
| --------------------------- | -------- | -------------------------------------------------------------- |
| **dashboard-id / chart-id** | ✅        | The unique identifier for the Toucan AI resource to render.    |
| **auth-token**              | ✅        | A secure, server-generated JWT used for session authorization. |
| **server-url**              | ✅        | The API endpoint for your specific Toucan AI instance.         |
| **data-theme**              | ❌        | Optional setting to toggle between "light" or "dark" modes.    |

***

### Architectural Advantages

* **Framework Independence**: The component runs natively in the browser, eliminating the risk of framework lock-in or version conflicts.
* **Zero Build Overhead**: Integration requires no npm installations or specialized build-time configurations.
* **Encapsulated Logic**: All rendering logic, data fetching, and interactivity are handled internally by the component.
* **Token-Driven Security**: Access control is strictly managed through server-side generated tokens, protecting sensitive API keys.

***

### Limitations

* **Interactivity Constraints**: Advanced programmatic interactivity may require the SDK or API-driven methods.
* **Session Isolation**: Authentication is limited to the embed token; the component does not share user sessions with the host application.


# SDK-based embedding

Toucan AI supports SDK-based embedding for developers who want more control and flexibility when integrating analytics into their applications. This method is ideal for React, Next.js, Vue, and vanilla JavaScript projects that need to programmatically mount, update, or unmount embedded dashboards and charts.

### How It Works

* **Loader Script:**\
  The SDK-based approach still relies on the Toucan AI web component loader:

  ```html
  <script type="module" src="https://toucanai.cloud/embed/embed.js"></script>
  ```
* **Programmatic Mounting:**\
  Instead of static HTML, you create and configure the `<tc-dashboard>` or `<tc-chart>` element in your application code (JavaScript/TypeScript), then mount it to a container.
* **Token Management:**\
  Secure embed tokens are fetched from your backend (never hardcoded), then set as an attribute on the component.
* **Framework Support:**
  * **React/Next.js:** Use `useEffect` to fetch tokens and mount/unmount the component.
  * **Vue:** Use `onMounted`/`onUnmounted` lifecycle hooks.
  * **Vanilla JS:** Use standard DOM APIs and event listeners.

***

### Example (React)

```javascript
import { useEffect, useState } from 'react';

function ToucanDashboard() {
  const [token, setToken] = useState('');

  useEffect(() => {
    async function getToken() {
      const response = await fetch('/api/toucan/token');
      const data = await response.json();
      setToken(data.token);
    }
    getToken();
  }, []);

  useEffect(() => {
    if (!token) return;
    const dashboard = document.createElement('tc-dashboard');
    dashboard.setAttribute('token', token);
    dashboard.setAttribute('dashboard-id', 'your-dashboard-id');
    dashboard.setAttribute('data-theme', 'light');
    const container = document.getElementById('toucan-container');
    container?.appendChild(dashboard);
    return () => { container?.removeChild(dashboard); };
  }, [token]);

  return <div id="toucan-container" style={{ height: '600px' }} />;
}
```

***

### Key Features

* **Dynamic Control:** Mount, update, or remove embedded analytics at runtime.
* **Framework Integration:** Works seamlessly with React, Next.js, Vue, and plain JS.
* **Secure:** Always uses server-generated, short-lived tokens.
* **Customizable:** All web component attributes and theming options are available.

***

### When to Use

* You need to embed analytics in a dynamic, single-page app.
* You want to control embedding lifecycle in code (e.g., show/hide, update on route change).
* You’re building with React, Next.js, Vue, or similar frameworks.

***

### Limitations

* Still relies on the web component under the hood.
* For deep API integration or custom data flows, consider the API-based method.

***

### Summary

SDK-based embedding with Toucan AI gives you programmatic control and seamless integration with modern frameworks, while maintaining security and flexibility. It’s ideal for dynamic apps that need to manage embedded analytics at runtime.


# API-driven analytics integration

{% hint style="info" %}
**Target Audience**: Developers
{% endhint %}

{% hint style="info" %}
This method does not embed a Toucan AI UI component. Instead, it allows you to fetch analytics data (dashboards, charts, or results) directly from the backend via API and render it using your own UI components. This approach is best described as API-driven analytics integration, not embedding.
{% endhint %}

### TL;DR

Toucan AI supports a "headless" integration model where analytics data is fetched directly via API, allowing you to render visualizations using your own custom UI components.

***

### When to use this

Choose this method when you require total control over the user interface, need to combine Toucan AI data with other internal data sources, or must build complex interactivity not supported by standard UI components.

***

### Functional Overview

Unlike web component or SDK embedding, this approach does not include a Toucan AI user interface. Instead, your application acts as the presentation layer, requesting raw or structured data from the Toucan AI backend.

* **Direct API Interaction**: Use REST or GraphQL endpoints to retrieve dashboard configurations, chart metadata, or query results.
* **Token-Based Security**: Every request must be authorized with a server-generated embed token to maintain data isolation and RLS.
* **Client-Side Rendering**: Your application is responsible for mapping the API response to your preferred charting library (e.g., D3.js, Chart.js, or Highcharts).

***

### Implementation Example

The following standard fetch request demonstrates how to retrieve dashboard data using a secure embed token:

```javascript
fetch('https://toucanai.cloud/api/v1/dashboards/your-dashboard-id', {
	method: 'GET',
	headers: {
		'Authorization': 'Bearer YOUR_EMBED_TOKEN'
	}
})
	.then(res => res.json())
	.then(data => {
		// Implement custom rendering logic here
		console.log(data);
	});
```

***

### Architectural Considerations

| Feature              | Impact                                                                                                  |
| -------------------- | ------------------------------------------------------------------------------------------------------- |
| **Customization**    | Offers maximum flexibility for branding and custom user workflows.                                      |
| **Development Cost** | Requires significantly more engineering effort as you must manage rendering, state, and error handling. |
| **Interactivity**    | Enables advanced data manipulation and custom business logic beyond standard dashboard features.        |
| **Maintenance**      | Developers must monitor API schema updates and handle versioning in their own code.                     |


# White-Labelling & Branding


# What can be customized?

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

***

### TL;DR

Toucan AI provides a comprehensive white-labeling system that allows for full control over themes, typography, and chart styles through preset palettes or custom JSON configurations.

***

### When to use this

Use this guide to align the visual identity of embedded dashboards and the AI assistant with your host application’s branding, ensuring a unified user experience.

***

### Themes and colors

Visual styles can be applied at a global level to modify the primary interface elements.

* **Preset Themes**: Access a library of professional color palettes, such as Catppuccin, for immediate deployment.
* **Custom Themes**: Define primary, secondary, accent, and background colors to match specific brand guidelines.
* **Light and Dark Modes**: Configure independent color schemes for both modes, including full control over transitions.
* **Sidebar Customization**: Adjust background, foreground, border, and ring colors for the navigation sidebar.

<figure><img src="/files/liRaTvpGZ6HhriwmON8J" alt="Theme"><figcaption></figcaption></figure>

***

### Typography and chart styles

Typography and visualization details are adjustable to maintain brand voice and accessibility standards.

* **Font Management**: Set custom font families and adjust base, heading, and label sizes via the theme configuration.
* **Chart Aesthetics**: Customize series colors, grid lines, and backgrounds for all visualizations.
* **Component Detailing**: Fine-tune specific chart elements including tooltips, legends, and axes.

***

### Deep theme customization

For advanced white-labeling, Toucan AI supports a detailed JSON configuration that overrides standard UI properties.

* **UI Elements**: Define the border radius for all buttons, cards, and popovers.
* **Refined Palettes**: Specify exact hex codes for destructive, muted, and border colors across light and dark themes.
* **Granular Chart Properties**: Control technical properties for bars, lines, and arcs, including width and radius.

<figure><img src="/files/O6rl4VYHy3HhdwQvgK1w" alt="Custom Theme"><figcaption></figcaption></figure>

#### Example JSON configuration

A custom theme can be uploaded as a JSON file to define the entire visual layer:

```json
{
  "borderRadius": 0.25,
  "typography": { 
    "fontFamily": "Montserrat",
    "baseSize": "14px"
  },
  "colors": { 
    "light": { "primary": "#1A73E8", "background": "#FFFFFF" }, 
    "dark": { "primary": "#8AB4F8", "background": "#121212" } 
  },
  "charts": { 
    "light": { "series": ["#1A73E8", "#34A853"] }, 
    "dark": { "series": ["#8AB4F8", "#81C995"] } 
  }
}
```


# Branding scope and limits

{% hint style="info" %}
**Target Audience**: Developers & Non technical users
{% endhint %}

***

### TL;DR

Toucan AI provides high-level aesthetic customization while maintaining fixed core brand elements and navigation structures to ensure product integrity.

***

### When to use this

Use this page to align expectations regarding white-labeling capabilities and to identify which UI elements will remain static within your integration.

***

### Branding capabilities

The following elements are fully customizable to align with your organization's visual identity:

* **Color Palettes**: You can modify primary, secondary, accent, and background colors for both light and dark modes.
* **Typography**: You can set the font family and adjust font sizes across the interface for a consistent brand voice.
* **Visualization Styles**: You can adjust chart palettes, series colors, axes, legends, and tooltip appearances.
* **UI Components**: You can control border radius and visual details for buttons, cards, and other interactive elements.
* **Sidebar UI**: You can configure the sidebar background, accent, and border colors via the theme settings.

***

### Branding limitations

To maintain platform stability and security, specific elements cannot be modified or white-labeled:

* **Favicon**: The browser favicon is static and remains the default Toucan AI icon.
* **Application Name**: The name "Toucan AI" is hardcoded into the interface and cannot be altered through theme settings.
* **Brand Logo**: The application logo is fixed and does not support user-specific uploads or customization.
* **Navigation Architecture**: The sidebar structure and navigation items are fixed; users cannot add, remove, or reorder these links.
* **System Interfaces**: Onboarding screens, login pages, and error messages may retain default Toucan AI branding.

***

### Rationale for limits

These boundaries exist to preserve product integrity and ensure a consistent user experience across different deployment models. Fixed elements simplify technical support, improve security compliance, and maintain functional reliability.

***

### Advanced branding requirements

If your integration requires white-labeling beyond these standard capabilities, contact the Toucan AI team. Advanced theming and enterprise-level integration options are available to support deeper customization needs.


# Self-Service configuration


# End-user filters


# Runtime parameters


# Feature exposure control


# Copy of Embed an AI Chat

Self-service AI Chat lets embedded users explore data using natural language, without accessing Toucan AI platform.

The chat is embedded in your product and governed by your data, security, and configuration rules.

<figure><img src="/files/N7je2tTfv7FdrMlQY1zx" alt=""><figcaption></figcaption></figure>

### What the feature does

This feature allows you to:

* Embed an **AI-powered chat** inside your product
* Let **Explorers** ask questions in natural language
* Return **tables and charts** generated from your data
* Restrict answers using **datasets, and RLS**

The embedded AI chat is designed for **data exploration**, not dashboard building.

***

### Prerequisites

Before enabling self-service AI chat, you must have:

* At least one connected database
* At least one generated API key
* At least one generated access token
* (Recommended) Dataset metadata analyzed or enriched
* (Recommended) Row-Level Security configured

***

### How to use it

#### Step 1 – Prepare your data

* Analyze datasets with AI
* Review and adjust column descriptions
* Ensure metric definitions are explicit

Good metadata directly impacts answer quality.

#### Step 2 – Set up security

* Define custom token attributes
* Map attributes to dataset columns using RLS

Always validate with multiple attribute values.

#### Step 3 – Configure embed token

When generating a token:

* Include required attributes
* Set token expiration
* Enable AI chat capability

Tokens fully define what the Explorer can see and do.

#### Step 4 – Embed the AI chat

Embed the chat using Web component. The chat runs fully inside your product UI.

```vue-html

<script type="module" src="https://toucanai.cloud/embed/embed.js"></script>
<link rel="stylesheet" href="https://toucanai.cloud/embed/embed.css" />

<tc-ai-assistant auth-token="your-auth-token"
server-url="https://toucanai.cloud/api" data-theme="light"></tc-ai-assistant>
```

#### Example

**Use case:** HR SaaS with multi-tenant customers

* Attribute: `customer_id`
* Dataset column: `customer_id`
* Explorer question:\
  \&#xNAN;*“How many hires last quarter?”*

Result:

* Query is filtered by `customer_id`
* Explorer only sees their own data
* No configuration or SQL required


# Operate

Goal: Help teams run Toucan AI in production.


# Performance & Scaling


# Query execution model


# Catching concepts


# Performance best practices




---

[Next Page](/llms-full.txt/1)

