Built with Tutify.io

    AIStudyLabs

    dbt Semantic Layer for AI Agents: Query Metrics Through MCP

    dbt Semantic Layer for AI Agents: Query Metrics Through MCP

    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

    Diagram of an AI agent calling the dbt MCP server tools list_metrics, get_dimensions and query_metrics, which go to the dbt Semantic Layer, where MetricFlow compiles SQL against semantic models and runs it on the data warehouse

    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:

    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:

    1. list_metrics finds average_order_value and reads its description.
    2. get_dimensions for that metric confirms metric_time is available at month grain.
    3. query_metrics runs with average_order_value, grouped by metric_time__month, filtered to this year.
    4. If the user asks how the number was calculated, get_metrics_compiled_sql returns 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:

    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.

    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.

    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

    Common mistakes

    Key takeaways