# How to Connect an AI Agent to Your Data Warehouse

> Connect an AI agent to your data warehouse: expose governed metrics over MCP, let agents query instead of writing raw SQL, and chart the result in Claude or ChatGPT. Full tutorial in under 30 minutes.

Most teams connecting AI agents to their data warehouse start with text-to-SQL. The agent generates SQL from natural language, runs it against the warehouse, and returns results. It works until it doesn't: hallucinated JOINs, inconsistent aggregations, no access control, no audit trail.

There's a better approach. Define your business metrics in a semantic layer, expose them via [MCP](/glossary/mcp) (Model Context Protocol), and let any AI agent query governed definitions instead of raw tables. Then add one tool so the agent can chart the result in Claude or ChatGPT. This tutorial shows how to set it up in under 30 minutes.

## Why does text-to-SQL break in production?

The agent sees column names but not business logic. It doesn't know that your company excludes refunds from revenue. It doesn't know that `status = 'completed'` means something different in `orders` than in `subscriptions`. It doesn't know that marketing and finance defined "active user" differently three years ago and never reconciled.

So the agent writes plausible SQL and returns plausible numbers. Ask the same question twice with different phrasing and you get different answers. Ask two different agents and you get two different numbers. Neither matches the number your finance team reports.

Beyond consistency, there's no row-level security. No multi-tenancy. No audit trail showing which agent queried what, when, and for whom. In production, with real customers, that's a non-starter.

[Text-to-SQL](/glossary/text-to-sql) gives you speed. It doesn't give you trust.

## What is the semantic layer approach?

Instead of letting agents write arbitrary SQL, define your metrics once in YAML: cubes, measures, dimensions, access rules. Then expose those definitions via MCP so agents query governed metrics, not raw tables.

The difference: every agent gets the same answer because the metric definition is fixed. `total_revenue` isn't a column the agent interprets. It's a pre-defined calculation with agreed-upon filters and aggregations. When your finance team updates the revenue definition to exclude trial conversions, that change propagates to every consumer instantly. No agent retrained. No dashboard patched. One diff in your schema repo.

This architecture also decouples the query interface from the warehouse dialect. Swap BigQuery for Snowflake and your agents don't notice. The semantic layer abstracts the SQL generation, so consumers stay stable while infrastructure evolves underneath.

| Approach | Governance | Consistency | Multi-tenant | Access Control | Setup Time |
|---|---|---|---|---|---|
| Direct SQL | None | Varies by query | Manual | Manual | Minutes |
| Text-to-SQL | None | Varies by prompt | Manual | Manual | Hours |
| Semantic Layer via MCP | Full | Guaranteed | Built-in | Row-level | Under 30 min |

The [semantic layer](/semantic-layer) is the control plane between your warehouse and every consumer, whether that's a human analyst, a React component, or an AI agent.

## Step 1: Set up your semantic layer

