
Chris Parmer
November 10, 2026
Building AI data apps with Databricks and Dash
TL;DR
- Many of the people who need your Databricks data don't use Databricks day to day. This guide shows how to get it to them in a Dash app with charts, an AI chat (Plotly Studio Embedded), and MCP tools, deployed on Dash Enterprise or Plotly Cloud.
- We cover four ways to build the AI part, and recommend the one that combines the other three: open-ended SQL guided by context files, verified metric functions, and the app's regular charts.
- In 225 test conversations with Claude Sonnet 5.5 on 30 million order lines, the AI's own SQL was right 41 times out of 45, and 45 out of 45 once it could read our context files. Metric functions alone never gave a wrong number but couldn't fully answer 15 of the 45.
- A daily snapshot answered queries in a median of 0.04 seconds, against 0.51 seconds on a warm SQL warehouse, for about $0.16 a day on Databricks.
- The same app can join Databricks with your other data sources, and who sees what is set on the app.
The domain experts who work with Databricks data every day, in finance, operations, sales, or engineering, want those numbers in something built for their job, with definitions they trust and an AI they can ask follow-up questions. A data app does that, with charts and tables for the daily numbers and an AI chat next to them for the rest. Our DataAnalyticsBench results show models are ready for that chat, with Claude Sonnet 5.5 answering 38 of 43 questions on a 20-million-row warehouse, as long as they get context: which table holds which number, which date a metric uses, and which column can't be summed.
The numbers in this guide come from a demo app we built on TPC-H data in Databricks, and the code is in the deep dives at the end. The tests use 30 million order lines; the screenshots come from the deployed demo, which runs a 12-million-line version, so its numbers are smaller.

Four ways to build an AI data app on Databricks data
Each option below explains what it is and when it fits, then ends with a prompt you can give a coding agent such as Claude Code to build it. The first three are layers more than alternatives, and Option 4 combines them, as our demo app does. The test results after the options show why that combination worked best.
Option 1: open-ended questions with semantic context
The AI reads the context that applies to a question, writes its own SQL against the gold tables and runs it through a read-only tool. The context is a folder of short markdown files, one per metric, table, glossary term, or known data issue, each with an owner: the format Google calls the Open Knowledge Format (OKF), which our semantic layer guide covers in detail. The people who own each number write down what it means. For example, consider a finance team: it writes down that average order value uses revenue by order date, the data team writes down that revenue_daily.orders can't be summed, and the AI reads both before it answers.

- Good for: the long tail of questions nobody has written a function for, and exploration by people who can't write SQL.
- What makes it work: the context files. Keeping them out of tool docstrings means the people who own the numbers can write and review them like code, without touching the app.
- In our test: 41 of 45 answers right without the context files, and 45 of 45 with them.
Prompt for a coding agent:
- Add Dash MCP tools to this Dash app (dash>=4.5, Dash(enable_mcp=True), configure_mcp_server(include_callbacks=False)).
- Add describe_tables and run_sql for our Databricks gold tables: run_sql accepts one SELECT, checked with duckdb.extract_statements, on a fresh read-only connection that attaches only the files the viewer's groups allow, then sets enable_external_access = false and lock_configuration = true, with a 15-second timeout and a 200-row cap.
- Add list_context and read_context, which read our Open Knowledge Format bundle in definitions/knowledge (markdown with YAML frontmatter: type, title, description, owner), and refuse any path outside it.
- Write the docstrings as instructions: read the definitions that apply before writing SQL, follow them, name the owner, and label every answer as an ad hoc query with its SQL.
Option 2: verified metric functions with parameters
Each number the business reports is one Python function, written and reviewed once, with optional parameters for the dates, breakdowns, and filters people ask for. The AI calls the function instead of writing SQL, so a question gets the same answer as the chart that shows it, along with the definition and SQL that produced it.
In the screenshot at the top of this post, the chat answered "What was revenue by region in 1997, and how is it calculated?" by calling get_revenue, and quoted the certified definition, its owner, and its source table with the numbers.
- Good for: the numbers in reports and board decks, which have to come out the same for everyone.
- The trade-off: coverage. A question needs a function that fits it, so in our test the metric functions alone answered 30 of 45 questions, gave part of an answer to 3, declined 12, and never gave a wrong number.
Prompt for a coding agent:
- Write metrics.py with one function per metric in definitions/knowledge/metrics, such as revenue(start, end, grain, group_by, region).
- Use Literal type hints for fixed choices (grain, group_by) so the tool schema lists them.
- Return the rows together with the metric's definition, owner, data date, and the exact SQL the function ran.
- Expose each function as a Dash MCP tool with @mcp_enabled(expose_docstring=True), and have every tool that reads restricted data check the viewer's groups and refuse without the right one.
Option 3: a regular data app
Charts and tables are still the fastest way to answer the questions people ask every day, and they cost nothing in AI usage. Because they call the same metric functions as the AI's tools, a number in the chat and the same number on the chart always match, and the definition under each chart is the one the AI quotes.

