Skip to content

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

infer db from query in transform_write mcp tool (#82461)

Aleksandr Lesnenko62831f5e4d11
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index e8d41411065..670b4009929 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1346,6 +1346,7 @@
util
util.config
warehouse-schema-overlay
+ warehouses
warehouses.schema}
:model-imports #{:model/Card
:model/Collection
diff --git a/src/metabase/mcp/v2/tools/transform.clj b/src/metabase/mcp/v2/tools/transform.clj
index 4effa01370c..aee5a06156c 100644
--- a/src/metabase/mcp/v2/tools/transform.clj
+++ b/src/metabase/mcp/v2/tools/transform.clj
@@ -26,7 +26,8 @@
[metabase.metabot.scope :as metabot.scope]
[metabase.models.interface :as mi]
[metabase.transforms.core :as transforms]
- [metabase.util :as u]))
+ [metabase.util :as u]
+ [metabase.warehouses.models.database :as database]))
(set! *warn-on-reflection* true)
@@ -57,6 +58,21 @@
(message/msg ["The transform's query is not valid MBQL: %s %s"] (common/ellipsize text 300) accepted-shapes)
(message/msg ["The transform's query is not valid MBQL. %s"] accepted-shapes))))))
+(defn- infer-database
+ "`query` with its top-level `:database` filled from the first stage's numeric `:source-table` when
+ the caller left it off. `execute_query` resolves the warehouse from the first stage and never
+ consults `:database`, and the accepted-shapes sentence promises `definition` takes that same
+ dialect, so a query that names its table is not sent back for the redundant key. Left alone when
+ `:database` is set or the first stage names no table by id, so [[normalize-transform-query]]
+ still reports the missing key. Read off the raw query rather than through `lib`, which only
+ accepts a normalized one — and normalizing is what needs the database. The first stage is
+ `stages[0]` of an MBQL 5 query, or the inner `:query` of a legacy MBQL 4 one."
+ [query]
+ (let [table-id (or (-> query :stages first :source-table) (-> query :query :source-table))]
+ (cond-> query
+ (and (nil? (:database query)) (pos-int? table-id))
+ (assoc :database (database/table-id->database-id table-id)))))
+
(defn- definition->query
"The query inside a caller-supplied `definition`, resolved to canonical MBQL 5. Source kinds this
tool can't author are refused here rather than stored in a degraded form."
@@ -90,7 +106,7 @@
(normalize-transform-query
(if (v2.queries/portable-query? query)
(v2.queries/resolve-external-query query accepted-shapes)
- query))))))
+ (infer-database query)))))))
(defn- check-native-source-gates!
"Throw unless `token-scopes` may store a native transform: they must match `agent:sql:run`, and the
diff --git a/test/metabase/mcp/v2/tools/transform_test.clj b/test/metabase/mcp/v2/tools/transform_test.clj
index e472d84547d..2e506650217 100644
--- a/test/metabase/mcp/v2/tools/transform_test.clj
+++ b/test/metabase/mcp/v2/tools/transform_test.clj
@@ -606,6 +606,104 @@
(finally
(t2/delete! :model/Transform :id (:id result)))))))))
+(defn- venues-stage-query
+ "An MBQL 5 query over venues in the numeric-id dialect with no top-level `:database` — the
+ shape `execute_query` takes, whose first stage alone names the warehouse. Carries the count and
+ breakout the agent's first real call did, so the inferred key lands on a query that then has to
+ normalize and preprocess as a whole."
+ []
+ {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table (mt/id :venues)
+ :aggregation [["count" {}]]
+ :breakout [["field" {} (mt/id :venues :category_id)]]}]})
+
+(deftest transform-write-infers-database-from-source-table-test
+ (testing "an inline `definition` whose first stage names a numeric source-table but no top-level
+ `database` is accepted, with the table's database filled in — execute_query takes that
+ query as-is, and the accepted-shapes sentence promises `definition` takes the same dialect"
+ (with-transforms
+ (with-target-db-support
+ (let [result (tool-result (write! {:method "create"
+ :name "Inferred database"
+ :definition {:type "query" :query (venues-stage-query)}
+ :target {:name "mcp_inferred_db" :schema (venues-schema)}}))
+ stored (t2/select-one-fn :source :model/Transform :id (:id result))]
+ (try
+ (testing "the stored source carries the inferred database"
+ (is (= (mt/id) (-> stored :query :database)))
+ (is (= (mt/id :venues) (-> stored :query :stages first :source-table))))
+ (testing "and the target database follows it"
+ (is (= (mt/id) (-> result :target :database))))
+ (finally
+ (t2/delete! :model/Transform :id (:id result)))))))))
+
+(deftest transform-write-database-inference-limits-test
+ (with-transforms
+ (with-target-db-support
+ (let [create! (fn [user query]
+ (write! user write-scopes {:method "create"
+ :name "x"
+ :definition {:type "query" :query query}
+ :target {:name "mcp_inference_limits" :schema (venues-schema)}}))]
+ (testing "a first stage naming no table by numeric id — nothing, or a source-card — is still refused for
+ the missing database"
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (venues-query)}]
+ (doseq [stage [{:lib/type "mbql.stage/mbql"}
+ {:lib/type "mbql.stage/mbql" :source-card card-id}]]
+ (let [error (tool-error (create! :crowberto {:lib/type "mbql/query" :stages [stage]}))]
+ (is (re-find #"not valid MBQL" error))
+ (is (re-find #"Query must include :database" error))))))
+ (testing "an unknown table id infers nothing, so the same refusal stands rather than a stack trace"
+ (let [error (tool-error (create! :crowberto {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table Integer/MAX_VALUE}]}))]
+ (is (re-find #"not valid MBQL" error))
+ (is (re-find #"Query must include :database" error))))
+ (testing "a caller without transform permissions on the inferred database is refused, exactly as with
+ an explicit `database` — inference fills in the key, it does not skip the create check"
+ (mt/with-no-data-perms-for-all-users!
+ (is (= "\"You don't have permissions to do that.\""
+ (tool-error (create! :rasta {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table (mt/id :venues)}]}))))))
+ (is (zero? (t2/count :model/Transform :name "x")) "nothing is written by any refusal")))))
+
+(deftest transform-write-cross-database-join-still-rejected-test
+ (testing "inferring the database from the first stage does not let a join on a table in another
+ database through: the query is rejected with or without an explicit `database`"
+ (with-transforms
+ (with-target-db-support
+ (let [orig-venues (mt/id :venues)
+ orig-venues-id (mt/id :venues :id)]
+ (mt/with-temp-copy-of-db
+ (let [other-db (mt/id)
+ other-venues (mt/id :venues)
+ cross-join (fn [database]
+ (cond-> {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table other-venues
+ :joins [{:lib/type "mbql/join"
+ :alias "v2"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table orig-venues}]
+ :conditions [["=" {}
+ ["field" {} (mt/id :venues :id)]
+ ["field" {:join-alias "v2"} orig-venues-id]]]}]}]}
+ database (assoc :database database)))
+ attempt! (fn [database]
+ (write! {:method "create"
+ :name "cross db join"
+ :definition {:type "query" :query (cross-join database)}
+ :target {:name "mcp_cross_db_join" :schema (venues-schema)}}))]
+ (is (not= orig-venues other-venues) "the copy really is a second database")
+ (let [inferred (tool-error (attempt! nil))
+ explicit (tool-error (attempt! other-db))]
+ (is (re-find #"belongs to a different Database" inferred))
+ (testing "and inference changes nothing but the missing key: both forms fail the same way"
+ (is (= explicit inferred))))
+ (is (zero? (t2/count :model/Transform :name "cross db join"))))))))))
+
(deftest transform-write-accepted-shapes-names-both-dialects-test
(testing "GHY-4240: the sentence every source-shape error ends with is what teaches the agent how to
retry, so it has to name both dialects the tool actually resolves — it once said