When an AI agent writes its own SQL against your warehouse, it makes the same choices a new analyst makes on their first day: which table, which column, which join, which filter. It just makes them faster and with more confidence. The dbt Semantic Layer takes those choices away. The agent asks for "order total by month," and MetricFlow compiles the SQL from definitions your analytics engineers wrote and reviewed.
This guide walks through the whole path: defining metrics in the current YAML spec, testing them locally, and exposing them to an agent through the official dbt MCP server. It's part of a series on the context layer for AI. The series overview on context layers explains where a semantic layer fits among the other kinds of context an agent needs.
Why use the dbt Semantic Layer for AI agents?
Three reasons, in order of how much they matter.
Consistency. The agent, the dashboard and the spreadsheet get the same number, because they all compile from one definition.
Accuracy. dbt Labs ran a text-to-SQL benchmark in April 2026. On a well-modeled project, Claude Sonnet 4.6 scored 90.0% writing SQL directly and 98.2% through the semantic layer. It's a small test, 11 questions with 20 runs each, run by the vendor, so treat it as a direction rather than a guarantee. The comparison in context layer vs semantic layer covers the evidence in more detail.
Safe failure. When a question falls outside what you've modeled, the dbt Semantic Layer is more likely to return an error than a plausible wrong number. For an agent, a clear "I can't answer that from governed metrics" is far better than a confident guess.
How the pieces fit together
- dbt models build clean tables in your warehouse.
- Semantic models describe those tables: their entities (join keys), dimensions and simple metrics.
- Metrics define business calculations, from simple sums to ratios and conversion rates.
- MetricFlow is the engine that compiles a metric request into SQL for your warehouse's dialect.
- The dbt MCP server exposes all of this to AI agents as tools.
MetricFlow has been open source under Apache 2.0 since October 2025, when dbt Labs released it as part of its commitment to the Open Semantic Interchange, now Apache Ossie. Earlier versions used the Business Source License, so older articles may describe different terms.
Define metrics in the new YAML spec
The YAML changed in dbt v1.12. If you've followed older tutorials, you'll have seen top-level semantic_models: blocks with measures: and type_params. In the latest spec:
- A semantic model is a
semantic_model:block inside the model's own entry. - Entities and dimensions are declared on the model's
columns. - Measures are gone. A
type: simplemetric with anaggreplaces them. type_paramsis deprecated, and its keys move to the top level of each metric.
Here's a semantic model for an orders table:
models:
- name: orders
semantic_model:
enabled: true
agg_time_dimension: ordered_at
columns:
- name: order_id
entity:
type: primary
name: order
- name: customer_id
entity:
type: foreign
name: customer
- name: ordered_at
granularity: day
dimension:
type: time
- name: order_status
dimension:
type: categorical
metrics:
- name: order_total
type: simple
label: Order total
agg: sum
expr: order_total
- name: order_count
type: simple
label: Order count
agg: count
expr: order_id
order_id is the primary entity, and customer_id is a foreign entity that lets MetricFlow join to a customers semantic model. ordered_at is the default time dimension for aggregation. The two simple metrics live inside the model because they only use this table.
Metrics that combine other metrics, or that span semantic models, go under a top-level metrics: key:
metrics:
- name: average_order_value
type: ratio
label: Average order value
numerator: order_total
denominator: order_count
- name: order_total_rolling_7d
type: cumulative
label: Order total, rolling 7 days
input_metric: order_total
window: 7 days
MetricFlow supports five metric types: simple, ratio, derived, cumulative and conversion. Derived metrics use an expr over input_metrics, and cumulative metrics need a time spine model in your project.
Two terms come up in every query. metric_time is the name MetricFlow gives each metric's default time dimension, so metrics from different models can share one time axis. A time spine is a model with one row per day, which cumulative metrics use to fill gaps in the data.
If you have an existing project on the old spec, the docs recommend running dbt-autofix deprecations --semantic-layer, then dbt parse and mf validate-configs. One limit as of October 2026: cross-project references aren't supported in the new spec yet, so dbt Mesh projects stay on the legacy format for now.
Test metrics locally with MetricFlow
Before any agent touches the metrics, query them yourself. With dbt Core, install MetricFlow with your warehouse adapter:
pip install "dbt-metricflow[dbt-snowflake]"
dbt parse
mf validate-configs
Then query a metric by time:
mf query --metrics order_total --group-by metric_time --limit 10
The MetricFlow commands page shows output like this for the sample project, shortened here to two rows:
ā Success š¦ - query completed after 1.24 seconds
| METRIC_TIME | ORDER_TOTAL |
|:--------------|--------------:|
| 2017-06-16 | 792.17 |
| 2017-06-17 | 458.35 |
To group by a categorical dimension, reference it through its entity with a double underscore:
mf query --metrics order_total,order_count --group-by metric_time__month,order__order_status
Note there's no space after the commas. On the dbt platform, the equivalent command is dbt sl query, which returns 100 rows by default. To see the SQL MetricFlow generates, add --explain locally or --compile on the platform. Reading that SQL is the fastest way to check a metric does what you think.
Set up the dbt MCP server
The dbt MCP server is open source and maintained by dbt Labs. It exposes several toolsets to MCP clients: the Semantic Layer, the Discovery API for models and lineage, SQL, the dbt CLI, and a few admin and codegen tools. If you're new to the protocol itself, start with the Model Context Protocol explained.
One requirement to know up front: the Semantic Layer tools need the dbt platform. They call its Semantic Layer API with DBT_HOST, DBT_TOKEN and DBT_PROD_ENV_ID. If you only run dbt Core, the Semantic Layer toolset doesn't call the local mf command, so your options are the mf CLI or the dbt CLI tools on the server.
The server runs with uvx, so you don't need to clone anything. The local setup docs recommend keeping credentials in an env file and pointing the client config at it:
{
"mcpServers": {
"dbt": {
"command": "uvx",
"args": ["--env-file", "/absolute/path/to/.env", "dbt-mcp"]
}
}
}
The env file holds values like these:
DBT_HOST=cloud.getdbt.com
DBT_TOKEN=your-service-token
DBT_PROD_ENV_ID=12345
DBT_PROJECT_DIR=/path/to/your/dbt/project
DBT_PATH=/path/to/dbt
Use an absolute path for the env file, and if your MCP client can't find uvx, put the full path from which uvx in command. DBT_PROD_ENV_ID takes the numeric ID, not a URL.
There's also a remote, HTTP-hosted version of the dbt MCP server. It's meant for consuming data and can't run dbt commands, which makes it a safer default for business-facing agents.
The dbt Semantic Layer tools in the MCP server
With the server connected, an agent sees these tools from the dbt Semantic Layer toolset:
| Tool | What it does |
|---|---|
| list_metrics | Lists metrics with their descriptions |
| get_dimensions | Lists the dimensions available for given metrics |
| get_entities | Lists the entities for given metrics |
| get_dimension_values | Returns the values of a dimension, such as all order statuses |
| query_metrics | Runs a metric query with dimensions, filters and ordering |
| get_metrics_compiled_sql | Returns the SQL MetricFlow would run, without running it |
| list_saved_queries | Lists saved queries defined in the project |
A typical agent exchange for "how did average order value change month by month this year?" goes like this:
list_metricsfindsaverage_order_valueand reads its description.get_dimensionsfor that metric confirmsmetric_timeis available at month grain.query_metricsruns withaverage_order_value, grouped bymetric_time__month, filtered to this year.- If the user asks how the number was calculated,
get_metrics_compiled_sqlreturns the exact SQL.
The agent never chose a table or wrote a join. Every number traces back to a reviewed definition.
get_dimension_values is worth calling out. Before filtering on "status = shipped", the agent can check which values exist. That avoids the classic mistake of filtering on a value that's spelled differently in the data and silently getting zero rows.
Write metric descriptions an agent can use
The agent picks metrics from list_metrics, which returns names and descriptions. Vague descriptions lead to wrong picks, so treat them as part of the metric. Compare these two versions of the metric from the orders model above, shown as fragments of that entry:
metrics:
- name: order_total
type: simple
label: Order total
description: Total order amount.
agg: sum
expr: order_total
metrics:
- name: order_total
type: simple
label: Order total
description: >
Gross order value in USD, including tax and shipping, before refunds.
Use for sales volume questions. For revenue, use net_revenue instead,
which excludes refunds and intercompany orders.
agg: sum
expr: order_total
The second one tells the agent what the number includes, which currency it's in, and which metric to use for the most common confusion. That last sentence steers the agent away from the most likely wrong pick.
A few habits help:
- State units and currency.
- Say what's included and excluded.
- Point to the right alternative for common confusions.
- Keep labels short and readable, since they show up in answers.
- Review descriptions in pull requests like any other code.
Do the same for dimensions. A region dimension that says whether it means sales territory or billing country saves the agent from a common filtering mistake in sales data.
Control what the agent can do
The dbt MCP server can do more than read metrics, and you should decide what it's allowed to do before connecting an agent.
- The SQL, codegen and metadata toolsets are off by default.
- The dbt CLI tools can run
buildandrun, which change objects in your warehouse. Enable them only for trusted developer clients, never for business users' agents. - You can switch toolsets off with variables such as
DISABLE_SEMANTIC_LAYERandDISABLE_TOOLS, or switch to allowlist mode withDBT_MCP_ENABLE_SEMANTIC_LAYERandDBT_MCP_ENABLE_TOOLS. - Setting
DBT_MCP_LOG_LEVEL=DEBUGlogs which toolsets are active, which is useful when a tool you expected doesn't appear.
For a business-facing analytics agent, a sensible setup is the Semantic Layer toolset only. Text-to-SQL is a separate tool, and the trade-off is covered below.
Governed metrics or text-to-SQL?
The dbt MCP server offers both, so it's a fair question. Text-to-SQL is flexible: the agent can answer questions nobody modeled. Governed metrics are constrained: they only answer what you defined. For exploratory analysis by people who read SQL, text-to-SQL with the generated query shown is reasonable. For business users who will act on a number without checking it, the constraint is the feature. A common pattern is to route through governed metrics first and fall back to text-to-SQL only with a clear label that the answer didn't come from reviewed definitions.
What the dbt Semantic Layer doesn't give an agent
The dbt Semantic Layer covers metrics, dimensions and entities well. It's one part of a context layer, not all of it.
- Undocumented meaning. The agent only knows what you wrote. A metric with no description or caveats gets used without them.
- Relationships beyond joins. Supply chains, org hierarchies and product compatibility are graph problems. Knowledge graphs for AI agents covers when to add one.
- Cross-platform semantics. If you also define metrics in a BI tool or a warehouse-native layer, they can drift. Platforms such as Snowflake Horizon Context and Microsoft Fabric IQ have their own semantic models, and Apache Ossie aims to make definitions portable between them.
- Context window management. Returning 300 metric descriptions to the model in one tool call wastes tokens and confuses tool choice. The techniques in context engineering for AI agents help here.
For the rest, such as certification, lineage across tools, access policies and documents, see how to build a context layer for AI.
A checklist before you connect an agent
- Every metric the use case needs has a description, units and an owner.
mf validate-configspasses, and you've read the compiled SQL for the most-used metrics.- A set of real test questions with verified answers (golden questions) exists, and you've run them through
query_metricsyourself. - The dbt MCP server runs with only the Semantic Layer toolset enabled.
- The service token has the narrowest permissions that work, and it lives in an env file, not in the client config.
- Someone is named to review the agent's failed answers each week.
Common mistakes
- Copying legacy YAML onto v1.12 or later.
semantic_models:,measures:andtype_paramsbelong to the old spec. - Defining cross-model metrics inside a model. Ratio, derived, cumulative and conversion metrics, and anything spanning models, go under top-level
metrics:. - Grouping by a bare dimension name. Use
entity__dimension, such asorder__order_status. - Forgetting
dbt parseafter editing metrics, so MetricFlow reads stale definitions. - Cumulative metrics without a time spine model.
- Giving a business agent the CLI toolset. Read-only Semantic Layer tools are enough for most agents.
Key takeaways
- The dbt Semantic Layer lets an AI agent ask for metrics by name while MetricFlow compiles governed SQL, which improves consistency and makes out-of-scope questions fail with an error.
- dbt v1.12 introduced a new YAML spec: semantic models live inside model entries, and simple metrics replace measures.
- Test every metric locally with
mf queryand read the compiled SQL before an agent uses it. - The dbt MCP server exposes
list_metrics,get_dimensions,query_metricsand related tools. The Semantic Layer tools need the dbt platform. - Keep business-facing agents on the read-only Semantic Layer toolset, and write metric descriptions for the model that will read them.