Skip to content

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

Treat a 403 from construct_notebook_query as agent-facing (#79983)

Chris Truter5f4bb206a10a
diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.clj
index ea2105327a4..9086fcf254c 100644
--- a/src/metabase/metabot/tools/construct.clj
+++ b/src/metabase/metabot/tools/construct.clj
@@ -542,7 +542,10 @@
"<instructions>\n" instruction-text "\n</instructions>")))
query-result)))
(catch Exception e
- (if (:agent-error? (ex-data e))
+ ;; A 403 counts as agent-facing even without the flag: `api/read-check` throws a bare one,
+ ;; and it means the user can't have the card they named rather than that anything broke.
+ (if (or (:agent-error? (ex-data e))
+ (= 403 (:status-code (ex-data e))))
;; Expected agent-facing signal (bad LLM input: unknown table, unknown schema,
;; URI-in-source-table, …). Log at debug only — no stacktrace — since the message
;; is the tool's result and the LLM is expected to self-correct on the next turn.
diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.clj
index 2e7a001d5ea..8e01c71ff60 100644
--- a/test/metabase/metabot/tools_test.clj
+++ b/test/metabase/metabot/tools_test.clj
@@ -171,6 +171,29 @@
(is (= "Total order count."
(get-in result [:data-parts 0 :data :description]))))))))
+(defn- construct-tool-output-for-thrown
+ "Run `construct_notebook_query` with `execute-representations-query` throwing `e`, and return
+ the `:output` the LLM would see."
+ [e]
+ (mt/with-dynamic-fn-redefs [construct/execute-representations-query (fn [_] (throw e))]
+ (:output (binding [shared/*profile-id* :nlq]
+ (agent-tools/construct-notebook-query-tool
+ {:query {:lib/type "mbql/query" :stages []}
+ :title "Seat check"
+ :description "Total order count."})))))
+
+(deftest construct-notebook-query-tool-permission-error-test
+ (testing (str "a 403 reaches the LLM as the permission message itself: `api/read-check` throws "
+ "a bare one with no `:agent-error?`, and the user not being allowed the card they "
+ "named is not a failure to report as one")
+ (is (= "You don't have permissions to do that."
+ (construct-tool-output-for-thrown
+ (ex-info "You don't have permissions to do that." {:status-code 403})))))
+ (testing "anything else without `:agent-error?` still gets the generic wrapper"
+ (is (= "Failed to construct notebook query: something went sideways"
+ (construct-tool-output-for-thrown
+ (ex-info "something went sideways" {:status-code 400}))))))
+
(deftest state-dependent-tools-test
(testing "state-dependent-tools set contains expected tools"
(is (contains? @#'agent-tools/state-dependent-tools "create_chart"))