- Good for: the numbers people check every morning, for people who'd rather click than type.
- Add the chat to it: with Plotly Studio Embedded turned on, the same page has an Ask AI panel for follow-up questions, and it can call the same metric functions as the charts.
Prompt for a coding agent:
- Build a Dash page with a year dropdown, a region dropdown, KPI cards, a monthly revenue chart, and a top-customers table.
- Get every number from the functions in metrics.py, not from new SQL.
- Under each chart, add a "How is this calculated?" section that shows the definition, owner, data date, and SQL the function returned.
- Show restricted cards only to viewers in the finance group.
Option 4: all of the above
This is how our demo app is built, apart from the analysis code and write-back, and it's what we recommend, because each layer covers what the one before it can't. The charts answer the daily questions without any AI usage, the metric functions keep reported numbers consistent when people ask the AI about them, and the SQL tool with context files picks up whatever no function covers.
Because a Dash app is Python, it isn't limited to reading data. It can hold the models your scientists, engineers, and quants already use, from a risk model to a reservoir simulation, as charts and as tools the AI can call. It can also write back: a viewer approves a forecast or corrects a mapping, and the app saves the change where the data team can review it. The tests below cover the first three options, because the demo has neither.
- Good for: most apps. Start with charts and metric functions for the numbers you report, and add the SQL tool and context files as people's questions spread out.
- In our test: all three together answered 45 of 45 right, at a median of 7.9 seconds per question.
Prompt for a coding agent:
- Combine the three options in one Dash app: the charts and tables call metrics.py, the same functions are MCP tools, and run_sql with the context files covers the questions no function fits.
- In the tool docstrings, tell the AI to use a metric function when one fits and to fall back to SQL with the context files when none does.
- Add our team's own analysis code as functions the charts and the AI can both call, such as our value-at-risk model or our decline-curve fit.
- Add a form where a viewer can approve a forecast or flag a bad row, and save it to a table the data team reviews.
- Turn on Plotly Studio Embedded.
How the options did on the same questions
We asked Claude Sonnet 5.5 15 questions through the demo app's MCP server, as a Finance viewer, with five different sets of tools: each option's tools on their own, and in combination. Twelve were questions of the kind an app's charts answer, from revenue by region and year to the number of customers whose margin halved from 1996 to 1997. One was "How many orders were placed in 1997?", and two needed something no metric function covers (quantity by ship mode, and the supplier nations selling most to Germany). Each question ran three times per tool set, 225 conversations in all, and we read every answer the grading script didn't match.

