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
Share agent query execution between MCP and Metabot (#83412)
Chris Truter1132fdb21883
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 44c8ac6d299..31ada1aaede 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1436,6 +1436,7 @@metabase.metabot.initmetabase.metabot.metadata-permsmetabase.metabot.persistence+ metabase.metabot.query-executionmetabase.metabot.schemametabase.metabot.schema.v2metabase.metabot.scopediff --git a/src/metabase/mcp/v2/tools/query.clj b/src/metabase/mcp/v2/tools/query.cljindex ffbbc803807..2b654d7c320 100644--- a/src/metabase/mcp/v2/tools/query.clj+++ b/src/metabase/mcp/v2/tools/query.clj@@ -37,10 +37,10 @@[metabase.mcp.v2.query :as v2.query][metabase.mcp.v2.registry :as registry][metabase.mcp.v2.resolve :as v2.resolve]+ [metabase.metabot.query-execution :as query-execution][metabase.metabot.scope :as metabot.scope][metabase.models.interface :as mi][metabase.query-processor.card :as qp.card]- [metabase.query-processor.core :as qp][metabase.query-processor.middleware.permissions :as qp.perms][metabase.util :as u]))@@ -109,56 +109,27 @@;;; ------------------------------------------------- Execution -----------------------------------------------------(def ^:private query-passthrough-keys- "The only keys of an incoming query that MCP forwards to the QP. Everything else — `:middleware`,- `:info`, `:constraints`, and any unknown key — is MCP's to set, because the query map is- caller-controlled and an agent that could name its own `:info` would forge `query_execution`- attribution. A fresh `:query` is also rejected upstream by the closed- `:metabase.lib.schema/query`, but that covers only the fresh path: a handle's stored query is- checked shallowly and the `/drills` callback stores one verbatim, so an unknown key does reach- here. This whitelist, not the schema, is what the guarantee rests on. The QP strips some of- these itself; that is defense in depth, not this boundary's contract."- [:lib/type :database :stages :parameters])-(defn- query-failure-message- "The teaching message for a QP `result` that didn't complete, carrying its error text quoted."- [result]- (if-let [error (:error result)]+ "The teaching message for a query that didn't complete, carrying the QP's `error` text quoted."+ [error]+ (if error(message/msg ["Query failed: %s"] error)(message/msg ["Query failed: unknown error"])))-(defn- execute!- "Run a serialized MBQL query through the QP with the standard agent userland preparation,- capping this call's rows at `row-limit` (within the backend's 2000/10000 userland- ceilings). Returns the QP result; surfaces a failed run as a teaching error."- [serialized-query row-limit]- (let [result (qp/process-query- (-> (select-keys serialized-query query-passthrough-keys)- (assoc :middleware {:js-int-to-string? true})- qp/userland-query-with-default-constraints- (assoc :constraints {:max-results row-limit- :max-results-bare-rows row-limit}- :info {:executed-by api/*current-user-id*- :context :agent})))]- (when-not (= (:status result) :completed)- (common/throw-teaching-error (query-failure-message result)))- result))-(defn- execute-page!- "Run `serialized-query` for one page of at most `row-limit` rows. Fetches one row past the- limit so truncation is *observed* rather than inferred from a full page: a result that fills- the page exactly is complete, and is reported that way. Returns- `{:cols :rows :returned :truncated?}` with the probe row already dropped, so `rows` is the- page and `(last rows)` is a real page boundary."+ "Run [[query-execution/execute-page!]] as an `:agent` query, turning a failed run into a teaching error."[serialized-query row-limit]- (let [result (execute! serialized-query (inc row-limit))- all-rows (vec (get-in result [:data :rows]))- truncated? (> (count all-rows) row-limit)- rows (cond-> all-rows truncated? (subvec 0 row-limit))]- {:cols (get-in result [:data :cols])- :rows rows- :returned (count rows)- :truncated? truncated?}))+ ;; Only the key whitelist in [[query-execution/execute-page!]] keeps unknown keys away from the QP.+ ;; A fresh `:query` is also rejected upstream by the closed `:metabase.lib.schema/query`, but that covers only the+ ;; fresh path: a handle's stored query is checked shallowly and the `/drills` callback stores one verbatim, so an+ ;; unknown key does reach here.+ (try+ (query-execution/execute-page! serialized-query row-limit :agent)+ (catch clojure.lang.ExceptionInfo e+ (let [{:keys [error query-error]} (ex-data e)]+ (if (= :query-failed error)+ (common/throw-teaching-error (query-failure-message query-error))+ (throw e))))))(defn- last-stage[serialized-query]@@ -195,15 +166,6 @@;;; ------------------------------------------------- Response ------------------------------------------------------(defn- response-cols- [cols]- (mapv (fn [{:keys [name base_type effective_type display_name]}]- (cond-> {:name name- :base_type (u/qualified-name base_type)- :display_name display_name}- effective_type (assoc :effective_type (u/qualified-name effective_type))))- cols))-(defn- steering-line[returned next-cursor](if next-cursor@@ -259,7 +221,7 @@:truncated truncated?}next-cursor (assoc :next_cursor next-cursor))payload (assoc counts- :cols (response-cols cols)+ :cols (query-execution/response-cols cols):rows rows)](common/success-content(if truncated?@@ -459,7 +421,7 @@ Dialect (JSON): tables and columns go by NUMERIC ID (from browse_data list_table:truncated truncated?}hint (assoc :hint hint))payload (assoc counts- :cols (response-cols cols)+ :cols (query-execution/response-cols cols):rows rows)](common/success-content(if truncated?@@ -611,7 +573,7 @@ Dialect (JSON): tables and columns go by NUMERIC ID (from browse_data list_table(fn [query info](qp (update query :info merge info) nil)))))](when-not (= (:status result) :completed)- (common/throw-teaching-error (query-failure-message result)))+ (common/throw-teaching-error (query-failure-message (:error result))))result))(defn- saved-question-steering-line@@ -669,7 +631,7 @@ Dialect (JSON): tables and columns go by NUMERIC ID (from browse_data list_tablereturned (count rows)counts {:returned returned :truncated truncated?}payload (assoc counts- :cols (response-cols cols)+ :cols (query-execution/response-cols cols):rows rows)](common/success-content(if truncated?diff --git a/src/metabase/metabot/query_execution.clj b/src/metabase/metabot/query_execution.cljnew file mode 100644index 00000000000..38bc706d77b--- /dev/null+++ b/src/metabase/metabot/query_execution.clj@@ -0,0 +1,68 @@+(ns metabase.metabot.query-execution+ "Run a serialized MBQL query on behalf of an agent and return one bounded page of rows."+ (:require+ [metabase.api.common :as api]+ [metabase.query-processor.core :as qp]+ [metabase.util :as u]+ [metabase.util.i18n :refer [tru]]))++(set! *warn-on-reflection* true)++(def ^:private query-passthrough-keys+ "The only keys of an incoming query forwarded to the QP.+ Everything else — `:middleware`, `:info`, `:constraints`, and any unknown key — is this namespace's to set,+ because the query map is caller-controlled and an agent that could name its own `:info` would forge+ `query_execution` attribution.+ This whitelist, not the query schema, is what the guarantee rests on.+ The QP strips some of these itself; that is defense in depth, not this boundary's contract."+ [:lib/type :database :stages :parameters])++(defn- execute!+ "Run a serialized MBQL query through the QP with the standard agent userland preparation.+ Caps this call's rows at `row-limit` (within the backend's 2000/10000 userland ceilings) and records the run+ under `context`."+ [serialized-query row-limit context]+ (let [result (qp/process-query+ (-> (select-keys serialized-query query-passthrough-keys)+ (assoc :middleware {:js-int-to-string? true})+ qp/userland-query-with-default-constraints+ (assoc :constraints {:max-results row-limit+ :max-results-bare-rows row-limit}+ :info {:executed-by api/*current-user-id*+ :context context})))]+ (when-not (= (:status result) :completed)+ (throw (ex-info (if-let [error (:error result)]+ (tru "Query failed: {0}" error)+ (tru "Query failed: unknown error"))+ {:agent-error? true+ :error :query-failed+ :query-error (:error result)})))+ result))++(defn execute-page!+ "Run `serialized-query` for one page of at most `row-limit` rows, recorded under the QP `context`.+ Returns `{:cols :rows :returned :truncated?}`.+ The `truncated?` flag is true only when more rows exist, so a result that fills the page exactly is complete.+ A run that doesn't complete throws an agent error whose message carries the QP's error text.+ Its ex-data is `{:agent-error? true :error :query-failed :query-error <QP error text or nil>}`."+ [serialized-query row-limit context]+ ;; Fetch one row past the limit so truncation is observed rather than inferred from a full page.+ ;; Dropping the probe row keeps `(last rows)` a real page boundary.+ (let [result (execute! serialized-query (inc row-limit) context)+ all-rows (vec (get-in result [:data :rows]))+ truncated? (> (count all-rows) row-limit)+ rows (cond-> all-rows truncated? (subvec 0 row-limit))]+ {:cols (get-in result [:data :cols])+ :rows rows+ :returned (count rows)+ :truncated? truncated?}))++(defn response-cols+ "The agent-facing description of result `cols`: name, display name, and qualified type names."+ [cols]+ (mapv (fn [{:keys [name base_type effective_type display_name]}]+ (cond-> {:name name+ :base_type (u/qualified-name base_type)+ :display_name display_name}+ effective_type (assoc :effective_type (u/qualified-name effective_type))))+ cols))diff --git a/test/metabase/mcp/v2/tools/query_test.clj b/test/metabase/mcp/v2/tools/query_test.cljindex 8f9e8b4219a..2da7aad4155 100644--- a/test/metabase/mcp/v2/tools/query_test.clj+++ b/test/metabase/mcp/v2/tools/query_test.clj@@ -972,7 +972,7 @@;;; ------------------------------------------- QP input whitelist -------------------------------------------------;;; GHY-4313: the QP only ever sees the keys MCP forwards-;;; ([[metabase.mcp.v2.tools.query/query-passthrough-keys]]). A fresh `query` is additionally+;;; ([[metabase.metabot.query-execution/query-passthrough-keys]]). A fresh `query` is additionally;;; rejected outright by the closed `:metabase.lib.schema/query`, but the handle path skips that;;; schema — `resolve-query-handle!` checks only that stages are non-empty and the last one has a;;; positive limit, and `POST /drills` stores a caller-supplied query verbatim. So an unknown keydiff --git a/test/metabase/metabot/query_execution_test.clj b/test/metabase/metabot/query_execution_test.cljnew file mode 100644index 00000000000..3d7bf713edb--- /dev/null+++ b/test/metabase/metabot/query_execution_test.clj@@ -0,0 +1,42 @@+(ns metabase.metabot.query-execution-test+ (:require+ [clojure.test :refer [deftest is testing]]+ [metabase.lib-be.core :as lib-be]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.metabot.query-execution :as query-execution]+ [metabase.metabot.tools.util :as tools.util]+ [metabase.query-processor.core :as qp]+ [metabase.test :as mt]))++(defn- venues-query+ [limit]+ (let [mp (lib-be/application-database-metadata-provider (mt/id))]+ (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/order-by (lib.metadata/field mp (mt/id :venues :id)))+ (lib/limit limit)+ lib/prepare-for-serialization)))++(deftest execute-page-truncation-test+ (mt/with-current-user (mt/user->id :rasta)+ (testing "a result that fills the page exactly is complete"+ (is (=? {:returned 3 :truncated? false :rows #(= 3 (count %))}+ (query-execution/execute-page! (venues-query 3) 3 :agent))))+ (testing "a result with more rows than the page is truncated to the page"+ (is (=? {:returned 2 :truncated? true :rows #(= 2 (count %))}+ (query-execution/execute-page! (venues-query 3) 2 :agent))))))++(deftest execute-page-failure-is-an-agent-error-test+ (mt/with-current-user (mt/user->id :rasta)+ (let [captured (atom nil)]+ (mt/with-dynamic-fn-redefs [qp/process-query (fn [query]+ (reset! captured query)+ {:status :failed :error "Column FOO not found"})]+ (is (= {:output "Query failed: Column FOO not found"}+ (try+ (query-execution/execute-page! (assoc (venues-query 3) :info {:context :ad-hoc}) 3 :agent)+ (catch clojure.lang.ExceptionInfo e+ (tools.util/handle-agent-error e)))))+ (testing "the run is recorded under the caller's context, not one named in the query"+ (is (=? {:info {:executed-by (mt/user->id :rasta) :context :agent}}+ @captured)))))))