Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

nudge for mbql, fix pagination (#82391)

Aleksandr Lesnenkoa6ce02d1c608
diff --git a/resources/mcp/v2/skills/query-dialect/SKILL.md b/resources/mcp/v2/skills/query-dialect/SKILL.md
index d46243e98c7..9e530db29a3 100644
--- a/resources/mcp/v2/skills/query-dialect/SKILL.md
+++ b/resources/mcp/v2/skills/query-dialect/SKILL.md
@@ -5,7 +5,12 @@ description: The query dialect execute_query and question_write's `query` accept
# The query dialect
-**MBQL or SQL?** MBQL (`execute_query`) for anything that will sit on a filtered dashboard, anything with a date/category/FK filter, every plain aggregate, breakout, or join — MBQL cards wire to dashboard filters as-is; a raw-SQL card must be rewritten with template tags first. SQL (`execute_sql`) for window functions, CTEs, set operations, engine-specific functions, or when the user asks for SQL. Unsure: start in MBQL — the server validates it and names what didn't resolve.
+**MBQL or SQL?** MBQL (`execute_query`) is the default for everything it can express (`execute_query`'s description lists the operations) and for anything that will sit on a filtered dashboard — an MBQL card wires to dashboard filters as-is; a raw-SQL card must be rewritten with template tags first. SQL (`execute_sql`) is warranted only for window functions, CTEs, set operations, engine-specific functions, an explicit request for SQL, or a structured attempt rejected for a reason you can't fix. Unsure: start in MBQL — the server validates it and names what didn't resolve. A whole-table count needs no field ids at all, just the table id from `list_tables` or `search`:
+
+```json
+{"lib/type": "mbql/query",
+ "stages": [{"lib/type": "mbql.stage/mbql", "source-table": 5, "aggregation": [["count", {}]]}]}
+```
Everything — tables, columns, saved questions, models, metrics, measures, segments — is named by **numeric id**, copied from `browse_data` (`list_tables`, `get_fields`), `search`, or `get_content`; never invented. A wrong name errors loudly; a wrong id that exists resolves to the wrong column *silently*. `get_content`'s `definition` include returns this same shape, so a read definition can be edited and sent back.
@@ -27,6 +32,19 @@ Loop: author → `execute_query` `validate_only: true` (shape + ids, mints a `qu
- First stage only: `source-table` (table id) **or** `source-card` (card id), exactly one; later stages read the previous stage's output.
- Optional stage keys: `filters`, `aggregation`, `breakout`, `expressions`, `fields`, `joins`, `order-by`, `limit`.
+## Limit and paging
+
+`limit: N` on a stage bounds the whole result to its first N rows in `order-by` order. `execute_query`'s `row_limit` is the page size (default 100), not a bound: a truncated page carries `next_cursor`, and each `cursor` call serves the next page until `truncated` is false. A limited query spends its limit down across pages, so its last page arrives `truncated: false` with no `next_cursor` — pagination ends by itself. "The first 400 charges by id" is therefore `order-by` + `limit: 400`, paged at the default size, never an unbounded query stopped after four pages by hand:
+
+```json
+{"lib/type": "mbql/query",
+ "stages": [{"lib/type": "mbql.stage/mbql",
+ "source-table": 30,
+ "fields": [["field", {}, 2751]],
+ "order-by": [["asc", {}, ["field", {}, 2751]]],
+ "limit": 400}]}
+```
+
## Two rules
1. **Every clause is `["op", {}, ...args]`** — options map at position 1 even when empty: `["count", {}]`, never `["count"]`. (Repaired server-side, but write it so your query matches later reads.) Never put a stage key (`aggregation`, `filters`, …) at a clause head — clauses go inside those arrays.
@@ -124,6 +142,7 @@ A metric's or measure's output column is named for the aggregation inside its de
## Translating the request
- "only / where / for X" is a **filter**; "by / per / for each / over time" is a **breakout**.
+- "first / top / latest N" is `order-by` + `limit: N` in the stage (see Limit and paging).
- Apply every stated constraint; add no analysis the user didn't ask for.
## Don't
@@ -133,3 +152,4 @@ A metric's or measure's output column is named for the aggregation inside its de
- Don't omit the `{}` options slot — the server repairs it, so your query stops matching later reads.
- Don't reference a previous stage's column by display label ("Max of Total") — machine name only.
- Don't turn "only / where X" into a breakout, or drop a stated constraint once the aggregation is in place.
+- Don't stop paging while `truncated` is true — follow `next_cursor`, or bound the result with a stage `limit: N`.
diff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.md
index 0c5b2296f5b..078b5f097b2 100644
--- a/src/metabase/mcp/README.md
+++ b/src/metabase/mcp/README.md
@@ -85,8 +85,8 @@ token missing it neither sees the tool in `tools/list` nor may call it.
| `dashboard_write` | `agent:content:write` | Create or update a dashboard and edit its layout with ordered ops. |
| `document_write` | `agent:content:write` | Create or update a document. |
| `duplicate_content` | `agent:content:write` | Copy a question, dashboard, or document into a collection — cheaper and safer than reading the original and re-creating it, and it preserves everything the read projections leave out. |
-| `execute_query` | `agent:query:run` | Validate and execute a query, returning rows plus a query_handle. |
-| `execute_sql` | `agent:sql:run` | Execute a raw SQL string against a database, returning rows plus a query_handle. |
+| `execute_query` | `agent:query:run` | The default way to answer a question from data: validate and execute a structured (MBQL) query over a table, model, metric, or saved question, returning rows plus a query_handle. |
+| `execute_sql` | `agent:sql:run` | Escape hatch: execute a raw SQL string against a database, returning rows plus a query_handle. |
| `get_content` | `agent:content:read` | Fetch content by {type, id} — the typed read for anything found via search or browse_collection. |
| `get_parameter_values` | `agent:content:read` | Fetch the valid values for one filter on a dashboard or saved question, so you filter with real values instead of guessing. |
| `learn` | `agent:content:read` | Read this server's task docs (skills) for the write dialects the schemas can't fully describe. |
@@ -102,8 +102,11 @@ token missing it neither sees the tool in `tools/list` nor may call it.
| `transform_write` | `agent:content:write` | Create or update a transform: a saved query that Metabase runs to materialize its results into a real table in your warehouse, which questions and other transforms can then query. |
| `visualize_query` | `agent:query:run` | Visualize a query as an interactive chart or table, rendered inline in the conversation. |
-Query results are limited to 200 rows per request. When more rows are available, the response includes a
-`continuation_token` that can be passed back to fetch the next page.
+`execute_query` returns `row_limit` rows per call (default 100, max 2000) — a page size, not a bound on the result.
+A truncated page reports `truncated: true` and, when the query has a total order, a `next_cursor` to pass back as
+`cursor` for the next page, until a page arrives with `truncated: false`. A query that wants only its first N rows
+carries `limit: N` in its stage (with an `order-by`); the server spends that limit down across pages, so the last
+page comes back complete with no cursor and pagination ends by itself.
## Resources
diff --git a/src/metabase/mcp/v2/api.clj b/src/metabase/mcp/v2/api.clj
index 2bc29dc76e6..433acbd5b99 100644
--- a/src/metabase/mcp/v2/api.clj
+++ b/src/metabase/mcp/v2/api.clj
@@ -117,10 +117,13 @@
(def ^:private server-instructions
"The `initialize` result's `instructions` — the only channel that reaches the model before any tool call, so it points
- at the `learn` skills once, in three lines."
+ at the `learn` skills once and, in one sentence, settles the routing choice a model makes before reading any
+ tool description closely: structured queries are the default, raw SQL the escape hatch."
(str "This server ships task-shaped docs as skills. learn() lists the topics; learn(topic) returns one.\n"
- "Before your first complex write — native template_tags, dashboard parameter wiring, an MBQL query, "
- "visualization settings — read the matching skill unless it is already in context.\n"
+ "Before your first complex write — native template_tags, dashboard parameter wiring, a multi-stage or joined "
+ "query, visualization settings — read the matching skill unless it is already in context.\n"
+ "Answer questions from data with execute_query (structured MBQL) by default; execute_sql is the escape hatch "
+ "for what MBQL cannot express or an explicit request for SQL.\n"
"Teaching errors embed the relevant contract, so a failed call always names its fix."))
(def ^:private default-ask-scopes
diff --git a/src/metabase/mcp/v2/skills.clj b/src/metabase/mcp/v2/skills.clj
index 97031518c1c..10c422fb3a2 100644
--- a/src/metabase/mcp/v2/skills.clj
+++ b/src/metabase/mcp/v2/skills.clj
@@ -34,7 +34,7 @@
"The pack catalog, in the order `learn()` lists it. `:description` doubles as the catalog line
and must say when to read the pack, not just what it is."
[{:name "query-dialect"
- :description "The query dialect for execute_query and question_write's `query`: numeric-id refs, clause grammar, joins, expressions, multi-stage queries. Read before any non-trivial query. Reference `operators`: every filter/aggregation/expression operator."
+ :description "The query dialect for execute_query (the default route) and question_write's `query`: numeric-id refs, clause grammar, joins, expressions, multi-stage queries, limit vs paging, when SQL is warranted. Read before any non-trivial query. Reference `operators`: every filter/aggregation/expression operator."
:references ["operators"]}
{:name "native-parameters"
:description "Template tags for native SQL (question_write's `native`): tag kinds, field filter vs raw variable, the template_tags shape, widget types, [[ ]] optional blocks. Read before first passing template_tags."
diff --git a/src/metabase/mcp/v2/tools/query.clj b/src/metabase/mcp/v2/tools/query.clj
index 88ab5504f88..ac0e7d723c4 100644
--- a/src/metabase/mcp/v2/tools/query.clj
+++ b/src/metabase/mcp/v2/tools/query.clj
@@ -201,7 +201,12 @@
(defn- steering-line
[returned next-cursor]
(if next-cursor
- (format "returned %d rows, more available — continue with `cursor`, or narrow the query (filter/aggregate)"
+ ;; Names both ways a chain ends. An agent asked for "the first N rows" that only ever sees
+ ;; "continue with `cursor`" counts pages by hand and stops with a live cursor in an unbounded
+ ;; query; a stage `limit` makes the last page arrive complete instead.
+ (format (str "returned %d rows, more available — continue with `cursor` until `truncated` is false, "
+ "re-run with a stage `limit: N` (with `order-by`) if only the first N rows are needed, "
+ "or narrow the query (filter/aggregate)")
returned)
(format "returned %d rows, more available — narrow the query (filter/aggregate), or raise `row_limit` (max %d)"
returned max-row-limit)))
@@ -258,7 +263,7 @@
(def ^:private execute-query-args-schema
[:map {:closed true}
[:query {:optional true}
- [:maybe [:map {:description "A fresh query (see the tool description): numeric table/field ids from browse_data, never base64. Exactly one of query | query_handle | cursor."}]]]
+ [:maybe [:map {:description "A fresh structured query (shape and examples in the tool description): numeric table/field ids from browse_data, never base64, never SQL. Exactly one of query | query_handle | cursor."}]]]
[:query_handle {:optional true}
[:maybe [:string {:min 1 :description "A query_handle from a previous call — re-validates and re-runs the exact stored query. Exactly one of query | query_handle | cursor."}]]]
[:cursor {:optional true}
@@ -268,12 +273,12 @@
[:validate_only {:optional true}
[:maybe [:boolean {:description "true validates against schema + database metadata and mints a query_handle without executing (default false)."}]]]
[:row_limit {:optional true}
- [:maybe [:int {:min 1 :max max-row-limit :description "Maximum rows to return in this call (default 100, max 2000)."}]]]])
+ [:maybe [:int {:min 1 :max max-row-limit :description "Maximum rows to return in this call (default 100, max 2000) — the page size, not a bound on the result; the bound is limit: N in the query's stage."}]]]])
(registry/deftool execute-query
- "Validate and execute a query, returning rows plus a query_handle. Pass exactly one of: query (a fresh query in the dialect below), query_handle (re-run a stored query), or cursor (continue a truncated result). Every call returns a query_handle — it holds the query that ran without the cursor's paging position, so saving or visualizing from any page gives the whole question rather than that one page. validate_only: true checks against schema + database metadata and mints a handle without executing. Results are cols + rows with returned/truncated counts; on next_cursor, call again with cursor (row_limit alongside keeps the page size), otherwise narrow the query (filter/aggregate) or raise row_limit (max 2000).
+ "The default way to answer a question from data: validate and execute a structured (MBQL) query over a table, model, metric, or saved question, returning rows plus a query_handle. Use it first for any count, sum, average, group-by, filter, sort, or join — including one-liners like \"how many X do we have\" — and fall back to execute_sql only for what MBQL cannot express (window functions, CTEs, set operations, engine-specific functions), an explicit request for SQL, or a structured attempt rejected for a reason you cannot fix. Only this route validates against database metadata and names what did not resolve, pages with a cursor, and saves as a question that wires to dashboard filters as-is — so any card bound for a filtered dashboard starts here; a raw-SQL card needs template tags first. Pass exactly one of: query (a fresh query in the dialect below), query_handle (re-run a stored query), or cursor (continue a truncated result). Every call returns a query_handle — it holds the query that ran without the cursor's paging position, so saving or visualizing from any page gives the whole question rather than that one page. validate_only: true checks against schema + database metadata and mints a handle without executing. Results are cols + rows with returned/truncated counts; on next_cursor, call again with cursor (row_limit alongside keeps the page size) until truncated is false, otherwise narrow the query (filter/aggregate) or raise row_limit (max 2000). row_limit is the page size, not the bound on the result: \"the first N / top N rows\" is a stage limit: N with an order-by (example below), served row_limit rows per call, whose last page arrives truncated: false with no next_cursor — never count pages by hand to stop at N.
-Dialect (JSON): tables and columns go by NUMERIC ID — discover ids first (browse_data get_fields lists every column's id) — never invent or guess ids, never base64. Top level: {\"lib/type\": \"mbql/query\", \"stages\": [...]}; each stage \"lib/type\": \"mbql.stage/mbql\" plus source-table: <numeric table id> or source-card: <numeric card id> on the FIRST stage only — later stages read the previous stage's output. Every clause is [\"op\", {}, ...args], options map mandatory at position 1. Field refs: [\"field\", {}, <numeric field id>], or a bare column-name string against a previous stage ([\"field\", {}, \"count\"]). Stage keys: filters, aggregation, breakout, expressions, fields, joins, order-by, limit. Simplest aggregate (row count of one table): {\"lib/type\": \"mbql/query\", \"stages\": [{\"lib/type\": \"mbql.stage/mbql\", \"source-table\": <TABLE_ID>, \"aggregation\": [[\"count\", {}]]}]}. Example (row count by month): {\"lib/type\": \"mbql/query\", \"stages\": [{\"lib/type\": \"mbql.stage/mbql\", \"source-table\": <TABLE_ID>, \"aggregation\": [[\"count\", {}]], \"breakout\": [[\"field\", {\"temporal-unit\": \"month\"}, <FIELD_ID>]]}]}. <TABLE_ID> and <FIELD_ID> are placeholders — ids differ per instance, so resolve yours with browse_data before calling. get_content's definition include returns queries in this same shape, so an edited definition can be sent back as-is. Call learn(\"query-dialect\") before authoring a non-trivial query (joins, expressions, multi-stage); learn(\"query-dialect\", \"operators\") lists every operator. Use this, not execute_sql, for any card bound for a filtered dashboard — MBQL cards wire to dashboard filters as-is, raw-SQL cards need template tags first. Native SQL is rejected at any depth — use execute_sql."
+Dialect (JSON): tables and columns go by NUMERIC ID — never invent or guess ids, never base64, never a schema-qualified name. A bare row count needs only the table id browse_data list_tables (or search) already returned; browse_data get_fields gives field ids when the query filters, groups, or aggregates over a column. Top level: {\"lib/type\": \"mbql/query\", \"stages\": [...]}; each stage \"lib/type\": \"mbql.stage/mbql\" plus source-table: <numeric table id> or source-card: <numeric card id> on the FIRST stage only — later stages read the previous stage's output. Every clause is [\"op\", {}, ...args], options map mandatory at position 1. Field refs: [\"field\", {}, <numeric field id>], or a bare column-name string against a previous stage ([\"field\", {}, \"count\"]). Stage keys: filters, aggregation, breakout, expressions, fields, joins, order-by, limit. Simplest aggregate (row count of one table — the whole query for \"how many rows\"): {\"lib/type\": \"mbql/query\", \"stages\": [{\"lib/type\": \"mbql.stage/mbql\", \"source-table\": <TABLE_ID>, \"aggregation\": [[\"count\", {}]]}]}. Example (row count by month): {\"lib/type\": \"mbql/query\", \"stages\": [{\"lib/type\": \"mbql.stage/mbql\", \"source-table\": <TABLE_ID>, \"aggregation\": [[\"count\", {}]], \"breakout\": [[\"field\", {\"temporal-unit\": \"month\"}, <FIELD_ID>]]}]}. First N rows (e.g. the first 400 ids, ascending) is a stage with only \"source-table\", \"fields\": [[\"field\", {}, <FIELD_ID>]], \"order-by\": [[\"asc\", {}, [\"field\", {}, <FIELD_ID>]]], \"limit\": 400. <TABLE_ID> and <FIELD_ID> are placeholders — ids differ per instance, so resolve yours with browse_data before calling. get_content's definition include returns queries in this same shape, so an edited definition can be sent back as-is. Call learn(\"query-dialect\") before authoring a non-trivial query (joins, expressions, multi-stage); learn(\"query-dialect\", \"operators\") lists every operator. Native SQL is rejected at any depth — it belongs in execute_sql."
{:name "execute_query"
:scope metabot.scope/agent-query-run
:annotations {:readOnlyHint true}
@@ -373,12 +378,13 @@ Dialect (JSON): tables and columns go by NUMERIC ID — discover ids first (brow
returned max-row-limit))
(def ^:private mbql-hint
- "Carried as `hint` by an `execute_sql` response whose SQL [[mbql-expressible-sql?]]. A raw-SQL card
- can't take dashboard filters until rewritten with template tags, so the steer toward MBQL is
- cheapest before the card exists."
- (str "This query can be expressed in MBQL; MBQL cards accept dashboard filters without changes. "
- "If the card will go on a filtered dashboard, build it with execute_query instead "
- "(learn(\"query-dialect\"))."))
+ "Carried as `hint` by an `execute_sql` response whose SQL [[mbql-expressible-sql?]]. The steer
+ back to the structured route is cheapest right after the SQL ran: the agent has the answer in
+ hand, so the hint costs it nothing now and shapes the next question. A raw-SQL card also can't
+ take dashboard filters until rewritten with template tags, so the steer lands before any card
+ exists."
+ (str "This query is expressible in MBQL: use execute_query, the default route, for questions like this one — "
+ "its cards accept dashboard filters without changes (learn(\"query-dialect\"))."))
(defn- strip-sql-noise
"Lower-cased `sql` with string literals, double-quoted identifiers, and comments blanked, so the
@@ -399,16 +405,18 @@ Dialect (JSON): tables and columns go by NUMERIC ID — discover ids first (brow
u/lower-case-en))
(defn- mbql-expressible-sql?
- "Whether `sql` is a plain `SELECT … GROUP BY` aggregate MBQL expresses directly: one SELECT
- statement with a GROUP BY and none of CTEs, window functions, set operations, subselects, or
- `{{tag}}` placeholders (a tagged query is no longer the same query in MBQL). A conservative regex
- heuristic, not a parse: a false negative costs one missed hint, a false positive would steer the
- caller to rewrite SQL that MBQL cannot express."
+ "Whether `sql` is a plain aggregate MBQL expresses directly: one SELECT statement that either
+ GROUPs BY or opens its select list with an aggregate function (`SELECT count(*) FROM …`, the
+ whole-table count an agent reaches for on \"how many X\"), and none of CTEs, window functions,
+ set operations, subselects, or `{{tag}}` placeholders (a tagged query is no longer the same
+ query in MBQL). A conservative regex heuristic, not a parse: a false negative costs one missed
+ hint, a false positive would steer the caller to rewrite SQL that MBQL cannot express."
[sql]
(let [s (-> (strip-sql-noise sql) str/trim (str/replace #";\s*$" ""))]
(boolean
(and (re-find #"^select\b" s)
- (re-find #"\bgroup\s+by\b" s)
+ (or (re-find #"\bgroup\s+by\b" s)
+ (re-find #"^select\s+(?:distinct\s+)?(?:count|sum|avg|min|max)\s*\(" s))
(not (str/includes? s ";"))
(not (str/includes? s "{{"))
(not (re-find #"\bwith\b" s))
@@ -463,7 +471,7 @@ Dialect (JSON): tables and columns go by NUMERIC ID — discover ids first (brow
[:maybe [:int {:min 1 :max max-row-limit :description "Maximum rows to return in this call (default 100, max 2000)."}]]]])
(registry/deftool execute-sql
- "Execute a raw SQL string against a database, returning rows plus a query_handle. Requires native-query permission on the database and the instance-level mcp-execute-sql-enabled setting — both enforced even with validate_only: true. Prefer execute_query for anything MBQL can express — a card saved from raw SQL cannot be filtered on a dashboard until rewritten with template tags, so a card bound for a filtered dashboard should be MBQL. The sql runs verbatim against the warehouse, so it is the injection surface — never splice caller- or user-supplied values into it; put values behind {{tag}} placeholders bound via template_tag_values, driver-level prepared-statement parameters that are injection-safe for the values. {{snippet: …}} and {{#123}} card-reference tags splice server-side SQL text and can never be populated through template_tag_values. validate_only: true mints a query_handle without executing (tags and permissions checked; the SQL text itself is not) — stage SQL for saving or visualizing without pulling rows into context. The query_handle is accepted by question_write; execute_query is MBQL-only and rejects it. Results are cols + rows with returned/truncated counts. No cursor pagination: the server cannot know whether arbitrary SQL has a total order, so page it yourself — ORDER BY a unique key plus WHERE <key> > <last value returned>, which is exact where an offset would silently repeat or skip rows. Otherwise narrow the SQL (filters/aggregation) or raise row_limit (max 2000)."
+ "Escape hatch for execute_query, the default for every question MBQL can express (see its description): execute a raw SQL string against a database, returning rows plus a query_handle. Use only for what MBQL cannot express (window functions, CTEs, set operations, engine-specific functions), an explicit request for SQL, or a structured attempt rejected for a reason you cannot fix. Raw SQL is checked only by the warehouse (no metadata validation, no teaching errors naming what is wrong), and a card saved from it cannot be filtered on a dashboard until rewritten with template tags. Requires native-query permission on the database and the instance-level mcp-execute-sql-enabled setting — both enforced even with validate_only: true. The sql runs verbatim against the warehouse, so it is the injection surface — never splice caller- or user-supplied values into it; put values behind {{tag}} placeholders bound via template_tag_values, driver-level prepared-statement parameters that are injection-safe for the values. {{snippet: …}} and {{#123}} card-reference tags splice server-side SQL text and can never be populated through template_tag_values. validate_only: true mints a query_handle without executing (tags and permissions checked; the SQL text itself is not) — stage SQL for saving or visualizing without pulling rows into context. The query_handle is accepted by question_write; execute_query is MBQL-only and rejects it. Results are cols + rows with returned/truncated counts. No cursor pagination: the server cannot know whether arbitrary SQL has a total order, so page it yourself — ORDER BY a unique key plus WHERE <key> > <last value returned>, which is exact where an offset would silently repeat or skip rows. Otherwise narrow the SQL (filters/aggregation) or raise row_limit (max 2000)."
{:name "execute_sql"
:scope metabot.scope/agent-sql-run
;; Unlike execute_query, arbitrary SQL can write. These match MCP's defaults for an unannotated
diff --git a/test/metabase/mcp/v2/tools/execute_sql_test.clj b/test/metabase/mcp/v2/tools/execute_sql_test.clj
index 4a6bbc2232d..9149d55d165 100644
--- a/test/metabase/mcp/v2/tools/execute_sql_test.clj
+++ b/test/metabase/mcp/v2/tools/execute_sql_test.clj
@@ -297,11 +297,16 @@
(is (true? (expressible? "SELECT status, count(*) FROM orders GROUP BY status")))
(is (true? (expressible? (str "select o.status, count(*) from orders o join products p on p.id = o.product_id "
"where o.total > 10 group by o.status having count(*) > 5 order by 2 desc limit 10;")))))
+ (testing "a whole-table aggregate with no GROUP BY — the SQL an agent reaches for on \"how many X\" — is expressible"
+ (is (true? (expressible? "SELECT COUNT(*) AS total_expense_reports FROM brex_enriched.int_brex_expense_facts")))
+ (is (true? (expressible? "select sum(total) from orders where total > 10")))
+ (is (true? (expressible? "SELECT DISTINCT count(*) FROM orders"))))
(testing "keywords inside string literals and comments do not disqualify"
(is (true? (expressible? "SELECT status, count(*) FROM orders WHERE note = 'with over (' GROUP BY status")))
(is (true? (expressible? "-- with\nSELECT status, count(*) FROM orders /* over ( */ GROUP BY status"))))
- (testing "no GROUP BY, CTEs, window functions, set ops, subselects, template tags, and multiple statements are not"
+ (testing "a bare projection with no GROUP BY, CTEs, window functions, set ops, subselects, template tags, and multiple statements are not"
(is (false? (expressible? "SELECT id FROM orders ORDER BY id")))
+ (is (false? (expressible? "SELECT id, count_of_things FROM orders")))
(is (false? (expressible? "WITH t AS (SELECT status FROM orders) SELECT status, count(*) FROM t GROUP BY status")))
(is (false? (expressible? "SELECT status, count(*) OVER () FROM orders GROUP BY status")))
(is (false? (expressible? "SELECT status, count(*) FROM orders GROUP BY status UNION SELECT 'x', 0")))
diff --git a/test/metabase/mcp/v2/tools/query_test.clj b/test/metabase/mcp/v2/tools/query_test.clj
index ad0b3beafcf..8c2ecf2dc71 100644
--- a/test/metabase/mcp/v2/tools/query_test.clj
+++ b/test/metabase/mcp/v2/tools/query_test.clj
@@ -249,6 +249,42 @@
(is (= (count ids) (count (distinct ids))))
(is (apply < ids))))))))
+;; not ^:parallel: mt/with-model-cleanup on the shared query-handle table
+(deftest limited-query-ends-its-own-cursor-chain-test
+ ;; The shape "the first N rows of X, by id" should run as: a PK-only projection ordered
+ ;; ascending with a stage limit, at a page size that divides it evenly. Every page but the
+ ;; last is truncated with a cursor and steers at both affordances — follow `cursor`, or bound
+ ;; with `limit` — and the last page fills exactly yet arrives complete, with no cursor and no
+ ;; steering, because the limit spent down across the chain leaves nothing for the probe row.
+ ;; An agent that paged the same query unbounded would still hold a live cursor at row N.
+ (mt/with-current-user (mt/user->id :rasta)
+ (mt/with-model-cleanup [:model/McpQueryHandle]
+ (let [sid (str (random-uuid))
+ page-size 5
+ query (orders-query {:fields [(field-name-ref :orders :id)]
+ :order-by [["asc" {} (field-name-ref :orders :id)]]
+ :limit (* 3 page-size)})
+ page1 (call! sid {:query query :row_limit page-size})
+ page2 (call! sid {:cursor (:next_cursor (payload page1)) :row_limit page-size})
+ page3 (call! sid {:cursor (:next_cursor (payload page2)) :row_limit page-size})]
+ (testing "pages before the limit are truncated, carry a cursor, and steer at both `cursor` and `limit`"
+ (doseq [page [page1 page2]
+ :let [body (payload page)]]
+ (is (= page-size (:returned body)))
+ (is (true? (:truncated body)))
+ (is (string? (:next_cursor body)))
+ (is (str/includes? (steering-line page) "continue with `cursor`"))
+ (is (str/includes? (steering-line page) "`limit: N`"))))
+ (testing "the page that exhausts the limit fills exactly and is complete: no cursor, no steering"
+ (let [body (payload page3)]
+ (is (= page-size (:returned body)))
+ (is (false? (:truncated body)))
+ (is (nil? (:next_cursor body)))
+ (is (nil? (steering-line page3)))))
+ (testing "the chain served exactly the first N ids, in order"
+ (is (= (vec (range 1 (inc (* 3 page-size))))
+ (into [] (mapcat (comp row-ids payload)) [page1 page2 page3]))))))))
+
;; not ^:parallel: mt/with-model-cleanup on the shared query-handle table
(deftest exact-fill-is-not-truncated-test
;; Companion to query-limit-bounds-the-cursor-chain-test, which pins the same property when the