Tools the AI had (45 answers each)
Right numbers
Declined, or answered part and said why
A different definition or wrong numbers
Metric functions only
30
15
0
Open-ended SQL only
41
0
4
SQL with the context files
45
0
0
Metric functions and SQL
45
0
0
All three together (Option 4), as in the demo app
45
0
0
- Without context, the AI's own SQL was usually right, and its wrong answers looked as confident as its right ones. All three average-order-value runs divided revenue by ship date, which runs to December, by orders placed, which stop on August 2 where the data ends, and reported $182,000 to $191,000 per order in a neat table. The right range, with both on order dates, is $143,000 to $148,000.
- Without context, one question got two answers. "How many customers had their 1997 margin fall to less than half of their 1996 margin?" came back as 96,481 twice and 150,524 once, because one run counted customers with no 1997 orders as a fall to zero. Both readings are reasonable, and a written definition is how a team picks one.
- With the context files, both went away. The model read the average-order-value file, used order-date revenue, and got all three runs right; it read the margin file, which says to compare only customers with orders in both years and report lapsed customers separately, and answered 96,481 every time, with the 54,056 lapsed customers listed alongside.
- Metric functions never guessed. When no function fit, the model said so ("Any number I gave would be a guess") rather than estimating, which is safe but leaves the question unanswered.
- With all three together, the model picked well. It used the metric functions for all 10 questions they cover and SQL with context for the five they don't, at a median of 7.9 seconds per question. Context costs a little time: SQL with context took 9.4 seconds against 7.4 without, because the model reads a few files first (a median of 13,009 tokens per question against 4,950).
We also found the most common trap in our own code. The orders column in revenue_daily counts distinct orders per ship date, nation, segment, and ship mode, so summing it over a year counts most orders several times. Our first get_revenue summed it, and the app's Orders card showed 4,541,477 orders in 1997 when 1,137,325 were placed. We fixed it once, with an orders_daily table and a get_orders function, and wrote the known issue into the context files. Asked the same question against the old tables without context, the SQL tool caught the problem when it could cross-check against the margin table (as Finance, 5 of 5 right) and led with 4.5 million when it couldn't (as an Analyst, 5 of 5, each with a note that it was probably an overcount).
That's why we recommend Option 4. When the same ad hoc question keeps coming up, turn it into a metric function.
Data is never in one place
Even companies that have moved most of their data into Databricks keep important numbers somewhere else: the CRM, the ERP's own database, the planning workbook a finance team updates every month, a vendor's API, or another team's warehouse. An assistant that lives inside the lakehouse can only answer from what has been loaded into it, and loading every source first is a project of its own, with pipelines someone has to build and pay for.
A Dash app is Python, so it can read each source where it lives and put them side by side for the people asking:
- Databricks gold tables, from the snapshot or a SQL warehouse, as in the rest of this guide.
- Operational databases such as Postgres, MySQL, or SQL Server, through their usual Python drivers, or attached read-only in DuckDB next to the snapshot so one query can join them.
- Files the business keeps, such as a planning workbook, a CSV export, or Parquet in S3, read with pandas or DuckDB.
- APIs and other MCP servers, such as the CRM, the ticketing system, or an internal service, called from a tool with the app's credentials, as in our post on Studio Embedded and MCP tools.
One tool can then answer a question that spans all of them. This example is illustrative, because our demo app only has the TPC-H tables, but every piece of it is standard DuckDB and pandas:
# Runs in the Dash app: one tool, three sources@mcp_enabled(expose_docstring=True)def revenue_vs_plan(year: int) -> dict:"""Actual revenue by region and month (Databricks gold tables) against Finance's plan(the planning workbook) and open pipeline (the CRM's Postgres database)."""plan = pd.read_excel(PLAN_XLSX, sheet_name=str(year)) # columns: region, month, planwith duckdb.connect() as con:con.execute(f"attach '{local_path('general')}' as gold (read_only)")con.execute("install postgres; load postgres")con.execute(f"attach '{CRM_DSN}' as crm (type postgres, read_only)")rows = con.execute("""select a.region, a.month, a.revenue, p.plan, c.pipelinefrom (select region, date_trunc('month', ship_date) as month, sum(revenue) as revenuefrom gold.revenue_daily where year(ship_date) = $year group by all) aleft join plan p using (region, month) -- the pandas DataFrame aboveleft join (select region, date_trunc('month', close_date) as month, sum(amount) as pipelinefrom crm.public.opportunities where stage <> 'Closed' group by all) cusing (region, month)order by a.region, a.month""", {"year": year}).df()return {"sources": {"revenue": "gold.revenue_daily (Databricks)", "plan": f"{PLAN_XLSX}, sheet {year}","pipeline": "crm.public.opportunities (Postgres)"},"rows": rows.to_dict("records")}
Each source's credentials stay in the app's environment, and the AI only sees the tool, so the chat never holds a connection to the CRM or the ERP. The tool says which source every column came from, and a context file can record the nuances between them, such as the plan being by order month while the CRM dates pipeline by expected close. When a source later moves into Databricks, only the tool changes; the charts, the chat and the questions people ask stay the same.
Live queries or a daily snapshot?
Separately from what the app offers, it needs a way to read the data. There are two, and one app can use both:
- Live: the app sends each query to a Databricks SQL warehouse, so the numbers are current to the minute, and Unity Catalog can apply its grants per viewer if the app queries with each viewer's own token.
- Snapshot: a scheduled Databricks job exports the gold tables to DuckDB files, one per permission level, and the app downloads them and queries them locally.
We measured both on a Databricks workspace in AWS us-east-1, with 12 questions of the kind a tool answers, run five times each, on the gold tables on a 2X-Small serverless SQL warehouse (result cache off), on the raw TPC-H tables on the same warehouse, and on the local DuckDB files on a 4-vCPU container. All three returned identical answers.

