Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@bonnard/cli

Package Overview
Dependencies
Maintainers
1
Versions
49
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bonnard/cli - npm Package Compare versions

Comparing version
0.2.8
to
0.2.9
+21
LICENSE
MIT License
Copyright (c) 2025-present Bonnard (meal-inc)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+2
-2
{
"name": "@bonnard/cli",
"version": "0.2.8",
"version": "0.2.9",
"type": "module",

@@ -12,3 +12,3 @@ "bin": {

"scripts": {
"build": "tsdown src/bin/bon.ts --format esm --out-dir dist/bin && cp -r src/templates dist/ && mkdir -p dist/docs/topics dist/docs/schemas && cp ../content/index.md dist/docs/_index.md && cp ../content/overview.md ../content/getting-started.md dist/docs/topics/ && cp ../content/modeling/*.md dist/docs/topics/ && cp ../content/dashboards/*.md dist/docs/topics/",
"build": "tsdown src/bin/bon.ts --format esm --out-dir dist/bin && cp -r src/templates dist/ && mkdir -p dist/docs/topics dist/docs/schemas && cp ./content/index.md dist/docs/_index.md && cp ./content/overview.md ./content/getting-started.md dist/docs/topics/ && cp ./content/modeling/*.md dist/docs/topics/ && cp ./content/dashboards/*.md dist/docs/topics/",
"dev": "tsdown src/bin/bon.ts --format esm --out-dir dist/bin --watch",

@@ -15,0 +15,0 @@ "test": "vitest run"

# Catalog
> Browse and understand your data model — no code required.
The Bonnard catalog gives everyone on your team a live view of your semantic layer. Browse cubes, views, measures, and dimensions from the browser. Understand what data is available before writing a single query.
## What you can explore
- **Cubes and Views** — See every deployed source with field counts at a glance
- **Measures** — Aggregation type, SQL expression, format (currency, percentage), and description
- **Dimensions** — Data type, time granularity options, and custom metadata
- **Segments** — Pre-defined filters available for queries
## Field-level detail
Click any field to see exactly how it's calculated:
- **SQL expression** — The underlying query logic
- **Type and format** — How the field is aggregated and displayed
- **Origin cube** — Which cube a view field traces back to
- **Referenced fields** — Dependencies this field relies on
- **Custom metadata** — Tags, labels, and annotations set by your data team
## Built for business users
The catalog is designed for anyone who needs to understand the data, not just engineers. No YAML, no terminal, no warehouse credentials. Browse the schema, read descriptions, and know exactly what to ask your AI agent for.
## See Also
- [views](views) — How to create curated views for your team
- [cubes.public](cubes.public) — Control which cubes are visible
# CLI
> Built for agent-first development by data engineers.
The Bonnard CLI (`bon`) takes you from zero to a deployed semantic layer in minutes. Initialize a project, connect your warehouse, define metrics in YAML, validate locally, and deploy — all from your terminal or your AI coding agent.
## Agent-ready from the start
`bon init` generates context files for your AI coding tools automatically:
- **Claude Code** — `.claude/rules/` + get-started skill
- **Cursor** — `.cursor/rules/` with auto-apply frontmatter
- **Codex** — `AGENTS.md` + skills folder
Your agent understands Bonnard's modeling language from the first prompt.
## Key commands
```bash
bon init # Scaffold project + agent context
bon datasource add --demo # Add a demo warehouse instantly
bon datasource add --from-dbt # Import connections from dbt
bon validate # Check YAML syntax
bon deploy -m "description" # Ship to production (message required)
bon query '{"measures":["orders.count"]}' # Test your semantic layer
bon deployments # List deployment history
bon diff <id> # View changes in a deployment
bon annotate <id> --data '{...}' # Add context to deployment changes
bon mcp # Get MCP setup instructions
bon docs cubes.measures # Read modeling docs in terminal
```
## CI/CD ready
Deploy from GitHub Actions, GitLab CI, or any pipeline:
```bash
bon deploy --ci -m "CI deploy"
```
Non-interactive mode. Datasources are synced automatically. Fails fast if anything is misconfigured.
## Deployment versioning
Every deploy creates a versioned deployment with automatic change detection — added, modified, removed, and breaking changes are flagged. Review history with `bon deployments`, inspect changes with `bon diff`, and add context with `bon annotate`.
## Built-in documentation
```bash
bon docs cubes.measures # Read modeling docs in your terminal
bon docs --search "joins" # Search across all topics
```
No context-switching. Learn and build in the same workflow.
## See Also
- [workflow.deploy](workflow.deploy) — Deployment details
- [workflow.validate](workflow.validate) — Validation reference
# Context Graph (Coming Soon)
> Visualize how your metrics connect. Coming soon.
The Business Context Graph will provide an interactive visual map of your entire semantic layer — cubes, views, joins, and field dependencies — so you can understand impact before making changes.
## Planned capabilities
- **Relationship visualization** — See how cubes connect through joins and shared dimensions
- **Impact analysis** — Understand which views and measures are affected when you change a cube
- **Field lineage** — Trace any metric back through its dependencies to the source table
- **Search and filter** — Navigate large models by searching for specific fields or cubes
## Why it matters
As your semantic layer grows, understanding the relationships between dozens of cubes and hundreds of fields becomes critical. The Context Graph gives your team a shared mental model of how metrics are defined and connected — reducing errors and speeding up development.
Interested in early access? Reach out at [hello@bonnard.dev](mailto:hello@bonnard.dev).
# Governance
> Control who can see which views, columns, and rows in your semantic layer.
Bonnard provides admin-managed data governance — control which views, columns, and rows each group of users can access. Policies are configured in the web UI and enforced automatically across MCP queries and the API. Changes take effect within one minute.
## How It Works
```
Admin configures in web UI:
Groups → Views → Field/Row restrictions
Enforced automatically:
MCP queries + API → only see what policies allow
```
Governance uses **groups** as the unit of access. Each group has a set of **policies** that define which views its members can see, and optionally restrict specific columns or rows within those views.
## Groups
Groups represent teams or roles in your organization — "Sales Team", "Finance", "Executive". Create and manage groups from the **Governance** page in the Bonnard dashboard.
Each group has:
- **Name** and optional description
- **Color** for visual identification
- **View access** — which views the group can query
- **Members** — which users belong to the group
Users can belong to multiple groups. Their effective access is the **union** of all group policies.
## View-Level Access (Level 1)
The simplest control: toggle which views a group can see. Unchecked views are completely invisible to group members — they won't appear in `explore_schema` or be queryable.
From the group detail page, check the views you want to grant access to and click **Save changes**. New policies default to "All fields" with no row filters.
## Field-Level Access (Level 2)
Fine-tune which measures and dimensions a group can see within a view. Click the gear icon on any granted view to open the fine-tune dialog.
Three modes:
- **All fields** — full access to every measure and dimension (default)
- **Only these** — whitelist specific fields; everything else is hidden
- **All except** — blacklist specific fields; everything else is visible
Hidden fields are removed from the schema — they don't appear in `explore_schema` and can't be used in queries.
## Row-Level Filters (Level 2)
Restrict which rows a group can see. Add row filters in the fine-tune dialog to limit data by dimension values.
For example, filter `traffic_source` to `equals B2B, Organic` so the group only sees rows where traffic_source is B2B or Organic. Multiple values in a single filter are OR'd (any match). Multiple separate filters are AND'd (all must match).
Row filters are applied server-side on every query — users cannot bypass them.
## Members
Assign users to groups from the **Members** tab. Each user shows which groups they belong to and a preview of their effective access (which views they can query, any field or row restrictions).
Users without any group assignment see nothing — they must be added to at least one group to query governed views.
## How Policies Are Enforced
Policies configured in the web UI are stored in Supabase and injected into the query engine at runtime. When a user queries via MCP or the API:
1. Their JWT is enriched with group memberships
2. The query engine loads policies for those groups
3. View visibility, field restrictions, and row filters are applied automatically
4. The user only sees data their policies allow
No YAML changes are needed — governance is fully managed through the dashboard.
## Best Practices
1. **Start with broad access, then restrict** — give groups all views first, then fine-tune as needed
2. **Use groups for teams, not individuals** — easier to manage and audit
3. **Test with MCP** — after changing policies, query via MCP to verify the restrictions work as expected
4. **Review after schema deploys** — new views need to be added to group policies to become visible
## See Also
- [features.mcp](features.mcp) — How AI agents query your semantic layer
- [views](views) — Creating curated data views
# MCP
> Connect your preferred AI agent to your semantic layer.
Bonnard exposes your semantic layer as a remote MCP server. Add one URL to your agent platform and it can explore your data model, run queries, and render charts — all through the Model Context Protocol.
![MCP chat with visualisations](/images/mcp-chat-demo.gif)
## Connect your agent
Bonnard works with any MCP-compatible client:
- **Claude Desktop** — Add as a custom connector
- **ChatGPT** — Add via Settings > Apps (Pro/Plus)
- **Cursor** — Add via Settings > MCP or `.cursor/mcp.json`
- **Microsoft Copilot Studio** — Add as an MCP tool with OAuth 2.0 authentication
- **VS Code / GitHub Copilot** — Add via Command Palette or `.vscode/mcp.json`
- **Claude Code** — Add via `claude mcp add` or `.mcp.json`
- **Windsurf** — Add via MCP config
- **Gemini CLI** — Add via `.gemini/settings.json`
One URL for all of them:
```
https://mcp.bonnard.dev/mcp
```
On first use, your browser opens to sign in — the agent receives a 30-day token automatically. No API keys, no config files, no secrets to rotate.
## Tools your agent gets
| Tool | What it does |
|------|-------------|
| `explore_schema` | Browse cubes, views, and fields — or search by keyword |
| `query` | Run structured queries with measures, dimensions, filters, and time grouping |
| `sql_query` | Execute raw SQL for complex analysis (CTEs, UNIONs, custom calculations) |
| `describe_field` | Inspect any field's SQL definition, type, format, and dependencies |
| `visualize` | Render line, bar, pie, and KPI charts directly inside the conversation |
## Charts in chat
The `visualize` tool renders interactive charts inline — auto-detected from your query shape. Charts support dark mode, currency and percentage formatting, and multi-series data.
Ask "show me revenue by region this quarter" and get a formatted chart in your conversation, not a data dump.
## See Also
- [workflow.mcp](workflow.mcp) — Step-by-step setup for each platform
# Features
> Everything you need to define, deploy, and query your semantic layer.
Bonnard is a semantic layer platform built for AI-first analytics. Define your metrics once in YAML, deploy in seconds, and query from anywhere — your IDE, your AI agent, or your own apps.
- **[MCP](features.mcp)** — Connect your preferred AI agent to your semantic layer
- **[CLI](features.cli)** — Agent-first development workflow for data engineers
- **[Semantic Layer](features.semantic-layer)** — Hosted, queryable metrics layer across all your warehouses
- **[Catalog](features.catalog)** — Browse and understand your data model from the browser
- **[SDK](features.sdk)** — Build custom data apps on top of Bonnard
- **[Governance](features.governance)** — User and group-level permissions for your data
- **[Context Graph](features.context-graph)** — Visual map of how your metrics connect (coming soon)
- **[Slack & Teams](features.slack-teams)** — AI agents in your team chat (coming soon)
- **[Deployment Versioning](workflow.deploy)** — Change detection, diff, and annotations for every deploy
# SDK
> Build custom data apps on top of your semantic layer.
The Bonnard SDK (`@bonnard/sdk`) is a lightweight TypeScript client for querying your deployed semantic layer programmatically. Build dashboards, embedded analytics, internal tools, or data pipelines — all backed by your governed metrics.
## Quick start
```bash
npm install @bonnard/sdk
```
```typescript
import { createClient } from '@bonnard/sdk';
const bonnard = createClient({
apiKey: 'your-api-key',
});
const result = await bonnard.query({
cube: 'orders',
measures: ['revenue', 'count'],
dimensions: ['status'],
timeDimension: {
dimension: 'created_at',
granularity: 'month',
dateRange: ['2025-01-01', '2025-12-31'],
},
});
```
## Type-safe queries
Full TypeScript support with inference. Measures, dimensions, filters, time dimensions, and sort orders are all typed. Query results include field annotations with titles and types.
```typescript
const result = await bonnard.sql<OrderRow>(
`SELECT status, MEASURE(revenue) FROM orders GROUP BY 1`
);
// result.data is OrderRow[]
```
## What you can build
- **Custom dashboards** — Query your semantic layer from Next.js, React, or any frontend
- **Embedded analytics** — Add governed metrics to your product
- **Data pipelines** — Consume semantic layer data in ETL workflows
- **Internal tools** — Build admin panels backed by consistent metrics
## See Also
- [features.semantic-layer](features.semantic-layer) — Platform overview
- [workflow.query](workflow.query) — Query format reference
# Semantic Layer
> Define metrics once. Query from anywhere.
Bonnard hosts your semantic layer so you don't have to. Define cubes and views in YAML, deploy with `bon deploy`, and query via JSON API, SQL, or MCP — no infrastructure to manage.
## Multi-warehouse
Connect any combination of warehouses through a single semantic layer:
- **PostgreSQL** — Direct TCP connection
- **Redshift** — Cluster or serverless endpoint
- **Snowflake** — Account-based authentication
- **BigQuery** — GCP service account
- **Databricks** — Token-based workspace connection
Metrics from different warehouses are queried through the same API. Your consumers never need to know where the data lives.
## Two query formats
**JSON API** — Structured queries with type-safe parameters:
```bash
bon query '{
"measures": ["orders.revenue"],
"dimensions": ["orders.status"],
"timeDimensions": [{
"dimension": "orders.created_at",
"granularity": "month",
"dateRange": ["2025-01-01", "2025-12-31"]
}]
}'
```
**SQL** — Full Cube SQL syntax for complex analysis:
```bash
bon query --sql "SELECT status, MEASURE(revenue) FROM orders GROUP BY 1"
```
## Fully managed
Your models are stored securely and served from Bonnard's infrastructure. Each organization gets isolated query execution scoped by JWT — no shared data, no noisy neighbors.
Deploy in seconds. Query in milliseconds.
## Built for AI agents
Views and descriptions are the discovery API for AI agents. When an agent calls `explore_schema`, it sees view names and descriptions — that's all it has to decide where to query. Well-written descriptions with scope, disambiguation, and dimension values make agents accurate. See the design guide principles in the CLI (`/bonnard-design-guide`) for details.
## See Also
- [workflow.query](workflow.query) — Query format reference
- [cubes](cubes) — Cube modeling guide
- [views](views) — View modeling guide
- [features.governance](features.governance) — Access control for views and data
# Slack & Teams (Coming Soon)
> AI agents in your team chat. Coming soon.
Bonnard will bring semantic layer queries directly into Slack and Microsoft Teams — so anyone on your team can ask questions about data without leaving the conversation.
## Planned capabilities
- **Natural language queries** — Ask "what was revenue last month?" in a channel and get an answer with a chart
- **Governed responses** — Every answer goes through your semantic layer, so metrics are always consistent
- **Shared context** — Results posted in channels are visible to the whole team, not siloed in individual AI chats
- **Proactive alerts** — Get notified when key metrics change beyond thresholds you define
## Why it matters
Your team already lives in Slack and Teams. Instead of asking analysts or switching to a BI tool, anyone can get instant, governed answers right where they work. The same semantic layer that powers your AI agents and dashboards powers your team chat.
Interested in early access? Reach out at [hello@bonnard.dev](mailto:hello@bonnard.dev).
# Deploy
> Deploy your cubes and views to the Bonnard platform using the CLI. Once deployed, your semantic layer is queryable via the REST API, MCP for AI agents, and connected BI tools.
## Overview
The `bon deploy` command uploads your cubes and views to Bonnard, making them available for querying via the API. It validates and tests connections before deploying, and creates a versioned deployment with change detection.
## Usage
```bash
bon deploy -m "description of changes"
```
A `-m` message is **required** — it describes what changed in this deployment.
### Flags
| Flag | Description |
|------|-------------|
| `-m "message"` | **Required.** Deployment description |
| `--ci` | Non-interactive mode |
Datasources are always synced automatically during deploy.
### CI/CD
For automated pipelines, use `--ci` for non-interactive mode:
```bash
bon deploy --ci -m "CI deploy"
```
## Prerequisites
1. **Logged in** — run `bon login` first
2. **Valid cubes and views** — must pass `bon validate`
3. **Working connections** — data sources must be accessible
## What Happens
1. **Validates** — checks cubes and views for errors
2. **Tests connections** — verifies data source access
3. **Uploads** — sends cubes and views to Bonnard
4. **Detects changes** — compares against the previous deployment
5. **Activates** — makes cubes and views available for queries
## Example Output
```
bon deploy -m "Add revenue metrics"
✓ Validating...
✓ bonnard/cubes/orders.yaml
✓ bonnard/cubes/users.yaml
✓ bonnard/views/orders_overview.yaml
✓ Testing connections...
✓ datasource "default" connected
✓ Deploying to Bonnard...
Uploading 2 cubes, 1 view...
✓ Deploy complete!
Changes:
+ orders.total_revenue (measure)
+ orders.avg_order_value (measure)
~ orders.count (measure) — type changed
⚠ 1 breaking change detected
```
## Change Detection
Every deployment is versioned. Bonnard automatically detects:
- **Added** — new cubes, views, measures, dimensions
- **Modified** — changes to type, SQL, format, description
- **Removed** — deleted fields (flagged as breaking)
- **Breaking changes** — removed measures/dimensions, type changes
## Reviewing Deployments
After deploying, use these commands to review history and changes:
### List deployments
```bash
bon deployments # Recent deployments
bon deployments --all # Full history
```
### View changes in a deployment
```bash
bon diff <deployment-id> # All changes
bon diff <deployment-id> --breaking # Breaking changes only
```
### Annotate changes
Add reasoning or context to deployment changes:
```bash
bon annotate <deployment-id> --data '{"object": "note about why this changed"}'
```
Annotations are visible in the schema catalog and help teammates understand why changes were made.
## Deploy Flow
```
bon deploy -m "message"
├── 1. bon validate (must pass)
├── 2. Test all datasource connections (must succeed)
├── 3. Upload to Bonnard API
│ - cubes from bonnard/cubes/
│ - views from bonnard/views/
│ - datasource configs
├── 4. Detect changes vs. previous deployment
└── 5. Activate deployment
```
## Error Handling
### Validation Errors
```
✗ Validating...
bonnard/cubes/orders.yaml:15:5
error: Unknown measure type "counts"
Deploy aborted. Fix validation errors first.
```
### Connection Errors
```
✗ Testing connections...
✗ datasource "analytics": Connection refused
Deploy aborted. Fix connection issues:
- Check credentials in .bon/datasources.yaml
- Verify network access to database
- Run: bon datasource add (to reconfigure)
```
### Auth Errors
```
✗ Not logged in.
Run: bon login
```
## What Gets Deployed
| Source | Deployed |
|--------|----------|
| `bonnard/cubes/*.yaml` | All cube definitions |
| `bonnard/views/*.yaml` | All view definitions |
| `.bon/datasources.yaml` | Connection configs (credentials encrypted) |
| `bon.yaml` | Project settings |
## Deployment Behavior
- **Replaces** previous deployment (not additive)
- **All or nothing** — partial deploys don't happen
- **Instant** — changes take effect immediately
- **Versioned** — every deployment is tracked with changes
## Best Practices
1. **Always include a meaningful message** — helps teammates understand what changed
2. **Validate first** — run `bon validate` before deploy
3. **Test locally** — verify queries work before deploying
4. **Use version control** — commit cubes and views before deploying
5. **Review after deploy** — use `bon diff` to check for unintended breaking changes
6. **Annotate breaking changes** — add context so consumers know what to update
## See Also
- workflow
- workflow.validate
- cubes
- views
# MCP
> Connect AI agents like Claude, ChatGPT, and Cursor to your semantic layer using the Model Context Protocol. MCP gives agents governed access to your metrics and dimensions.
## Overview
After deploying with `bon deploy`, AI agents can query your semantic layer through the Model Context Protocol (MCP). Bonnard's MCP server provides tools for exploring your data model and running queries.
MCP is supported by Claude, ChatGPT, Cursor, Windsurf, VS Code, Gemini, and more.
## MCP URL
```
https://mcp.bonnard.dev/mcp
```
## Setup
### Claude Desktop
1. Click the **+** button in the chat input, then select **Connectors > Manage connectors**
![Claude Desktop — Connectors menu in chat](/images/claude-chat-connectors.png)
2. Click **Add custom connector**
3. Enter a name (e.g. "Bonnard MCP") and the MCP URL: `https://mcp.bonnard.dev/mcp`
4. Click **Add**
![Claude Desktop — Add custom connector dialog](/images/claude-add-connector.png)
Once added, enable the Bonnard connector in any chat via the **Connectors** menu.
Remote MCP servers in Claude Desktop must be added through the Connectors UI, not the JSON config file.
### ChatGPT
Custom MCP servers must be added in the browser at [chatgpt.com](https://chatgpt.com) — the desktop app does not support this.
1. Go to [chatgpt.com](https://chatgpt.com) in your browser
2. Open **Settings > Apps**
![ChatGPT — Settings > Apps](/images/chatgpt-apps.png)
3. Click **Advanced settings**, enable **Developer mode**, then click **Create app**
![ChatGPT — Advanced settings with Developer mode and Create app](/images/advanced-create-app-chatgpt.png)
4. Enter a name (e.g. "Bonnard MCP"), the MCP URL `https://mcp.bonnard.dev/mcp`, and select **OAuth** for authentication
5. Check the acknowledgement box and click **Create**
![ChatGPT — Create new app with MCP URL](/images/chatgpt-new-app.png)
Once created, the Bonnard connector appears under **Enabled apps**:
![ChatGPT — Bonnard MCP available in chat](/images/chatgpt-chat-apps.png)
Available on Pro and Plus plans.
### Cursor
Open **Settings > MCP** and add the server URL, or add to `.cursor/mcp.json` in your project:
```json
{
"mcpServers": {
"bonnard": {
"url": "https://mcp.bonnard.dev/mcp"
}
}
}
```
On first use, your browser will open to sign in and authorize the connection.
### VS Code / GitHub Copilot
Open the Command Palette and run **MCP: Add Server**, or add to `.vscode/mcp.json` in your project:
```json
{
"servers": {
"bonnard": {
"type": "http",
"url": "https://mcp.bonnard.dev/mcp"
}
}
}
```
On first use, your browser will open to sign in and authorize the connection.
### Claude Code
Run in your terminal:
```bash
claude mcp add --transport http bonnard https://mcp.bonnard.dev/mcp
```
Or add to `.mcp.json` in your project:
```json
{
"mcpServers": {
"bonnard": {
"type": "http",
"url": "https://mcp.bonnard.dev/mcp"
}
}
}
```
### Windsurf
Open **Settings > Plugins > Manage plugins > View raw config**, or edit `~/.codeium/windsurf/mcp_config.json`:
```json
{
"mcpServers": {
"bonnard": {
"serverUrl": "https://mcp.bonnard.dev/mcp"
}
}
}
```
### Gemini CLI
Add to `.gemini/settings.json` in your project or `~/.gemini/settings.json` globally:
```json
{
"mcpServers": {
"bonnard": {
"url": "https://mcp.bonnard.dev/mcp"
}
}
}
```
## Authentication
MCP uses OAuth 2.0 with PKCE. When an agent first connects:
1. Agent discovers OAuth endpoints automatically
2. You are redirected to Bonnard to sign in and authorize
3. Agent receives an access token (valid for 30 days)
No API keys or manual token management needed.
## Available Tools
Once connected, AI agents can use these MCP tools:
| Tool | Description |
|------|-------------|
| `explore_schema` | Discover views and cubes, list their measures, dimensions, and segments. Supports browsing a specific source by name or searching across all fields by keyword. |
| `query` | Query the semantic layer with measures, dimensions, time dimensions, filters, segments, and pagination. |
| `sql_query` | Execute raw SQL against the semantic layer using Cube SQL syntax with `MEASURE()` for aggregations. Use for CTEs, UNIONs, and custom calculations. |
| `describe_field` | Get detailed metadata for a field — SQL expression, type, format, origin cube, and referenced fields. |
## Testing
```bash
# Verify the MCP server is reachable
bon mcp test
# View connection info
bon mcp
```
## Managing Connections
Active MCP connections can be viewed and revoked in the Bonnard dashboard under **MCP**.
## See Also
- workflow.deploy
- workflow.query
# Workflow
> The end-to-end workflow for building a semantic layer with Bonnard: validate your YAML definitions locally, deploy to the platform, and query your metrics via API or MCP.
## Overview
Building a semantic layer with Bonnard follows a development workflow: initialize a project, connect data sources, define cubes and views, validate, and deploy.
## Quick Start
```bash
# 1. Initialize project
bon init
# 2. Add a data source
bon datasource add
# 3. Create cubes in bonnard/cubes/ and views in bonnard/views/
# 4. Validate
bon validate
# 5. Deploy to Bonnard
bon deploy -m "Initial semantic layer"
```
## Project Structure
After `bon init`, your project has:
```
my-project/
├── bon.yaml # Project configuration
├── bonnard/ # Semantic layer definitions
│ ├── cubes/ # Cube definitions
│ │ └── orders.yaml
│ └── views/ # View definitions
│ └── orders_overview.yaml
└── .bon/ # Local config (gitignored)
└── datasources.yaml # Data source credentials
```
## Development Cycle
### 1. Define Cubes
Create cubes that map to your database tables:
```yaml
# bonnard/cubes/orders.yaml
cubes:
- name: orders
sql_table: public.orders
measures:
- name: count
type: count
dimensions:
- name: status
type: string
sql: status
```
### 2. Define Views
Create views that expose cubes to consumers:
```yaml
# bonnard/views/orders_overview.yaml
views:
- name: orders_overview
cubes:
- join_path: orders
includes:
- count
- status
```
### 3. Validate
Check for syntax errors and test connections:
```bash
bon validate
```
### 4. Deploy
Push cubes and views to Bonnard:
```bash
bon deploy -m "Add orders cube and overview view"
```
### 5. Review
Check what changed in your deployment:
```bash
bon deployments # List recent deployments
bon diff <deployment-id> # View all changes
bon diff <deployment-id> --breaking # Breaking changes only
```
## File Organization
### One Cube Per File
```
bonnard/cubes/
├── orders.yaml
├── users.yaml
├── products.yaml
└── line_items.yaml
```
### Related Cubes Together
```
bonnard/cubes/
├── sales/
│ ├── orders.yaml
│ └── line_items.yaml
├── users/
│ ├── users.yaml
│ └── profiles.yaml
└── products/
└── products.yaml
```
## Best Practices
1. **Start from questions** — collect the most common questions your team asks, then build views that answer them. Don't just mirror your warehouse tables.
2. **Add filtered measures** — if a dashboard card has a WHERE clause beyond a date range, that filter should be a filtered measure. This is the #1 way to match real dashboard numbers.
3. **Write descriptions for agents** — descriptions are how AI agents choose which view and measure to use. Lead with scope, cross-reference related views, include dimension values.
4. **Validate often** — run `bon validate` after each change
5. **Test with real questions** — after deploying, ask an AI agent via MCP the same questions your team asks. Check it picks the right view and measure.
6. **Iterate** — expect 2-4 rounds of deploying, testing with questions, and improving descriptions before agents reliably answer the top 10 questions.
## Commands Reference
| Command | Description |
|---------|-------------|
| `bon init` | Create project structure |
| `bon datasource add` | Add a data source |
| `bon datasource add --demo` | Add demo dataset (no warehouse needed) |
| `bon datasource add --from-dbt` | Import from dbt profiles |
| `bon datasource list` | List configured sources |
| `bon validate` | Check cube and view syntax |
| `bon deploy -m "message"` | Deploy to Bonnard (message required) |
| `bon deploy --ci` | Non-interactive deploy |
| `bon deployments` | List deployment history |
| `bon diff <id>` | View changes in a deployment |
| `bon annotate <id>` | Add context to deployment changes |
| `bon query '{...}'` | Query the semantic layer |
| `bon mcp` | MCP setup instructions for AI agents |
| `bon docs` | Browse documentation |
## See Also
- workflow.validate
- workflow.deploy
- cubes
- views
# Query
> Query your deployed semantic layer using the Bonnard REST API. Send JSON query objects or SQL strings to retrieve measures and dimensions with filtering, grouping, and time ranges.
## Overview
After deploying with `bon deploy`, you can query the semantic layer using `bon query`. This tests that your cubes and views work correctly and returns data from your warehouse through Bonnard.
## Query Formats
Bonnard supports two query formats:
### JSON Format (Default)
The JSON format uses the REST API structure:
```bash
bon query '{"measures": ["orders.count"]}'
bon query '{
"measures": ["orders.total_revenue"],
"dimensions": ["orders.status"],
"filters": [{
"member": "orders.created_at",
"operator": "inDateRange",
"values": ["2024-01-01", "2024-12-31"]
}]
}'
```
**JSON Query Properties:**
| Property | Description |
|----------|-------------|
| `measures` | Array of measures to calculate (e.g., `["orders.count"]`) |
| `dimensions` | Array of dimensions to group by (e.g., `["orders.status"]`) |
| `filters` | Array of filter objects |
| `timeDimensions` | Time-based grouping with granularity |
| `segments` | Named filters defined in cubes |
| `limit` | Max rows to return |
| `offset` | Skip rows (pagination) |
| `order` | Sort specification |
**Filter Operators:**
| Operator | Use Case |
|----------|----------|
| `equals`, `notEquals` | Exact match |
| `contains`, `notContains` | String contains |
| `startsWith`, `endsWith` | String prefix/suffix |
| `gt`, `gte`, `lt`, `lte` | Numeric comparison |
| `inDateRange`, `beforeDate`, `afterDate` | Time filtering |
| `set`, `notSet` | NULL checks |
### SQL Format
The SQL format uses the SQL API, where cubes are tables:
```bash
bon query --sql "SELECT status, MEASURE(count) FROM orders GROUP BY 1"
bon query --sql "SELECT
city,
MEASURE(total_revenue),
MEASURE(avg_order_value)
FROM orders
WHERE status = 'completed'
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10"
```
**SQL Syntax Rules:**
1. **Cubes/views are tables** — `FROM orders` references the `orders` cube
2. **Dimensions are columns** — Include in `SELECT` and `GROUP BY`
3. **Measures use `MEASURE()`** — Or matching aggregates (`SUM`, `COUNT`, etc.)
4. **Segments are boolean** — Filter with `WHERE is_completed IS TRUE`
**Examples:**
```sql
-- Count orders by status
SELECT status, MEASURE(count) FROM orders GROUP BY 1
-- Revenue by city with filter
SELECT city, SUM(amount) FROM orders WHERE status = 'shipped' GROUP BY 1
-- Using time dimension with granularity
SELECT DATE_TRUNC('month', created_at), MEASURE(total_revenue)
FROM orders
GROUP BY 1
ORDER BY 1
```
## CLI Usage
```bash
# JSON format (default)
bon query '{"measures": ["orders.count"]}'
# SQL format
bon query --sql "SELECT MEASURE(count) FROM orders"
# Limit rows
bon query '{"measures": ["orders.count"], "dimensions": ["orders.city"]}' --limit 10
# JSON output (instead of table)
bon query '{"measures": ["orders.count"]}' --format json
```
## Output Formats
### Table Format (Default)
```
┌─────────┬───────────────┐
│ status │ orders.count │
├─────────┼───────────────┤
│ pending │ 42 │
│ shipped │ 156 │
│ done │ 892 │
└─────────┴───────────────┘
```
### JSON Format
```bash
bon query '{"measures": ["orders.count"]}' --format json
```
```json
[
{ "orders.status": "pending", "orders.count": 42 },
{ "orders.status": "shipped", "orders.count": 156 },
{ "orders.status": "done", "orders.count": 892 }
]
```
## Common Patterns
### Time Series Analysis
```bash
bon query '{
"measures": ["orders.total_revenue"],
"timeDimensions": [{
"dimension": "orders.created_at",
"granularity": "month",
"dateRange": ["2024-01-01", "2024-12-31"]
}]
}'
```
### Filtering by Dimension
```bash
bon query '{
"measures": ["orders.count"],
"dimensions": ["orders.city"],
"filters": [{
"member": "orders.status",
"operator": "equals",
"values": ["completed"]
}]
}'
```
### Multiple Measures
```bash
bon query '{
"measures": ["orders.count", "orders.total_revenue", "orders.avg_order_value"],
"dimensions": ["orders.category"]
}'
```
## Error Handling
### Common Errors
**"Projection references non-aggregate values"**
- All dimensions must be in `GROUP BY`
- All measures must use `MEASURE()` or matching aggregate
**"Cube not found"**
- Check cube name matches deployed cube
- Run `bon deploy` if cubes changed
**"Not logged in"**
- Run `bon login` first
## See Also
- [workflow.deploy](workflow.deploy) - Deploy before querying
- [cubes.measures](cubes.measures) - Define measures
- [cubes.dimensions](cubes.dimensions) - Define dimensions
- [views](views) - Create focused query interfaces
# Validate
> Run validation checks on your cubes and views before deploying to catch YAML syntax errors, missing references, circular joins, and other issues. Use `bon validate` from the CLI.
## Overview
The `bon validate` command checks your YAML cubes and views for syntax errors and schema violations. Run this before deploying to catch issues early.
## Usage
```bash
bon validate
```
## What Gets Validated
### YAML Syntax
- Valid YAML format
- Proper indentation
- Correct quoting
### Schema Compliance
- Required fields present (name, type, sql)
- Valid field values (known measure types, relationship types)
- Consistent naming conventions
### Reference Integrity
- Referenced cubes exist
- Referenced members exist
- Join relationships are valid
## Example Output
### Success
```
✓ Validating YAML syntax...
✓ Checking bonnard/cubes/orders.yaml
✓ Checking bonnard/cubes/users.yaml
✓ Checking bonnard/views/orders_overview.yaml
All cubes and views valid.
```
### Errors
```
✗ Validating YAML syntax...
bonnard/cubes/orders.yaml:15:5
error: Unknown measure type "counts"
Did you mean "count"?
14: measures:
15: - name: order_count
16: type: counts <-- here
17: sql: id
1 error found.
```
## Common Errors
### Missing Required Field
```yaml
# Error: "sql" is required
measures:
- name: count
type: count
# Missing: sql: id
```
### Invalid Type
```yaml
# Error: Unknown dimension type "text"
dimensions:
- name: status
type: text # Should be: string
sql: status
```
### Reference Not Found
```yaml
# Error: Cube "user" not found (did you mean "users"?)
joins:
- name: user
relationship: many_to_one
sql: "{CUBE}.user_id = {user.id}"
```
### YAML Syntax
```yaml
# Error: Bad indentation
measures:
- name: count # Should be indented
type: count
```
## Exit Codes
| Code | Meaning |
|------|---------|
| 0 | All validations passed |
| 1 | Validation errors found |
## Best Practices
1. **Run before every deploy** — `bon validate && bon deploy`
2. **Add to CI/CD** — validate on pull requests
3. **Fix errors first** — don't deploy with validation errors
4. **Test connections** — connections are tested automatically during `bon deploy`
## See Also
- workflow
- workflow.deploy
- syntax

Sorry, the diff of this file is too big to display