Stand up a semantic layer that connects to your warehouse and exposes metrics over MCP. Open-source engines like [Cube](https://cube.dev) connect to [BigQuery](/integrations/bigquery), [Snowflake](/integrations/snowflake), [Redshift](/integrations/redshift), [Databricks](/integrations/databricks), [PostgreSQL](/integrations/postgres) (including Supabase, Neon, and RDS), and [DuckDB](/integrations/duckdb) (including MotherDuck). You configure your warehouse connection in a config file or pass credentials via environment variables.

If you want to explore without connecting your own warehouse, point the semantic layer at a sample PostgreSQL database with orders, customers, and products data so you can follow along with the rest of this tutorial. A few thousand rows across three tables is enough to test aggregations, filters, and multi-dimensional queries.

## Step 2: Define your metrics

Create a cube that maps to a table in your warehouse and defines the metrics your agents will query.

```yaml
cubes:
  - name: orders
    sql_table: public.orders
    measures:
      - name: total_revenue
        sql: amount
        type: sum
      - name: count
        type: count
    dimensions:
      - name: status
        sql: status
        type: string
      - name: created_at
        sql: created_at
        type: time
```

**Measures** are the numbers you aggregate: sums, counts, averages. **Dimensions** are the columns you filter and group by: status, date, category. One definition. Every tool, dashboard, and AI agent that queries `total_revenue` gets the same number.

You can also define `pre_aggregations` in the same file to cache expensive computations. For example, a daily rollup of `total_revenue` by `status` can cut query times from seconds to single-digit milliseconds. The semantic layer rebuilds these rollups on a configurable schedule and invalidates stale caches automatically.

Schemas are version-controlled alongside your application code. Review metric changes in pull requests. Roll back a bad definition with `git revert`. Your data contracts get the same CI/CD workflow as your product.

To control what's exposed to specific consumers, define a view:

```yaml
views:
  - name: order_metrics
    cubes:
      - join_path: orders
        includes:
          - total_revenue
          - count
          - status
          - created_at
```

Views act as a curated interface. Your agents see `order_metrics` with four fields instead of navigating the full schema.

## Step 3: Deploy and connect your agent

Deploy your schema so the semantic layer serves it over an MCP endpoint, then add the MCP server URL to your client's config:

```json
{
  "mcpServers": {
    "semantic-layer": {
      "type": "http",
      "url": "https://your-semantic-layer.example.com/mcp"
    }
  }
}
```

Paste this into your MCP client's config file and restart. For Claude Desktop, that's `~/Library/Application Support/Claude/claude_desktop_config.json`. For Cursor, it's `.cursor/mcp.json` in your project root. Claude Code reads from `.mcp.json` in your project directory.

The MCP server handles tool discovery, schema introspection, and query execution over HTTP. Your agent sees available metrics the same way it sees any other MCP tool. No custom integration code required.

For customer-facing use cases, scope each connection to a specific tenant's data with row-level security defined in the schema, so a customer's agent sees only that customer's rows.

## Step 4: Query from your agent

Once connected, your AI agent can discover and query your metrics using natural language. Behind the scenes, the agent calls MCP tools.

Ask: "What's our total revenue this quarter?"

The agent calls `explore_schema` to discover available metrics, then calls `query` with the right measures and time filters. The response comes back as structured data, not raw SQL results.

Ask: "Break down order count by status for the last 30 days."

Same flow. The agent uses `query` with `count` as the measure, `status` as the dimension, and a date filter on `created_at`.

A semantic layer typically exposes a handful of MCP tools:

- **`explore_schema`**: Discover available cubes, measures, and dimensions
- **`query`**: Fetch aggregated data using governed metric definitions
- **`sql_query`**: Run queries for cases that need custom SQL (still governed by access controls)
- **`describe_field`**: Get metadata about a specific measure or dimension

Every query runs through the semantic layer. The agent never touches raw tables. Read more about the architecture in our [agentic analytics](/agentic-analytics) guide.

## Charting the agent's results

A governed query returns rows. The agent usually needs to show the user a chart, not a wall of numbers. Leaving the model to draw HTML puts the most important part of the answer in its hands to improvise.

[`@bonnard/mcp-charts`](https://www.npmjs.com/package/@bonnard/mcp-charts) fixes that. It adds a `visualize` tool to your MCP server in a few lines:

```bash
npm install @bonnard/mcp-charts
```

```ts
import { addCharts } from "@bonnard/mcp-charts";

// your data, your connection. Bonnard never touches the database
addCharts(server, { runSql });
```

The agent calls `visualize` with a query, your `runSql` returns the rows, and Bonnard infers the chart from the typed result, then renders an interactive widget in Claude or ChatGPT. It renders line, bar, area, pie, scatter, funnel, waterfall, and table, with bar variants for stacked, grouped, horizontal, and 100% stacked. The chart comes from your query result, not from tokens the model invents. Same data, same chart, every time. Full walkthrough: [MCP Charts](/blog/mcp-charts).

## From raw SQL to governed metrics

You started with a warehouse and an AI agent that writes its own SQL. Now you have governed metrics defined in YAML, exposed via MCP, queryable from any AI tool your team or customers use. Setup took under 30 minutes.

The shift from raw SQL to governed metrics pays off immediately: consistent numbers across every consumer, row-level access control per tenant, and a full audit trail for every query. As your team adds more agents and surfaces, the semantic layer scales with you. No duplicate logic. No drift between dashboards and AI answers.

Give the agent a way to chart what it queries: `npm install @bonnard/mcp-charts`, call `addCharts(server, { runSql })`, and interactive charts render in Claude and ChatGPT. The repo is on [GitHub](https://github.com/bonnard-data/mcp-charts). Read the [MCP Charts guide](/blog/mcp-charts) to go deeper.

## Related reading

- [What is MCP?](/glossary/mcp) -- the protocol that powers agent-to-data connections
- [MCP Charts](/blog/mcp-charts) -- add a `visualize` tool so agents chart query results in Claude and ChatGPT
- [Snowflake integration](/integrations/snowflake) -- connect to your Snowflake warehouse

## Frequently asked questions

### Do I need to retrain my AI model?

No. A semantic layer with MCP support works with any MCP-compatible AI agent out of the box. Your agent discovers available metrics through the MCP protocol at runtime. There is no fine-tuning, prompt engineering, or model modification required.

### What data warehouses does this work with?

A semantic layer connects to BigQuery, Snowflake, Redshift, Databricks, PostgreSQL (including Supabase, Neon, and RDS), and DuckDB (including MotherDuck). For charting the agent's results, `@bonnard/mcp-charts` ships native adapters for Postgres, BigQuery, Snowflake, Databricks, and DuckDB, or you pass your own `runSql`. Bonnard never touches your database.

### How is this different from text-to-SQL?

Text-to-SQL lets an AI agent generate arbitrary SQL from natural language. It has no governance, no consistency guarantees, and no access control. A semantic layer defines metrics once in YAML and exposes them as governed APIs. Every consumer gets the same answer because the calculation is fixed, not interpreted per query. And when the agent charts the result, `@bonnard/mcp-charts` renders from the query result, not from tokens the model invents.

### How do I let the agent show charts?

Install [`@bonnard/mcp-charts`](https://www.npmjs.com/package/@bonnard/mcp-charts) and call `addCharts(server, { runSql })` on your MCP server. That registers a `visualize` tool. The agent calls it with a query, your callback returns the rows, and an interactive chart renders in Claude or ChatGPT. No frontend code.

### How long does setup take?

Under 30 minutes for most teams. Stand up a semantic layer, connect your warehouse, define a few metrics in YAML, and deploy it over MCP. Add charts with `npm install @bonnard/mcp-charts` and one `addCharts` call. The tutorial above walks through each step with working code examples.