Median per query, 12 questions
Typical
Fastest
Slowest
DuckDB file on the app server
0.04 s
0.02 s
0.35 s
SQL warehouse, gold tables
0.51 s
0.48 s
0.77 s
SQL warehouse, raw tables
1.19 s
0.73 s
2.33 s
The first query after the warehouse had auto-stopped took 10.5 seconds. About 0.2 seconds of each warehouse query was the network between our container and Databricks, so an app server in the same region would be a little faster; most of the remaining gap is fixed overhead per query rather than the scan, and an AI question often runs several queries.
Databricks bills SQL warehouses per DBU (Databricks Unit) per second while they run. List prices on AWS US East as of November 2026, from Databricks' pricing page, are $0.70 per DBU for SQL Serverless, and a 2X-Small serverless warehouse uses 4 DBUs an hour.
Cost
Daily snapshot
Live queries
Warehouse while people use the app
None
About $2.80 an hour for 2X-Small serverless, or about $616 a month kept up 10 hours a day, 22 days a month
Scheduled compute
One job a day: ours ran for 99 seconds and used 0.45 DBUs of serverless jobs compute, about $0.16 a run at $0.35 per DBU
None
Data transfer
One file a day: serverless egress is $0.09/GB, so a 1 GB file a day is under $3 a month
Query results only
Freshness
As of the last export
Live
Use the snapshot for most internal apps, where yesterday's numbers are fine and people ask a lot of questions. Query live for numbers that must be current to the minute, or where Unity Catalog's per-user row filters have to apply.
What runs where
The code in this guide runs in two places, and it helps to keep them apart. Databricks keeps doing what it does; the app is a separate project, which domain experts write with a coding agent and deploy on Dash Enterprise or Plotly Cloud.

