Skip to content

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

Check queries before MCP's visualize_query reports a chart as ready

Andrei Simionescuc4f414321120
diff --git a/src/metabase/mcp/v2/queries.clj b/src/metabase/mcp/v2/queries.clj
index 6fc07532e0a..1c128c3d5ce 100644
--- a/src/metabase/mcp/v2/queries.clj
+++ b/src/metabase/mcp/v2/queries.clj
@@ -44,28 +44,37 @@
(defn- with-recovery-hint
"`e` rewrapped by [[common/message-ex-info]] with v2's recovery message for its `ex-data` on a line after its
- message, keeping its data and with `e` as the cause, or unchanged when there is none."
+ message, keeping its data and with `e` as the cause, or unchanged when there is none.
+
+ `e`'s message is quoted, except for a preprocessing rejection. The pipeline writes that message from server text
+ and quotes the query processor's text in it."
[^clojure.lang.ExceptionInfo e]
(if-let [hint (v2.recovery-hints/recovery-hint (ex-data e))]
(common/message-ex-info (if-let [text (common/exception-message e)]
- (message/msg ["%s" "%s"] text hint)
+ (message/msg ["%s" "%s"]
+ (cond-> text
+ (= :query-preprocessing-failed (:error (ex-data e))) message/raw)
+ hint)
hint)
(ex-data e)
e)
e))
(defn execute-representations-query
- "Run the shared representations pipeline (validate → repair → resolve) as the MCP v2 surface —
- the one entry point for v2 tools that accept an agent-authored MBQL query. Binds the numeric-id
- dialect on. A structural failure gains the offending paths ([[with-schema-detail]]), and an
- agent error gains v2's recovery message ([[with-recovery-hint]])."
- [external-query]
- (binding [serdes.resolve/*numeric-ids-allowed?* true]
- (try
- (metabot.construct/execute-representations-query external-query)
- (catch clojure.lang.ExceptionInfo e
- (throw (cond-> (with-schema-detail e)
- (:agent-error? (ex-data e)) with-recovery-hint))))))
+ "Run the shared representations pipeline for MCP v2 queries.
+ Validate, repair and resolve an agent-authored MBQL query with numeric IDs allowed.
+ Add the offending paths to structural errors ([[with-schema-detail]]) and v2 recovery advice to
+ agent errors when available ([[with-recovery-hint]]). Pass `opts` to
+ [[metabot.construct/execute-representations-query]]."
+ ([external-query]
+ (execute-representations-query external-query nil))
+ ([external-query opts]
+ (binding [serdes.resolve/*numeric-ids-allowed?* true]
+ (try
+ (metabot.construct/execute-representations-query external-query opts)
+ (catch clojure.lang.ExceptionInfo e
+ (throw (cond-> (with-schema-detail e)
+ (:agent-error? (ex-data e)) with-recovery-hint)))))))
;;; ------------------------------------------------ Portable queries ----------------------------------------------
diff --git a/src/metabase/mcp/v2/recovery_hints.clj b/src/metabase/mcp/v2/recovery_hints.clj
index d32b59cf6f8..548e4a1c6ee 100644
--- a/src/metabase/mcp/v2/recovery_hints.clj
+++ b/src/metabase/mcp/v2/recovery_hints.clj
@@ -122,4 +122,7 @@
:missing-source-in-first-stage
(message/msg ["`source-table:` takes a numeric table id; `source-card:` takes a saved-card numeric id."])
+ :query-preprocessing-failed
+ (message/msg ["Fix that part of the query and retry."])
+
nil))
diff --git a/src/metabase/mcp/v2/tools/visualize.clj b/src/metabase/mcp/v2/tools/visualize.clj
index ecfeabfdec0..e8da5334447 100644
--- a/src/metabase/mcp/v2/tools/visualize.clj
+++ b/src/metabase/mcp/v2/tools/visualize.clj
@@ -48,16 +48,14 @@
(message/msg ["Query handle not found — it may have expired; run the query again."]))))
(defn- handle-for-visualization!
- "Resolve `visualize_query`'s mutually exclusive inputs to the handle the iframe will render.
+ "Return the handle that the iframe will render for `visualize_query`.
- A fresh `query` runs the representations pipeline (validate → repair → resolve, permission
- checked) and mints a handle, so the iframe renders exactly what was resolved. A supplied
- `query_handle` is reused as-is rather than re-minted — the stored query is unchanged, and a
- duplicate handle would only add a row for the GC to collect.
+ Accept exactly one of `query` or `query_handle`. Validate, repair and resolve a fresh `query`,
+ check permissions and run the query processor's preprocessing check before creating a handle.
+ Reuse a supplied `query_handle` without changing the stored query.
- Native is allowed through the handle path but not the fresh path: `execute_sql` mints handles
- whose SQL is visualizable by design, while inline `query` is MBQL 5 only, matching
- `execute_query`."
+ A fresh `query` must be MBQL 5, as in `execute_query`. A `query_handle` can also contain native
+ SQL from `execute_sql`."
[{:keys [query query_handle prompt]} session-id]
(let [provided (cond-> []
query (conj :query)
@@ -74,7 +72,7 @@
(v2.queries/mint-query-handle!
session-id
api/*current-user-id*
- (-> (v2.queries/execute-representations-query query)
+ (-> (v2.queries/execute-representations-query query {:preprocess-check? true})
(get-in [:structured-output :query])
lib/prepare-for-serialization
v2.queries/encode-serialized-query)
diff --git a/test/metabase/mcp/v2/tools/visualize_test.clj b/test/metabase/mcp/v2/tools/visualize_test.clj
index 3678759b7b5..90db60b6086 100644
--- a/test/metabase/mcp/v2/tools/visualize_test.clj
+++ b/test/metabase/mcp/v2/tools/visualize_test.clj
@@ -131,6 +131,31 @@
(testing "and carries the prompt for the visualization feedback flow"
(is (= "show me orders" prompt)))))))))
+(deftest visualize-query-rejects-fresh-query-that-wont-run-test
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ orders (lib/query mp (lib.metadata/table mp (mt/id :orders)))]
+ (mt/with-temp [:model/Card {metric-id :id} {:type :metric :dataset_query (lib/aggregate orders (lib/count))}]
+ (testing "BOT-2391: a fresh query that the query processor rejects returns an error with recovery advice"
+ (doseq [[description stage rejection]
+ [["a number column compared to text"
+ {:filters [["=" {} ["field" {} (mt/id :orders :total)] "abc"]]}
+ (str "\"Error filtering against :type/Float Field: unable to parse String \\\"abc\\\" "
+ "to a :type/Float\"")]
+ ["a metric used in a filter"
+ {:aggregation [["count" {}]]
+ :filters [[">" {} ["metric" {} metric-id] 100]]}
+ (str "Metabase could not expand a metric reference. Check that it is in an aggregation and "
+ "applies to this stage's source.")]]]
+ (testing description
+ (is (= (str "Metabase could not prepare this query to run: " rejection "\n"
+ "Fix that part of the query and retry.")
+ (error-text (call! "visualize_query" (str (random-uuid))
+ {:query {:lib/type "mbql/query"
+ :stages [(merge {:lib/type "mbql.stage/mbql"
+ :source-table (mt/id :orders)}
+ stage)]}})))))))))))
+
;; not ^:parallel: mt/with-model-cleanup on the shared query-handle table
(deftest visualize-query-rejects-display-test
;; `display` was accepted, enum-validated and echoed, but no renderer ever read it, and