Skip to content

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

Normalize scalar search tool arguments (#80107)

Maksym Yakubych0421c77905e9
diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.clj
index ef10900e093..a04054232fd 100644
--- a/src/metabase/metabot/self/core.clj
+++ b/src/metabase/metabot/self/core.clj
@@ -5,6 +5,7 @@
[clojure.string :as str]
[clojure.walk :as walk]
[malli.core :as mc]
+ [malli.error :as me]
[malli.transform :as mtx]
[metabase.ai-tracing.core :as ait]
[metabase.llm.settings :as llm]
@@ -14,6 +15,7 @@
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
[metabase.util.log :as log]
+ [metabase.util.malli.registry :as mr]
[metabase.util.o11y :refer [with-span]])
(:import
(java.io BufferedReader Closeable InputStream)
@@ -166,6 +168,33 @@
;; rather than a cryptic JSON parse stacktrace.
{:_raw_arguments raw}))))
+(defn- try-decode-json-string
+ "If `v` is a string that looks like a JSON object or array, decode it.
+ Returns the decoded value on success, or the original value on failure."
+ [v]
+ (if (and (string? v)
+ (let [trimmed (str/trim v)]
+ (or (str/starts-with? trimmed "{")
+ (str/starts-with? trimmed "["))))
+ (try
+ (json/decode+kw v)
+ (catch Exception _ v))
+ v))
+
+(defn- coerce-stringified-json
+ "Walk tool arguments and decode any string values that are actually stringified
+ JSON objects/arrays. LLMs sometimes double-encode nested arguments."
+ [args]
+ (if (map? args)
+ (reduce-kv (fn [m k v]
+ (assoc m k (cond
+ (string? v) (try-decode-json-string v)
+ (map? v) (coerce-stringified-json v)
+ :else v)))
+ {}
+ args)
+ args))
+
(defn- aisdk-chunks->part [[chunk :as chunks]]
(case (:type chunk)
:start {:type :start
@@ -265,19 +294,23 @@
(defn stamp-tool-titles-xf
"Stamp a client-facing `:title` onto `:tool-input` parts via each tool's
- optional `:title-fn`. A throwing title-fn leaves the part untitled."
+ optional `:title-fn`. Stringified JSON is coerced and the tool's `:decode` is
+ applied first, when it has one, so the title describes the arguments the tool
+ will run with. A throwing title-fn or decode leaves the part untitled."
[tools]
(map (fn [part]
- (if-let [title-fn (and (= :tool-input (:type part))
- (:title-fn (get tools (:function part))))]
- (let [title (try
- (title-fn (:arguments part))
- (catch Throwable e
- (log/debug e "tool title-fn failed" {:tool (:function part)})
- nil))]
- (cond-> part
- (string? title) (assoc :title title)))
- part))))
+ (let [{:keys [title-fn decode]} (when (= :tool-input (:type part))
+ (get tools (:function part)))]
+ (if title-fn
+ (let [title (try
+ (title-fn (cond-> (coerce-stringified-json (:arguments part))
+ decode decode))
+ (catch Throwable e
+ (log/debug e "tool title-fn failed" {:tool (:function part)})
+ nil))]
+ (cond-> part
+ (string? title) (assoc :title title)))
+ part)))))
;;; AI SDK SSE Output
;;
@@ -611,33 +644,6 @@
;; Other errors
(or (ex-message e) "Unknown error"))))
-(defn- try-decode-json-string
- "If `v` is a string that looks like a JSON object or array, decode it.
- Returns the decoded value on success, or the original value on failure."
- [v]
- (if (and (string? v)
- (let [trimmed (str/trim v)]
- (or (str/starts-with? trimmed "{")
- (str/starts-with? trimmed "["))))
- (try
- (json/decode+kw v)
- (catch Exception _ v))
- v))
-
-(defn- coerce-stringified-json
- "Walk tool arguments and decode any string values that are actually stringified
- JSON objects/arrays. LLMs sometimes double-encode nested arguments."
- [args]
- (if (map? args)
- (reduce-kv (fn [m k v]
- (assoc m k (cond
- (string? v) (try-decode-json-string v)
- (map? v) (coerce-stringified-json v)
- :else v)))
- {}
- args)
- args))
-
(def ^:private stringified-scalar-transformer
"Parses stringified numbers and booleans back into scalars, driven by the tool's own schema.
Restricted to the types models get wrong — strings, keywords and enums are left alone."
@@ -664,6 +670,49 @@
(catch Exception _ nil))
arguments))
+(defn- json-type-name
+ [v]
+ (cond
+ (nil? v) "null"
+ (string? v) "a string"
+ (boolean? v) "a boolean"
+ (number? v) "a number"
+ (map? v) "an object"
+ (sequential? v) "an array"
+ :else "an unsupported value"))
+
+(defn- argument-error-text
+ [arguments field messages]
+ (let [texts (->> (tree-seq coll? seq messages) (filter string?) distinct vec)]
+ (condp = texts
+ ["disallowed key"] (str "`" (name field) "` is not a supported argument.")
+ ["missing required key"] (str "`" (name field) "` is required.")
+ (str "`" (name field) "` " (str/join "; " texts)
+ (when (every? string? messages)
+ (str "; received " (json-type-name (get arguments field))))
+ "."))))
+
+(defn- invalid-arguments-message
+ "A repair-oriented message describing how `arguments` violate `schema`, or nil when they match."
+ [schema arguments]
+ (when-let [error (mr/explain schema arguments)]
+ (let [humanized (me/humanize error)]
+ (str "Invalid tool arguments: "
+ (if (map? humanized)
+ (str/join " " (for [[field messages] (sort-by (comp name key) humanized)]
+ (argument-error-text arguments field messages)))
+ (str "expected an object of named arguments; received "
+ (json-type-name arguments) "."))))))
+
+(defn- validate-tool-arguments!
+ [tool arguments]
+ (when (and (map? arguments) (contains? arguments :_raw_arguments))
+ (throw (ex-info "Invalid tool arguments: the arguments were not valid JSON. Send the call again as a JSON object."
+ {:agent-error? true})))
+ (when-let [schema (tool-args-schema tool)]
+ (when-let [message (invalid-arguments-message schema arguments)]
+ (throw (ex-info message {:agent-error? true})))))
+
(defn- tool-decode-fn
"Extract the `:decode` function from a tool definition map.
The decode function transforms tool arguments before the tool runs.
@@ -683,6 +732,10 @@
arguments before invocation. The decode function can coerce values and throw
`:agent-error?` exceptions for validation failures.
+ The arguments are then checked against the tool's declared schema in every
+ environment — `mu/defn` only instruments dev and test namespaces — and a
+ mismatch is returned to the model as a repair-oriented error.
+
Chunks have a ::duration-ms key added for internal use which is not part of the aisdk spec."
[tool-call-id tool-name tool chunks]
(ait/with-tool-call {:ai/tool-name tool-name
@@ -700,7 +753,8 @@
arguments (or (coerce-stringified-json arguments) {})
arguments (coerce-stringified-scalars tool arguments)
decode (tool-decode-fn tool)
- arguments (cond-> arguments decode decode)]
+ arguments (cond-> arguments decode decode)
+ _ (validate-tool-arguments! tool arguments)]
(log/debug "Executing tool" {:tool-name tool-name})
(when (ait/capture-active?)
(ait/record! {:ai/tool-args arguments}))
diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.clj
index ca10d12ea0c..7049489517a 100644
--- a/src/metabase/metabot/tools/resources.clj
+++ b/src/metabase/metabot/tools/resources.clj
@@ -1094,7 +1094,8 @@
- metabase://chart/{chart_id} - the chart's type and its query
- metabase://query/{query_id} - the query definition"
[{:keys [uris]} :- [:map {:closed true}
- [:uris [:sequential [:string {:description "Metabase resource URIs to fetch"}]]]]]
+ [:uris [:sequential {:error/message "must be an array of URI strings"}
+ [:string {:description "Metabase resource URIs to fetch"}]]]]]
(try
(read-resource {:uris uris})
(catch Exception e
diff --git a/src/metabase/metabot/tools/search.clj b/src/metabase/metabot/tools/search.clj
index e214e266b04..98517e1d973 100644
--- a/src/metabase/metabot/tools/search.clj
+++ b/src/metabase/metabot/tools/search.clj
@@ -570,17 +570,38 @@
(log/error (str "Error in " label ": " (ex-message e)))
{:output (str "Search failed: " (or (ex-message e) "Unknown error"))}))))
+(def ^:private semantic-queries-schema
+ [:sequential {:error/message "must be an array of strings"}
+ [:string {:description semantic-query-desc}]])
+
+(def ^:private keyword-queries-schema
+ [:sequential {:error/message "must be an array of strings"}
+ [:string {:description keyword-query-desc}]])
+
+(defn- entity-types-schema
+ [& types]
+ [:maybe [:sequential {:error/message "must be an array of supported entity type strings"}
+ (into [:enum {:description entity-types-desc}] types)]])
+
+(def ^:private limit-schema
+ [:maybe [:int {:min 1 :max max-search-limit :description limit-desc}]])
+
(def ^:private search-schema
[:map {:closed true}
- [:semantic_queries {:optional true :feature :semantic-search} [:sequential [:string {:description semantic-query-desc}]]]
- [:keyword_queries {:optional true} [:sequential [:string {:description keyword-query-desc}]]]
+ [:semantic_queries {:optional true :feature :semantic-search} semantic-queries-schema]
+ [:keyword_queries {:optional true} keyword-queries-schema]
[:entity_types {:optional true}
- [:maybe [:sequential [:enum {:description entity-types-desc} "table" "model" "metric" "dashboard" "document" "question"]]]]
- [:limit {:optional true} [:maybe [:int {:min 1 :max max-search-limit :description limit-desc}]]]])
+ (entity-types-schema "table" "model" "metric" "dashboard" "document" "question")]
+ [:limit {:optional true} limit-schema]])
(defn- search-display
[{:keys [keyword_queries semantic_queries]}]
- (let [queries (distinct (concat keyword_queries semantic_queries))]
+ (let [query-lists [keyword_queries semantic_queries]
+ well-formed? (every? #(or (nil? %) (sequential? %)) query-lists)
+ queries (when well-formed?
+ (->> (apply concat query-lists)
+ (filter string?)
+ distinct))]
(when (seq queries)
;; just the object (the queries) — the client wraps it in the verb + tense
;; ("Searching for …" while active, "Searched for …" once finished)
@@ -596,12 +617,11 @@
(def ^:private sql-search-schema
[:map {:closed true}
- [:semantic_queries {:optional true :feature :semantic-search} [:sequential [:string {:description semantic-query-desc}]]]
- [:keyword_queries {:optional true} [:sequential [:string {:description keyword-query-desc}]]]
+ [:semantic_queries {:optional true :feature :semantic-search} semantic-queries-schema]
+ [:keyword_queries {:optional true} keyword-queries-schema]
[:database_id [:int {:description "ID of the database to search — use the database currently selected in the SQL editor."}]]
- [:entity_types {:optional true}
- [:maybe [:sequential [:enum {:description entity-types-desc} "table" "model"]]]]
- [:limit {:optional true} [:maybe [:int {:min 1 :max max-search-limit :description limit-desc}]]]])
+ [:entity_types {:optional true} (entity-types-schema "table" "model")]
+ [:limit {:optional true} limit-schema]])
(mu/defn ^{:tool-name "search"
:scope scope/agent-search
@@ -613,12 +633,11 @@
(def ^:private nlq-search-schema
[:map {:closed true}
- [:semantic_queries {:optional true :feature :semantic-search} [:sequential [:string {:description semantic-query-desc}]]]
- [:keyword_queries {:optional true} [:sequential [:string {:description keyword-query-desc}]]]
+ [:semantic_queries {:optional true :feature :semantic-search} semantic-queries-schema]
+ [:keyword_queries {:optional true} keyword-queries-schema]
[:entity_types {:optional true}
- [:maybe [:sequential [:enum {:description entity-types-desc}
- "table" "model" "metric" "question" "dashboard" "document"]]]]
- [:limit {:optional true} [:maybe [:int {:min 1 :max max-search-limit :description limit-desc}]]]])
+ (entity-types-schema "table" "model" "metric" "question" "dashboard" "document")]
+ [:limit {:optional true} limit-schema]])
(mu/defn ^{:tool-name "search"
:scope scope/agent-search
@@ -634,12 +653,11 @@
(def ^:private transform-search-schema
[:map {:closed true}
- [:semantic_queries {:optional true :feature :semantic-search} [:sequential [:string {:description semantic-query-desc}]]]
- [:keyword_queries {:optional true} [:sequential [:string {:description keyword-query-desc}]]]
+ [:semantic_queries {:optional true :feature :semantic-search} semantic-queries-schema]
+ [:keyword_queries {:optional true} keyword-queries-schema]
[:search_native_query {:optional true} [:maybe [:boolean {:description "Also match against the native SQL text of transforms, not just names and descriptions."}]]]
- [:entity_types {:optional true}
- [:maybe [:sequential [:enum {:description entity-types-desc} "table" "model" "transform"]]]]
- [:limit {:optional true} [:maybe [:int {:min 1 :max max-search-limit :description limit-desc}]]]])
+ [:entity_types {:optional true} (entity-types-schema "table" "model" "transform")]
+ [:limit {:optional true} limit-schema]])
(mu/defn ^{:tool-name "search"
:scope scope/agent-search
diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.clj
index 406268d59b7..752ca62d276 100644
--- a/test/metabase/metabot/self_test.clj
+++ b/test/metabase/metabot/self_test.clj
@@ -464,6 +464,67 @@
(is (= chunks result)
"Unknown tools should be ignored, chunks pass through unchanged"))))
+;;; tool argument validation tests
+
+(defn- schema-tool
+ [args-schema]
+ {:fn (fn [_args] {:output "ok"})
+ :doc "validation test tool"
+ :schema [:=> [:cat args-schema] :any]})
+
+(defn- validation-error
+ [args-schema arguments]
+ (let [tools {"validated" (schema-tool args-schema)}
+ chunks (test-util/parts->aisdk-chunks
+ [{:type :start :id "msg-v"}
+ {:type :tool-input :id "call-v" :function "validated" :arguments arguments}])]
+ (-> (into [] (self.core/tool-executor-xf tools) chunks) last :error :message)))
+
+(deftest ^:parallel tool-argument-validation-test
+ (let [schema [:map {:closed true}
+ [:names {:optional true} [:sequential {:error/message "must be an array of strings"} :string]]
+ [:limit {:optional true} [:int {:min 1 :max 50}]]]]
+ (testing "a well-formed call is accepted"
+ (is (nil? (validation-error schema {:names ["orders"] :limit 10}))))
+ (testing "a scalar where an array is declared names the field and what it received"
+ (is (= "Invalid tool arguments: `names` must be an array of strings; received a string."
+ (validation-error schema {:names "orders"}))))
+ (testing "the received type reflects the value the model actually sent"
+ (is (= "Invalid tool arguments: `names` must be an array of strings; received a number."
+ (validation-error schema {:names 5})))
+ (is (= "Invalid tool arguments: `names` must be an array of strings; received an object."
+ (validation-error schema {:names {:a 1}}))))
+ (testing "a bad element reports the element's constraint without a received clause"
+ (is (= "Invalid tool arguments: `names` should be a string."
+ (validation-error schema {:names ["ok" 5]}))))
+ (testing "an unsupported key is called out as such"
+ (is (= "Invalid tool arguments: `nope` is not a supported argument."
+ (validation-error schema {:names ["ok"] :nope 1}))))
+ (testing "constraint violations on scalars are reported too"
+ (is (= "Invalid tool arguments: `limit` should be at most 50; received a number."
+ (validation-error schema {:limit 999}))))
+ (testing "arguments that aren't an object at all"
+ (is (= "Invalid tool arguments: expected an object of named arguments; received an array."
+ (validation-error schema ["orders"]))))))
+
+(deftest ^:parallel tool-unparseable-arguments-test
+ (testing "arguments the provider streamed as invalid JSON are reported as such"
+ (let [tools {"validated" (schema-tool [:map {:closed true} [:names {:optional true} [:sequential :string]]])}
+ chunks (concat [{:type :tool-input-start :toolName "validated" :toolCallId "call-j"}]
+ [{:type :tool-input-delta :toolCallId "call-j" :inputTextDelta "{\"names\": ["}]
+ [{:type :tool-input-available :toolName "validated" :toolCallId "call-j"}])]
+ (is (= "Invalid tool arguments: the arguments were not valid JSON. Send the call again as a JSON object."
+ (-> (into [] (self.core/tool-executor-xf tools) chunks) last :error :message))))))
+
+(deftest ^:parallel tool-without-schema-is-not-validated-test
+ (testing "a tool with no declared argument schema is left alone"
+ (let [tools {"anything" {:fn (fn [_args] {:output "ok"}) :doc "d" :schema nil}}
+ chunks (test-util/parts->aisdk-chunks
+ [{:type :start :id "msg-ns"}
+ {:type :tool-input :id "call-ns" :function "anything" :arguments {:whatever "x"}}])]
+ (is (=? {:type :tool-output-available :toolCallId "call-ns" :result {:output "ok"}}
+ (last (into [] (self.core/tool-executor-xf tools) chunks)))))))
+
;;; tool :decode tests
(defn- make-decode-tool
@@ -476,7 +537,7 @@
{:output "ok"})]
(cond-> {:fn f
:doc (str tool-name " test tool")
- :schema [:=> [:cat [:map [:x :any]]] :any]}
+ :schema [:=> [:cat [:map]] :any]}
decode-fn (assoc :decode decode-fn))))
(deftest ^:parallel tool-decode-var-test
@@ -641,10 +702,11 @@
{:keyword_queries ["15"]
:entity_types ["table"]})))))
-(deftest ^:parallel tool-args-unparseable-scalar-left-alone-test
- (testing "a string that isn't a number is passed through so the tool still reports the error"
- (is (= {:limit "abc"}
- (tool-received-args [:map [:limit [:maybe :int]]] {:limit "abc"})))))
+(deftest ^:parallel tool-args-unparseable-scalar-rejected-test
+ (testing "a string that isn't a number is rejected at the boundary instead of reaching the tool"
+ (is (nil? (tool-received-args [:map [:limit [:maybe :int]]] {:limit "abc"})))
+ (is (= "Invalid tool arguments: `limit` should be an integer; received a string."
+ (validation-error [:map [:limit [:maybe :int]]] {:limit "abc"})))))
(deftest ^:parallel tool-args-coercion-tolerates-unusable-schema-test
(testing "a tool without a usable schema still receives its arguments"
@@ -855,10 +917,16 @@
:arguments {} :title "Inspecting [Orders](metabase://dashboard/5)"}]))))))
(deftest ^:parallel stamp-tool-titles-xf-test
- (let [tools {"greet" {:tool-name "greet" :title-fn (fn [{:keys [who]}] (str "Greeting " who))}
- "boom" {:tool-name "boom" :title-fn (fn [_] (throw (ex-info "nope" {})))}
- "num" {:tool-name "num" :title-fn (fn [_] 42)}
- "plain" {:tool-name "plain"}}
+ (let [tools {"greet" {:tool-name "greet" :title-fn (fn [{:keys [who]}] (str "Greeting " who))}
+ "boom" {:tool-name "boom" :title-fn (fn [_] (throw (ex-info "nope" {})))}
+ "num" {:tool-name "num" :title-fn (fn [_] 42)}
+ "plain" {:tool-name "plain"}
+ "decoded" {:tool-name "decoded"
+ :decode (fn [args] (update args :who (fn [who] (if (string? who) [who] who))))
+ :title-fn (fn [{:keys [who]}] (str "Greeting " (str/join ", " who)))}
+ "badcode" {:tool-name "badcode"
+ :decode (fn [_] (throw (ex-info "nope" {})))
+ :title-fn (fn [_] "never")}}
stamp #(into [] (self.core/stamp-tool-titles-xf tools) [%])]
(testing "title-fn result becomes :title"
(is (= [{:type :tool-input :id "c1" :function "greet" :arguments {:who "Sam"}
@@ -873,6 +941,17 @@
(testing "a tool without a title-fn is untouched"
(is (= [{:type :tool-input :id "c4" :function "plain" :arguments {}}]
(stamp {:type :tool-input :id "c4" :function "plain" :arguments {}}))))
+ (testing "the tool's :decode runs first, so the title describes the arguments the tool will run with"
+ (is (= [{:type :tool-input :id "c5" :function "decoded" :arguments {:who "Sam"}
+ :title "Greeting Sam"}]
+ (stamp {:type :tool-input :id "c5" :function "decoded" :arguments {:who "Sam"}}))))
+ (testing "a throwing :decode leaves the part untitled"
+ (is (= [{:type :tool-input :id "c6" :function "badcode" :arguments {}}]
+ (stamp {:type :tool-input :id "c6" :function "badcode" :arguments {}}))))
+ (testing "a double-encoded argument is coerced before :decode, as it is before the tool runs"
+ (is (= [{:type :tool-input :id "c7" :function "decoded" :arguments {:who "[\"Sam\",\"Kim\"]"}
+ :title "Greeting Sam, Kim"}]
+ (stamp {:type :tool-input :id "c7" :function "decoded" :arguments {:who "[\"Sam\",\"Kim\"]"}}))))
(testing "non-tool-input parts pass through"
(is (= [{:type :text :id "t1" :text "hi"}]
(stamp {:type :text :id "t1" :text "hi"}))))))
diff --git a/test/metabase/metabot/test_util.clj b/test/metabase/metabot/test_util.clj
index 1e37bb6f977..48b7fdbd5de 100644
--- a/test/metabase/metabot/test_util.clj
+++ b/test/metabase/metabot/test_util.clj
@@ -2,6 +2,8 @@
(:require
[clojure.java.io :as io]
[clojure.string :as str]
+ [metabase.metabot.self.core :as self.core]
+ [metabase.metabot.tools :as metabot.tools]
[metabase.util.json :as json]
[metabase.util.log :as log]))
@@ -91,6 +93,19 @@
[{:type :tool-input-available :toolName (:function part) :toolCallId id}])))
parts))
+(defn tool-boundary-error
+ "Run one tool call through the agent tool boundary — the path production uses — and
+ return the error message the model would see, or nil when the call was accepted."
+ [tool-name tool-var arguments]
+ (let [tools (metabot.tools/wrap-tools-with-state {tool-name tool-var} (atom {}) nil nil)
+ chunks (parts->aisdk-chunks
+ [{:type :start :id "msg-boundary"}
+ {:type :tool-input :id "call-boundary" :function tool-name :arguments arguments}])]
+ (-> (into [] (self.core/tool-executor-xf tools) chunks)
+ last
+ :error
+ :message)))
+
(defn mock-llm-response
"Create a mock LLM response (reducible) from high-level parts."
[parts]
diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.clj
index 107bb44ecf7..f144c5e782f 100644
--- a/test/metabase/metabot/tools/resources_test.clj
+++ b/test/metabase/metabot/tools/resources_test.clj
@@ -6,6 +6,8 @@
[medley.core :as m]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.metabot.test-util :as test-util]
+ [metabase.metabot.tools :as metabot.tools]
[metabase.metabot.tools.resources :as read-resource]
[metabase.metabot.tools.shared :as tools.shared]
[metabase.metabot.tools.shared.llm-shape :as llm-shape]
@@ -15,6 +17,12 @@
[metabase.transforms.core :as transforms.core]
[toucan2.core :as t2]))
+(deftest ^:parallel scalar-uris-arg-test
+ (testing "a scalar `uris` is rejected with guidance on how to repair the call"
+ (is (= "Invalid tool arguments: `uris` must be an array of URI strings; received a string."
+ (test-util/tool-boundary-error "read_resource" #'metabot.tools/read-resource-tool
+ {:uris "metabase://table/1"})))))
+
(deftest parse-uri-test
(testing "parses single-segment URIs (top-level lists)"
(is (= {:segments ["databases"] :query-params nil}
diff --git a/test/metabase/metabot/tools/search_test.clj b/test/metabase/metabot/tools/search_test.clj
index 0762763ff32..7f250a24a7d 100644
--- a/test/metabase/metabot/tools/search_test.clj
+++ b/test/metabase/metabot/tools/search_test.clj
@@ -5,6 +5,8 @@
[metabase.api.common :as api]
[metabase.lib-be.metadata.jvm :as lib-be]
[metabase.lib.core :as lib]
+ [metabase.metabot.test-util :as test-util]
+ [metabase.metabot.tools :as metabot.tools]
[metabase.metabot.tools.search :as search]
[metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.permissions.core :as perms]
@@ -23,7 +25,12 @@
(is (= "revenue"
(#'search/search-display {:keyword_queries ["revenue"] :semantic_queries ["revenue"]}))))
(testing "no queries -> nil"
- (is (nil? (#'search/search-display {})))))
+ (is (nil? (#'search/search-display {}))))
+ (testing "a malformed query argument is left untitled rather than rendered character by character"
+ (is (nil? (#'search/search-display {:keyword_queries "metabot byok"})))
+ (is (nil? (#'search/search-display {:semantic_queries "monthly revenue"})))
+ (is (= "orders"
+ (#'search/search-display {:keyword_queries ["orders"] :semantic_queries nil})))))
(deftest ^:parallel search-result->item-test
(testing "trims a result to the fields the results card renders, nesting collection id+name"
@@ -453,6 +460,30 @@
(is (thrown? Exception
(search/search-tool {:keyword_queries ["x"] :limit 0}))))))))
+(deftest ^:parallel scalar-search-args-test
+ (testing "a scalar where an array is declared is rejected with guidance on how to repair the call"
+ (doseq [[field value message]
+ [[:keyword_queries "metabot byok"
+ "Invalid tool arguments: `keyword_queries` must be an array of strings; received a string."]
+ [:semantic_queries "monthly revenue"
+ "Invalid tool arguments: `semantic_queries` must be an array of strings; received a string."]
+ [:entity_types "table"
+ "Invalid tool arguments: `entity_types` must be an array of supported entity type strings; received a string."]]]
+ (testing (str "a scalar " field)
+ (is (= message
+ (test-util/tool-boundary-error "search" #'metabot.tools/search-tool {field value})))))))
+
+(deftest ^:parallel scalar-search-args-every-variant-test
+ (testing "every search tool variant rejects a scalar the same way"
+ (doseq [[tool-var extra-args] [[#'metabot.tools/search-tool {}]
+ [#'metabot.tools/sql-search-tool {:database_id 1}]
+ [#'metabot.tools/nlq-search-tool {}]
+ [#'metabot.tools/transform-search-tool {}]]]
+ (testing (str tool-var)
+ (is (= "Invalid tool arguments: `keyword_queries` must be an array of strings; received a string."
+ (test-util/tool-boundary-error "search" tool-var
+ (assoc extra-args :keyword_queries "metabot byok"))))))))
+
(deftest other-user-collection-test
(testing "excludes entities from other users' collections"
(mt/with-test-user :crowberto