- In Databricks: the gold tables (SQL your data team already writes), and either a SQL warehouse the app queries or a scheduled job that exports the tables. Nothing about Unity Catalog changes.
- In the Dash app: the code that reads the data (a warehouse connection or the downloaded files), the context files, metrics.py, the app's layout and callbacks, any analytic functions and write-back forms, the MCP tools, and the checks on who sees what.
- On the platform: Dash Enterprise or Plotly Cloud signs viewers in, decides who can open the app, runs Plotly Studio Embedded's chat, and serves the app's MCP endpoint to Claude, ChatGPT, and Copilot with the same viewer access.
Who sees what: authentication and authorization
Three separate questions decide what a viewer sees, and each is answered in a different place.
1. Who can open the app
This is a platform setting, so there's no code to write. On Dash Enterprise, open the app in App Manager, go to Access and choose Restricted (only the users and groups you add, the default for new apps), Authenticated (anyone signed in to Dash Enterprise) or Unauthenticated (anyone who can reach it). Groups come from your identity provider. On Plotly Cloud, the app's Settings > Sharing tab sets view and edit access for anyone with the link, your team, or specific people (the last two need a Pro plan or higher).
The app's MCP endpoint follows the same settings: on both platforms, someone who can't open the app can't connect Claude or ChatGPT to it either.
2. Who the viewer is
On Dash Enterprise, the app can read the signed-in viewer's username and details, including their groups from your identity provider, with dash_enterprise_auth (add dash-enterprise-libraries to requirements.txt). The docs say to call it inside callbacks. Tools that Plotly Studio Embedded calls run with the viewer's own request, so they can read the same identity, but test that on your instance before relying on it:
import dash_enterprise_auth as authdef viewer_groups() -> set[str]:user = auth.get_user_data() # the signed-in viewerreturn set(user.get("groups", [])) # which field carries groups depends on your setup@callback(Output("greeting", "children"), Input("url", "pathname"))def greet(_):return f"Signed in as {auth.get_username()}"
Print get_user_data() once on your instance to see which field carries the groups. On Plotly Cloud, control access with the sharing settings above.
In the demo, a switch on the page stands in for the viewer's group. Signed in as an Analyst, the chat can't get margin through any tool, and says so:

