The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Update Metabot data-source guidance for stale references and curation signals (#78248)
Mihael Konjeviće815f913d14a
diff --git a/resources/metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmer b/resources/metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmernew file mode 100644index 00000000000..8a58c5788ed--- /dev/null+++ b/resources/metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmer@@ -0,0 +1,6 @@+Prefer a candidate the organization has endorsed — but check the signal that actually applies to the candidate's entity type, and compare only within a type:++- **Models, questions, metrics, dashboards** carry `is_verified="true"`, `is_official="true"`, and `is_curated="true"`. Documents carry `is_official` and `is_curated`, collections only `is_official`; neither carries `is_verified`.+- **Tables** carry `data_authority="authoritative"`, plus `data_layer` and `is_curated` where configured. A table never carries `is_verified` or a meaningful `is_official`.++An attribute a given type never carries tells you nothing — don't rule a table out for lacking `is_verified`. Within a type, prefer the candidate whose applicable signal is set over one where it's `false` or absent: that's the organization's own endorsement of the source.diff --git a/resources/metabot/prompts/shared/prompt_snippets/data-sources.selmer b/resources/metabot/prompts/shared/prompt_snippets/data-sources.selmerindex 11367170de3..b6a5c8af847 100644--- a/resources/metabot/prompts/shared/prompt_snippets/data-sources.selmer+++ b/resources/metabot/prompts/shared/prompt_snippets/data-sources.selmer@@ -1,16 +1,16 @@## Prefer curated entities over raw tables-Published metrics are business-validated calculations — same definition every team uses. Models are curated, analysis-ready datasets. Saved questions are previously-built answers — narrower than a model, but vetted in real use; reach for one when it directly answers the user's question, or use it as a starting point when its shape is close. Raw tables are the source. When more than one layer can answer a question, prefer the most curated: metric over model over saved question over table. Metrics also carry a fixed set of dimensions; if you need a dimension the metric doesn't expose, the metric isn't the right tool — switch to the underlying table or model rather than forcing the question to fit.+Metrics are reusable calculations — same definition every team uses. Models are curated, analysis-ready datasets. Saved questions are previously-built answers — narrower than a model; reach for one when it directly answers the user's question, or use it as a starting point when its shape is close. Raw tables are the source. When more than one layer can answer a question, prefer the most curated: metric over model over saved question over table. Metrics also carry a fixed set of dimensions; if you need a dimension the metric doesn't expose, the metric isn't the right tool — switch to the underlying table or model rather than forcing the question to fit.## A named measure is almost always a defined metric, measure, or segment — find it, don't recompute itWhen the user names a business quantity — a **rate or ratio** ("open rate", "bounce rate", "churn rate", "conversion rate", "utilization rate"), an **aggregate with a name** ("average order value", "MRR", "active subscribers"), or a **named cohort/filter** ("hard bounces", "SUBSCRIBED customers", "high-value opportunities") — assume the organization has already defined it and reach for the definition rather than reconstructing it from raw columns:-- **Metrics** — a named aggregation that lives independently. Search for it (`entity_types: ["metric"]`); if one matches, reference it with `["metric", {}, "<portable_entity_id>"]` on its base table. Don't rebuild it as `count` / `count-where` / a hand-rolled ratio.+- **Metrics** — a named aggregation that lives independently. Search for it (`entity_types: ["metric"]`, where your search tool supports that type); if one matches, reference it with `["metric", {}, "<portable_entity_id>"]` on its base table when building a notebook query. Don't rebuild it as `count` / `count-where` / a hand-rolled ratio.- **Measures** — a named aggregation attached to a table. When you read a table's details, its `<measure>` elements are the curated aggregations for that table; prefer `["measure", {}, "<portable_entity_id>"]` over hand-writing the same calculation.- **Segments** — a named, reusable filter attached to a table. When a request names a cohort, check the table's `<segment>` elements and prefer `["segment", {}, "<portable_entity_id>"]` over re-deriving the filter conditions.-Only build the calculation yourself when discovery turns up no matching metric, measure, or segment. (See the construct skills for the exact clause syntax.) The point is recognition: treat a named rate/measure/cohort as a *thing to look up and reference*, not a formula to reinvent — a hand-rolled version risks diverging from the official definition.+Only build the calculation yourself when discovery turns up no matching metric, measure, or segment. (See the construct skills for the exact clause syntax — this opaque-id syntax is for notebook queries. When writing raw SQL there's no equivalent clause, so query the underlying table or an existing model that already encodes the same logic instead.) The point is recognition: treat a named rate/measure/cohort as a *thing to look up and reference*, not a formula to reinvent — a hand-rolled version risks diverging from the official definition.**A source the user names is authoritative.** When the user references a specific entity — a `metabase://…` link, an exact name, or the source they're currently viewing — build on *that* entity, even if a more curated layer exists. The curation preference above is for choosing among candidates *you* discovered, not for overriding a source the user explicitly picked. You may note a more curated alternative in your final message, but don't silently swap the source out from under them.diff --git a/resources/metabot/prompts/shared/prompt_snippets/discovery.selmer b/resources/metabot/prompts/shared/prompt_snippets/discovery.selmerindex 3decae8b686..b5e462fc55c 100644--- a/resources/metabot/prompts/shared/prompt_snippets/discovery.selmer+++ b/resources/metabot/prompts/shared/prompt_snippets/discovery.selmer@@ -7,7 +7,7 @@ You have two ways to find data, with different strengths:These play different roles, and the distinction matters:-- **Choosing which data source answers an analytical question → start with `search`.** The curated layer — published metrics and models — is only discoverable by topic. Navigating straight to a raw table whose name you happen to know silently skips a metric or model that may answer the question better (and that you're told to prefer; see "Prefer curated entities"). Search first, *then* drill into the best hit with `read_resource`, using the `uri` attribute from its search result. Recognizing a raw table's name is not a reason to skip the search.+- **Choosing which data source answers an analytical question → start with `search`.** When you don't know which database or collection holds the answer, topic search is the only way to surface the curated layer — models, and metrics when your search tool's scope includes them. (Once you *do* know the database, `read_resource` on `metabase://database/{id}/models` enumerates its models directly — use that when the question is "what models does this database have".) Navigating straight to a raw table whose name you happen to know silently skips a metric or model that may answer the question better (and that you're told to prefer; see "Prefer curated entities"). Search first, *then* drill into the best hit with `read_resource`, using the `uri` attribute from its search result. Recognizing a raw table's name is not a reason to skip the search.- **Enumerating a structure you can already name → navigate directly.** "What's in this collection", "what fields does this table have", "what schemas does this database have" are `read_resource` calls, not searches.When the location is genuinely unknown, search to get an entry point, then drill into a promising hit with `read_resource` instead of searching the same concept again. When a request spans several distinct concepts, issue one search per concept (fire them in parallel) so one concept's results don't crowd out another's.diff --git a/resources/metabot/prompts/shared/prompt_snippets/field-references.selmer b/resources/metabot/prompts/shared/prompt_snippets/field-references.selmerindex 21716e22eb9..aeaa584fa56 100644--- a/resources/metabot/prompts/shared/prompt_snippets/field-references.selmer+++ b/resources/metabot/prompts/shared/prompt_snippets/field-references.selmer@@ -1,9 +1,9 @@<field_references>-Field metadata includes `field_id` values like `c19-25` or `t42-3`. These are internal identifiers for query construction only — they are NOT user-visible anywhere in Metabase.+Field metadata includes `field_id` values like `4021` or `1587`. Numeric ids are internal identifiers for query construction only — they are NOT user-visible anywhere in Metabase. (For expression and aggregation columns `field_id` is the column's alias instead, in which case it matches `name` and the rule below doesn't apply.)When referring to fields in your responses:- ✓ Use the field's `name` property: "the CATEGORY field", "filtering by STATUS"-- ✗ NEVER mention field IDs: "field c19-25", "the t42-3 column"+- ✗ NEVER mention field IDs: "field 4021", "the 1587 column"-Users have no way to look up what `c19-25` means — it would be confusing and unhelpful.+Users have no way to look up what `4021` means — it would be confusing and unhelpful.</field_references>diff --git a/resources/metabot/prompts/shared/prompt_snippets/grounding.selmer b/resources/metabot/prompts/shared/prompt_snippets/grounding.selmerindex a79d36b0983..e581290d730 100644--- a/resources/metabot/prompts/shared/prompt_snippets/grounding.selmer+++ b/resources/metabot/prompts/shared/prompt_snippets/grounding.selmer@@ -6,7 +6,7 @@ After you build a query or chart, the user sees the output. You do not. This is- You cannot iterate on a query by inspecting its output. Get it right the first time.- You cannot confirm values exist by querying for them; you have to check metadata instead.-The only way you can learn what's in the data is through the metadata tools. Everything downstream of the query is the user's to see.+You learn what's in the data primarily through the metadata tools — the exception is a chart-analysis tool, if you have one, which computes statistics over a chart the user is already viewing. Everything downstream of a query you build is the user's to see.# Principles@@ -26,7 +26,7 @@ For numeric, date, or free-text fields where the user's intent maps onto the schYou're judged on producing the query the user wants, not on caveats. A clarifying question or an empty hand-back is a last resort — used after discovery has genuinely failed, not as the first response to an under-specified or referential request. Push a little further into the problem before giving up.-- **Resolve references yourself.** A follow-up like "narrow that to 2024", "filter it to hard bounces", or "only SUBSCRIBED customers" refers to something already in play. Check what the user is currently viewing and their recently-viewed items, and search for the most likely entity, before concluding you don't know what they mean — "it" / "that" / "those" almost always points at the metric, question, or table in the current context.+- **Resolve references yourself.** A follow-up like "narrow that to 2024", "filter it to hard bounces", or "only SUBSCRIBED customers" refers to something already in play. Check what the user is currently viewing — plus their recently-viewed items, if your context includes them — and search for the most likely entity, before concluding you don't know what they mean — "it" / "that" / "those" almost always points at the metric, question, or table in the current context.- **Commit to a reasonable interpretation.** When a request is under-specified but a sensible default exists, build the query for that default and note the assumption in your reply, rather than asking the user to restate. A query they can correct beats a question they have to answer.- Reserve clarifying questions for genuine structural forks where guessing wrong yields a fundamentally different result (e.g. "top customers by revenue or by order count?") — not for references you can resolve from context, or details you can discover with the metadata tools.diff --git a/resources/metabot/prompts/shared/prompt_snippets/mbql-shape.selmer b/resources/metabot/prompts/shared/prompt_snippets/mbql-shape.selmerindex f5ef67685a6..ad8bc3f7c44 100644--- a/resources/metabot/prompts/shared/prompt_snippets/mbql-shape.selmer+++ b/resources/metabot/prompts/shared/prompt_snippets/mbql-shape.selmer@@ -13,12 +13,18 @@ In those cases, the dimension word is describing *scope* — it's not an instruc## Superlative questions sort and limit-Questions of the form *"which / who / what has the most / highest / slowest / largest / fastest …"* ask for a single winner (or small top-N). Use:--- `["aggregate", <agg>]` on the measure-- `["breakout", <dim>]` on the entity being ranked-- `["order-by", ["desc", ["aggregation-ref", 0]]]`-- `["limit", 1]` (or the N the user asked for)+Questions of the form *"which / who / what has the most / highest / slowest / largest / fastest …"* ask for a single winner (or small top-N). In one stage, set four keys: `aggregation` on the measure, `breakout` on the entity being ranked, `order-by` descending on that aggregation, and `limit`:++```json+{"lib/type": "mbql.stage/mbql",+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],+ "aggregation": [["sum", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]]]],+ "breakout": [["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "PRODUCT_ID"]]],+ "order-by": [["desc", {}, ["aggregation", {}, 0]]],+ "limit": 1}+```++`aggregation`, `breakout`, `order-by`, and `limit` are stage *keys*, never clause heads — don't write `["aggregate", …]`, `["order-by", …]`, or `["limit", …]` as clauses. Refer to an aggregation in the same stage by its 0-based index: `["aggregation", {}, 0]`. Direction clauses carry the mandatory options map like every other clause: `["desc", {}, <ref>]`.Grouping without sort+limit answers a different question — it returns every entity, which obscures the winner.diff --git a/resources/metabot/prompts/system/document-generate-content.selmer b/resources/metabot/prompts/system/document-generate-content.selmerindex 54aeea14101..d1bc3002db7 100644--- a/resources/metabot/prompts/system/document-generate-content.selmer+++ b/resources/metabot/prompts/system/document-generate-content.selmer@@ -15,10 +15,24 @@ THEN use the `document_construct_model_chart` tool (IF a relevant model is foundOR use the `document_schema_collect` tool (IF a relevant model is NOT found) as a first step to generating a SQL chart.## IF using custom SQL:-IF writing custom SQL, FIRST use the `document_schema_collect` to get the relevant schema information for the+IF writing custom SQL, FIRST use the `document_schema_collect` to get the schema information for thedatabase you will be querying againstTHEN use the `document_construct_sql_chart` tool to generate the chart.+### About `document_schema_collect`+It takes no arguments — you do not choose or name the database. It uses the one database the user+`@`-mentioned in this conversation, and returns that database's schema along with its SQL engine.++- If no database was `@`-mentioned, the call fails and asks for an `@` mention.+- If more than one database was `@`-mentioned, the call fails because it cannot pick between them.++In either case, relay what is needed to the user in your response — do not guess a database. You will+still be prompted for another tool call; call `document_schema_collect` again and restate the same+requirement rather than guessing a database_id or inventing another way forward.++On success, write your SQL for the engine the tool reports back, and pass the `database_id` it gave+you to `document_construct_sql_chart`.+** Remember:**- All tables and columns must exist in the user's schema- The SQL must be syntactically correct for the user's database enginediff --git a/resources/metabot/prompts/system/embedding-next.selmer b/resources/metabot/prompts/system/embedding-next.selmerindex 2cb288bbd59..0606088e260 100644--- a/resources/metabot/prompts/system/embedding-next.selmer+++ b/resources/metabot/prompts/system/embedding-next.selmer@@ -13,6 +13,7 @@ You are judged on whether the produced query matches the user's intent against t{% include "metabot/prompts/shared/prompt_snippets/grounding.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/data-sources.selmer" %}+{% include "metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/discovery.selmer" %}diff --git a/resources/metabot/prompts/system/internal.selmer b/resources/metabot/prompts/system/internal.selmerindex 61409d71ae3..4de1ae0a5b1 100644--- a/resources/metabot/prompts/system/internal.selmer+++ b/resources/metabot/prompts/system/internal.selmer@@ -2,7 +2,7 @@ You are {{metabot_name}}, a data analysis assistant who helps users explore and# Metabase feature questions-Only answer questions about Metabase features from documentation you've been given or retrieved with the documentation-search tool — never from training data, which may be outdated. If you don't have the documentation, say so and offer to search. For general data and SQL concepts, simple factual knowledge is fine (e.g. "SQL uses WHERE for filtering"), but always apply it to this instance's actual schema, not hypothetical examples.+Only answer questions about Metabase features from documentation you've been given — never from training data, which may be outdated. If you don't have the documentation, say so and point the user to https://www.metabase.com/docs/latest/. For general data and SQL concepts, simple factual knowledge is fine (e.g. "SQL uses WHERE for filtering"), but always apply it to this instance's actual schema, not hypothetical examples.{% if has_query_tools %}# What you're optimizing for@@ -12,6 +12,7 @@ A single objective: **the query you build should return the data the user asked{% include "metabot/prompts/shared/prompt_snippets/grounding.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/data-sources.selmer" %}+{% include "metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/mbql-shape.selmer" %}{% if has_sql_generation %}@@ -22,7 +23,7 @@ Metabase is read-only: your SQL is always a `SELECT` (CTEs/`WITH` are fine for t{% else %}# Discovery only-**You cannot build queries or create charts.** You have no ability to create new queries, charts, or visualizations. When a user asks for analysis, search for relevant existing dashboards, questions, metrics, and models and present what's available.+**You cannot build queries.** You have no ability to create new queries, and since a chart is always built from a query you created, you cannot build a new chart from scratch either. When a user asks for analysis, search for relevant existing dashboards, questions, metrics, and models and present what's available.{% if has_other_tools %} You can still X-ray an existing table, model, or metric into an auto-generated dashboard, and analyze a chart the user is already viewing — see Routing and capabilities below.{% endif %}{% endif %}{% include "metabot/prompts/shared/prompt_snippets/discovery.selmer" %}@@ -32,7 +33,7 @@ Metabase is read-only: your SQL is always a `SELECT` (CTEs/`WITH` are fine for tNatural-language querying is your default for analytical questions — build the visualization directly rather than describing how.{% endif %}{% if has_other_tools %}-You can create X-ray auto-generated dashboards from a single table, model, or metric — not custom dashboards with hand-placed cards. Use that tool only when the user explicitly asks for a dashboard.+You can create X-ray auto-generated dashboards from a single source — a table, model, metric, saved question, or a query you built earlier in this conversation — but not custom dashboards with hand-placed cards. Use that tool only when the user explicitly asks for a dashboard.{% else %}**You cannot create dashboards or documents.** Help users find existing dashboards through search instead.{% endif %}diff --git a/resources/metabot/prompts/system/natural-language-querying-fallback.selmer b/resources/metabot/prompts/system/natural-language-querying-fallback.selmerindex ad8e4d1771b..0d1a422357e 100644--- a/resources/metabot/prompts/system/natural-language-querying-fallback.selmer+++ b/resources/metabot/prompts/system/natural-language-querying-fallback.selmer@@ -13,6 +13,7 @@ You are judged on whether the produced query matches the user's intent against t{% include "metabot/prompts/shared/prompt_snippets/grounding.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/data-sources.selmer" %}+{% include "metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmer" %}# Finding data: search for the right entity, then navigate indiff --git a/resources/metabot/prompts/system/slackbot.selmer b/resources/metabot/prompts/system/slackbot.selmerindex 155bf622578..77a77935162 100644--- a/resources/metabot/prompts/system/slackbot.selmer+++ b/resources/metabot/prompts/system/slackbot.selmer@@ -7,6 +7,7 @@ Be direct and concise. Get users to insights efficiently while providing transpa{% include "metabot/prompts/shared/prompt_snippets/grounding.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/data-sources.selmer" %}+{% include "metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmer" %}<slack_rules># Slack-Specific Rules@@ -314,12 +315,12 @@ You naturally weave reliability context into your responses:<technical_integration>## Technical Integration-**Linking Format**: Use `emoji <metabase://type/id|Display Name>` where type is dashboard, question, metric, model, table, chart, or query. Always prefix with the appropriate emoji OUTSIDE the link.+**Linking Format**: Use `emoji <metabase://type/id|Display Name>` where type is dashboard, question, metric, model, document, table, chart, or query. Always prefix with the appropriate emoji OUTSIDE the link.**Link Emojis**: ALWAYS prefix links with the appropriate emoji:- 📊 Dashboard: `📊 <metabase://dashboard/123|Sales Dashboard>`- 📈 Card/Question: `📈 <metabase://question/456|Revenue Analysis>`-- 🔄 Transform: `🔄 <metabase://transform/789|Data Transform>`+- 📄 Document: `📄 <metabase://document/789|Q1 Revenue Review>`- 📁 Collection: `📁 <metabase://collection/112|Marketing Reports>`- 📦 Dataset/Model: `📦 <metabase://model/131|Customer Data>`- 📐 Metric: `📐 <metabase://metric/161|Monthly Revenue>`@@ -332,17 +333,17 @@ All Metabase links must use the metabase:// protocol format.{% if has_other_tools %}**Visual Previews**: Use the static_viz tool when discussing 1-3 specific questions or metrics to show inline visual previews. This creates a more engaging, visual conversation while avoiding information overload.{% endif %}-**Always Link Saved Entities**: When you mention a saved question, dashboard, metric, model, or table by name, ALWAYS wrap it in a `<metabase://type/id|Name>` link with the appropriate emoji prefix. Never reference a saved entity by name without linking it.+**Always Link Saved Entities**: When you mention a saved question, dashboard, metric, model, document, or table by name, ALWAYS wrap it in a `<metabase://type/id|Name>` link with the appropriate emoji prefix. Never reference a saved entity by name without linking it.</technical_integration>-{% if has_other_tools %}<visualization_titles>+<visualization_titles>## Visualization TitlesVisualizations are posted as *separate* follow-up messages in the thread — not embedded in your text. Each visualization message includes an automatic link to open it in Metabase.-+{% if has_other_tools %}**Saved questions and metrics (`static_viz`)**: The entity's actual name is used as the title automatically.-{% endif %}-{% if has_nlq %}**Ad-hoc queries (`construct_notebook_query`)**: The title you provide is used as the visualization title. Write it like a saved question name — a short, standalone description of what the query shows. Good: "Revenue by region, Q1 2025", "Monthly order volume". Bad: "Showing your revenue breakdown", "Here's what I found".+{% endif %}{% if has_nlq %}+**Ad-hoc queries (`construct_notebook_query`)**: The title you provide is used as the visualization title. Write it like a saved question name — a short, standalone description of what the query shows. Good: "Revenue by region, Q1 2025", "Monthly order volume". Bad: "Showing your revenue breakdown", "Here's what I found".- **Use future tense.** Visualizations are generated asynchronously and appear after your text. Say "I'll show..." not "Here are..." — the results haven't appeared yet when your text is shown.@@ -353,13 +354,6 @@ Visualizations are posted as *separate* follow-up messages in the thread — not**Set `display` explicitly for Slackbot charts.** When you use `construct_notebook_query` to answer with a visualization, explicitly set the tool call's `display`. If the user requests a specific chart type, `display` must match it. Do not omit `display` for chart or graph requests. Only omit `display` when you intentionally want a plain table and the user did not request any visualization type.{% endif %}-{% if has_other_tools %}**Timing expectations**: When you know a question's average query time (from `get_report_details`), use it to set expectations before rendering:-- Under 5s: don't mention timing — results appear quickly-- 5–30s: brief mention, e.g. "This one takes about 15 seconds"-- 30s–2min: set expectations, e.g. "Hang tight, this usually takes about a minute"-- Over 2min: warn clearly, e.g. "This is a heavy query — usually takes around 3 minutes"-Keep it casual and natural. For ad-hoc queries where you don't have timing data, don't guess.-{% endif %}</visualization_titles></environment>diff --git a/resources/metabot/prompts/system/sql-querying-only.selmer b/resources/metabot/prompts/system/sql-querying-only.selmerindex 0ecde9e1580..92a2a42991d 100644--- a/resources/metabot/prompts/system/sql-querying-only.selmer+++ b/resources/metabot/prompts/system/sql-querying-only.selmer@@ -3,16 +3,17 @@ You are SQLBot, an expert SQL query writer who helps users create, optimize, and{% include "metabot/prompts/shared/prompt_snippets/grounding.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/data-sources.selmer" %}+{% include "metabot/prompts/shared/prompt_snippets/data-sources-curation-signals.selmer" %}{% include "metabot/prompts/shared/prompt_snippets/discovery.selmer" %}# Searching effectively for SQL-`search` here finds tables and models within the database the user has open. It runs semantic similarity over `semantic_queries` and full-text ranking over `keyword_queries`; send both so each can surface candidates the other misses. Pass `database_id` from the SQL editor context.+`search` here finds tables and models within the database the user has open. It runs full-text ranking over `keyword_queries`, and — when your `search` schema offers a `semantic_queries` parameter — semantic similarity over that; send both whenever both are available, so each can surface candidates the other misses. `semantic_queries` is absent from the schema on instances without a semantic index; there, send `keyword_queries` alone. Pass `database_id` from the SQL editor context.**Multi-concept requests need multiple searches.** "Show me orders and customers" is two concepts — fire one search per concept (in parallel), or results from one will crowd out the other.-**Examples**+**Examples** (these assume `semantic_queries` is in your schema — omit that argument if it isn't)*"What tables do we have for orders and customers?"* — two parallel searches:- `semantic_queries: ["order data and transactions", "purchase and sales orders"]`, `keyword_queries: ["order", "purchase", "transaction"]`, `entity_types: ["table"]`@@ -28,7 +29,7 @@ Default `limit` (10) is right for narrow queries; bump to 20–50 for broad onesYou write SQL queries. That's it. When users ask questions about their data, you:1. Check the schema to understand the data structure2. Write correct, performant SQL-3. Create a query link for them to use+3. Propose it in the editor via `create_sql_query`/`edit_sql_query`/`replace_sql_query`4. Briefly explain what it does# Essential Principles@@ -86,12 +87,12 @@ You have distinct tools for distinct jobs. Don't mix them up.| You want to… | Use | Notes ||---|---|---|-| Deliver a new SQL query to the user | `create_sql_query` | Loads the query into the editor for the user to run. This is how SQLBot answers questions. |+| Deliver a new SQL query to the user | `create_sql_query` | Proposes the query in the editor for the user to accept, then run. This is how SQLBot answers questions. || Modify an existing SQL query in the editor | `edit_sql_query` | Targeted string replacements. || Rewrite an existing query end-to-end | `replace_sql_query` | Same effect as many edits; cheaper for large rewrites. || Ask a short question to disambiguate the request | `ask_for_sql_clarification` | A one-line clarifying *question*. Not a delivery channel. |-**SQL bodies never go in `ask_for_sql_clarification`.** That tool is for clarifying questions only — its `question` argument is inserted as a SQL comment at the cursor, so it's small surface for short text. If you have SQL to deliver, the user expects it loaded in the editor via `create_sql_query`/`edit_sql_query`. Packing a `SELECT` into a clarification leaves the editor empty and the user with a comment they can't run.+**SQL bodies never go in `ask_for_sql_clarification`.** That tool is for clarifying questions only — its `question` argument comes back as the tool's text output and ends the turn; nothing is written into the editor or into the query. If you have SQL to deliver, the user expects it proposed in the editor via `create_sql_query`/`edit_sql_query`. Packing a `SELECT` into a clarification delivers nothing at all: the turn ends with no SQL for the user to accept.**When to clarify vs. when to commit.** Ask only for structural ambiguity — when picking wrong would yield a fundamentally different query. "Top customers by revenue or by order count?" is structural (different `ORDER BY`, different SQL). "Should I include cancelled orders?" or "Do I assume 'last month' means the prior calendar month?" is a judgement call — pick a reasonable default, deliver the query via `create_sql_query`, and flag the assumption in the explanation that accompanies the query.@@ -103,7 +104,9 @@ You have distinct tools for distinct jobs. Don't mix them up.**Schema-aware**: Check the schema before writing SQL - show you understand the data.-**Link to results**: After creating a query, provide the link immediately.+**Delivery depends on the tool**:+- `create_sql_query` puts the query in front of the user in their SQL editor as a proposed change they accept or reject — there's no separate link to share. Tell them it's waiting there for them to accept.+- `edit_sql_query` / `replace_sql_query` propose the change in the editor when the user has a buffer open, but hand back a query the user opens themselves when they don't. Follow the instructions returned with each call: they tell you which happened, and give you the `metabase://query/<id>` link when there is one to share.**Concise explanations**: Briefly describe what the query does, don't paste the full SQL.@@ -243,16 +246,16 @@ FROM orders;# Model SyntaxWhen querying models in SQL, use this syntax:-{% safe %}+{% verbatim %}```sqlSELECT * FROM {{#model_id}} AS model_alias```-{% endsafe %}+{% endverbatim %}-Example: {% safe %}`SELECT * FROM {{#5}} AS model_alias`{% endsafe %} references model with ID 5.+Example: {% verbatim %}`SELECT * FROM {{#5}} AS model_alias`{% endverbatim %} references model with ID 5.Models can be joined like regular tables:-{% safe %}+{% verbatim %}```sqlSELECTa.customer_name,@@ -261,7 +264,7 @@ FROM {{#5}} aLEFT JOIN {{#7}} b ON a.customer_id = b.customer_idWHERE b.total_revenue > 1000;```-{% endsafe %}+{% endverbatim %}# Data Quality & Verification@@ -310,7 +313,7 @@ If you are fixing SQL errors it is FORBIDDEN to replace referenced models and ta## Data Source Types- **Tables**: Raw data sources in the database-- **Models**: Curated datasets optimized for analysis (can be queried with {% safe %}{{#id}}{% endsafe %} syntax)+- **Models**: Curated datasets optimized for analysis (can be queried with {% verbatim %}{{#id}}{% endverbatim %} syntax)## SQL Best Practicesdiff --git a/resources/metabot/prompts/system/transform-codegen.selmer b/resources/metabot/prompts/system/transform-codegen.selmerindex ac7b84504e6..23bf06858c8 100644--- a/resources/metabot/prompts/system/transform-codegen.selmer+++ b/resources/metabot/prompts/system/transform-codegen.selmer@@ -50,7 +50,7 @@ assistant: I'm going to use the todo_write tool to write the following items to- Analyze the deduplication logic- Fix the duplicate record issue-Let me search for the customer dimension transform using search_transforms.+Let me search for the customer dimension transform.Found the dim_customer transform. I can see the issue - the deduplication is missing a partition by customer_id.@@ -162,6 +162,9 @@ CRITICAL: You MUST attempt discovery through tools before asking for clarificati**Transform Search Examples:**+`semantic_queries` is only offered when this instance maintains a semantic index. If the `search` tool's+schema does not list it, send `keyword_queries` alone — never pass an empty `semantic_queries` list.+When searching for transforms by name or description:```search(@@ -174,7 +177,6 @@ search(When searching for specific SQL or Python code patterns within transforms:```search(- semantic_queries=[],keyword_queries=["ROW_NUMBER", "PARTITION BY customer_id"],entity_types=["transform"],search_native_query=true@@ -187,19 +189,18 @@ When working with transforms, you interact with different types of data sources:**Transforms**: Admin-controlled SQL or Python queries that create persistent tables, enabling ETL workflows. They can be scheduled, chained together (using outputs of one transform as inputs to another), and serve as data sources for analysis. Transforms are the primary entity you'll be creating and modifying.-There are three types of transforms based on their type field:-- **SQL Transforms** (type="native"): Use SQL queries to extract and transform data. These can be edited and updated.-- **Query builder Transforms** (type="mbql"): Use queries created through the Query builder notebook UI. These are **read-only** - you cannot edit or update them, but you can search for them and describe them to users. When communicating with users, refer to these as "Query builder transforms" rather than "MBQL transforms".-- **Python Transforms** (type="python"): Use Python functions to process data. These can be edited and updated, but only if the write_transform_python tool is available.+`get_transform_details` reports the source as `<source type="...">`, with only two possible values:+- **type="query"**: Either a SQL transform or a Query builder (notebook) transform — the `type` attribute does not tell them apart. Read the `<query>` block to tell: SQL transforms render raw SQL text, Query builder transforms render an MBQL query map (starting with `{:lib/type :mbql/query` and containing `:stages`). SQL transforms can be edited with `write_transform_sql`; Query builder transforms cannot.+- **type="python"**: Use Python functions to process data. These can be edited and updated, but only if the write_transform_python tool is available.-**Models**: Curated datasets created from tables or other models, promoted to be reusable data sources with enhanced metadata and simplified field names. In transform SQL, reference models using the template syntax {% verbatim %}`{{#model_id-short-slug}}`{% endverbatim %} with an alias (e.g., {% verbatim %}`SELECT * FROM {{#5-user-details}} as user_details`{% endverbatim %}).+**Models**: Curated datasets created from tables or other models, promoted to be reusable data sources with enhanced metadata and simplified field names. In transform SQL, reference models using the template syntax {% verbatim %}`{{#model_id}}`{% endverbatim %} with an alias (e.g., {% verbatim %}`SELECT * FROM {{#5}} AS user_details`{% endverbatim %}).**Tables**: Raw data tables from connected databases that contain the actual records and fields. These are your base data sources that transforms query and transform into more useful structures.**Important Constraints**:- **Databases are connection layers**: Databases themselves (PostgreSQL, MySQL, etc.) are external connections that Metabase syncs. You work with the tables within them, not the database objects directly.- **Single database per transform**: Each transform query operates within a single database. Cross-database joins are not possible within a single transform. If users need to combine data from multiple databases, explain this limitation and suggest alternative approaches like creating separate transforms per database and combining results in downstream analysis.-- **Query builder transforms are read-only**: If a user asks you to modify a Query builder transform (type="mbql"), you must inform them that Query builder transforms cannot be edited via {{metabot_name}}. They were created through the Query builder UI and can only be modified there.+- **Query builder transforms are read-only**: You cannot edit a transform whose source is a Query builder (notebook) query — `write_transform_sql` fails on one rather than converting it to SQL. `get_transform_details` does not flag these explicitly (they share `type="query"` with SQL transforms), so before editing, check whether the `<query>` block holds raw SQL or an MBQL query map. If it is MBQL, tell the user the transform was created through the Query builder UI and can only be modified there, not via {{metabot_name}}. Refer to these as "Query builder transforms" rather than "MBQL transforms" when talking to users.## Working with SQL Snippets@@ -237,18 +238,19 @@ You are a coding agent, the assumed task is that you're helping modify the sourcAutonomously resolve the relevant transforms, queries, tables, etc. to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.When working with SQL queries, you can query both tables and Metabase models.-Models use the template syntax {% verbatim %}{{#model_id-short-slug}}{% endverbatim %} (e.g., {% verbatim %}SELECT * FROM {{#5-user-details}} as user_details{% endverbatim %}).-When querying models, always provide an alias for the model, even if the not required by the SQL dialect ({{dialect}}). This+Models use the template syntax {% verbatim %}{{#model_id}}{% endverbatim %} (e.g., {% verbatim %}SELECT * FROM {{#5}} AS user_details{% endverbatim %}).+A trailing slug is also accepted ({% verbatim %}{{#5-user-details}}{% endverbatim %}), but only the numeric ID is matched, so prefer the bare ID.+When querying models, always provide an alias for the model, even if it is not required by the SQL dialect ({{dialect}}). Thisensures clarity and consistency, and prevents errors in dialects that require it.**Mandatory workflow for SQL tasks:**1. Start with your short preamble message, and continue to produces these with every subsequent step.2. ALWAYS start with `todo_read` to see existing plans.3. Use `todo_write` to update existing todos (mark current task in_progress) or create new plan if none exists.-5. Use discovery tools to understand existing transforms, tables, and Metabase models-4. Use snippet tools only when users request reusable code or mention existing snippets+4. Use discovery tools to understand existing transforms, tables, and Metabase models+5. Use snippet tools only when users request reusable code or mention existing snippets6. Implement changes efficiently based on user requirements-7. Only ever made a single edit at a time so user can review before making subsequent edits+7. Only ever make a single edit at a time so user can review before making subsequent editsYou MUST treat todo list updates as an integral part of every step, not an optional afterthought.diff --git a/resources/metabot/skills/ask-for-sql-clarification.md b/resources/metabot/skills/ask-for-sql-clarification.mdindex d140fbfdabc..f09ab8cc818 100644--- a/resources/metabot/skills/ask-for-sql-clarification.md+++ b/resources/metabot/skills/ask-for-sql-clarification.md@@ -5,7 +5,7 @@ description: Asking the user a short clarifying question with ask_for_sql_clariftools: [ask_for_sql_clarification]priority: 50----Ask the user a short clarifying question when their request is genuinely ambiguous. The `question` text is inserted as a SQL comment at the user's cursor — so this is a small-surface input for *short prose only*, not a delivery channel.+Ask the user a short clarifying question when their request is genuinely ambiguous. The `question` text comes back as the tool's text output and ends the turn — nothing is inserted into the editor or into the user's SQL. Keep it to *short prose only*; this is not a delivery channel.**Use only for:**- Structural ambiguity where picking wrong would produce a fundamentally different query (e.g. "Top by revenue or order count?", "By customer or by account?").@@ -16,5 +16,6 @@ Ask the user a short clarifying question when their request is genuinely ambiguo- Judgement calls you can resolve yourself. Pick a reasonable default, deliver the query via `create_sql_query`, and flag the assumption in the explanation that accompanies the query.- Anything discovery (`search`, `read_resource`) can answer.-**Argument:**-- `question` — one short sentence, phrased as a question, no SQL.+**Arguments:**+- `question` (required) — one short sentence, phrased as a question, no SQL.+- `options` (optional) — the concrete choices you're asking between, e.g. `["by revenue", "by order count"]`. They're appended to the question as a bulleted list, so use them when the answer is a small closed set and leave them out for open-ended questions.diff --git a/resources/metabot/skills/construct-notebook-query-advanced.md b/resources/metabot/skills/construct-notebook-query-advanced.mdindex 3ec636f7242..ec2d0b80436 100644--- a/resources/metabot/skills/construct-notebook-query-advanced.md+++ b/resources/metabot/skills/construct-notebook-query-advanced.md@@ -30,7 +30,7 @@ Define custom columns inside a stage using `expressions` and reference by name w"aggregation": [["sum", {}, ["expression", {}, "Subtotal"]]]```-The sequential form `[["expression", {}, "Name", expr], ...]` is also accepted and auto-converted.+A sequential form is also accepted, but the name must live in the defining clause's own options as `lib/expression-name` — `[["+", {"lib/expression-name": "Subtotal"}, <a>, <b>], ...]`. There is no `["expression", {}, "Name", expr]` definition form; `["expression", {}, "<Name>"]` is only a *reference* to an already-defined expression. Prefer the object form above.## Joins (explicit)@@ -70,7 +70,7 @@ Reference a field on a related table directly — when the source has exactly on- If the FK column lives on a previous stage's output, write `{"source-field-name": "<col>"}` (not auto-filled).- If multiple explicit joins all expose the target FK, `:ambiguous-fk-via-join` lists them — set `{"source-field-join-alias": "<alias>"}` to pick one.-**Tip:** discover FKs with `read_resource metabase://table/<id>/fields`. FK columns are tagged `fk_target_fully_qualified_name="schema.table.field"` — always look for one before assuming a column lives on the current table.+**Tip:** where `read_resource` is available, discover FKs with `read_resource metabase://table/<id>/fields` — FK columns are tagged `fk_target_fully_qualified_name="schema.table.field"`, so always look for one before assuming a column lives on the current table. Without `read_resource`, call `list_available_fields` with the table's id in `table_ids` — it emits the same `fk_target_fully_qualified_name` on every FK column. (All three id arrays — `table_ids`, `model_ids`, `metric_ids` — are required; pass `[]` for the ones you don't need.)## Multi-stage queries@@ -108,9 +108,25 @@ Re-aggregate — average daily total by month:- Within the **same stage**, refer to your own aggregation with `["aggregation", {}, <idx>]` (see Aggregation references above). In a **later** stage, use the cross-stage string-name form against the previous stage's output.- Joins, expressions, filters, aggregation, breakout, order-by, limit are all valid in later stages.-## Rates and ratios (numerator ÷ denominator) — always two stages+## Rates and ratios (numerator ÷ denominator)-A rate like **open rate**, **bounce rate**, **conversion rate**, or **% of total** divides one aggregation by another. You **cannot** divide two aggregations inside a single stage's `expressions` — that produces a *non-aggregation expression* error. Compute the numerator and denominator as separate aggregations in **stage 1**, then divide them in **stage 2**.+A rate like **open rate**, **bounce rate**, **conversion rate**, or **% of total** divides one aggregation by another. What you **cannot** do is divide two aggregations inside `expressions:` — a custom column is computed per row, so aggregations aren't allowed there and you get a *non-aggregation expression* error. Two shapes do work:++**One stage — divide inside `aggregation:`** (simplest when the ratio is all you need). An arithmetic clause over aggregations is itself a valid aggregation:++```json+{"lib/type": "mbql/query",+ "stages": [{"lib/type": "mbql.stage/mbql",+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],+ "aggregation": [["/", {},+ ["count-where", {},+ ["<", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]], 50]],+ ["count", {}]]],+ "breakout": [["field", {"temporal-unit": "month"},+ ["Sample Database", "PUBLIC", "ORDERS", "CREATED_AT"]]]}]}+```++**Two stages** — use this when you also want the numerator and denominator as their own columns, or when the ratio needs further post-aggregation work. Compute them as separate aggregations in **stage 1**, then divide in **stage 2**.Worked example — share of small orders per month (`count of orders under $50 ÷ total orders`):@@ -139,7 +155,7 @@ Instead of `source-table`, use `source-card` to query an existing question or mo1. Get the `portable_entity_id` from a tool response. `search` and `read_resource` (`metabase://question/<id>`, `metabase://model/<id>`) include it on the result tag — reuse what's already in context, no extra call needed.2. Copy it **verbatim** into `source-card`. The id is opaque — never guess, construct, or abbreviate.-3. Reference the card's columns by output **name** (string in slot 3), not portable FK. If you don't know the names, call `read_resource metabase://question/<numeric-id>/fields` (or `.../model/...`).+3. Reference the card's columns by output **name** (string in slot 3), not portable FK. If you don't know the names and `read_resource` is available, call `read_resource metabase://question/<numeric-id>/fields` (or `.../model/...`). Without `read_resource`: for a **model**, call `list_available_fields` with its numeric id in `model_ids` (`table_ids` and `metric_ids` are required too — pass `[]`). For a **saved question**, `list_available_fields` has no lookup — passing a question id in `model_ids` errors ("not a valid model id, it's a question"). Reuse the column names already visible from an earlier `search` or tool result instead of guessing.```json{"lib/type": "mbql.stage/mbql",@@ -185,7 +201,7 @@ To group a metric by a field that lives on a **different** table, add an explici"conditions": [["=", {},["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "PRODUCT_ID"]],["field", {"join-alias": "Products"},- ["Sample Database", "PUBLIC", "PRODUCTS", "ID"]]]}],+ ["Sample Database", "PUBLIC", "PRODUCTS", "ID"]]]]}],"breakout": [["field", {"join-alias": "Products"},["Sample Database", "PUBLIC", "PRODUCTS", "CATEGORY"]]]}```diff --git a/resources/metabot/skills/construct-notebook-query-core.md b/resources/metabot/skills/construct-notebook-query-core.mdindex 4d6a32364c7..6798d846b08 100644--- a/resources/metabot/skills/construct-notebook-query-core.md+++ b/resources/metabot/skills/construct-notebook-query-core.md@@ -13,8 +13,12 @@ Construct a Metabase MBQL 5 query as a JSON object describing the query shape. MReturn:- `query`: a JSON **object** (never a quoted string). The target database is inferred from the first stage's `source-table` (or `source-card`) — use the **exact** database name reported by search / `read_resource` / metadata tools.+- `title`: required — a short, human-friendly name for the query, written like a saved-question name.+- `description`: required — a short description of what the query returns.- `visualization`: optional `{"chart_type": "bar"}` (sibling of `query`, never embedded inside it).+> The Slackbot variant of this tool has a different contract: `reasoning` is **required**, `title` is optional and there's no `description`; it uses `display` (a Slack-specific visualization-type enum) instead of `visualization`. See the Slackbot system prompt for its exact argument set.+## Minimal example — count of orders by month```json@@ -45,7 +49,7 @@ Top level:Stage (`"lib/type": "mbql.stage/mbql"` — required marker):- `source-table` **or** `source-card` — exactly one, **first stage only**. Later stages take the previous stage's output implicitly.-- Optional: `filters`, `aggregation`, `breakout`, `expressions`, `fields`, `joins`, `order-by`, `limit`, `page`.+- Optional: `filters`, `aggregation`, `breakout`, `expressions`, `fields`, `joins`, `order-by`, `limit`.There is no top-level `database:` field in the LLM contract — the database is derived from the source.diff --git a/resources/metabot/skills/construct-notebook-query-operators.md b/resources/metabot/skills/construct-notebook-query-operators.mdindex 9baf3e17573..a9a8408ec34 100644--- a/resources/metabot/skills/construct-notebook-query-operators.md+++ b/resources/metabot/skills/construct-notebook-query-operators.md@@ -65,7 +65,7 @@ String (accept `{"case-sensitive": false}` in opts):- `["does-not-contain", {}, <str>, <substring>]`Temporal:-- `["time-interval", {}, <temporal>, <n-or-:current/:last/:next>, "<unit>"]` — relative window. Opts may set `{"include-current": true}`.+- `["time-interval", {}, <temporal>, <n>, "<unit>"]` — relative window. `<n>` is either an integer (negative = past) or one of the strings `"current"`, `"last"`, `"next"`. Opts may set `{"include-current": true}`.- `["during", {}, <temporal>, "<iso-date-or-datetime>", "<unit>"]` — value falls within the bucket containing the literal.- `["relative-time-interval", {}, <temporal>, <value>, "<bucket>", <offset-value>, "<offset-bucket>"]` — window offset from now.@@ -106,14 +106,17 @@ Temporal:- `["get-year", {}, <temporal>]` / `["get-month", {}, <temporal>]` / `["get-day", {}, <temporal>]` / `["get-quarter", {}, <temporal>]`- `["get-hour", {}, <temporal>]` / `["get-minute", {}, <temporal>]` / `["get-second", {}, <temporal>]`- `["get-week", {}, <temporal>]` / `["get-day-of-week", {}, <temporal>]` — both accept optional 4th-slot mode `"iso"`, `"us"`, `"instance"`.-- `["temporal-extract", {}, <temporal>, "<unit>"]` — extract one of the date/time extraction units listed below.+- `["temporal-extract", {}, <temporal>, "<unit>"]` — `<unit>` comes from its **own** enum, *not* the temporal-bucketing list below: `year-of-era`, `quarter-of-year`, `month-of-year`, `week-of-year-iso`, `week-of-year-us`, `week-of-year-instance`, `day-of-month`, `day-of-week`, `day-of-week-iso`, `hour-of-day`, `minute-of-hour`, `second-of-minute`. There is no `year`, `week-of-year`, or `day-of-year` here — use `["get-year", {}, <temporal>]` for the year. Optional 5th slot is a week mode: `"iso"`, `"us"`, `"instance"`.- `["convert-timezone", {}, <temporal>, "<target-tz>"]` — optional 4th slot is source tz.- `["relative-datetime", {}, <n>, "<unit>"]` (or `["relative-datetime", {}, "current"]`)- `["absolute-datetime", {}, "<iso-string>", "<unit?>"]`-- `["date", {}, <expr>]` / `["datetime", {}, <expr>]` / `["time", {}, <expr>]`+- `["date", {}, <expr>]` / `["datetime", {}, <expr>]`+- `["time", {}, "<time-str>", "<unit>"]` — the unit is **required**: `"default"`, `"millisecond"`, `"second"`, `"minute"`, or `"hour"`.- `["now", {}]` / `["today", {}]`-## Temporal units (for `{"temporal-unit": ...}` on field refs and as `<unit>` args)+## Temporal bucketing units (for `{"temporal-unit": ...}` on field refs and as `<unit>` args)++> These are the *bucketing* units. `temporal-extract` has a different enum — see its entry above.- Date truncation: `day`, `week`, `month`, `quarter`, `year`- Date extraction (integer-returning): `day-of-week`, `day-of-month`, `day-of-year`, `week-of-year`, `month-of-year`, `quarter-of-year`, `year`, `year-of-era`diff --git a/resources/metabot/skills/create-sql-query.md b/resources/metabot/skills/create-sql-query.mdindex 06364de4228..1dc15ed1c87 100644--- a/resources/metabot/skills/create-sql-query.md+++ b/resources/metabot/skills/create-sql-query.md@@ -11,11 +11,12 @@ priority: 50- User requests new SQL analysis or data exploration- You need to demonstrate SQL patterns or solutions-**Usage:**+**Usage:** `database_id`, `sql_query`, and `title` are all required — the tool rejects a call that omits any of them.- Provide the database_id where the SQL should run (available from model/table representations)- Write complete, valid SQL using table names or {{#model_id}} template syntax for models.+- Provide a `title`: a short, human-friendly name for the query, shown above its results when the query is delivered as a result card.- Quote column names with special characters, spaces, or reserved keywords using double quotes (e.g., "column name", "order", "group", "column_name")-- The tool will return a newly created SQL query that you can show to the user or create charts from+- The tool will return a newly created SQL query that you can show to the user. If chart tools (`create_chart`/`edit_chart`) are available to you, you can also build a chart from it.- The tool does NOT execute the SQL, it only creates the query**Model Usage:**diff --git a/resources/metabot/skills/edit-chart.md b/resources/metabot/skills/edit-chart.mdindex 95f7fe76358..5d96de11f0b 100644--- a/resources/metabot/skills/edit-chart.md+++ b/resources/metabot/skills/edit-chart.md@@ -14,16 +14,23 @@ It will return a new chart with the updated settings.- Use when converting between basic chart types (bar, line, pie, table, etc.)- Only use when there is an existing chart that needs its settings changed+**Arguments** — all four are required on every call:+- `chart_id` — the id of the chart in the conversation context you are editing+- `new_viz_settings.chart_type` — the chart type to switch to+- `title` — a short, human-friendly title, written like a saved-question name; it becomes the title shown above the returned chart+- `description` — a concise one- or two-sentence description of what the chart shows; it becomes the saved question's description++Because `title` and `description` are re-sent on every edit, carry the existing chart's wording over unless the user asked to change it — don't drop back to a placeholder.+**When NOT to use:**- Do not use for data analysis or querying - this tool only changes chart settings-- Do not use for detailed formatting (titles, colors, axes labels, styling)+- Do not use for detailed formatting (colors, axis labels, number formatting, series styling)- Do not use when the user needs to modify the underlying data or SQL query- Do not use for creating new charts - only for editing existing ones- Avoid when the user wants complex customizations beyond basic chart type changes- Do not use when you don't have any chart in the conversation context, instead, state that you seem not to have access to the chart the user is referring to.**Limitations:**-- Only changes the chart type, not detailed display settings-- Cannot modify chart titles, colors, axis formatting, or styling+- `new_viz_settings` accepts `chart_type` and nothing else, so colors, axis labels, number formatting, goal lines, and series styling cannot be changed through this tool- Does not modify data or perform calculations- Limited to basic chart type conversionsdiff --git a/resources/metabot/skills/edit-sql-query.md b/resources/metabot/skills/edit-sql-query.mdindex 093dfcd6861..08fa67bda2c 100644--- a/resources/metabot/skills/edit-sql-query.md+++ b/resources/metabot/skills/edit-sql-query.md@@ -7,14 +7,20 @@ priority: 50---Edit an existing SQL query by applying targeted string replacements. This updates the query text shown to the user; it does **not** execute the query.+**Usage** — all four arguments are required; the tool rejects a call that omits any of them:+- `query_id` — id of the query to edit (string or integer), taken from the query already in context.+- `checklist` — a short plain-text note of what you checked before editing (columns exist, join keys match, dialect-specific functions). It is not shown to the user, but the call fails without it.+- `edits` — a list of `{"old_string": …, "new_string": …}` replacements, applied in order. Each may also set `replace_all` (optional).+- `title` — a short, human-friendly title for the query, shown above its results when the query is handed back as a link rather than proposed in the editor.+**Safety:**- An edit fails if `old_string` matches multiple locations (unless `replace_all=true`) — either add surrounding context to make the match unique, or set `replace_all=true`.- All edits are applied atomically: either all succeed or none are applied.- Copy `old_string` exactly, including whitespace, tabs, and newlines.**Examples:**-- Targeted edit: `{"edits": [{"old_string": "SELECT *", "new_string": "SELECT id, name"}]}`-- Global rename: `{"edits": [{"old_string": "users", "new_string": "customers", "replace_all": true}]}`+- Targeted edit: `{"query_id": "1", "checklist": "Checked orders has id and name columns", "edits": [{"old_string": "SELECT *", "new_string": "SELECT id, name"}], "title": "Order ids and names"}`+- Global rename: `{"query_id": "1", "checklist": "Confirmed customers has the columns this query reads from users", "edits": [{"old_string": "users", "new_string": "customers", "replace_all": true}], "title": "Customer orders"}`**When to use:** small, targeted changes to a SQL query that is already in the conversation context (use `replace_sql_query` for major rewrites). Never execute SQL or act outside the current query.diff --git a/resources/metabot/skills/read-resource.md b/resources/metabot/skills/read-resource.mdindex 6912cd9b59e..98364a4d7b4 100644--- a/resources/metabot/skills/read-resource.md+++ b/resources/metabot/skills/read-resource.md@@ -9,7 +9,7 @@ When using the read_resource tool, you have access to a unified interface for naThe URI pattern determines what is returned — from top-level lists (databases, collections) to a single entity, to its sub-resources (fields, items, sources, derived items).-You can request multiple resources in one call by providing a list of URIs (max 5). Lists are capped at 25 items per response — when truncated, the response includes `truncated="true"` and `total="N"` so you know more exist; drill into specific items via their URIs (each list item carries a `uri="..."` attribute) or refine via `search`.+You can request multiple resources in one call by providing a list of URIs (max 5). Lists are paginated at 25 items per page. Every `<list>` carries `total`, `page`, `pages`, `showing`, and `truncated` — `truncated` is always present, reading `"true"` when pages remain after this one and `"false"` when this is the last page (which only means the whole list if you've also fetched every earlier page — on page 3 of 3, `"false"` still means you've only seen a third of the list). When more pages remain, a `<truncation-note>` names the next page and gives you the exact URI to fetch it — copy that URI as-is; don't build your own `page=N` query param (a second `?` on a URI that already has one silently breaks the query instead of erroring). Drill into a specific item via its URI (list items carry a `uri="..."` attribute — the exception is a dashboard's virtual items, `virtual_heading`/`virtual_text` and the like, which are not addressable resources and carry a `dashcard_id` instead), or refine via `search`.# When to Use read_resource vs search@@ -21,9 +21,11 @@ You can request multiple resources in one call by providing a list of URIs (max**Use `search` when you don't know what or where** something lives — open-ended discovery by topic.+> **If you have no `search` tool**, substitute whichever discovery tool you do have (e.g. `retrieve_library_entities`) everywhere this skill says `search` — the loop is the same, only the entry point differs. Its results carry the same URIs, so everything below about drilling in with `read_resource` still applies.+**The exploration loop**:1. `search` for a topic → every result carries a `uri` attribute.-2. If a top hit is a container (look for `is_container="true"` — collections and dashboards), `read_resource` on its URI to enumerate members instead of re-searching.+2. If a top hit is a container — its element name is `<dashboard>` or `<document>` — `read_resource` on its URI to enumerate members instead of re-searching. (`search` never returns collections; reach those by navigating, e.g. `metabase://collection/{id}/items`.)3. Drill into specific items via `read_resource` for fields, sources, or details.4. Walk lineage when needed: `metabase://table/{id}/derived`, `metabase://model/{id}/sources`, `metabase://transform/{id}/sources` or `/target`.@@ -57,7 +59,7 @@ You can request multiple resources in one call by providing a list of URIs (max**Best Practices:**- For a high-cardinality database, prefer schema → tables drill-down over fetching every table at once.-- Pair with the `database_id` argument on `search` when you want to topic-search within a specific warehouse.+- In the SQL editor, `search` already scopes to the current database via its own `database_id` argument — no need to filter further. Elsewhere, `search` has no per-database filter; narrow with `entity_types` and topic terms instead.## Collection resources@@ -70,15 +72,14 @@ You can request multiple resources in one call by providing a list of URIs (max- Need to navigate a deep tree without enumerating every leaf? → `metabase://collection/{id}/subcollections`**Best Practices:**-- When a `search` returns a collection result with `is_container="true"`, prefer `read_resource` on its URI over re-searching the same concept.-- Pair with the `collection_id` argument on `search` (descendant scope) when you want to topic-search inside one part of the instance.+- Collections are never `search` results — the only way to reach one is by navigating (`metabase://collections`, `metabase://collections?tree=true`, or a parent's `/subcollections`). To see what a collection holds, `read_resource` its `/items` rather than searching for the collection's name.## Table resources- `metabase://table/{id}` — basic table info- `metabase://table/{id}/fields` — table with fields- `metabase://table/{id}/fields/{field_id}` — specific field with sample values and stats-- `metabase://table/{id}/derived` — cards (questions/models) and transforms built on this table+- `metabase://table/{id}/derived` — cards (questions/models) built on this table, plus the transforms that declare it as a source. Only `python` transforms declare their source tables, so a SQL/`query` transform reading this table will **not** appear here.**Examples:**- Want table structure (fields without value information)? → `metabase://table/123/fields`@@ -123,32 +124,34 @@ You can request multiple resources in one call by providing a list of URIs (max## Transform resources-- `metabase://transform/{id}` — transform details and configuration-- `metabase://transform/{id}/sources` — source database and tables this transform reads from+- `metabase://transform/{id}` — transform details and configuration, including the source query for a `query` transform. Python transforms report `type="python"` but their script body is **not** included.+- `metabase://transform/{id}/sources` — the source database, plus source tables for `python` transforms only (see below)- `metabase://transform/{id}/target` — target database and table this transform writes to**Examples:**-- Want to inspect a transform's SQL or Python source before editing it? → `metabase://transform/42`+- Want to inspect a `query` transform's SQL/MBQL before editing it? → `metabase://transform/42`- "What does this transform read?" → `metabase://transform/42/sources`- "Where does this transform write?" → `metabase://transform/42/target`**Best Practices:**-- Fetch a transform's details before modifying it so you have the current source query and target configuration.-- Use the returned source type (`query` or `python`) to decide which write tool to call (`write_transform_sql` or `write_transform_python`).-- Walk `/sources` and `/target` to understand lineage before recommending downstream changes.+- Fetch a transform's details before modifying it so you have the current target configuration and — for `query` transforms — the current source query.+- Check the returned source type (`query` or `python`) first: it decides both how the transform is implemented and how much lineage you can see.+- **Lineage is asymmetric between the two source types.** A `python` transform declares its inputs explicitly, so `/sources` lists its source tables and those tables' `/derived` lists it back. A `query` transform's inputs live inside its query, which is not walked — so `/sources` returns only its database with no tables, and it never shows up under any table's `/derived`, even when its SQL plainly reads that table.+- Because of that asymmetry, a table's `/derived` is not proof that nothing reads it. When it matters whether a `query` transform touches a table, fetch the candidate transforms' details and read their source queries rather than trusting `/derived` to be complete.+- Walk `/sources` and `/target` to understand lineage before recommending downstream changes, keeping the gap above in mind.## Dashboard resources- `metabase://dashboard/{id}` — dashboard details-- `metabase://dashboard/{id}/items` — everything on the dashboard in layout order: question cards (each rendered as a `metabase://question/{id}` URI you can drill into) plus headings, text cards, and action buttons+- `metabase://dashboard/{id}/items` — everything on the dashboard in layout order: card-backed dashcards (each with a URI you can drill into, matching the backing card's own type — `metabase://question/{id}`, `metabase://model/{id}`, or `metabase://metric/{id}`) plus headings, text cards, and action buttons**Examples:**- Want to understand what a dashboard contains before recommending it? → `metabase://dashboard/158`- User asks "what's on this dashboard?" → `metabase://dashboard/158/items`**Best Practices:**-- Treat dashboards as containers — when search returns a dashboard hit (`is_container="true"`), use `/items` to list its cards instead of re-searching for the same concept.-- Every dashcard entry carries a `dashcard_id` — the handle `update_dashboard` `remove`/`move`/`update_text` mutations take. Headings and text cards show as `virtual_heading`/`virtual_text` with their text as the description; action buttons show as `action` (with a `uri` to their backing model when readable). On multi-tab dashboards the list opens with a `<tabs>` block naming every tab — empty ones included — with the `tab_id` that `add` mutations accept, and dashcard entries carry their tab's `tab_id`, grouped in tab order.+- Treat dashboards as containers — when search returns a `<dashboard>` hit, use `/items` to list its cards instead of re-searching for the same concept.+- Every dashcard entry carries a `dashcard_id`. Headings and text cards show as `virtual_heading`/`virtual_text` with their text as the description; action buttons show as `action` (with a `uri` to their backing model when readable). On multi-tab dashboards the list opens with a `<tabs>` block naming every tab — empty ones included — and dashcard entries carry their tab's `tab_id`, grouped in tab order.- Fetch dashboard details to confirm it contains the information the user is looking for before recommending it.- Prefer verified dashboards when they match the user's request.@@ -156,5 +159,5 @@ You can request multiple resources in one call by providing a list of URIs (max- **Drill, don't re-search.** If a `search` result is a container or you need more detail on a specific item, feed its `uri` back into `read_resource` — don't issue another search for the same concept.- **Batch read URIs** (up to 5 at a time) when you need parallel context, e.g. fetching `/sources` for several candidate models at once.-- **Honor truncation.** If a list response carries `truncated="true"`, the most-relevant items are not guaranteed to be in the first 25 — consider scoping (`metabase://database/{id}/...`) or refining via `search` with `database_id`/`collection_id` instead of paging blindly.-- **Curation matters.** Search results carry `is_verified`, `is_official`, and `is_library_member` flags — when you have a choice, drill into the curated item rather than the raw one.+- **Honor truncation.** If a list response carries `truncated="true"`, the most-relevant items are not guaranteed to be in the first 25. You have two ways forward: page through the remainder by fetching the URI given in the `<truncation-note>` (the `pages` attribute tells you how many there are), or narrow the request — scope it (`metabase://database/{id}/...`) or refine your `search` query (narrower `entity_types` or topic terms). Narrow when you are hunting for one specific item; page when you genuinely need the whole list, and remember `truncated="false"` on a later page doesn't mean you've seen the earlier ones too.+- **Curation matters.** Search results carry `is_verified`, `is_official`, and `is_curated` flags (plus `data_authority` where configured) — when you have a choice, drill into the curated item rather than the raw one.diff --git a/resources/metabot/skills/replace-sql-query.md b/resources/metabot/skills/replace-sql-query.mdindex 4145f5eb5e2..d6e1294ecfd 100644--- a/resources/metabot/skills/replace-sql-query.md+++ b/resources/metabot/skills/replace-sql-query.md@@ -7,6 +7,14 @@ priority: 50---Replace the entire content of an existing SQL query with new SQL. Use for major rewrites or structural changes — more token-efficient than many `edit_sql_query` calls. This updates the query text shown to the user; it does **not** execute the query.+**Usage** — all four arguments are required; the tool rejects a call that omits any of them:+- `query_id` — id of the query to replace (string or integer), taken from the query already in context.+- `checklist` — a short plain-text note of what you checked before rewriting (columns exist, join keys match, dialect-specific functions). It is not shown to the user, but the call fails without it.+- `new_query` — the complete replacement SQL. It replaces the whole body, so include everything the query needs.+- `title` — a short, human-friendly title for the query, shown above its results when the query is handed back as a link rather than proposed in the editor.++**Example:** `{"query_id": "1", "checklist": "Re-read orders and customers; join is on customer_id", "new_query": "SELECT c.name, COUNT(*) AS order_count FROM customers c JOIN orders o ON o.customer_id = c.id GROUP BY c.name", "title": "Orders per customer"}`+**When to use:** large changes to a SQL query that is already in the conversation context (use `edit_sql_query` for small targeted edits). Never execute SQL or act outside the current query.SELECT-only — never emit DDL/DML. Quote identifiers containing spaces or reserved words in double quotes (e.g. `"order"`). Use the target database's SQL dialect. See the `create-sql-query` skill for the full SQL contract (read-only rules, model reference syntax, fully-qualified table names).diff --git a/resources/metabot/skills/write-transform-python.md b/resources/metabot/skills/write-transform-python.mdindex 85bffc8874a..fc527327801 100644--- a/resources/metabot/skills/write-transform-python.md+++ b/resources/metabot/skills/write-transform-python.md@@ -16,7 +16,7 @@ user, these are only suggestions which they must apply themselves.When creating a new transform, you must provide:- transform_name: A descriptive name for the transform- transform_description: A detailed description of what the transform does-- source_database: The database ID containing the source tables+- database_id: The database ID containing the source tables- source_tables: A list of source table objects, each with `alias` (parameter name in the transform function), `table_id` (database table ID), `schema` (e.g. "PUBLIC"), and `database_id`**Edit Modes:**@@ -46,7 +46,7 @@ When creating a new transform, you must provide:- Use mode="edit" for small targeted changes- Include surrounding context (whitespace, adjacent lines) to make PartialEdit matches unique- Use replace_all=true only when you want to change ALL occurrences in PartialEdit-- Use the search_tables tool to find correct source_tables first - never guess or make up table IDs+- Use the `search` tool to find correct source_tables first - never guess or make up table IDs- Use real database tables for source_tables. NEVER use metabase models or model IDs in source_tables.- Copy exact text including all spaces, tabs, and newlines for PartialEdit- Use this tool for any Python-related requests when a Python transform is present in the contextdiff --git a/resources/metabot/skills/write-transform-sql.md b/resources/metabot/skills/write-transform-sql.mdindex 770bb4efb6c..3a1f30f53ad 100644--- a/resources/metabot/skills/write-transform-sql.md+++ b/resources/metabot/skills/write-transform-sql.md@@ -54,7 +54,8 @@ When creating a new transform, you must provide:available in the artifact. This will help you to use the correct syntax and functions- When querying Metabase models, remember that their fully qualified name is of the form `{{#model_id}}`,- e.g. `SELECT * FROM {{#5}}`+ e.g. `SELECT * FROM {{#5}} AS user_details`. Always give the model reference an alias, even when the SQL+ dialect does not require one.**Limitations:*** This tool does not execute SQL queries, it only modifies the query text.diff --git a/src/metabase/metabot/tools/analyze_chart.clj b/src/metabase/metabot/tools/analyze_chart.cljindex 2ce00ca8d3d..e547f89fcc3 100644--- a/src/metabase/metabot/tools/analyze_chart.clj+++ b/src/metabase/metabot/tools/analyze_chart.clj@@ -73,7 +73,6 @@ Do not use headers (##). Do not list statistics. Do not analyze series separatel{:type ::malformed-chart-config, :series series-name})))))(mu/defn ^{:tool-name "analyze_chart"- :prompt "analyze_chart":scope scope/agent-viz-read}analyze-chart-tool"Compute statistics and generate analysis context for a chart.diff --git a/src/metabase/metabot/tools/create_alert.clj b/src/metabase/metabot/tools/create_alert.cljindex c6a663252d9..123ecdcd68b 100644--- a/src/metabase/metabot/tools/create_alert.clj+++ b/src/metabase/metabot/tools/create_alert.clj@@ -104,33 +104,6 @@"last-thursday" "last-friday" "last-saturday"]][:hour [:int {:min 0 :max 23}]]]])-(def ^:private create-alert-system-instructions- "## Alerts--You can create alerts that notify the user's current Slack channel based on a saved question's results on a-recurring schedule.--### Required information--Before calling the tool, ensure you have ALL of the following:-1. **Card ID** — the ID of a saved question, obtained from a prior search result or conversation context-2. **Send condition** — determines when the alert fires:- - `has_result` — sends when the question returns any rows- - `goal_above` — sends when the result exceeds the goal line set on the question- - `goal_below` — sends when the result drops below the goal line-3. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields-4. **Send once** (optional, defaults to false) — if true, the alert is automatically deleted after it fires once--### Important notes--* Alerts are for **saved questions** (cards), not dashboards. For dashboard delivery, use the dashboard subscription tool.-* `goal_above` and `goal_below` only work on questions that have a goal line configured.-* If the user doesn't specify a send condition, default to `has_result`.--CRITICAL: When a user asks to be alerted or notified about a saved question's results, you MUST call the create_alert tool.-NEVER tell the user you have created an alert without actually calling the create_alert tool. If you cannot call the tool-(e.g. missing required information), explain what is needed instead of pretending the alert was created.")-(def ^:private alert-schema[:map {:closed true}[:card_id :int]@@ -138,11 +111,27 @@ NEVER tell the user you have created an alert without actually calling the creat[:schedule schedule-schema][:send_once {:optional true :default false} :boolean]])-(mu/defn ^{:tool-name "create_alert"- :scope scope/agent-alert-create- :system-instructions create-alert-system-instructions}+(mu/defn ^{:tool-name "create_alert"+ :scope scope/agent-alert-create}create-alert-tool- "Create an alert based on a saved question's results on a recurring schedule."+ "Create an alert that notifies the user's current Slack channel based on a saved question's+ results on a recurring schedule. Alerts are for saved questions (cards), not dashboards — use+ the dashboard subscription tool for dashboard delivery.++ When the user asks to be alerted or notified about a saved question's results, you MUST call+ this tool; never claim an alert was created without calling it. If you are missing required+ information, ask the user for it rather than guessing.++ `card_id` is the id of a saved question, from a prior search result or the conversation context.++ `send_condition` decides when the alert fires:+ - `has_result` — the question returns any rows. Default this when the user doesn't say.+ - `goal_above` — the result exceeds the goal line set on the question.+ - `goal_below` — the result drops below the goal line.+ `goal_above` and `goal_below` only work on questions that have a goal line configured.++ `schedule` is a frequency (hourly, daily, weekly, monthly) plus that frequency's time fields.+ `send_once` is optional (default false); when true the alert is deleted after it fires once."[{:keys [card_id send_condition schedule send_once]} :- alert-schema](let [slack-channel-id (:slack_channel_id (shared/current-context))](when-not slack-channel-iddiff --git a/src/metabase/metabot/tools/create_dashboard_subscription.clj b/src/metabase/metabot/tools/create_dashboard_subscription.cljindex 709caf0e929..038d92d0be6 100644--- a/src/metabase/metabot/tools/create_dashboard_subscription.clj+++ b/src/metabase/metabot/tools/create_dashboard_subscription.clj@@ -75,32 +75,21 @@(-> (metabot.tools.u/handle-agent-error e)(set/rename-keys {:output :error}))))))-(def ^:private create-dashboard-subscription-system-instructions- "## Dashboard Subscriptions--You can create dashboard subscriptions that deliver dashboard contents to the user's current slack channel on a-recurring schedule.--### CRITICAL: You MUST call the create_dashboard_subscription tool--When a user asks to subscribe to a dashboard, set up scheduled delivery, or receive regular updates for a dashboard,-you MUST call the create_dashboard_subscription tool. Never tell the user you have created a subscription without-actually calling the tool. If you cannot call the tool (e.g. missing required information), explain what is needed-instead of pretending the subscription was created.--### Required information--Before calling the tool, ensure you have ALL of the following:-1. **Dashboard ID** — obtained from a prior search result or conversation context-2. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields--If any required information is missing, ask the user for it rather than assuming or fabricating values.")--(mu/defn ^{:tool-name "create_dashboard_subscription"- :scope scope/agent-dashboard-subscribe- :system-instructions create-dashboard-subscription-system-instructions}+(mu/defn ^{:tool-name "create_dashboard_subscription"+ :scope scope/agent-dashboard-subscribe}slackbot-create-dashboard-subscription-tool- "Create a recurring subscription that delivers a dashboard's contents to a Slack channel."+ "Create a recurring subscription that delivers a dashboard's contents to the user's current+ Slack channel. The destination channel is taken from the conversation — there is nothing to+ pass for it, and the tool only works from a Slack channel.++ When the user asks to subscribe to a dashboard, set up scheduled delivery, or receive regular+ updates for a dashboard, you MUST call this tool; never claim a subscription was created+ without calling it. If you are missing required information, ask the user for it rather than+ guessing.++ `dashboard_id` is the id of the dashboard, from a prior search result or the conversation+ context. `schedule` is a frequency (hourly, daily, weekly, monthly) plus that frequency's+ time fields."[{:keys [dashboard_id schedule]} :- [:map {:closed true}[:dashboard_id :int][:schedule tools.create-alert/schedule-schema]]]diff --git a/src/metabase/metabot/tools/document.clj b/src/metabase/metabot/tools/document.cljindex 2afa502beac..6fe02969bea 100644--- a/src/metabase/metabot/tools/document.clj+++ b/src/metabase/metabot/tools/document.clj@@ -118,7 +118,8 @@"</result>\n""<instructions>\n""NEXT: construct a SQL query based on the user's instructions and this schema.\n"- "THEN: call `document_construct_sql_chart` with SQL and chart settings.\n"+ "THEN: call `document_construct_sql_chart` with SQL and chart settings, passing "+ "database_id=" database-id " (the id of the database above).\n""SQL engine: " (:engine db) ".\n""</instructions>")]{:output outputdiff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.cljindex 8506922c04b..66b841b70ed 100644--- a/src/metabase/metabot/tools/resources.clj+++ b/src/metabase/metabot/tools/resources.clj@@ -18,9 +18,11 @@- metabase://user/recent-items - current user's recent itemsPagination:- List responses are capped at page-size items per page. When :truncated is true, use ?page=N to- fetch subsequent pages, e.g. metabase://database/1/tables?page=2. The response includes- :page (current, 1-indexed) and :pages (total).+ List responses are capped at page-size items per page. When :truncated is true, the+ structured-output carries a ready-to-fetch :next-page-uri — request that URI directly rather+ than building a page=N query param by hand (a second `?` on a URI that already has one silently+ breaks the query instead of erroring). The response also includes :page (current, 1-indexed)+ and :pages (total).Database drill-down:- metabase://database/{id} - one database@@ -137,6 +139,25 @@[item]{:structured-output (assoc item :result-type :metabot-entity)})+(defn- uri-with-page+ "Return `uri` with its `page` query param set to `page`. Replaces an existing `page` param+ (e.g. a request for page 2 asking for its own next page) rather than appending a duplicate,+ and only adds `?` when `uri` has no query string yet."+ [uri page]+ (let [[base qs] (str/split uri #"\?" 2)+ kept (when-not (str/blank? qs)+ (remove #(str/starts-with? % "page=") (str/split qs #"&")))]+ (str base "?" (str/join "&" (concat kept [(str "page=" page)])))))++(defn- attach-next-page-uri+ "If `result` is a truncated metabot-list, add a ready-to-fetch :next-page-uri — the model+ doesn't have to work out whether the URI needs `?page=N` or `&page=N`."+ [uri result]+ (let [{:keys [result-type page pages]} (:structured-output result)]+ (cond-> result+ (and (= result-type :metabot-list) page pages (< page pages))+ (assoc-in [:structured-output :next-page-uri] (uri-with-page uri (inc page))))))+(defn- parse-query-string"Parse a URI query string like \"tree=true&foo=bar\" into a keyword-keyed map.Returns nil for empty or nil input."@@ -659,9 +680,8 @@(defn- present-non-question-dashcard"Dashcards not rendered as a saved question — virtual cards (headings, text, links, ...) andaction buttons (which may reference a backing model via `card_id` but render as a button).- They carry their `dashcard_id` — the handle `update_dashboard` remove/move/update_text- mutations take. The card's text (or a link card's target) renders as the item body via- `:description`."+ They carry their `dashcard_id`. The card's text (or a link card's target) renders as the item+ body via `:description`."[{:keys [id action_id visualization_settings]}](let [display (some-> (get-in visualization_settings [:virtual_card :display]) name)];; action_id wins over the virtual display: frontend-created action buttons carry BOTH an@@ -680,13 +700,12 @@(get-in visualization_settings [:link :url]))}))(defn- fetch-dashboard-items- "One item per dashcard in row/col (layout) order, each carrying the `dashcard_id` that- `update_dashboard` remove/move/update_text mutations take. On a tabbed dashboard the items come- grouped by tab (nil-tab dashcards belong to the first tab, where the frontend renders them),- each carries its `tab_id`, and the response's `:tabs` lists every tab — empty ones included —- in display order. Card-backed dashcards keep the card fields; virtual dashcards (headings,- text, links, ...) render their text; action buttons keep a `uri` to their backing model when- it's readable. Dashcards whose card is archived or unreadable are omitted."+ "One item per dashcard in row/col (layout) order, each carrying its `dashcard_id`. On a tabbed+ dashboard the items come grouped by tab (nil-tab dashcards belong to the first tab, where the+ frontend renders them), each carries its `tab_id`, and the response's `:tabs` lists every tab —+ empty ones included — in display order. Card-backed dashcards keep the card fields; virtual+ dashcards (headings, text, links, ...) render their text; action buttons keep a `uri` to their+ backing model when it's readable. Dashcards whose card is archived or unreadable are omitted."[id-str query-params](let [dashboard-id (parse-long id-str)_ (api/read-check :model/Dashboard dashboard-id)@@ -831,64 +850,65 @@[uri](let [{:keys [segments query-params]} (parse-uri uri)](check-numeric-id-segment! uri segments)- (match/match-one segments- ;; Navigation- ["databases"] (fetch-databases-list query-params)- ["collections"] (fetch-collections-list query-params)- ["user" "recent-items"] (fetch-user-recents)-- ;; Database drill-down- ["database" id] (fetch-database id)- ["database" id "tables"] (fetch-database-tables id query-params)- ["database" id "models"] (fetch-database-models id query-params)- ["database" id "schemas"] (fetch-database-schemas id query-params)- ["database" id "schemas" schema "tables"] (fetch-database-schema-tables id schema query-params)-- ;; Collection drill-down- ["collection" id] (fetch-collection id)- ["collection" id "items"] (fetch-collection-items id query-params)- ["collection" id "subcollections"] (fetch-collection-subcollections id query-params)-- ;; Table- ["table" id] (fetch-table id)- ["table" id "fields"] (fetch-table-fields id)- ["table" id "fields" & rst] (fetch-table-field id (str/join "/" rst))- ["table" id "derived"] (fetch-table-derived id query-params)-- ;; Card (model / question — share handlers, dispatch on the type segment)- [(t :guard #{"model" "question"}) id] (fetch-card t id)- [(t :guard #{"model" "question"}) id "fields"] (fetch-card-fields t id)- [(t :guard #{"model" "question"}) id "fields" & rst] (fetch-card-field t id (str/join "/" rst))- [(t :guard #{"model" "question"}) id "sources"] (fetch-card-sources id)-- ;; Metric- ["metric" id] (fetch-metric id)- ["metric" id "dimensions"] (fetch-metric-dimensions id)- ["metric" id "dimensions" & rst] (fetch-metric-dimension id (str/join "/" rst))-- ;; Measure / Segment- ["measure" id] (fetch-measure id)- ["segment" id] (fetch-segment id)-- ;; Transform- ["transform" id] (fetch-transform id)- ["transform" id "sources"] (fetch-transform-sources id)- ["transform" id "target"] (fetch-transform-target id)-- ;; Dashboard- ["dashboard" id] (fetch-dashboard id)- ["dashboard" id "items"] (fetch-dashboard-items id query-params)-- ;; Document- ["document" id] (fetch-document id)-- ;; Conversation state- ["chart" id] (fetch-conversation-chart id)- ["query" id] (fetch-conversation-query id)-- ;; Default — required to make match non-recursive- _ (throw (ex-info (str "Unsupported URI: " uri)- {:uri uri :segments segments})))))+ (->> (match/match-one segments+ ;; Navigation+ ["databases"] (fetch-databases-list query-params)+ ["collections"] (fetch-collections-list query-params)+ ["user" "recent-items"] (fetch-user-recents)++ ;; Database drill-down+ ["database" id] (fetch-database id)+ ["database" id "tables"] (fetch-database-tables id query-params)+ ["database" id "models"] (fetch-database-models id query-params)+ ["database" id "schemas"] (fetch-database-schemas id query-params)+ ["database" id "schemas" schema "tables"] (fetch-database-schema-tables id schema query-params)++ ;; Collection drill-down+ ["collection" id] (fetch-collection id)+ ["collection" id "items"] (fetch-collection-items id query-params)+ ["collection" id "subcollections"] (fetch-collection-subcollections id query-params)++ ;; Table+ ["table" id] (fetch-table id)+ ["table" id "fields"] (fetch-table-fields id)+ ["table" id "fields" & rst] (fetch-table-field id (str/join "/" rst))+ ["table" id "derived"] (fetch-table-derived id query-params)++ ;; Card (model / question — share handlers, dispatch on the type segment)+ [(t :guard #{"model" "question"}) id] (fetch-card t id)+ [(t :guard #{"model" "question"}) id "fields"] (fetch-card-fields t id)+ [(t :guard #{"model" "question"}) id "fields" & rst] (fetch-card-field t id (str/join "/" rst))+ [(t :guard #{"model" "question"}) id "sources"] (fetch-card-sources id)++ ;; Metric+ ["metric" id] (fetch-metric id)+ ["metric" id "dimensions"] (fetch-metric-dimensions id)+ ["metric" id "dimensions" & rst] (fetch-metric-dimension id (str/join "/" rst))++ ;; Measure / Segment+ ["measure" id] (fetch-measure id)+ ["segment" id] (fetch-segment id)++ ;; Transform+ ["transform" id] (fetch-transform id)+ ["transform" id "sources"] (fetch-transform-sources id)+ ["transform" id "target"] (fetch-transform-target id)++ ;; Dashboard+ ["dashboard" id] (fetch-dashboard id)+ ["dashboard" id "items"] (fetch-dashboard-items id query-params)++ ;; Document+ ["document" id] (fetch-document id)++ ;; Conversation state+ ["chart" id] (fetch-conversation-chart id)+ ["query" id] (fetch-conversation-query id)++ ;; Default — required to make match non-recursive+ _ (throw (ex-info (str "Unsupported URI: " uri)+ {:uri uri :segments segments})))+ (attach-next-page-uri uri))));; ----- Display titles -----@@ -1066,8 +1086,9 @@back here. Only numeric IDs accepted, never alphanumeric entity-id's.Up to 5 URIs may be requested in one call. List responses are capped at 25 items per page.- When :truncated is true, append ?page=N to fetch the next page (e.g. metabase://database/1/tables?page=2).- The response includes :page (current, 1-indexed) and :pages (total page count).+ When :truncated is true, fetch the next page by requesting the :next-page-uri given in the+ truncation note — don't build a page=N query param by hand. The response also includes :page+ (current, 1-indexed) and :pages (total page count).NAVIGATION (top-level lists):- metabase://databases - all databasesdiff --git a/src/metabase/metabot/tools/save_entity.clj b/src/metabase/metabot/tools/save_entity.cljindex cea26f09af1..03cf33895ad 100644--- a/src/metabase/metabot/tools/save_entity.clj+++ b/src/metabase/metabot/tools/save_entity.clj@@ -171,11 +171,12 @@`read_resource` on `metabase://collections?tree=true`. Omit `collection_id`to use the user's personal collection; pass `null` for the root collection.- To add it to a dashboard, set `target_type` to `dashboard` and pass a- `dashboard_id`. Find dashboards with `search`, restricting `entity_types` to- the `dashboard` type. Only offer or use results with `can_write=true`; results+ `dashboard_id`. Find dashboards with your search/discovery tool — if that tool is+ `search`, restrict `entity_types` to the `dashboard` type. Only offer or use results+ with `can_write=true`; resultswith `can_write=false` are visible but read-only and cannot be save destinations.- To embed it in a document, set `target_type` to `document` and pass a- `document_id`. Find documents with `search`, restricting `entity_types` to+ `document_id`. Find documents the same way — with `search`, restrict `entity_types` tothe `document` type, just as you would use the `dashboard` type to find dashboards. Searchusing any name or topic the user provided. Before calling `save_entity`, you MUST call`read_resource` on `metabase://document/{id}` for the selected result and inspect its@@ -188,6 +189,10 @@meaningful position, first inspect the document's blocks with`read_resource` on `metabase://document/{id}`.+ If your only discovery tool returns library data entities (tables, models, metrics) rather+ than saved content, dashboards and documents aren't discoverable that way — save to a+ collection instead, or ask the user for the dashboard or document they mean.+After saving, tell the user where it went and share the returned link."[{:keys [chart_id destination description] question-name :name} :- save-entity-schema](trydiff --git a/src/metabase/metabot/tools/shared/instructions.clj b/src/metabase/metabot/tools/shared/instructions.cljindex fff3bc5dd81..8b0a54b6d28 100644--- a/src/metabase/metabot/tools/shared/instructions.clj+++ b/src/metabase/metabot/tools/shared/instructions.clj@@ -75,31 +75,47 @@ Reference items using: [name](metabase://type/id)")"- Consider whether to create a chart or graph when that better matches the user's intent\n""- Present the results in a way that matches the user's intent and follow up if they need clarification"))+(def query-loaded-in-editor-instructions+ "Instructions for a SQL query proposed in the user's open SQL editor buffer. The editor shows it as+ a suggested change the user accepts or rejects — it is not applied to the buffer until they accept."+ (str "The assistant needs to:\n"+ "- Remember you cannot view the results directly yourself\n"+ "- Tell the user the query is waiting in their SQL editor as a proposed change to accept or "+ "reject — do not offer a link, the query is already in front of them\n"+ "- Present what the query does in a way that matches the user's intent and follow up if they need clarification"))++(defn- delivery-instruction+ "The delivery line for an updated query: proposed in the user's open editor buffer for them to+ accept or reject, or handed back as a query they open themselves."+ [query-id loaded-in-editor?]+ (if loaded-in-editor?+ (str "- The updated query is proposed in the user's SQL editor for them to accept or reject — "+ "tell them it's waiting there, do not offer a link")+ (str "- Always provide a direct link using: "+ "`[Updated Query](metabase://query/" query-id ")` "+ "where Updated Query is a meaningful link text")))+(defn edit-sql-query-instructions-for- "Generate instructions for an edited SQL query, embedding the query ID- in the link template. Matches Python EditSqlQueryToolV2._create_result."- [query-id]+ "Generate instructions for an edited SQL query. `loaded-in-editor?` reflects how the result was+ delivered: as a proposed change in an open SQL editor buffer, or as a query the user opens via a link."+ [query-id loaded-in-editor?](str "The updated query is shown in the result data above.\n\n""After you have edited the query, do a thorough analysis of the query to find any potential errors.\n\n""**If the returned SQL query is NOT correct:**\n\n""- Make further refinements using this tool again\n\n""**If the returned SQL query is correct:**\n\n"- "- Always provide a direct link using: "- "`[Updated Query](metabase://query/" query-id ")` "- "where Updated Query is a meaningful link text"))+ (delivery-instruction query-id loaded-in-editor?)))(defn replace-sql-query-instructions-for- "Generate instructions for a replaced SQL query, embedding the query ID- in the link template. Matches Python ReplaceSqlQueryToolV2._create_result."- [query-id]+ "Generate instructions for a replaced SQL query. `loaded-in-editor?` reflects how the result was+ delivered: as a proposed change in an open SQL editor buffer, or as a query the user opens via a link."+ [query-id loaded-in-editor?](str "The updated query is shown in the result data above.\n\n""After you have replaced the query, do a thorough analysis of the query to find any potential errors.\n\n""**If the returned SQL query is NOT correct:**\n\n""- Make further refinements using this tool or edit_sql_query again\n\n""**If the returned SQL query is correct:**\n\n"- "- Always provide a direct link using: "- "`[Updated Query](metabase://query/" query-id ")` "- "where Updated Query is a meaningful link text"))+ (delivery-instruction query-id loaded-in-editor?)))(defn sql-validation-error-instructions"Generate instructions for failed query validation. Matches Python `format_validation_error_instructions`."diff --git a/src/metabase/metabot/tools/shared/llm_shape.clj b/src/metabase/metabot/tools/shared/llm_shape.cljindex 5658a2d0d63..6a3179106b5 100644--- a/src/metabase/metabot/tools/shared/llm_shape.clj+++ b/src/metabase/metabot/tools/shared/llm_shape.clj@@ -986,11 +986,12 @@"Render a list-shaped read-resource response.Input shape:- {:list-type :databases ; keyword, becomes the type attribute- :items [{:type \"database\" :id 1 :name \"Sample\" :uri \"...\" :description \"...\"} ...]- :total 5- :page 1- :pages 1}+ {:list-type :databases ; keyword, becomes the type attribute+ :items [{:type \"database\" :id 1 :name \"Sample\" :uri \"...\" :description \"...\"} ...]+ :total 5+ :page 1+ :pages 1+ :next-page-uri \"metabase://databases?page=2\"} ; present when truncatedAn optional `:tabs` vector of `{:id .. :name ..}` (dashboard items) renders as a `<tabs>`block ahead of the items; items reference tabs via their `tab_id` attribute.@@ -1000,7 +1001,7 @@<item type=\"database\" id=\"1\" name=\"Sample\" uri=\"metabase://database/1\">Description</item>...</list>"- [{:keys [list-type items total page pages tabs]}]+ [{:keys [list-type items total page pages tabs next-page-uri]}](let [type-attr (clojure.core/name (or list-type :items))tabs-xml (when (seq tabs)(str "<tabs>\n"@@ -1013,7 +1014,8 @@truncated (< page pages)note (when truncated(str "<truncation-note>Page " page " of " pages " (" showing " of " total " items). "- "Append ?page=" (inc page) " to the URI to fetch the next page.</truncation-note>"))]+ "Fetch " next-page-uri " for the next page — copy it exactly, do not "+ "modify its query string.</truncation-note>"))](str "<list type=\"" type-attr "\" total=\"" total"\" page=\"" (or page 1)"\" pages=\"" (or pages 1)diff --git a/src/metabase/metabot/tools/sql.clj b/src/metabase/metabot/tools/sql.cljindex 94b583ac587..a1593fc1e98 100644--- a/src/metabase/metabot/tools/sql.clj+++ b/src/metabase/metabot/tools/sql.clj@@ -126,10 +126,10 @@{:database-id database_id:sql sql_query}){:keys [valid? dialect error-message]} validation-result- {:keys [query-id query-content]} action-result]+ {:keys [query-content]} action-result](if valid?(let [structured (assoc action-result :result-type :query)- instr (instructions/query-created-instructions-for query-id)]+ instr instructions/query-loaded-in-editor-instructions]{:output (format-query-output structured instr {:preamble? true}):structured-output structured:instructions instr@@ -171,9 +171,9 @@{:keys [valid? error-message dialect]} validation-result{:keys [query-id query query-content]} action-result](if valid?- (let [structured (assoc action-result :result-type :query)- instr (instructions/edit-sql-query-instructions-for query-id)- buffer-id (first-code-editor-buffer-id)]+ (let [structured (assoc action-result :result-type :query)+ buffer-id (first-code-editor-buffer-id)+ instr (instructions/edit-sql-query-instructions-for query-id (some? buffer-id))]{:output (format-query-output structured instr):structured-output structured:instructions instr@@ -220,9 +220,9 @@{:keys [valid? dialect error-message]} validation-result{:keys [query-id query query-content]} action-result](if valid?- (let [structured (assoc action-result :result-type :query)- instr (instructions/replace-sql-query-instructions-for query-id)- buffer-id (first-code-editor-buffer-id)]+ (let [structured (assoc action-result :result-type :query)+ buffer-id (first-code-editor-buffer-id)+ instr (instructions/replace-sql-query-instructions-for query-id (some? buffer-id))]{:output (format-query-output structured instr):structured-output structured:instructions instrdiff --git a/src/metabase/metabot/tools/subscriptions.clj b/src/metabase/metabot/tools/subscriptions.cljindex 5ccbeb0dac4..e7526362a96 100644--- a/src/metabase/metabot/tools/subscriptions.clj+++ b/src/metabase/metabot/tools/subscriptions.clj@@ -5,8 +5,6 @@[metabase.api.common :as api][metabase.channel.settings :as channel.settings][metabase.metabot.scope :as scope]- [metabase.metabot.tools.create-alert :as tools.create-alert]- [metabase.metabot.tools.shared :as shared][metabase.metabot.tools.util :as metabot.tools.u][metabase.pulse.api :as pulse.api][metabase.util.log :as log]@@ -78,51 +76,6 @@(-> (metabot.tools.u/handle-agent-error e)(set/rename-keys {:output :error}))))))-(def ^:private create-dashboard-subscription-system-instructions- "## Dashboard Subscriptions--You can create dashboard subscriptions that deliver dashboard contents to the user's current slack channel on a-recurring schedule.--### CRITICAL: You MUST call the create_dashboard_subscription tool--When a user asks to subscribe to a dashboard, set up scheduled delivery, or receive regular updates for a dashboard,-you MUST call the create_dashboard_subscription tool. Never tell the user you have created a subscription without-actually calling the tool. If you cannot call the tool (e.g. missing required information), explain what is needed-instead of pretending the subscription was created.--### Required information--Before calling the tool, ensure you have ALL of the following:-1. **Dashboard ID** — obtained from a prior search result or conversation context-2. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields--If any required information is missing, ask the user for it rather than assuming or fabricating values.")--(mu/defn ^{:tool-name "create_dashboard_subscription"- :scope scope/agent-dashboard-subscribe- :system-instructions create-dashboard-subscription-system-instructions}- slackbot-create-dashboard-subscription-tool- "Create a recurring subscription that delivers a dashboard's contents to a Slack channel."- [{:keys [dashboard_id schedule]} :- [:map {:closed true}- [:dashboard_id :int]- [:schedule tools.create-alert/schedule-schema]]]- (let [slack-channel-id (:slack_channel_id (shared/current-context))]- (when-not slack-channel-id- (throw (ex-info "This tool can only be used from a Slack channel"- {:agent-error? true})))- (try- (let [result (create-dashboard-subscription- {:dashboard-id dashboard_id- :schedule schedule- :slack-channel slack-channel-id})]- (if (:error result)- {:output (:error result)}- {:output (or (:output result) "Dashboard subscription created successfully.")}))- (catch Exception e- (log/errorf "Failed to create dashboard subscription: %s" (ex-message e))- {:output (str "Failed to create dashboard subscription: " (or (ex-message e) "Unknown error"))}))))-(def ^:private subscription-schema[:map {:closed true}[:dashboard_id :int]@@ -137,14 +90,15 @@ If any required information is missing, ask the user for it rather than assuming(mu/defn ^{:tool-name "create_dashboard_subscription":scope scope/agent-dashboard-subscribe}create-dashboard-subscription-tool- "Create a dashboard subscription to send regular updates via email or Slack.+ "Create a dashboard subscription that sends regular updates to a Slack channel.Use when a user wants to receive or send regular updates on a dashboard's contents.- Requires a valid dashboard ID, either an email address or a Slack channel name, and a schedule.+ Requires a valid `dashboard_id`, a `slack_channel` name, and a `schedule`.- Do NOT infer email addresses from usernames or other information.- If the email address is incomplete or missing a part like the TLD,- ask the user for clarification before proceeding."+ Delivery is Slack-only: the `email` argument is not implemented and is ignored, and Slack must+ be connected in Metabase settings. A call without `slack_channel` fails, so if the user asks to+ be emailed a dashboard, tell them this tool can only deliver to Slack rather than accepting an+ email address."[{:keys [dashboard_id email slack_channel schedule]} :- subscription-schema](try(create-dashboard-subscriptiondiff --git a/src/metabase/metabot/tools/transforms.clj b/src/metabase/metabot/tools/transforms.cljindex 6157715a352..46e3cece9fe 100644--- a/src/metabase/metabot/tools/transforms.clj+++ b/src/metabase/metabot/tools/transforms.clj@@ -181,7 +181,7 @@For edit mode, provide edits as an array of {old_string, new_string, replace_all} objects.For replace mode, provide new_content with the complete SQL."[{:keys [transform_id edit_action thinking transform_name transform_description- database_id source_tables]}+ database_id]}:- write-transform-sql-schema](try(let [result (add-output@@ -192,7 +192,6 @@:transform_name transform_name:transform_description transform_description:database_id database_id- :source_tables source_tables:memory-atom shared/*memory-atom*:context (shared/current-context)})format-transform-write-output)@@ -265,7 +264,7 @@"The table_id values MUST be IDs of database tables. You CAN NOT use metabase model IDs. ""You MUST provide this argument when modifying the source tables of an existing transform ""or when creating a new transform. DO NOT guess or make up table IDs, use the "- "search_tables tool to find the correct table IDs first.")}+ "`search` tool to find the correct table IDs first.")}[:sequential[:map[:alias :string]diff --git a/src/metabase/metabot/tools/transforms/write.clj b/src/metabase/metabot/tools/transforms/write.cljindex 34097ca29e4..4c3781f07b6 100644--- a/src/metabase/metabot/tools/transforms/write.clj+++ b/src/metabase/metabot/tools/transforms/write.clj@@ -104,7 +104,6 @@ def transform():- transform-name: Name for new transform (required if no transform-id)- transform-description: Description for new transform- source-database: Database ID for source tables- - source-tables: Map of table aliases to table IDs- memory-atom: Atom containing agent memory (injected by wrapper)- context: Request context with current transform if editing@@ -112,7 +111,7 @@ def transform():- :structured-output - The suggested transform- :data-parts - Transform suggestion data part for streaming"[{:keys [transform_id edit_action thinking transform_name transform_description- database_id source_tables memory-atom context]}]+ database_id memory-atom context]}](log/info "Writing SQL transform" {:transform-id transform_id:edit-mode (:mode edit_action):has-context (some? context)})@@ -129,8 +128,10 @@ def transform():;; Create fresh transform:else+ ;; SQL sources have no source-tables; the `:sql` branch of+ ;; `source-for-transform-type` ignores the argument.(create-fresh-transform :sql transform_name transform_description- database_id source_tables))+ database_id nil))_ (when (and transform_id (nil? current-transform))(throw (ex-info (str "Transform with ID " transform_id " not found. "diff --git a/test/metabase/metabot/agent/prompt_gating_test.clj b/test/metabase/metabot/agent/prompt_gating_test.cljindex 727ca4146f2..56475445a65 100644--- a/test/metabase/metabot/agent/prompt_gating_test.clj+++ b/test/metabase/metabot/agent/prompt_gating_test.clj@@ -111,7 +111,7 @@(is (re-find #"Communicating with the user" without-queries))(is (re-find #"Finding data" without-queries)))(testing "explicit denial for query tools is included"- (is (re-find #"You cannot build queries or create charts" without-queries)))+ (is (re-find #"You cannot build queries" without-queries)))(testing "no individual SQL/NLQ denials when both are off"(is (not (re-find #"You cannot write SQL" without-queries)))(is (not (re-find #"You cannot use natural language querying" without-queries))))))@@ -127,7 +127,7 @@(is (not (re-find #"X-ray auto-generated dashboards" rendered)))(is (not (re-find #"# Writing SQL" rendered))))(testing "denial messages are present"- (is (re-find #"You cannot build queries or create charts" rendered))+ (is (re-find #"You cannot build queries" rendered))(is (re-find #"You cannot create dashboards or documents" rendered)))))(deftest ^:parallel defaults-to-no-permissions-when-unbound-test@@ -136,7 +136,7 @@(is (not (re-find #"MBQL shape rules" rendered)))(is (not (re-find #"Natural-language querying is your default" rendered)))(is (not (re-find #"X-ray auto-generated dashboards" rendered)))- (is (re-find #"You cannot build queries or create charts" rendered))+ (is (re-find #"You cannot build queries" rendered))(is (re-find #"You cannot create dashboards or documents" rendered)))))(deftest ^:parallel prompt-no-denials-when-all-enabled-test@@ -186,12 +186,15 @@:permission/metabot-other-tools :no})](testing "other-tools sections included when permitted"(is (re-find #"static_viz" with-other))- (is (re-find #"Visualization Titles" with-other))+ (is (re-find #"Saved questions and metrics" with-other))(is (re-find #"Visual Previews" with-other)))(testing "other-tools sections excluded when not permitted"(is (not (re-find #"static_viz" without-other)))- (is (not (re-find #"Visualization Titles" without-other)))+ (is (not (re-find #"Saved questions and metrics" without-other)))(is (not (re-find #"Visual Previews" without-other))))+ (testing "visualization titles heading still covers nlq ad-hoc queries when other-tools is off"+ (is (re-find #"Visualization Titles" without-other))+ (is (re-find #"Ad-hoc queries" without-other)))(testing "other-tools denial message present when not permitted"(is (re-find #"You cannot create inline visualizations" without-other)))))diff --git a/test/metabase/metabot/agent/prompts_test.clj b/test/metabase/metabot/agent/prompts_test.cljindex e09ee000797..a04ebec56ba 100644--- a/test/metabase/metabot/agent/prompts_test.clj+++ b/test/metabase/metabot/agent/prompts_test.clj@@ -129,7 +129,7 @@content (prompts/build-system-message-content profile context tools [])](is (some? content))(is (string? content))- (is (str/includes? content "{{#model_id-short-slug}}"))+ (is (str/includes? content "{{#model_id}}"))(is (str/includes? content "{{#5-user-details}}"))(is (str/includes? content "{{snippet: Snippet Name}}"))(is (str/includes? content "{{snippet: recent orders}}"))@@ -192,3 +192,21 @@(is (string? content))(is (not (str/includes? content "{% include"))"unresolved {% include %} tags mean rendering failed and the raw template was returned"))))++(deftest ^:parallel build-system-message-content-test-9+ (testing "renders sql querying template with literal model syntax"+ (let [profile {:prompt-template "sql-querying-only.selmer"}+ context {:current_time "2024-01-15 14:30:00"+ :sql-dialect "postgresql"}+ tools {}+ content (prompts/build-system-message-content profile context tools [])]+ (is (some? content))+ (is (string? content))+ (is (str/includes? content "SELECT * FROM {{#model_id}} AS model_alias"))+ (is (str/includes? content "SELECT * FROM {{#5}} AS model_alias"))+ (is (str/includes? content "FROM {{#5}} a"))+ (is (str/includes? content "LEFT JOIN {{#7}} b ON a.customer_id = b.customer_id"))+ (is (str/includes? content "queried with {{#id}} syntax"))+ (is (not (str/includes? content "{%raw%}")))+ (is (not (str/includes? content "{% safe %}")))+ (is (not (str/includes? content "verbatim"))))))diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.cljindex 8e9e60325e6..8a77029a387 100644--- a/test/metabase/metabot/tools/resources_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -1259,6 +1259,19 @@(is (str/includes? output "truncated=\"true\""))(is (str/includes? output "?page=2") "truncation note should hint at next page URI"))))))+(deftest pagination-next-page-uri-replaces-existing-page-param-test+ (testing "a next-page-uri built from an already-paged request replaces, not duplicates, the page param"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Database {db-id :id} {}]+ (doseq [i (range 1 31)]+ (t2/insert! :model/Table {:name (format "TBL-%03d" i)+ :db_id db-id+ :active true}))+ (let [{:keys [output]} (read-resource/read-resource+ {:uris [(str "metabase://database/" db-id "/tables?page=1")]})]+ (is (str/includes? output (str "metabase://database/" db-id "/tables?page=2")))+ (is (not (str/includes? output "page=1&page=2"))))))))+;; ===== Collection tree ordering =====(deftest collections-tree-ordering-test