Semantic layer + MCP: AI analytics that doesn't invent metrics
How a semantic layer and MCP turn questions into governed metrics: modeling, text-to-SQL, tools, permissions, scenarios, and a checklist.
Table of Contents
It is Monday at nine in the morning and the CEO asks how much the business grew in Europe last quarter. The warehouse has forty tables, three definitions of “active customer,” and a dashboard that says 12% while the finance spreadsheet says 9%. A language model can write the SQL in three seconds. The problem is that the SQL will be plausible, and probably wrong.
AI analytics does not fail because the model cannot write SQL. It fails because nobody gave it a clear contract for what each metric means, how tables join, and what each user is allowed to see. The semantic layer is that contract. MCP is the plug that lets an agent query it without bypassing the rules.
This guide explains how the pieces fit and how to build the MCP server that exposes governed metrics, not a back door to the warehouse.
The problem isn’t writing SQL
The symptom is semantic entropy: the same metric defined five different ways across five dashboards. One team filters by status = 'paid', another by status != 'cancelled', another includes tax, another does not. Each definition is defensible on its own. Together they are a company that cannot answer how much it sold.
An LLM amplifies that problem because it can generate a hundred variants per minute. You give it a forty-table schema and it writes a JOIN that looks reasonable, picks the wrong date field, and aggregates a table that multiplies rows. The query runs. The number is plausible. Nobody can defend it.
The right question is not “can the model write SQL?” It is “can the business defend the answer?” That requires one definition per metric, joins defined once, and permissions enforced before the query runs.
What a semantic layer is (and isn’t)
A semantic layer is a governed layer between consumers and the warehouse. It defines metrics, dimensions, entities, joins, and access rules, and compiles a business request into SQL. It is the difference between asking for “revenue by country” and asking for “the sum of amount from orders with these filters and this join.”
It is not just a dashboard or a data catalog: it is the source of truth for definitions.
There are several implementations: dbt Semantic Layer with MetricFlow, Cube, LookML in Looker, AtScale, or Snowflake semantic views. If your company already models with dbt, you probably have the raw material. The same definition serves a dashboard, a notebook, and an agent: change “revenue” once and it changes in all three.
Metrics, dimensions, entities, and joins
A metric is a named aggregation with a filter and a grain. revenue is not a column: it is sum(amount) over paid orders, in the reporting currency, with a business date. A dimension is an attribute to group by: country, plan, channel, month. An entity is the business key that connects tables: order, customer, subscription. A join is the relationship between entities, defined once.
Grain is the level of detail. An additive metric can be summed from day to month; a non-additive metric, like a balance or a ratio, cannot. If the semantic layer does not know the grain, the agent will sum ratios and produce averages of averages.
Here is a semantic model in current dbt syntax:
models:
- name: fct_orders
semantic_model:
enabled: true
agg_time_dimension: order_date
columns:
- name: order_id
entity: { type: primary, name: order }
- name: order_date
granularity: day
dimension: { type: time }
- name: country
dimension: { type: categorical, name: order_country }
metrics:
- name: revenue
type: simple
agg: sum
expr: amount
order_id is the primary entity; order_country is a categorical dimension and order_date is a time dimension. revenue sums amount.
The agent does not invent the join: the semantic engine resolves it from entities. That prevents the classic fan-out of joining orders to order lines and multiplying the amount. When the data model is right, the generated SQL is boring, and that is exactly what you want.
If your project uses an older dbt version, the syntax lives in a separate semantic_models block.
Permissions: the layer the LLM can’t skip
A serious semantic layer does not just define metrics: it enforces permissions. Metric access, dimension access, row-level security by tenant or region, and masking of sensitive columns. The policy is evaluated with the user’s identity before the SQL is compiled.
The prompt is not an access control. “Do not show data from other customers” is an instruction, not a guarantee. The guarantee is a policy in the semantic layer that adds WHERE tenant_id = :tenant before execution.
Text-to-SQL vs semantic layer
| Text-to-SQL | Semantic layer | |
|---|---|---|
| Source of truth | Schema and prompt | Versioned model |
| Joins | Invented by the model | Defined once |
| Permissions | Depend on generated SQL | Enforced by the layer |
| Consistency | Varies per question | Same definition |
| Best for | Exploration | Decisions and agents |
| Failure mode | Plausible and wrong | Constrained and auditable |
Text-to-SQL is still useful for exploring and answering new questions. It is not the right tool for the number that goes to the board. The semantic layer shrinks the space of possible answers to the ones the company already defined.
The hybrid pattern that works best: the LLM picks the metric, dimensions, time range, and filters; the semantic layer compiles the SQL and applies permissions. The model does not write free-form SQL; it chooses from a menu. That reduces hallucinations and makes the answer reproducible.
MCP: the standard plug
MCP (Model Context Protocol) is an open standard for connecting AI applications to external systems. It uses JSON-RPC 2.0 and a host-client-server architecture: the host is the AI application, the client maintains the connection, and the server exposes capabilities.
Servers can offer three primitives: tools the model can invoke, resources that provide context, and prompts that are reusable templates. For analytics, tools are the main piece.
MCP supports stdio for local servers and Streamable HTTP for remote servers. For production you want the latter, behind OAuth and with the user’s identity propagated. For a local prototype, stdio is enough.
MCP does not define what revenue means or who can see it. It defines how the agent discovers and calls tools. Your server provides the meaning and the rules.
From the model to tools
The temptation is to expose a run_sql tool and let the model do the rest. That is the fastest way to turn the warehouse into a minefield. Instead, expose a small, governed menu:
list_metrics: returns the catalog with name, description, owner, allowed dimensions, default grain, and freshness.query_metrics: takes a metric, dimensions, date range, grain, and filters; returns rows plus metadata.
The query_metrics contract should be explicit. Here is an example schema:
{
"name": "query_metrics",
"description": "Query one governed metric after list_metrics.",
"inputSchema": {
"type": "object",
"properties": {
"metric": { "type": "string", "enum": ["revenue", "orders", "average_order_value"] },
"group_by": { "type": "array", "items": { "type": "string", "enum": ["order_country", "order_date"] } },
"grain": { "type": "string", "enum": ["day", "week", "month"] },
"start": { "type": "string", "format": "date" },
"end": { "type": "string", "format": "date" }
},
"required": ["metric", "start", "end"]
}
}
Enums prevent the model from inventing dimensions. Generate the schema from the catalog so it cannot drift, and always return metadata: compiled SQL, version, freshness, row count, and whether the result was truncated.
A minimal MCP server in Python
The Python SDK exposes MCPServer. Type hints and the docstring generate the tool schema; you only write the function. This server is an adapter over the semantic layer, not a free-form SQL executor:
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from analytics.semantic_layer import SemanticLayer
sl = SemanticLayer.from_env()
mcp = MCPServer("analytics")
@mcp.tool()
def list_metrics() -> dict[str, dict]:
"""List governed metrics with owner, description, allowed dimensions, and freshness."""
return sl.catalog()
@mcp.tool()
def query_metrics(
metric: str,
start: str,
end: str,
group_by: list[str] | None = None,
grain: str = "month",
) -> dict:
"""Query one governed metric. Call list_metrics first.
group_by must be one of the dimensions returned for that metric.
grain is day, week, or month.
"""
catalog = sl.catalog()
if metric not in catalog:
raise ToolError(f"unknown metric: {metric}. Call list_metrics first.")
allowed = set(catalog[metric]["dimensions"])
requested = set(group_by or [])
if not requested <= allowed:
raise ToolError(f"dimensions not allowed: {sorted(requested - allowed)}")
if grain not in {"day", "week", "month"}:
raise ToolError(f"invalid grain: {grain}")
return sl.query(
metric=metric,
start=start,
end=end,
group_by=sorted(requested),
grain=grain,
)
To start it locally, call mcp.run(transport="stdio").
Three production details. The user’s identity is not a tool parameter: the server resolves it from the token or authenticated session and passes it to the semantic layer. ToolError returns a clear error to the client instead of an empty table the model interprets as “no data.” And in a stdio server, never log to stdout: you break JSON-RPC.
For a remote server, switch stdio for Streamable HTTP and put it behind OAuth with audience validation. Never forward a token issued for another service: that is token passthrough.
Governing the agent: identity, audit, and limits
Identity is the foundation. Every query should run as the real user, not a shared service account. The MCP server validates the token, checks the audience, and passes the principal to the semantic layer, which applies RLS and masking.
Limits prevent one curious question from costing more than the quarter. Set a maximum date range, a row limit, a timeout, a query budget, and a concurrency cap. Cache what does not change and mark whether a result is fresh.
Audit answers the question that comes after the incident: who asked what, with which dimensions, which SQL ran, and which metric version was used. If you emit OpenTelemetry traces from the MCP server, you can correlate the query with the rest of your observability.
Evals are your safety net. Build a set of golden questions with the expected metric and dimensions, and run it whenever the semantic model changes. Include cross-tenant permission tests and the “no data” case: the agent must say so, not invent an explanation. Treat results as untrusted data: a row should not change the system’s rules.
Real scenarios
Weekly business review. The CEO asks for revenue by country. The semantic layer resolves the definition, currency, and paid-order filter. The agent presents the table, the definition, and freshness.
Incident triage. “Why did checkout errors spike?” The agent queries error rate by service and route, then jumps to traces and logs. The metric says whether there is a problem; observability says where.
Customer success. “Which enterprise accounts are at risk?” RLS is mandatory: the agent only sees accounts in its territory, and the semantic layer applies the policy before the model sees a row.
Financial close. Reconciling bookings against revenue requires certified metrics, audit trails, and versioning. Text-to-SQL is too risky for a number that goes to the board.
Common mistakes and a checklist
-
Exposing
run_sql. It is the back door that cancels all the governance. -
No date range or row limit. One query can scan years of history.
-
Using a service account with full access. The agent becomes a confused deputy.
-
Trusting the prompt for permissions. The prompt is not an access control.
-
Not handling “no data.” The agent fills the gap with an invented explanation.
-
The main metrics have an owner, definition, filter, and test.
-
Joins live in the semantic layer, not in the prompt.
-
The MCP server uses the user’s identity, not a service account.
-
RLS and masking are applied before SQL compilation.
-
list_metricsreturns description, owner, dimensions, and freshness. -
query_metricsvalidates metric, dimensions, grain, and range. -
Responses include SQL, version, and freshness.
-
There is an eval set with golden questions and permission tests.
An agent does not need to know SQL. It needs to know what “revenue” means in your company. The semantic layer is that answer; MCP is how the question reaches it.
Related articles
By relevance
The modern data analytics stack in 2026: from giant Excel files to the AI-powered lakehouse
Informative guide to the 2026 data stack: DuckDB, Polars, Iceberg, Parquet, AI, log observability, and how to read large files fast.
dbt hands-on: modern transformations from theory to warehouse
Hands-on dbt guide: models, sources, tests, macros, seeds, snapshots, docs, lineage, incremental models, and performance on DuckDB, Postgres, and Snowflake.
PostgreSQL Advanced: Data Extraction, Complex Analysis & Query Optimization at Scale
Master advanced PostgreSQL for analytical workloads. Learn extraction patterns, query optimization, materialized views, JSON analysis, and performance tuning for enterprise-grade data analytics.
SQL for Data Analysis: Advanced Queries, Patterns & Real-World Analytics
Master SQL for data analysis. Learn advanced query patterns, window functions, CTEs, aggregations, and optimization techniques. Write powerful analytical queries that answer real business questions.