3. Which data each viewer's tools can read
Most teams connect the app to Databricks with one service principal that can read the gold schema (OAuth machine-to-machine, with DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET in the app's environment), and enforce per-viewer access in the app:
- Split the snapshot by permission level. The export writes the sensitive tables to their own file, so a viewer without the finance group never has that file attached, in a chart, a metric function, or the SQL tool.
- Check the group in every tool that reads restricted data, and tell the AI not to estimate what it can't see:
@mcp_enabled(expose_docstring=True)def get_margin(start_month: str, end_month: str, group_by: MarginDimension | None = None, top_n: int = 10) -> dict:"""Revenue, supply cost, margin and margin % between two order months (YYYY-MM).Restricted: only viewers in the finance group can see margin."""if "finance" not in viewer_groups():raise PermissionError("Margin data is restricted to the finance group. Don't estimate it.")return metrics.margin(start_month, end_month, group_by, top_n)
- Filter rows in the query for rules like "only the clients in my region", using the viewer's attributes.
If you'd rather Unity Catalog apply each viewer's grants, row filters, and column masks, the app has to query Databricks live with that viewer's own Databricks OAuth token. That takes more setup, and those filters can't be read through the Unity REST APIs or by file path, so they don't apply to an export.
Deep dives: the code, by where it runs
The sections below follow the data from Databricks to the viewer. Each code block says where it runs.
In Databricks: build the gold tables
The biggest improvement to AI answers, whichever option you choose, is tables a person could read: names joined in, clear column names, a one-line description, and one row per something obvious. We built four from TPC-H with Databricks SQL on a 2X-Small warehouse:
-- Runs in Databricks (SQL warehouse or a scheduled notebook)create or replace table analytics.ai_layer.orders_dailycomment 'Orders placed, one row per order date, customer nation and market segment. Each order is counted once, so orders can be summed across rows.' asselect o.o_orderdate as order_date, r.r_name as region, n.n_name as nation, c.c_mktsegment as market_segment,count(*) as ordersfrom samples.tpch.orders ojoin samples.tpch.customer c on c.c_custkey = o.o_custkeyjoin samples.tpch.nation n on n.n_nationkey = c.c_nationkeyjoin samples.tpch.region r on r.r_regionkey = n.n_regionkeygroup by all;
The others are revenue by ship date, nation, segment, and ship mode (2.2 million rows), line-level detail for the last 90 days only (1.1 million rows), and margin per customer per month (6.8 million rows), which is the sensitive one. On the same warehouse, our 12 benchmark questions ran 2.3 times faster against the gold tables than against the raw tables (median 0.51 seconds against 1.19).
In Databricks: export the snapshot
A serverless Python job with duckdb as a dependency writes each gold table to Parquet in a Volume, loads it into a DuckDB file on the job's local disk, and copies the finished file to the Volume. The manifest goes last, so the app never sees a half-written version:
# Runs in Databricks (serverless jobs compute, scheduled daily)FILES = {"general": ["revenue_daily", "orders_daily", "order_lines_recent"], "commercial": ["margin_by_customer_monthly"]}for level, tables in FILES.items():con = duckdb.connect(f"/tmp/{level}.duckdb") # local disk, not the Volumefor t in tables:spark.table(f"{SRC}.{t}").write.mode("overwrite").parquet(f"{staging}/{t}")con.execute(f"create table {t} as select * from read_parquet('{staging}/{t}/*.parquet')")con.execute(f"comment on table {t} is '{comments[t]}'")con.close() # checkpoints, so there's no .wal fileshutil.copyfile(f"/tmp/{level}.duckdb", VOL / "duckdb" / f"{level}-{stamp}.duckdb")(VOL / "duckdb" / "latest.json").write_text(json.dumps(manifest))
Ours ran in 99 seconds and wrote two files, 69 MB for the general tables and 146 MB for the margin table.
In the Dash app: download the snapshot
The app polls the manifest with the Databricks SDK, downloads new files to a temporary name in the same folder, and swaps each into place with os.replace(), which is atomic on Linux. Queries already running finish on the old file and new queries open the new one, so there's no restart:
# Runs in the Dash app, every 15 minutes in a background threadfrom databricks.sdk import WorkspaceClientfrom filelock import FileLockw = WorkspaceClient() # service principal: DATABRICKS_HOST, DATABRICKS_CLIENT_ID, DATABRICKS_CLIENT_SECRETdef sync_once() -> bool:with FileLock(str(LOCAL_DIR / ".sync.lock")): # one worker downloads at a timemanifest = json.loads(w.files.download(f"{VOLUME_DIR}/latest.json").contents.read())marker = LOCAL_DIR / "version.txt"if marker.exists() and marker.read_text() == manifest["version"]:return Falsefor level, info in manifest["files"].items():tmp = LOCAL_DIR / f"{level}.duckdb.part"with open(tmp, "wb") as f:shutil.copyfileobj(w.files.download(info["path"]).contents, f)os.replace(tmp, LOCAL_DIR / f"{level}.duckdb")marker.write_text(manifest["version"])return True
Our two files downloaded in about 10 seconds, and checking for a new version takes about half a second. On Dash Enterprise, put the folder on a persistent volume so a restart doesn't need a fresh download.
In the Dash app: query Databricks live instead
For live numbers, the same functions can query the warehouse with the Databricks SQL connector. If your team defines metrics in Unity Catalog metric views, query them with MEASURE(), so the definition stays where the data team maintains it:
# Runs in the Dash app; the query runs on a Databricks SQL warehousefrom databricks import sqldef warehouse():return sql.connect(server_hostname=HOST, http_path=f"/sql/1.0/warehouses/{WAREHOUSE_ID}",credentials_provider=service_principal)def query_metric(measure: Measure, start: str, end: str, group_by: Dimension | None = None) -> list[dict]:dims = f"{group_by}, " if group_by else ""with warehouse() as conn, conn.cursor() as cur:cur.execute(f"select {dims}measure({measure}) as {measure} from analytics.gold.order_metrics ""where date between :start and :end group by all", {"start": start, "end": end})return cur.fetchall_arrow().to_pylist()
In the Dash app: metric functions
Each metric is one function, and each function returns its definition, owner, data date, and SQL with the rows. The app's charts and the MCP tools both call it:
# Runs in the Dash app (metrics.py)Grain = Literal["year", "quarter", "month"]RevenueDimension = Literal["region", "nation", "market_segment", "ship_mode"]def revenue(start: str, end: str, grain: Grain = "year", group_by: RevenueDimension | None = None,region: str | None = None) -> dict:dim = f"{group_by}, " if group_by else ""sql = f"""select date_trunc('{grain}', ship_date) as period, {dim}sum(revenue) as revenuefrom revenue_dailywhere ship_date between $start and $end and ($region is null or region = upper($region))group by all order by period"""params = {"start": start, "end": end, "region": region}rows = query("general", sql, params) # fresh read-only DuckDB connection per queryreturn {"metric": "revenue", **DEFINITIONS["revenue"], "data_as_of": snapshot_date(),"sql": sql, "parameters": params, "rows": rows}
The Literal types become fixed lists of choices in the tool's schema, so the AI can't ask for a breakdown that doesn't exist.
In the Dash app: MCP tools
Create the app with enable_mcp=True and mark the functions the AI may call. Turning off the default of exposing every callback as a tool means a callback can never be called by the AI:
# Runs in the Dash app (app.py)from dash import Dashfrom dash.mcp import configure_mcp_server, mcp_enabledapp = Dash(__name__, enable_mcp=True)configure_mcp_server(include_callbacks=False, include_layout=False)@mcp_enabled(expose_docstring=True)def get_revenue(start: str, end: str, grain: Grain = "year", group_by: RevenueDimension | None = None,region: str | None = None) -> dict:"""Revenue between two ship dates (YYYY-MM-DD), by year, quarter or month, optionallysplit by region, nation, market segment or ship mode. Same definition as the charts.Returns the rows, the definition and the SQL; show the SQL if asked."""return metrics.revenue(start, end, grain, group_by, region)
Write each docstring as instructions to the AI: when to use the tool, what the arguments mean, and what to do with the result. The demo has 11 tools: seven for the metrics (list_metrics and six get_ functions), the two context tools and the two SQL tools.
In the Dash app: context files
The context lives in definitions/knowledge/ as markdown, one file per metric, table, glossary term, or known issue. In production, keep it in a repo the owners can edit, and clone or sync it into the app. A file looks like this:
---type: Metrictitle: Average order valuedescription: Revenue by order date divided by orders placed, both from the same orders.owner: Finance---Average order value (AOV) = revenue of the orders placed in the period / number of orders placed in the period.- Both parts must be **by order date**: `sum(revenue) / sum(orders)` from `margin_by_customer_monthly`.- **Never divide `revenue_daily` revenue (ship date) by orders.** Ship dates run months past thelast order date, so the result is too high.
Two tools give the AI the bundle: one lists the files, and one reads a file in full and refuses any path outside the folder:
# Runs in the Dash app (context.py and app.py)KNOWLEDGE = Path("definitions/knowledge").resolve()@mcp_enabled(expose_docstring=True)def list_context(kind: Literal["Metric", "Table", "Glossary Term", "Known Issue"] | None = None) -> list[dict]:"""List the company's written definitions, each with an owner. Before writing SQL withrun_sql, call this and read every definition that applies with read_context."""docs = [_read(p) for p in sorted(KNOWLEDGE.rglob("*.md"))]return [{k: d.get(k) for k in ("path", "type", "title", "description", "owner")}for d in docs if kind is None or d.get("type") == kind]@mcp_enabled(expose_docstring=True)def read_context(path: str) -> dict:"""Read one definition in full. Follow its rules exactly when you write SQL, say whichdefinition you used and who owns it, and mention any known issue that affects the answer."""target = (KNOWLEDGE / path).resolve()if not target.is_relative_to(KNOWLEDGE) or target.suffix != ".md":raise ValueError("Use a path from list_context.")return _read(target)
The demo has 13 files: five metrics, four tables, two glossary terms, and two known issues, between 300 and 800 characters each.
In the Dash app: the open-ended SQL tool
Most of the code is the set of checks that make it safe to offer:
# Runs in the Dash app (adhoc.py and app.py)def run(sql: str, levels: list[str]) -> dict:stmts = duckdb.extract_statements(sql) # DuckDB's own parser, not a regexif len(stmts) != 1 or stmts[0].type != duckdb.StatementType.SELECT:raise ValueError("Send exactly one SELECT statement.")with duckdb.connect() as con: # in memory, fresh for each queryfor level in levels: # only the files the viewer may seecon.execute(f"attach '{local_path(level)}' as {level} (read_only)")for t in FILES[level]:con.execute(f"create view main.{t} as select * from {level}.main.{t}")con.execute("set enable_external_access = false") # no files, URLs or new ATTACHescon.execute("set lock_configuration = true") # and the query can't turn them back ontimer = threading.Timer(15, con.interrupt) # stop a runaway query after 15 stimer.start()try:cur = con.execute(sql)cols, rows = [d[0] for d in cur.description], cur.fetchmany(201)finally:timer.cancel()return {"sql": sql, "note": "Ad hoc query written by the AI, not a certified metric.","rows": [dict(zip(cols, r)) for r in rows[:200]]}@mcp_enabled(expose_docstring=True)def run_sql(sql: str) -> dict:"""Run one read-only DuckDB SELECT against the gold tables, for questions no metric functionanswers. Read the definitions that apply with list_context and read_context first. Tell theuser the answer comes from an ad hoc query, and show the SQL. Returns at most 200 rows."""levels = ["general", "commercial"] if "finance" in viewer_groups() else ["general"]return run(sql, levels)
We tried a DELETE, two statements in one call, read_csv('/etc/passwd'), an ATTACH, and a cross join that would have run for hours, and each was refused or stopped after 15 seconds. When the app queries Databricks live instead, give the tool a warehouse connection whose service principal can only read the gold schema.
On the platform: turn on Plotly Studio Embedded
On Plotly Cloud, open the app's Plotly Studio Embedded tab and select Enable Plotly Studio Embedded for this app. The chat finds the app's MCP tools and lists them in its App tools panel. Studio Embedded comes to Dash Enterprise in Q4 2026, where you add it as a package and a component in the layout, which also lets you show starting questions in the empty chat:
# Runs in the Dash app (Dash Enterprise)from plotly_studio_embedded import PlotlyStudioEmbeddedapp.layout = html.Div([...,PlotlyStudioEmbedded(suggested_prompts=["What was revenue by region in 1997?","What was average order value by nation and segment in 1998?",]),])
Before rollout: check the answers against the charts
Ask the chat the questions the app's charts already answer, and check that the numbers match to the cent and that the chat names the definition it used. Ask for something restricted while signed in without the group, and check that it refuses rather than estimating. Then ask a few questions no metric function covers, read the SQL, and write a context file for anything it got wrong.
If your team already uses Genie
A Dash app can also call a Databricks Genie Agent from a tool, with a service principal, which is useful when another team already curates one. On our 12 questions, the Genie Agent answered in a median of 19.7 seconds (13.9 to 26.5), because Genie plans, writes, and runs its own SQL, and Genie One over Databricks' MCP service took 38.4 seconds. Genie Agents are free until January 31, 2027; after that, each user gets 150 DBUs a month and pays $0.07 per DBU, plus warehouse compute.
Summary
Databricks builds and governs the data, and a Dash app delivers it to the people who use it, with charts and tables for the daily numbers and an AI chat for the rest. Build the AI part in layers, with metric functions for the numbers you report and open-ended SQL for everything else. Have the people who own the numbers write context files for the SQL tool, which in our test took its answers from 41 to 45 correct out of 45. Read the data from a daily snapshot unless it has to be live, control who can open the app on the platform, and check the viewer's groups in every tool that reads restricted data.