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
Support query_handle consistently across MCP tools (#75403)
Chris Truter685421c95afb
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 0cce808823d..ce9b49039f8 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -311,6 +311,19 @@json/encodeu/encode-base64))+(defn- decode-base64-json-map+ "Decode a base64-encoded JSON object to a Clojure map, returning a 400 (not a 500) on malformed input.+ The query_handle and continuation-token payloads are client-reachable, so garbage in must surface as+ a clean 400 rather than a decode exception that bubbles up as a 500."+ [encoded]+ (let [decoded (try+ (-> encoded u/decode-base64 json/decode+kw)+ (catch Exception _ ::invalid))]+ (if (map? decoded)+ decoded+ (throw (ex-info "Invalid request: expected a base64-encoded JSON object."+ {:status-code 400})))))+(defn- decode-continuation-token"Decode a base64-encoded continuation token into {:query ... :pagination ...}.The token is client-supplied, so sanity-check the pagination ints to turn@@ -318,7 +331,7 @@the embedded query happens in [[check-token-query-permissions!]] — a tokendoesn't grant access the bearer wouldn't otherwise have."[token]- (let [decoded (-> token u/decode-base64 json/decode+kw)+ (let [decoded (decode-base64-json-map token){:keys [limit page]} (:pagination decoded)](api/check (and (int? limit) (pos? limit))[400 "Invalid continuation token: limit must be a positive integer"])@@ -326,14 +339,24 @@[400 "Invalid continuation token: page must be a positive integer"])decoded))+(defn- clamp-total-limit+ "Default a missing :limit and cap it at the combined endpoint's hard maximum.+ This is the app-level total-row budget enforced across paginated responses; each page's QP-level+ cap comes from `:page.items`, which `remaining-page-rows` clamps to respect this total."+ [limit]+ (min (or limit default-query-row-limit) max-total-row-limit))+(defn- total-row-limit- "The user's requested :limit, defaulted when absent and capped at the combined- endpoint's hard maximum. This is the app-level total-row budget enforced across- paginated responses; each page's QP-level cap comes from `:page.items`, which- `remaining-page-rows` clamps to respect this total."+ "The user's requested :limit read from a resolved lib query, defaulted and capped."[live-query]- (min (or (lib/current-limit live-query) default-query-row-limit)- max-total-row-limit))+ (clamp-total-limit (lib/current-limit live-query)))++(defn- serialized-query-limit+ "Read the last-stage :limit from a serialized MBQL 5 query map — the `lib/current-limit`+ equivalent for the plain-map form carried by a query_handle (already resolved, so we read it+ off the map rather than rehydrating a live query)."+ [query-map]+ (get-in query-map [:stages (dec (count (:stages query-map))) :limit]))(defn- rows-before-page"Total rows consumed by the pages preceding `page`. Single source of truth for@@ -382,17 +405,78 @@:max-results-bare-rows page-size}))(mr/def ::query-request- "Request body for /v2/query. Accepts either a fresh-query payload (`{:query <external-query>}`,- same shape as /v2/construct-query) or a `:continuation_token` from a prior response.-- Both branches are closed maps: extra top-level keys (e.g. the legacy- `source_entity` / `referenced_entities` envelope, or sending `:query` and- `:continuation_token` simultaneously) are rejected with a 400."+ "Request body for /v2/query, one of three shapes:+ - `{:continuation_token <string>}` from a prior response (pagination);+ - `{:query <base64-string>}` — a query_handle resolved by the MCP layer to its stored base64+ MBQL; already resolved, so it's executed directly (like /v1/execute) rather than re-run+ through the representations pipeline;+ - `{:query <external-query-object>}` — a fresh portable MBQL 5 payload, same shape as+ /v2/construct-query.++ The string-vs-object `:query` distinction is what the `:dispatch` keys on. Each branch is a+ closed map: extra top-level keys (e.g. the legacy `source_entity` / `referenced_entities`+ envelope, or sending `:query` and `:continuation_token` simultaneously) are rejected with a 400."[:multi {:dispatch (fn [m]- (if (:continuation_token m) :continuation :fresh))}+ (cond+ (:continuation_token m) :continuation+ (string? (:query m)) :handle+ :else :fresh))}[:continuation [:map {:closed true} [:continuation_token ms/NonBlankString]]]+ [:handle [:map {:closed true} [:query ms/NonBlankString]]][:fresh ::construct-query-request]])+(defn- native-marker?+ "True if `node` is a map carrying a native-SQL marker: a `:native` query body (the universal signal+ across legacy and MBQL 5 native forms), a legacy `:type :native`, or an MBQL 5 `:mbql.stage/native`+ `:lib/type`. Membership tests cover the keyword and json-decoded string forms and never coerce, so+ junk values don't throw. A legitimate serialized MBQL query carries none of these."+ [node]+ (and (map? node)+ (or (contains? node :native)+ (contains? #{:native "native"} (:type node))+ (contains? #{:mbql.stage/native "mbql.stage/native"} (:lib/type node)))))++(defn- native-query?+ "True if `query-map` (a decoded, client-reachable query) contains native SQL anywhere in its tree —+ legacy top-level `:type :native`, a legacy nested `:source-query`'s `:native`, or an MBQL 5+ `:mbql.stage/native` stage, including inside joins or nested joins.+ A whole-tree scan, because these endpoints are MBQL-only by scope: a native marker at any depth+ means the payload is smuggling raw SQL, regardless of how it's nested."+ [query-map]+ (boolean (some native-marker? (tree-seq coll? seq query-map))))++(defn- reject-native-query!+ "Throw a 400 if `query-map` is a native query.++ `/v2/query` and `/v1/execute` are gated by the MBQL-execution scopes (`agent:query` /+ `agent:query:execute`), not `agent:sql:execute`. The opaque base64 payloads they accept (a+ query_handle, a continuation token) could carry a native query — legacy top-level `:type :native`+ or an MBQL 5 native stage; allowing either would let a token without the SQL-execution scope run+ raw SQL, defeating the scope split and bypassing the execute-sql kill switch. Force native+ execution onto `/v1/execute-sql`, which is correctly scoped."+ [query-map]+ (when (native-query? query-map)+ (throw (ex-info "Native queries are not supported here; use execute_sql instead."+ {:status-code 400 :query-map query-map}))))++(defn- validate-serialized-query!+ "Sanity-check a decoded MBQL query map from a client-reachable base64 payload (query_handle or token).+ Require `:stages` to be a non-empty sequence of maps, and the last-stage `:limit` (if present) an+ integer; otherwise `serialized-query-limit`, `clamp-total-limit`, and `apply-page-to-query` would+ throw on the malformed shape and surface a 500 instead of a clean 400.+ Deep MBQL validation still happens in the QP at execution."+ [query-map]+ (let [stages (:stages query-map)]+ (when-not (and (sequential? stages) (seq stages) (every? map? stages))+ (throw (ex-info "Invalid query: expected a serialized MBQL query with a non-empty :stages of maps."+ {:status-code 400 :query-map query-map})))+ ;; `contains?` (not `when-let`) so an explicit `false`/`nil` limit is caught, not skipped.+ (when (contains? (last stages) :limit)+ (let [limit (:limit (last stages))]+ (when-not (and (int? limit) (pos? limit))+ (throw (ex-info "Invalid query: last-stage :limit must be a positive integer."+ {:status-code 400 :query-map query-map})))))))+(defn- check-token-query-permissions!"Re-validate query permissions on the continuation-token path.@@ -407,16 +491,32 @@(api/query-check :model/Table table-id))))(defn- initial-page-state- "Normalize the two /v2/query entry points into a single {:query :total-limit :page}- shape. A fresh request body is evaluated through the representations pipeline and the- total-row budget is derived from the resolved query's `:limit`; a continuation token- carries that state from a prior response (and re-validates query permissions, since the- token is client-supplied and per-user permissions can change between pages)."+ "Normalize the three /v2/query entry points into a single {:query :total-limit :page} shape.++ - A continuation token carries the query + pagination state from a prior response (and+ re-validates query permissions, since the token is client-supplied and per-user permissions+ can change between pages).+ - A base64 `:query` string is a query_handle the MCP layer already resolved to its stored MBQL;+ it's decoded and executed directly (like /v1/execute), skipping the representations pipeline.+ Permissions are enforced by the QP at execution time, as on /v1/execute.+ - A fresh request body is evaluated through the representations pipeline and the total-row budget+ is derived from the resolved query's `:limit`."[body]- (if-let [token (:continuation_token body)]- (let [{:keys [query pagination]} (decode-continuation-token token)]+ (cond+ (:continuation_token body)+ (let [{:keys [query pagination]} (decode-continuation-token (:continuation_token body))]+ (reject-native-query! query)+ (validate-serialized-query! query)(check-token-query-permissions! query){:query query :total-limit (:limit pagination) :page (:page pagination)})++ (string? (:query body))+ (let [query (decode-base64-json-map (:query body))]+ (reject-native-query! query)+ (validate-serialized-query! query)+ {:query query :total-limit (clamp-total-limit (serialized-query-limit query)) :page 1})++ :else(let [live-query (evaluate-external-query-to-live-query body)]{:query (lib/prepare-for-serialization live-query):total-limit (total-row-limit live-query)@@ -436,10 +536,11 @@:description (str "Execute a Metabase query and return results with column ""metadata. If more rows are available, the response includes a ""continuation_token — pass it back to get the next page.\n\n"- "The body is either `{\"query\": <object>}` (same shape as "- "construct_query; see the `construct_notebook_query` tool for "- "the format reference) or `{\"continuation_token\": \"...\"}` "- "from a previous response.")+ "Provide one of: a `query_handle` returned by construct_query "+ "(preferred when you have one); a `{\"query\": <object>}` body "+ "(same shape as construct_query; see the `construct_notebook_query` "+ "tool for the format reference); or a `{\"continuation_token\": "+ "\"...\"}` from a previous response."):annotations {:read-only? true}}}[_route-params_query-params@@ -518,15 +619,7 @@(let [query (-> encoded-queryu/decode-base64json/decode+kw)]- ;; `/v1/execute` is gated by the `agent:query:execute` scope and is intended for MBQL.- ;; The opaque base64 payload could carry `:type :native`, but `execute_sql` is gated by- ;; a distinct `agent:sql:execute` scope - allowing native here would let a token with- ;; only the broader scope run raw SQL, defeating the scope distinction. Force callers- ;; to use `/v1/execute-sql` (correctly scoped) for native execution. Compare via the- ;; normalized type since the decoded payload may carry the type as a string or keyword.- (when (= :native (some-> query :type keyword))- (throw (ex-info "Native queries are not supported on /v1/execute; use execute_sql instead."- {:status-code 400})))+ (reject-native-query! query)(qp.streaming/streaming-response [rff :api](qp/process-query (prepare-combined-query query) rff))))diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.cljindex 8f5d418f77a..1331d78a3b7 100644--- a/src/metabase/mcp/tools.clj+++ b/src/metabase/mcp/tools.clj@@ -73,12 +73,18 @@`::lib.schema/external-query` — that pulls in `::query`'s `:optional` non-nullable`:lib/metadata` (and emits `prefixItems` / `allOf` JSON Schema constructs that strict MCPclients reject). This override publishes the same opaque-object `:query` field used by- `construct_query`, plus the `:continuation_token` alternative for pagination."+ `construct_query`, plus the `:query_handle` and `:continuation_token` alternatives. The handle+ is swapped for the stored base64 `:query` by [[resolve-query-arg]] before dispatch."[:map[:query {:optional true- :tool/description (str "Metabase MBQL 5 query. "- "Omit when paginating via `continuation_token`.")}+ :tool/description (str "Metabase MBQL 5 query. Use `query_handle` instead "+ "when you have one. Omit when paginating via "+ "`continuation_token`.")}[:maybe external-query-mcp-malli]]+ [:query_handle {:optional true+ :tool/description (str "Handle returned by construct_query — preferred over "+ "raw `query`.")}+ [:maybe ms/UUIDString]][:continuation_token {:optional true:tool/description (str "Token returned by a previous `query` response — pass ""it back to fetch the next page. Mutually exclusive "@@ -316,9 +322,12 @@new-body)body)))-;; Tools that accept :query_handle as an alternative to a raw base64 :query string.+;; Tools whose :query_handle is resolved by `resolve-query-arg` (it swaps the handle for the stored+;; base64 :query) before the agent-api dispatch in `call-tool`. `visualize_query` also accepts a+;; handle, but it's a UI tool that resolves the handle itself (see `metabase.mcp.resources`) and+;; never reaches this dispatch path, so it's intentionally absent here.(def ^:private tools-accepting-query-handle- #{"execute_query" "visualize_query" "create_question" "update_question"})+ #{"execute_query" "query" "create_question" "update_question"});;; ------------------------------------------------- Tool Dispatch -------------------------------------------------diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex ff72ab18260..16cce8cf63e 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -305,15 +305,17 @@execute-resp))))(testing "Rejects native queries with 400; force callers onto /v1/execute-sql";; The scope `agent:query:execute` gates /v1/execute; `agent:sql:execute` gates- ;; /v1/execute-sql. If /v1/execute accepted a base64 payload carrying :type :native,- ;; a token with only the broader scope could run raw SQL, defeating the scope split.- (let [native-query {:database (mt/id)- :type "native"- :native {:query "select 1"}}- base64-query (u/encode-base64 (json/encode native-query))- resp (mt/user-http-request :rasta :post 400 "agent/v1/execute"- {:query base64-query})]- (is (re-find #"Native queries are not supported" (str resp))))))+ ;; /v1/execute-sql. If /v1/execute accepted a base64 payload carrying native SQL —+ ;; at the top level or nested in a source-query/join — a token with only the broader+ ;; scope could run raw SQL, defeating the scope split.+ (doseq [[label q] [["top-level :type native"+ {:database (mt/id) :type "native" :native {:query "select 1"}}]+ ["nested legacy source-query"+ {:database (mt/id) :type "query" :query {:source-query {:native "select 1"}}}]]]+ (testing label+ (is (re-find #"Native queries are not supported"+ (str (mt/user-http-request :rasta :post 400 "agent/v1/execute"+ {:query (u/encode-base64 (json/encode q))}))))))))(deftest construct-metric-query-test(mt/with-temp [:model/Card metric {:name "Test Metric"@@ -399,6 +401,88 @@(mt/user-http-request :rasta :post 202 "agent/v2/query"{:query (orders-query :limit 1000)})))))+(deftest combined-query-accepts-resolved-handle-test+ (testing "`/v2/query` executes a base64 `:query` string (a resolved query_handle) directly,+ skipping the representations pipeline"+ (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query (orders-query+ :order-by [["asc" {} (orders-field-ref "ID")]]+ :limit 5)})]+ (is (=? {:status "completed"+ :row_count 5+ :continuation_token nil?+ :data {:cols sequential?+ :rows (fn [rows] (= 5 (count rows)))}}+ (mt/user-http-request :rasta :post 202 "agent/v2/query"+ {:query (:query construct-resp)})))))+ (testing "Pagination works on the resolved-handle path: the per-query :limit drives the+ continuation_token across pages"+ (let [page-size 200+ total-rows 250+ construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query (orders-query+ :order-by [["asc" {} (orders-field-ref "ID")]]+ :limit total-rows)})+ page1 (mt/user-http-request :rasta :post 202 "agent/v2/query"+ {:query (:query construct-resp)})+ page2 (mt/user-http-request :rasta :post 202 "agent/v2/query"+ {:continuation_token (:continuation_token page1)})]+ (is (=? {:row_count page-size :continuation_token string?} page1))+ (is (=? {:row_count (- total-rows page-size) :continuation_token nil?} page2)))))++(deftest combined-query-rejects-native-handle-test+ (testing "`/v2/query` rejects a base64 native query with 400 — `agent:query` must not run raw SQL,+ same scope split `/v1/execute` enforces — in both the legacy and MBQL 5 native forms"+ (doseq [[label q] [["legacy top-level :type"+ {:database (mt/id) :type "native" :native {:query "select 1"}}]+ ["MBQL 5 native stage"+ {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/native" :native "select 1"}]}]+ ["MBQL 5 native stage nested in a join"+ {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :joins [{:lib/type "mbql/join"+ :stages [{:lib/type "mbql.stage/native"+ :native "select 1"}]}]}]}]+ ["legacy nested native source-query"+ {:database (mt/id) :type "query"+ :query {:source-query {:native "select 1"}}}]]]+ (testing label+ (is (re-find #"Native queries are not supported"+ (str (mt/user-http-request :rasta :post 400 "agent/v2/query"+ {:query (u/encode-base64 (json/encode q))}))))))))++(deftest combined-query-rejects-malformed-payload-test+ (testing "`/v2/query` returns 400 (not 500) when a base64 `:query` isn't a valid JSON object"+ (doseq [[label q] [["not valid base64/JSON" "@@@not-base64@@@"]+ ["valid base64 of a non-object" (u/encode-base64 (json/encode 5))]]]+ (testing label+ (is (re-find #"Invalid request"+ (str (mt/user-http-request :rasta :post 400 "agent/v2/query" {:query q})))))))+ (testing "`/v2/query` returns 400 (not 500) for a JSON object that isn't a serialized MBQL query"+ (doseq [[label q] [["non-sequential :stages" {:stages 1}]+ ["missing :stages" {:lib/type "mbql/query"}]+ ["non-map stage" {:stages [1]}]+ ["malformed :type" {:type 1 :stages 1}]]]+ (testing label+ (is (re-find #"expected a serialized MBQL query"+ (str (mt/user-http-request :rasta :post 400 "agent/v2/query"+ {:query (u/encode-base64 (json/encode q))})))))))+ (testing "`/v2/query` returns 400 (not 500) for an invalid present last-stage :limit"+ (doseq [[label limit] [["string" "lots"]+ ["zero" 0]+ ["negative" -5]+ ["boolean" false]]]+ (testing label+ (is (re-find #":limit must be a positive integer"+ (str (mt/user-http-request :rasta :post 400 "agent/v2/query"+ {:query (u/encode-base64+ (json/encode {:stages [{:limit limit}]}))})))))))+ (testing "`/v2/query` returns 400 for a malformed continuation_token"+ (is (re-find #"Invalid request"+ (str (mt/user-http-request :rasta :post 400 "agent/v2/query"+ {:continuation_token "@@@not-base64@@@"}))))))+(defn- make-continuation-token [pagination](-> {:query {:database (mt/id) :stages [{:source-table (mt/id :orders)}]}:pagination pagination}diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex 89a91ddc692..f1f6947d80a 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -772,6 +772,36 @@:rows (fn [rows] (= 5 (count rows)))}}execute-data)))))))+(deftest tools-call-query-accepts-query-handle-test+ (testing "the `query` tool resolves a query_handle and streams results, same as a fresh query body"+ (let [[session-id _] (initialize!)+ db-name (t2/select-one-fn :name :model/Database (mt/id))+ external-query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table [db-name "PUBLIC" "ORDERS"]+ :limit 5}]}+ construct-data (call-tool session-id "construct_query" {:query external-query})+ query-data (call-tool session-id "query"+ {:query_handle (:query_handle construct-data)})]+ (is (=? {:status "completed"+ :row_count 5+ :continuation_token nil?+ :data {:cols sequential?+ :rows (fn [rows] (= 5 (count rows)))}}+ query-data)))))++(deftest tools-call-query-stale-query-handle-test+ (testing "the `query` tool returns a tool-level error for an unknown handle rather than a 500"+ (let [[session-id _] (initialize!)+ result (mcp-request (jsonrpc-request "tools/call"+ {:name "query"+ :arguments {:query_handle (str (random-uuid))}})+ {"mcp-session-id" session-id})]+ (is (=? {:status 200+ :body {:result {:isError true+ :content [{:text #(str/includes? % "Query handle not found")}]}}}+ result)))))+(deftest tools-call-create-question-accepts-query-handle-test(testing "create_question resolves query_handle through the MCP layer instead of requiring raw base64"(let [[session-id _] (initialize!)