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
Bot 2252 error shape protocols (#84000)
Mihael Konjević2b12351c2d94
diff --git a/.claude/agents/ai-backend-expert.md b/.claude/agents/ai-backend-expert.mdindex 4e2b3c9fedd..14592ad638a 100644--- a/.claude/agents/ai-backend-expert.md+++ b/.claude/agents/ai-backend-expert.md@@ -50,7 +50,7 @@ Enterprise (`enterprise/backend/src/metabase_enterprise/`):- Tool-specific instructions live in skills (`metabase.metabot.skills`, `resources/metabot/skills/`), not in the system prompt. Keep the cached system-prompt prefix stable.- Conversation writes that race need `metabase.metabot.persistence/with-conversation-lock` (a `FOR UPDATE` row lock).- `metabase.ai-tracing.core` captures only under its eval binding. Do not use it for production observability.-- `metabase.metabot.tools.deftool` builds HTTP tool endpoints, not agent tools. Its only caller is its own test. Do not use it as the pattern for new agent tools.+- Agent tools are declared with `metabase.metabot.tools.core/deftool` and report failure by throwing: `defrecoverable` for something the agent can work around, `unrecoverable!` for something only the user can act on. `metabase.metabot.tools.runtime/invoke` decides which audience hears about a failure and in what words — tool code never writes the model-facing text for an undeclared error. Not every tool has been migrated yet; the older ones still use `mu/defn` plus `metabase.metabot.tools.util/handle-agent-error`.## How to workdiff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex 66585900562..78b01407c30 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -201,6 +201,17 @@metabase.mcp.v2.tools.metric-test/call-tool!;; the `!` is for the throw (a teaching error), not a mutation; no shared mutable statemetabase.mcp.v2.tools.browse/validate-args-for-action!+ ;; Metabot tool errors: the `!` is for the throw, not a mutation. A recoverable constructor and+ ;; `unrecoverable!` only build an ex-info and raise it, and `validate-tool!` only inspects a+ ;; declaration. `declare-recoverable!` is deliberately absent — it writes the global catalog.+ metabase.metabot.tools.core/validate-tool!+ metabase.metabot.tools.error/throw-recoverable!+ metabase.metabot.tools.error/unrecoverable!+ metabase.metabot.tools.error-test/test-custom-status!+ metabase.metabot.tools.error-test/test-no-widget!+ metabase.metabot.tools.recoverable.pipeline-test/text-for!+ metabase.metabot.tools.recoverable.pipeline-test/two-surface-error!+ metabase.metabot.tools.recoverable.pipeline/unknown-table!metabase.channel.core/send!metabase.channel.render.pdf/draw-too-large!metabase.channel.render.pdf/draw-no-results!@@ -517,6 +528,9 @@metabase.driver.sql-jdbc.execute.diagnostic/capturing-diagnostic-info clojure.core/fnmetabase.driver-api.core/defsetting hooks.metabase.settings.models.setting/defsettingmetabase.mcp.v2.registry/deftool clojure.core/defn+ metabase.metabot.tools.core/defrecoverable clojure.core/defn+ metabase.metabot.tools.error/defrecoverable clojure.core/defn+ metabase.metabot.tools.recoverable.pipeline/defpipeline-error clojure.core/defmetabase.models.json-migration/def-json-migration clj-kondo.lint-as/def-catch-allmetabase.models.util.spec-update/define-spec clojure.core/defmetabase.notification.test-util/with-card-notification clojure.core/letdiff --git a/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/api_test.cljindex d637c2bab86..6e78cb251dc 100644--- a/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj@@ -5,6 +5,7 @@[metabase-enterprise.test :as met][metabase.driver :as driver][metabase.driver.settings :as driver.settings]+ [metabase.metabot.test-util :as test-util][metabase.metabot.tools.resources :as read-resource][metabase.permissions-rest.data-permissions.graph :as data-perms.graph][metabase.permissions.core :as perms]@@ -218,22 +219,24 @@(met/with-user-attributes! :rasta {"db_name" "customer-a"}(mt/with-current-user (mt/user->id :rasta)(testing "database list includes the router and hides destination databases"- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://databases"]})]+ (let [{:keys [output]} (test-util/call-tool read-resource/read-resource-tool+ {:uris ["metabase://databases"]})](is (str/includes? output "Postgres Router"))(is (not (str/includes? output "customer-a")))(is (not (str/includes? output "customer-b")))))+ ;; A read that found nothing is a failed call, so these assert the failure rather than+ ;; probing a per-URI `:error` — that list is the Agent API's shape, and the tool no longer+ ;; builds it.(testing "a sibling destination cannot be read by URI"- (is (some? (-> (read-resource/read-resource- {:uris [(str "metabase://database/" other-destination-id)]})- :resources- first- :error))))+ (is (= :metabase.metabot.tools.core/all-items-failed+ (:code (test-util/tool-failure+ read-resource/read-resource-tool+ {:uris [(str "metabase://database/" other-destination-id)]})))))(testing "the current user's routed destination cannot be read by URI"- (is (some? (-> (read-resource/read-resource- {:uris [(str "metabase://database/" selected-destination-id)]})- :resources- first- :error))))))))+ (is (= :metabase.metabot.tools.core/all-items-failed+ (:code (test-util/tool-failure+ read-resource/read-resource-tool+ {:uris [(str "metabase://database/" selected-destination-id)]})))))))))(deftest destination-databases-excluded-from-permissions-graph(mt/with-temp [:model/Database {db-id :id} {}diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 64c4ca50a83..8040ce8014d 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -27,6 +27,7 @@[metabase.lib.schema.common :as lib.schema.common][metabase.metabot.core :as metabot][metabase.metabot.tools.construct :as metabot-construct]+ [metabase.metabot.tools.core :as tools.core][metabase.metabot.tools.recovery-hints :as recovery-hints][metabase.metabot.tools.resources :as metabot-resources][metabase.metabot.tools.search :as metabot-search]@@ -40,6 +41,7 @@[metabase.request.core :as request][metabase.server.streaming-response :as streaming-response][metabase.util :as u]+ [metabase.util.i18n :refer [tru]][metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli.registry :as mr]@@ -678,9 +680,12 @@;;; -------------------------------------------------- Read Resource -------------------------------------------------(mr/def ::read-resource-request- "Request shape for /v1/read-resource. Accepts up to 5 metabase:// URIs."- [:map {:closed true}- [:uris [:sequential ms/NonBlankString]]])+ "Request shape for /v1/read-resource: the tool's own published arguments.++ Taken from the tool rather than written out again, so this endpoint and the agent loop offer the+ same shape and the same limits. Before, this was a hand-written copy that had already lost the+ 5-URI cap the tool enforces."+ (:args (tools.core/validate-tool! metabot-resources/read-resource-tool)))(mr/def ::read-resource-item"One fetched resource. Either `:content` (success) or `:error` (failure) is present."@@ -696,12 +701,33 @@[:resources [:sequential ::read-resource-item]][:output :string]])+(def ^:private read-resource-ctx+ "The tool context for this endpoint.++ `:tool-names` decides which recovery steps a per-URI failure keeps: a step is dropped unless the+ caller has every tool its text names. This API publishes `search` (see `/v1/search` below), so the+ \"find it with search\" steps survive here. Renaming that endpoint's tool drops those steps rather+ than sending the caller at something it does not have, which is the point of `:uses`."+ {:tool-names #{"search"}})++(defn- read-resource-item+ "One [[::read-resource-item]] from the tool's entry for that URI.++ This endpoint's published item shape, built here rather than by the tool: a URI that could not be+ read is this item's `:error`, not the call's. The tool reports per item and leaves what that means+ to its caller."+ [{:keys [item output failed? structured-output]}]+ (cond-> {:uri (:uri item)}+ failed? (assoc :error output)+ (not failed?) (assoc :content {:structured-output structured-output})))+(api.macros/defendpoint :post "/v1/read-resource" :- ::read-resource-response"Read one or more Metabase resources via metabase:// URI patterns.- Dispatches into the shared URI resolver in `metabase.metabot.tools.resources`,- which validates URIs, fetches entities with per-URI permission checks, and- returns a map of `{:resources ... :output ...}`. Up to 5 URIs per call."+ Calls the `read_resource` tool in `metabase.metabot.tools.resources` — the same record the agent+ loop calls, so URI dispatch, per-URI permission checks and the per-URI failure text are shared.+ A URI that cannot be read becomes that item's `:error`; the call still returns 200 with the items+ that did read. Up to 5 URIs per call, rejected as a 400 by `::read-resource-request`."{:scope metabot/agent-resource-read:tool {:name "read_resource":description (str "Read Metabase entities by metabase:// URI. "@@ -712,15 +738,29 @@[_route-params_query-paramsbody :- ::read-resource-request]- (try- (metabot-resources/read-resource body)- (catch clojure.lang.ExceptionInfo e- ;; The Metabot dispatcher's "too many URIs" guard throws ex-info without a- ;; :status-code. Surface it as a 400 to the HTTP boundary rather than the- ;; default 500.- (throw (ex-info (ex-message e)- (merge {:status-code 400} (ex-data e))- e)))))+ ;; `with-batched-entries` rather than `tools.core/call`, because this endpoint's contract differs+ ;; from the agent loop's in exactly one way: a call where no URI could be read is still a 200 with+ ;; an `:error` per item, where the agent loop needs it to be a failed call. Composing the entries+ ;; here is what lets both be true without the tool knowing either of us.+ (tools.core/with-batched-entries metabot-resources/read-resource-tool body read-resource-ctx+ {:on-item-fault+ (fn [{:keys [uri]} e]+ ;; One URI hitting a fault is this item's error, not the call's: the others read fine and the+ ;; published response promises every URI it was given. Master did this too, with+ ;; `(ex-message e)` as the text — a message written for a developer, crossing an API boundary+ ;; to an agent that can do nothing with it. The exception goes to the log; the caller gets a+ ;; sentence that is true and says nothing about our internals.+ (log/error e "Reading a resource faulted" {:uri uri})+ {:item {:uri uri}+ :failed? true+ :output (tru "This resource could not be read.")})}+ (fn [entries]+ {:resources (mapv read-resource-item entries)+ ;; The tool's own envelope, so the text is identical to what the agent loop reads. Its+ ;; `:structured-output` and `:data-parts` title are not part of this response.+ :output (tools.core/render-text+ (:output (tools.core/compose metabot-resources/read-resource-tool entries+ read-resource-ctx)))})));;; ------------------------------------------------- Create Question ------------------------------------------------diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.cljindex 4e7ed6fc727..5899d45c262 100644--- a/src/metabase/metabot/agent/core.clj+++ b/src/metabase/metabot/agent/core.clj@@ -26,6 +26,7 @@[metabase.metabot.tools :as tools][metabase.util :as u][metabase.util.async :as async.u]+ [metabase.util.i18n :refer [tru]][metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]@@ -177,11 +178,31 @@(defn- successful-tool-output?"Whether a `:tool-output` part represents a successful call.- Answer-producing tools attach `:structured-output` when they produce a result (a query, a chart- draft, a clarification question), and return just an `:output` error string on validation/exception- failures — so its presence is the success signal."++ Success is the absence of `:error`. It used to be the presence of `:structured-output`, which made+ a tool that produced no structured output indistinguishable from one that failed, and forced+ answer-producing tools to attach one whether a consumer read it or not."[part](and (= (:type part) :tool-output)+ (nil? (get-in part [:result :error]))))++(defn- answer-producing?+ "Whether this `:tool-output` part delivered an answer, rather than reporting a failure.++ Success is the absence of `:error` ([[successful-tool-output?]]), and that is the rule everywhere+ else. Ending a turn needs more, for exactly as long as the terminal tools are unconverted: each of+ them catches its own exceptions and *returns* `{:output \"Query 3 not found\"}` — a failure with+ no `:error` anywhere on it, because nothing was thrown for the adapter to classify. Ending the+ turn on the absence of `:error` would hand that sentence to the user as the answer.++ An unconverted tool's one remaining signal is that it attaches `:structured-output` when it really+ produced something, which is the signal this branch otherwise removed for being unreliable. It is+ reliable for this one set, because every tool in it is answer-producing by definition.++ `metabase.metabot.agent.profiles-test/terminal-tools-are-still-unconverted-test` fails the day one+ of them is converted, which is when this goes away."+ [part]+ (and (successful-tool-output? part)(some? (get-in part [:result :structured-output]))))(defn- terminal-tool-call?@@ -191,11 +212,12 @@forcing the model to keep emitting tool calls under `:required-tool-call?`.Terminality is a per-profile decision — the same tool is non-terminal in profiles that don't list- it. A *failed* terminal-tool call does not end the turn, so the model can still self-correct."+ it. A *failed* terminal-tool call does not end the turn, so the model can still self-correct; see+ [[answer-producing?]] for how a failure is recognised while these tools are unconverted."[terminal-tools parts](boolean(when (seq terminal-tools)- (let [success-ids (into #{} (comp (filter successful-tool-output?) (map :id)) parts)]+ (let [success-ids (into #{} (comp (filter answer-producing?) (map :id)) parts)](some (fn [p](and (= (:type p) :tool-input)(contains? terminal-tools (:function p))@@ -217,12 +239,17 @@(some #(= (:type %) :error) parts))(defn- terminal-error-message- "Message from a tool failure no retry can fix (a permission denial), or nil if there was none."+ "The user-facing message from a tool failure no retry can fix, or nil if there was none.++ An unrecoverable failure is one only the user can act on — a permission denial, a server fault —+ so the turn ends. The message is the `:user-message` the tool chose; a tool that set none gets the+ generic one, because `:output` is written for the model and says only that the call failed."[parts](some (fn [part](when (and (= (:type part) :tool-output)- (get-in part [:result :terminal-error?]))- (not-empty (get-in part [:result :output]))))+ (= :unrecoverable (get-in part [:result :error :class])))+ (or (not-empty (get-in part [:result :error :user-message]))+ (tru "Something went wrong."))))parts))(defn- should-continue?@@ -524,9 +551,14 @@:request-canceled-chan request-canceled-chan)(memory/add-client-ids (client-content-ids context)))memory-atom (doto (or external-memory-atom (atom nil)) (reset! memory))- ;; The show_chart argument only does anything alongside run_query, so a turn without run_query declares- ;; construct_notebook_query as it was before the argument existed.- tools (update-vals (cond-> (tools/wrap-tools-with-state base-tools memory-atom metabot profile-id)+ ;; `profile->tools` keys by name; `->entries` takes the tools themselves and keys them from+ ;; their declarations, so converted and unconverted ones arrive the same way.+ ;;+ ;; The show_chart argument only does anything alongside run_query, so a turn without+ ;; run_query declares construct_notebook_query as it was before the argument existed.+ ;; `without-show-chart` edits the entry's `:schema`, which `->entries` synthesises in the+ ;; same `[:=> [:cat args] out]` shape it read off the var before.+ tools (update-vals (cond-> (tools/->entries (vals base-tools) memory-atom metabot profile-id)(not (contains? base-tools "run_query"))(m/update-existing "construct_notebook_query" tools/without-show-chart))#(assoc % :declaration (delay (self.schema/tool-function %))))]@@ -645,9 +677,11 @@(do(log/debug "Got parts" {:count (count parts) :types (mapv :type parts)})(swap! memory-atom update-memory parts)- ;; these profiles cannot answer in text, so a denial would otherwise loop to max-iterations- (let [terminal-error (when (:required-tool-call? profile)- (terminal-error-message parts))]+ ;; Every profile, not just the `:required-tool-call?` ones. An unrecoverable failure is+ ;; defined as one only the user can act on, so the class is the decision and the profile+ ;; is not part of it. A tool that wants the agent to carry on past a failure declares it+ ;; recoverable, which is a choice made at the error, where the reason for it is visible.+ (let [terminal-error (terminal-error-message parts)](cond(reduced? result');; consumer signalled early termination (e.g. client disconnect / cancellation)diff --git a/src/metabase/metabot/agent/profiles.clj b/src/metabase/metabot/agent/profiles.cljindex 49c51849cce..42d08b2fd6d 100644--- a/src/metabase/metabot/agent/profiles.clj+++ b/src/metabase/metabot/agent/profiles.clj@@ -14,19 +14,26 @@[metabase.metabot.settings :as metabot.settings][metabase.metabot.skills :as skills][metabase.metabot.tools :as tools]+ [metabase.metabot.tools.core :as tools.core][metabase.metabot.tools.explorations :as tools.explorations]+ [metabase.metabot.tools.legacy :as tools.legacy][metabase.search.entity-retrieval.core :as entity-retrieval][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]))(def ^:private tool-var-schema- "Schema for a tool var: must be a var with :tool-name and :schema in metadata."- [:fn {:error/message "Expected a var with :tool-name and :schema metadata"}+ "Schema for one of a profile's tools.++ Either kind: a var whose value implements `metabase.metabot.tools.core/Tool`, or — until it is+ converted — a var with `:tool-name` and `:schema` in its metadata. A profile names both as vars,+ so converting a tool does not touch any profile."+ [:fn {:error/message (str "Expected a var holding a metabase.metabot.tools.core/Tool, "+ "or a var with :tool-name and :schema metadata")}(fn [v](and (var? v)- (string? (:tool-name (meta v)))- (some? (:schema (meta v)))))])+ (or (tools.legacy/legacy-tool? v)+ (satisfies? tools.core/Tool (deref v)))))])(def ^:private *profiles"Map of profile-id to profile configuration"@@ -86,7 +93,10 @@[:terminal-tools {:optional true} [:set :string]][:system-prompt-context {:optional true} [:fn ifn?]]]](let [tool-vars (:tools profile)- tool-name-seq (map #(:tool-name (meta %)) tool-vars)+ ;; The declaration, not the var's metadata: a converted tool is a record held by a var and+ ;; carries no `:tool-name` meta, so reading meta made every converted tool in a profile+ ;; report `nil` and the second one look like a duplicate of the first.+ tool-name-seq (map #(:name (tools.legacy/declaration-of %)) tool-vars)tool-names (set tool-name-seq)](doseq [tool-var tool-vars](validate-tool-var! tool-var))@@ -258,32 +268,36 @@#'tools/select-exploration-timelines-tool]})(defn- filter-by-capabilities- "Filter tool vars by user capabilities.+ "Filter tools by user capabilities.Removes tools that require capabilities the user doesn't have.Capabilities from the API arrive as strings (e.g. \"permission:write_sql_queries\")while tool metadata uses keywords (e.g. :permission-write-sql-queries), so wenormalize to keywords before comparing."- [tool-vars capabilities]+ [tools capabilities](let [capabilities-set (capabilities/capability-set capabilities)]- (filter (fn [tool-var]- (every? capabilities-set (:capabilities (meta tool-var))))- tool-vars)))+ (filter (fn [tool]+ (every? capabilities-set+ (:metabot/capabilities (tools.legacy/declaration-of tool))))+ tools)))(defn- filter-by-scope- "Filter tool vars by the current user's scope set.- Removes tools whose `:scope` metadata is not satisfied by `*current-user-scope*`.- Tools without `:scope` metadata pass through."- [tool-vars]- (filter (fn [tool-var]- (let [required-scope (:scope (meta tool-var))]+ "Filter tools by the current user's scope set.+ Removes tools whose declared `:scope` is not satisfied by `*current-user-scope*`.+ Tools that declare no scope pass through."+ [tools]+ (filter (fn [tool]+ (let [required-scope (:scope (tools.legacy/declaration-of tool))](or (nil? required-scope)(api-scope/scope-matches? scope/*current-user-scope* required-scope))))- tool-vars))+ tools))(defn- tool-map- "Create a map of tool-name -> tool-var from a sequence of tool vars."- [tool-vars]- (into {} (map (juxt #(:tool-name (meta %)) identity) tool-vars)))+ "Create a map of model-facing tool name -> tool from a sequence of tools.++ A tool is a converted record or a var that is still the old shape; its declaration answers either+ way, which is why this no longer reads var metadata."+ [tools]+ (into {} (map (juxt #(:name (tools.legacy/declaration-of %)) identity) tools)));;; APIdiff --git a/src/metabase/metabot/persistence.clj b/src/metabase/metabot/persistence.cljindex a842974d1ef..82fcb6f00d3 100644--- a/src/metabase/metabot/persistence.clj+++ b/src/metabase/metabot/persistence.clj@@ -9,7 +9,6 @@[metabase.metabot.agent.streaming :as streaming][metabase.metabot.db :as metabot.db][metabase.metabot.schema :as metabot.schema]- [metabase.metabot.schema.migrate-v1-to-v2 :as migrate][metabase.metabot.schema.v2 :as schema.v2][metabase.metabot.self.core :as self.core][metabase.metabot.settings :as metabot.settings]@@ -48,7 +47,7 @@"The stored `:output` value for a v2 tool part. A map result is trimmed to`:output` (the LLM-facing text adapters read on history replay) plus the`persisted-structured-output-keys` subset of structured output, canonicalized- to `:structured_output`; everything else (`:resources`, `:data-parts`,+ to `:structured_output`; everything else (`:data-parts`,`:reactions`, …) is dropped — that's where the bulk of the bloat lives. Anon-map result (a tool that returned a bare string/scalar) is stored as-is —the v2 part schema types `:output` as any JSON value — so readers must@@ -81,7 +80,10 @@:text {:type "text" :text (:text part) :state "done"}:tool-input(let [output (get outputs (:id part))- error (:error output)]+ ;; From the result, not the part: a failed call carries its `:error`+ ;; there and nowhere else. Reading the part stored every failure as+ ;; `output-available`, so history and replay saw a success.+ error (get-in output [:result :error])](cond-> {:type (str "tool-" (:function part)):toolCallId (:id part):state (cond@@ -93,7 +95,14 @@(assoc :output (tool-result->storable-output (:result output)))(some? error)- (assoc :errorText (migrate/error->text error))))+ ;; The model-facing text, not the reader-facing one. `:errorText` is+ ;; what [[tool-part->llm-messages]] replays to the model for a failed+ ;; step, so storing a generic sentence here would lose the authored+ ;; failure — the table that was missing, the argument to repair — on+ ;; every replay. One field, two audiences; the model wins, because the+ ;; live SSE channel has its own and the whole point of the text is that+ ;; the agent can act on it.+ (assoc :errorText (str (get-in output [:result :output]))))):data {:type (str "data-" (or (:data-type part) "data")):data (:data part)}(do (log/warn "Dropping internal part with no v2 storage representation"diff --git a/src/metabase/metabot/self.clj b/src/metabase/metabot/self.cljindex 13cb81cf1c0..7a70551326d 100644--- a/src/metabase/metabot/self.clj+++ b/src/metabase/metabot/self.clj@@ -298,7 +298,11 @@:session-id session-id:profile (some-> profile-id name):duration-ms (some-> (:duration-ms part) long)- :result (if (:error part) "error" "success")+ ;; A failed call carries `:error` on its result — success+ ;; is the absence of it, as it is everywhere else.+ :result (if (get-in part [:result :error])+ "error"+ "success"):event-details (cond-> {"tool_name" (if (contains? tools (:function part))(:function part)"unknown")}diff --git a/src/metabase/metabot/self/claude.clj b/src/metabase/metabot/self/claude.cljindex 6461f58409d..76fe4ae04c8 100644--- a/src/metabase/metabot/self/claude.clj+++ b/src/metabase/metabot/self/claude.clj@@ -255,12 +255,16 @@:name (:function part):input (or (:arguments part) {})}]}:tool-output {:role "user"- :content [{:type "tool_result"- :tool_use_id (:id part)- :content (or (get-in part [:result :output])- (when-let [err (:error part)]- (str "Error: " (:message err)))- (pr-str (:result part)))}]}+ :content [(cond-> {:type "tool_result"+ :tool_use_id (:id part)+ :content (or (get-in part [:result :output])+ (pr-str (:result part)))}+ ;; A failed call is marked as one. Without this the+ ;; model reads the failure text as an ordinary+ ;; result, and the thinking panel shows the step as+ ;; having worked.+ (get-in part [:result :error])+ (assoc :is_error true))]};; User messages pass through{:role (name (or (:role part) "user")):content (:content part)}))))diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.cljindex 0fd7e708a6e..3fa64e98d30 100644--- a/src/metabase/metabot/self/core.clj+++ b/src/metabase/metabot/self/core.clj@@ -5,11 +5,11 @@[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][metabase.metabot.schema.v2 :as schema.v2]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.runtime :as tools.runtime][metabase.premium-features.core :as premium-features][metabase.settings.core :as setting][metabase.util :as u]@@ -71,14 +71,14 @@[:mistral {:optional true} [:maybe MistralProviderMetadata]]])(def ToolEntry- "A tool definition map with :tool-name, :doc, :schema, :fn, and optionally :decode/:prompt."+ "One tool as the agent loop and the adapters see it, built by `metabase.metabot.tools/->entries`.+ `:fn` performs the whole call through `metabase.metabot.tools.runtime/invoke` and never throws."[:map {:closed true}[:tool-name :string][:doc {:optional true} [:maybe :string]][:schema MalliSchema][:declaration {:optional true} [:maybe [:fn delay?]]][:fn [:fn fn?]]- [:decode {:optional true} [:maybe [:fn fn?]]][:prompt {:optional true} [:maybe :string]][:title-fn {:optional true} [:maybe [:fn fn?]]][:system-instructions {:optional true} [:maybe :string]]@@ -94,26 +94,19 @@[:data {:optional true} [:maybe ::schema.v2/tool-io]]])(def ^:private ToolResult- "The raw return value of a tool's `:fn`, before it is trimmed for persistence or forwarded to- a provider (see [[collect-tool-result]])."- [:or- :string- :keyword- number?- :boolean- :nil- [:map {:closed true}- [:output {:optional true} [:maybe :string]]- [:structured-output {:optional true} [:maybe ::schema.v2/tool-io]]- [:structured_output {:optional true} [:maybe ::schema.v2/tool-io]]- [:terminal-error? {:optional true} :boolean]- [:data-parts {:optional true} [:sequential DataPart]]- [:resources {:optional true} [:sequential ::schema.v2/tool-io]]- [:instructions {:optional true} [:maybe :string]]- [:status-code {:optional true} [:maybe :int]]- [:error {:optional true} [:maybe [:map {:closed true}- [:message {:optional true} [:maybe :string]]- [:type {:optional true} [:maybe :string]]]]]]])+ "What a tool's `:fn` returns: a `metabase.metabot.tools.runtime` outcome.++ A success is the handler's result. A failure carries the text the model reads in `:output` plus the+ machine-readable `:error`, so success is the absence of `:error` and nothing has to inspect+ `:structured-output` to tell them apart."+ [:map {:closed true}+ [:output :string]+ [:structured-output {:optional true} [:maybe ::schema.v2/tool-io]]+ [:data-parts {:optional true} [:sequential DataPart]]+ [:error {:optional true} [:map {:closed true}+ [:class [:enum :validation :recoverable :unrecoverable]]+ [:code :keyword]+ [:user-message {:optional true} :string]]]])(mr/def ::decoded-json"A value decoded from JSON with `json/decode`, with string object keys at every depth.@@ -488,11 +481,13 @@:function (:toolName chunk):arguments (parse-tool-arguments chunks)}pm (assoc :provider-metadata pm)))+ ;; No `:error` on the part. A failed call carries its `:error` inside `:result`, which is the one+ ;; place anything asks — the agent loop, the SSE writer, persistence and telemetry all read it+ ;; there. A second copy here is what let a failure reach the client as a success.:tool-output-available {:type :tool-output:id (:toolCallId chunk):function (:toolName chunk):result (:result chunk)- :error (:error chunk):duration-ms (::duration-ms chunk)};; A group opening with a continuation chunk (:tool-input-delta, :text-delta, ...) has lost its start chunk,;; and with it the data the part needs (a tool call's name), so it cannot be assembled.@@ -589,17 +584,15 @@(defn stamp-tool-titles-xf"Stamp a client-facing `:title` onto `:tool-input` parts via each tool's- 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."+ optional `:title-fn`. Stringified JSON is coerced first, so the title describes the arguments the+ tool will run with. A throwing title-fn leaves the part untitled."[tools](map (fn [part]- (let [{:keys [title-fn decode]} (when (= :tool-input (:type part))- (get tools (:function part)))]+ (let [{:keys [title-fn]} (when (= :tool-input (:type part))+ (get tools (:function part)))](if title-fn(let [title (try- (title-fn (cond-> (walk/keywordize-keys (coerce-stringified-json (:arguments part)))- decode decode))+ (title-fn (walk/keywordize-keys (coerce-stringified-json (:arguments part))))(catch Throwable e(log/debug e "tool title-fn failed" {:tool (:function part)})nil))]@@ -735,7 +728,7 @@(defn- tool-output->wire-output"The `tool-output-available` event's `:output` value: the LLM-facing output- string. The full result map (`:resources`, `:data-parts`, …) stays off the+ string. The full result map (`:structured-output`, `:data-parts`, …) stays off thewire — anything the client renders arrives as its own `:data` part."[result](cond@@ -892,10 +885,11 @@:tool-output(rf result(format-sse-event- (if-let [error (:error part)]+ (if-let [error (get-in part [:result :error])]{:type "tool-output-error":toolCallId (:id part)- :errorText (or (:message error) (str error))}+ ;; Not `:output`, which is written for the model; see `step-failure-text`.+ :errorText (tools.error/step-failure-text error)}{:type "tool-output-available":toolCallId (:id part):output (tool-output->wire-output (:result part))})))@@ -963,44 +957,6 @@result)[(assoc ids :type :tool-output-available :result result)])))-(defn- concise-tool-error- "Produce a concise error message for the LLM from a tool execution exception.- For malli validation errors, extracts the humanized map and summarizes it.- For other errors, uses the exception message."- [^Exception e]- (let [data (ex-data e)]- (if-let [humanized (:humanized data)]- ;; Malli validation error — produce a short summary the LLM can act on- (str "Invalid tool arguments: " (pr-str humanized))- ;; Other errors- (or (ex-message e) "Unknown error"))))--(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."- (mtx/transformer- {:name :llm-stringified-scalars- :decoders (select-keys (mtx/-string-decoders)- [:int :double :float :boolean 'int? 'double? 'float? 'boolean?- 'integer? 'nat-int? 'neg-int? 'pos-int? 'number? 'decimal?])}))--(defn- tool-args-schema- "The schema for a tool's argument map, from its `[:=> [:cat args] out]` schema."- [tool]- (let [[_:=> [_:cat args] _out] (:schema tool)]- args))--(defn- coerce-stringified-scalars- "Coerce string tool `arguments` to the scalar types the tool's schema declares.- Some models send numbers as JSON strings, e.g. `{\"limit\": \"15\"}`.- Values that can't be parsed and tools without a usable schema are left alone."- [tool arguments]- (or (try- (some-> (tool-args-schema tool)- (mc/decode arguments stringified-scalar-transformer))- (catch Exception _ nil))- arguments))-(defn- json-type-name[v](cond@@ -1012,76 +968,40 @@(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- non-object-arguments-message"The error for tool `arguments` that are not a JSON object, e.g. `[\"orders\"]`."[arguments](str "Invalid tool arguments: expected an object of named arguments; received " (json-type-name arguments) "."))-(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)]- (if (map? humanized)- (str "Invalid tool arguments: "- (str/join " " (for [[field messages] (sort-by (comp name key) humanized)]- (argument-error-text arguments field messages))))- ;; The error isn't per-field. Today that only happens when a tool's own `:decode` returns a non-map: a- ;; JSON array the model sent is rejected earlier by [[reject-unparsed-arguments!]].- (non-object-arguments-message arguments)))))--(defn- reject-unparsed-arguments!- "Throw an agent error when `arguments` is a [[parse-tool-arguments]] sentinel rather than a JSON object."+(defn- unparsed-arguments-outcome+ "The validation outcome for `arguments` that came off the stream as a [[parse-tool-arguments]]+ sentinel rather than a JSON object, or nil when they parsed.++ Diagnosed here and not in `metabase.metabot.tools.runtime`, which otherwise owns every argument+ check: the sentinel is an artifact of reading the stream, which is this namespace's job and+ something the runtime never sees. The runtime's question is whether a parsed object matches the+ tool's schema.++ Returns an outcome rather than throwing so the class stays `:validation` — the model can repair+ this by resending the call — instead of landing in `run-tool`'s catch as an `:internal` fault."[arguments](when-let [unparsed (unparsed-arguments arguments)](if (contains? unparsed :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}))- (throw (ex-info (non-object-arguments-message (:non-object-arguments unparsed))- {:agent-error? true})))))--(defn- validate-tool-arguments!- [tool arguments]- (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.- Returns `nil` if the tool has no decoder."- [tool]- (:decode tool))--(defn- tool-call-fn- "Extract the callable function from a tool definition map."- [tool]- (:fn tool))+ {:output "Invalid tool arguments: the arguments were not valid JSON. Send the call again as a JSON object."+ :error {:class :validation :code :invalid-json}}+ {:output (non-object-arguments-message (:non-object-arguments unparsed))+ :error {:class :validation :code :invalid-arguments}})))(defn- run-tool- "Execute a tool and return output chunks. Handles errors gracefully.-- If the tool has a `:decode` metadata function, it is applied to the parsed- arguments before invocation. The decode function can coerce values and throw- `:agent-error?` exceptions for validation failures.+ "Execute a tool and return output chunks.- 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.+ Everything about the call itself belongs to `metabase.metabot.tools.runtime/invoke`, which an+ entry's `:fn` reaches: argument coercion, argument validation against the tool's schema, the scope+ check, the call, the result check, and turning any failure into text for the right audience. It+ does not throw, so a `tool_use` always gets a `tool_result`.- A call to a tool outside `tools` gets an error listing the ones it can call. Its name is model output,- so logs and span data record it as \"unknown\".+ A call to a tool outside `tools` gets an error listing the ones it can call. Its name is model+ output, so logs and span data record it as \"unknown\".Chunks have a ::duration-ms key added for internal use which is not part of the aisdk spec."[tool-call-id tool-name tools chunks]@@ -1097,42 +1017,31 @@(fn [chunk](cond-> chunk(= (:type chunk) :tool-output-available) (assoc ::duration-ms duration-ms))))- results (try- (when-not tool- (throw (ex-info (str "Tool `" tool-name "` does not exist. Available tools: "- (str/join ", " (sort (keys tools))) ".")- {:agent-error? true})))- (let [{:keys [arguments]} (into {} (aisdk-xf) chunks)- ;; Before coercion: `coerce-stringified-json` would decode a double-encoded- ;; `{::non-object-arguments "{...}"}` into an object and garble the message.- _ (reject-unparsed-arguments! arguments)- arguments (walk/keywordize-keys (or (coerce-stringified-json arguments) {}))- arguments (coerce-stringified-scalars tool arguments)- decode (tool-decode-fn tool)- arguments (cond-> arguments decode decode)- _ (validate-tool-arguments! tool arguments)]- (log/debug "Executing tool" {:tool-name safe-name})- (when (ait/capture-active?)- (ait/record! {:ai/tool-args arguments}))- (let [tool-fn (tool-call-fn tool)- result (tool-fn arguments)]- (log/debug "Tool returned" {:tool-name safe-name :result-type (type result)})- (collect-tool-result tool-call-id tool-name result)))- (catch Exception e- (cond- (nil? tool)- (log/debugf "Tool call %s: unknown tool" tool-call-id)-- (:agent-error? (ex-data e))- (log/debugf "Tool %s: agent validation error: %s" safe-name (ex-message e))-- :else- (log/error e "Tool execution failed" {:tool-name safe-name}))- [{:type :tool-output-available- :toolCallId tool-call-id- :toolName tool-name- :error {:message (concise-tool-error e)- :type (str (type e))}}]))]+ outcome (if-not tool+ (do (log/debugf "Tool call %s: unknown tool" tool-call-id)+ (tools.runtime/unknown-tool-outcome tool-name (keys tools)))+ (let [{:keys [arguments]} (into {} (aisdk-xf) chunks)]+ ;; Checked before coercion: `coerce-stringified-json` would decode a+ ;; double-encoded `{::non-object-arguments "{…}"}` into an object and+ ;; garble the message.+ (or+ (unparsed-arguments-outcome arguments)+ (let [arguments (walk/keywordize-keys+ (or (coerce-stringified-json arguments) {}))]+ (log/debug "Executing tool" {:tool-name safe-name})+ (when (ait/capture-active?)+ (ait/record! {:ai/tool-args arguments}))+ (try+ ((:fn tool) arguments)+ (catch Throwable e+ ;; `invoke` does not throw. If something gets past it, pairing the+ ;; call with a result still matters more than the diagnosis, so+ ;; log and report the same shape a server fault reports.+ (log/error e "Tool invocation escaped the runtime"+ {:tool-name safe-name})+ {:output "This call failed and the user was shown the error (:internal). Don't retry it."+ :error {:class :unrecoverable :code :internal}}))))))+ results (collect-tool-result tool-call-id tool-name outcome)](when (ait/capture-active?)(ait/record! {:ai/tool-output results}))(mapv (assoc-ms (u/since-ms start-ms))diff --git a/src/metabase/metabot/tools.clj b/src/metabase/metabot/tools.cljindex 7880b3f7d0d..9b2f7d664eb 100644--- a/src/metabase/metabot/tools.clj+++ b/src/metabase/metabot/tools.clj@@ -1,29 +1,29 @@(ns metabase.metabot.tools"Tool registry for the agent loop.- Provides tool vars and state-aware wrapping.- Each tool is a var whose metadata contains `:tool-name`, `:schema`, and optionally- `:capabilities`, `:prompt`, `:decode`, and `:system-instructions`. The var itself- is a function that takes the tool arguments and returns a result map."+ A tool is either a record implementing `metabase.metabot.tools.core/Tool`, or — until it is+ converted — an `mu/defn` var whose metadata carries `:tool-name`, `:schema` and friends.+ `metabase.metabot.tools.legacy` wraps the second kind, so [[->entries]] treats both the same."(:require- [metabase.api-scope.core :as api-scope][metabase.metabot.scope :as scope][metabase.metabot.tools.analyze-chart :as tools.analyze-chart][metabase.metabot.tools.autogen-dashboard :as tools.autogen-dashboard][metabase.metabot.tools.charts :as tools.charts][metabase.metabot.tools.clarification :as tools.clarification][metabase.metabot.tools.construct :as tools.construct]+ [metabase.metabot.tools.core :as tools.core][metabase.metabot.tools.create-alert :as tools.create-alert][metabase.metabot.tools.create-dashboard-subscription :as tools.create-dashboard-subscription][metabase.metabot.tools.document :as tools.document][metabase.metabot.tools.entity-retrieval :as tools.entity-retrieval][metabase.metabot.tools.explorations :as tools.explorations]+ [metabase.metabot.tools.legacy :as tools.legacy][metabase.metabot.tools.metadata :as tools.metadata][metabase.metabot.tools.resources :as tools.resources][metabase.metabot.tools.run-query :as tools.run-query]+ [metabase.metabot.tools.runtime :as tools.runtime][metabase.metabot.tools.save-entity :as tools.save-entity][metabase.metabot.tools.search :as tools.search]- [metabase.metabot.tools.shared :as shared][metabase.metabot.tools.skills :as tools.skills][metabase.metabot.tools.slackbot-query :as tools.slackbot-query][metabase.metabot.tools.snippets :as tools.snippets]@@ -33,7 +33,6 @@[metabase.metabot.tools.timelines :as tools.timelines][metabase.metabot.tools.todo :as tools.todo][metabase.metabot.tools.transforms :as tools.transforms]- [metabase.util.log :as log][potemkin :as p]))(set! *warn-on-reflection* true)@@ -117,69 +116,42 @@"replace_sql_query""construct_notebook_query"})-(def ^:private state-dependent-tools- "Set of tool names that require access to agent state."- #{"analyze_chart"- "create_chart" "edit_chart" "save_entity" "todo_write" "todo_read"- "create_autogenerated_dashboard"- "create_sql_query" "edit_sql_query" "replace_sql_query" "construct_notebook_query"- "document_schema_collect" "document_construct_sql_chart" "document_construct_model_chart"- "create_alert" "create_dashboard_subscription" "static_viz"- "read_resource" "run_query"})+(defn ->entries+ "The agent's tool entries for one turn: a map of model-facing tool name to entry.-(defn- wrap-with-scope-check- "Wrap a tool function with a scope check. Returns a function that checks- `*current-user-scope*` against `required-scope` before calling `f`.- Returns a denial message if the scope is not satisfied."- [f tool-name required-scope]- (fn [args]- (if (api-scope/scope-matches? scope/*current-user-scope* required-scope)- (f args)- (do (log/warnf "Scope check failed for tool %s — required: %s, granted: %s"- tool-name required-scope scope/*current-user-scope*)- {:output "You do not have permission to use this tool."}))))+ `tool-list` holds the profile's tools, converted or not — `tools.legacy/adapt-all` wraps the ones+ that are still `mu/defn` vars, so from here on nothing distinguishes them.-(defn wrap-tools-with-state- "Wrap state-dependent tools with access to the memory atom.- Tools in `state-dependent-tools` will have access to the memory atom- via the dynamic `shared/*memory-atom*` binding.+ An entry keeps the keys the adapters and the system-message builder already read (`:tool-name`,+ `:doc`, `:schema`, `:title-fn`, `:prompt`, `:system-instructions`, `:capabilities`, `:scope`), and+ its `:fn` performs the whole call through `metabase.metabot.tools.runtime/invoke`. So argument+ coercion, argument validation, the scope check, the result check and error rendering all happen in+ one place, and `:fn` never throws.- Takes a tools map where values are tool vars. Returns a tools map where- values are tool definition maps (with :doc, :schema, :prompt, :fn, and- optionally :decode keys).-- Tool-specific *instructions* are no longer carried in the prompt. They live in- the skill registry (`metabase.metabot.skills`) and are surfaced as a manifest- in the system prompt, with full bodies loaded on demand via the `load_skill`- tool."- [tools memory-atom metabot profile-id]- (reduce-kv- (fn [acc tool-name tool-var]- (let [m (meta tool-var)- base-fn (if (contains? state-dependent-tools tool-name)- (fn [args]- (binding [shared/*memory-atom* memory-atom- shared/*metabot* metabot- shared/*profile-id* profile-id]- (tool-var args)))- (fn [args]- (binding [shared/*metabot* metabot- shared/*profile-id* profile-id]- (tool-var args))))- tool-scope (:scope m)- tool-fn (if tool-scope- (wrap-with-scope-check base-fn tool-name tool-scope)- base-fn)- tool-def {:tool-name (:tool-name m)- :doc (:doc m)- :schema (:schema m)- :prompt (:prompt m)- :decode (:decode m)- :title-fn (:title-fn m)- :system-instructions (:system-instructions m)- :capabilities (:capabilities m)- :scope (:scope m)- :fn tool-fn}]- (assoc acc tool-name tool-def)))- {}- tools))+ `:schema` is synthesised as `[:=> [:cat args] :any]` because that is the shape+ `metabase.metabot.self.schema/tool-function` reads. It is the declaration's `:args` either way."+ [tool-list memory-atom metabot profile-id]+ (let [entries (tools.core/entries (tools.legacy/adapt-all tool-list))+ ;; `*current-user-scope*` is read here, once per turn and inside the request, rather than by+ ;; the runtime: `metabase.metabot.scope` reaches the provider adapters through+ ;; `metabot.settings`, and those require `metabase.metabot.self.core`, which requires the+ ;; runtime — so the runtime cannot require scope without a load cycle.+ ctx {:profile-id profile-id+ :metabot metabot+ :user-scope scope/*current-user-scope*+ :tool-names (set (keys entries))+ :memory-atom memory-atom}]+ (update-vals+ entries+ (fn [{:keys [declaration]}]+ (let [{tool-name :name :keys [description args scope]} declaration]+ {:tool-name tool-name+ :doc description+ :schema [:=> [:cat args] :any]+ :scope scope+ :capabilities (:metabot/capabilities declaration)+ :title-fn (:metabot/title-fn declaration)+ :prompt (:metabot/prompt declaration)+ :system-instructions (:metabot/system-instructions declaration)+ :fn (fn [arguments]+ (tools.runtime/invoke entries ctx tool-name arguments))})))))diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.cljindex bda67be343c..626d9c739e7 100644--- a/src/metabase/metabot/tools/construct.clj+++ b/src/metabase/metabot/tools/construct.clj@@ -18,7 +18,7 @@[metabase.metabot.scope :as scope][metabase.metabot.tmpl :as te][metabase.metabot.tools.charts.create :as create-chart-tools]- [metabase.metabot.tools.recovery-hints :as recovery-hints]+ [metabase.metabot.tools.core :as tools][metabase.metabot.tools.shared :as shared][metabase.metabot.tools.shared.content-store :as shared.content-store][metabase.metabot.tools.shared.instructions :as instructions]@@ -860,76 +860,86 @@;;; ---------------------------------------- Main tool -----------------------------------------(mu/defn ^{:tool-name "construct_notebook_query"- :scope scope/agent-notebook-create}- construct-notebook-query-tool- "Construct and visualize a notebook query from a metric, model, or table.-- Accepts an MBQL 5 query as a JSON object matching `::lib.schema/external-query`, plus a- short, human-friendly `title` shown above the resulting chart. Also provide a concise- one- or two-sentence `description` of what the chart shows (the metric, the grouping, and- any notable filter); it is used as the saved question's description. See- `resources/metabot/prompts/tools/construct_notebook_query.md` for the prompt contract."- [{:keys [_reasoning query visualization show_chart title description]} :- construct-notebook-query-args-schema]- (try- (let [normalized-visualization (some-> visualization (update-keys (comp keyword u/->kebab-case-en name)))- chart-type (or (chart-type->keyword (:chart-type normalized-visualization))- :table)- query-result (execute-representations-query- query- {:recovery-hint recovery-hints/recovery-hint})- structured (or (:structured-output query-result) (:structured_output query-result))- ;; A query built only to be read needs run_query, so without it the chart is the one way the user sees- ;; anything and is always shown.- show-chart? (not (and (false? show_chart) (shared/tool-offered? "run_query")))]- (cond- (not (and structured (:query-id structured) (:query structured)))- ;; query-result may already have :output (error) or only :structured-output- (if structured- (let [query-xml (llm-shape/query->xml (structured->query-data structured))- instruction-text (instructions/query-created-instructions-for (:query-id structured) false)]- (assoc query-result :output (tool-output query-xml instruction-text)))- query-result)-- (not show-chart?)+(def ^:private tool-description+ "What the model is told `construct_notebook_query` is."+ (str+ "Construct and visualize a notebook query from a metric, model, or table.\n"+ "\n"+ "Accepts an MBQL 5 query as a JSON object matching `::lib.schema/external-query`, plus a\n"+ "short, human-friendly `title` shown above the resulting chart. Also provide a concise\n"+ "one- or two-sentence `description` of what the chart shows (the metric, the grouping, and\n"+ "any notable filter); it is used as the saved question's description. See\n"+ "`resources/metabot/prompts/tools/construct_notebook_query.md` for the prompt contract."))++(defn- chart-instructions+ "What to tell the model to do with the chart it just got."+ [chart-id]+ (let [link (te/link "Chart" "metabase://chart/" chart-id)]+ (te/lines+ "Your query and chart have been created successfully."+ ""+ "Next steps to present the chart to the user:"+ (str "- Always provide a direct link using: `" link "` where Chart is a meaningful link text")+ "- If creating multiple charts, present all chart links")))++(defrecord ConstructNotebookQueryTool []+ tools/Tool+ (declaration [_]+ {:name "construct_notebook_query"+ :description tool-description+ :scope scope/agent-notebook-create+ :args construct-notebook-query-args-schema})++ (handle [_ {:keys [query visualization show_chart title description]} _ctx]+ (let [chart-type (or (-> visualization+ (some-> (update-keys (comp keyword u/->kebab-case-en name)))+ :chart-type+ chart-type->keyword)+ :table)+ ;; The one place a representations-pipeline error is allowed to become something the+ ;; model reads. A `:error` code the pipeline declares becomes that recoverable error with+ ;; its recovery steps; anything else — a lib, toucan2 or JDBC failure that the pipeline's+ ;; `as-agent-input-error` stamped `:agent-error?` onto without authoring a sentence for+ ;; it — stays unrecoverable and ends the turn.+ ;;+ ;; `execute-representations-query` either throws or returns a structured output carrying+ ;; both `:query-id` and `:query`, so there is nothing to branch on after it.+ structured (:structured-output (tools/with-pipeline-errors+ (execute-representations-query query)))+ ;; A query built only to be read needs run_query, so without it the chart is the one way+ ;; the user sees anything and is always shown.+ show-chart? (not (and (false? show_chart) (shared/tool-offered? "run_query")))]+ (if-not show-chart?(let [instruction-text (te/lines"Your query has been created. The user has not been shown it."""(str "To read its values, call `run_query` with `query_id` `"(:query-id structured) "`."))]- {:output (tool-output (llm-shape/query->xml (structured->query-data structured)) instruction-text)- :structured-output (assoc structured :result-type :query)- :instructions instruction-text})-- :else- (let [chart-result (create-chart-tools/create-chart- {:query-id (:query-id structured)- :chart-type chart-type- :queries-state {(:query-id structured) (:query structured)}})- full-structured (assoc structured+ {:output (tool-output (llm-shape/query->xml (structured->query-data structured))+ instruction-text)+ :structured-output (assoc structured :result-type :query)})+ (let [chart (create-chart-tools/create-chart+ {:query-id (:query-id structured)+ :chart-type chart-type+ :queries-state {(:query-id structured) (:query structured)}})+ instruction-text (chart-instructions (:chart-id chart))]+ {:output (tool-output (structured->chart-xml structured (:chart-id chart) chart-type)+ instruction-text)+ :structured-output (assoc structured:result-type :query- :chart-id (:chart-id chart-result)- :chart-type (:chart-type chart-result)- :chart-link (:chart-link chart-result)- :chart-content (:chart-content chart-result))- instruction-text- (let [link (te/link "Chart" "metabase://chart/" (:chart-id chart-result))]- (te/lines- "Your query and chart have been created successfully."- ""- "Next steps to present the chart to the user:"- (str "- Always provide a direct link using: `" link "` where Chart is a meaningful link text")- "- If creating multiple charts, present all chart links"))- chart-xml (structured->chart-xml structured (:chart-id chart-result) chart-type)]- {:output (tool-output chart-xml instruction-text)+ :chart-id (:chart-id chart)+ :chart-type (:chart-type chart)+ :chart-link (:chart-link chart)+ :chart-content (:chart-content chart)):data-parts [(streaming/viz-part- {:entity-id (:chart-id chart-result)+ {:entity-id (:chart-id chart):query-id (:query-id structured):query (links/->legacy-mbql (:query structured)):display chart-type:title title- :description description})]- :structured-output full-structured- :instructions instruction-text})))- (catch Exception e- (tools.u/handle-agent-or-api-error e))))+ :description description})]})))))++(def construct-notebook-query-tool+ "`construct_notebook_query`: run an agent-authored MBQL 5 query through the representations+ pipeline and attach a chart to the conversation."+ (->ConstructNotebookQueryTool))diff --git a/src/metabase/metabot/tools/core.clj b/src/metabase/metabot/tools/core.cljnew file mode 100644index 00000000000..de10da5184a--- /dev/null+++ b/src/metabase/metabot/tools/core.clj@@ -0,0 +1,524 @@+(ns metabase.metabot.tools.core+ "The API a Metabot tool author writes against.++ A tool is a record implementing [[Tool]]. It says what it is ([[declaration]]) and what it does+ ([[handle]]), and it reports failure by throwing: `defrecoverable` for a failure the agent can work+ around, `unrecoverable!` for one only the user can act on. Nothing here decides where an error goes+ or what text each audience sees — that is `metabase.metabot.tools.runtime`'s job, so a tool says+ what happened exactly once.++ A record rather than a function because several of our tools are the *same* tool under different+ configuration, and a record says so. The four `search` tools share a scope, a title function and a+ body, and differ only in their name, description, argument schema, allowed entity types and an+ options map — four instances of one type, not four functions that happen to resemble each other.++ Handlers return success only. There is no error-shaped success value and no `{:output \"Failed+ to …\"}` convention: a failure is thrown, so forgetting to handle one cannot silently hand the+ model a sentence nobody wrote.++ Everything a tool does about a failure is written at the call site, and the default — doing+ nothing — is that the failure ends the turn:++ - *relay a foreign error*: a converter ([[with-entity]], [[with-pipeline-errors]]) turns one known+ shape into a declared recoverable error. A shape a converter does not recognise passes through+ unchanged and is therefore unrecoverable.+ - *do one thing per item*: implement [[BatchedTool]] as well, and let [[handle]] delegate to+ [[handle-each]]. A declared recoverable error then becomes that item's contribution instead of+ ending the turn.+ - *give up on the user's behalf*: `unrecoverable!`, with a `:user-message`.++ Note what is deliberately absent: the runtime knows only [[Tool]]. It calls [[handle]] and that is+ all. [[BatchedTool]] is a contract between a tool and [[handle-each]], not something the runtime+ branches on, so there is no `satisfies?` test anywhere in the invocation path and a reader can+ follow one tool's behaviour without knowing which other shapes exist."+ (:require+ [clojure.string :as str]+ [metabase.metabot.metadata-perms :as metabot.perms]+ [metabase.metabot.schema.v2 :as schema.v2]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.recoverable.common :as recoverable.common]+ [metabase.metabot.tools.recoverable.pipeline :as recoverable.pipeline]+ [metabase.util.malli.registry :as mr]+ [potemkin :as p]))++(set! *warn-on-reflection* true)++(p/import-vars+ [tools.error+ defrecoverable+ unrecoverable!])++;;; ------------------------------------------------ Renderable ----------------------------------------------------++(defprotocol Renderable+ "Agent-facing text that the *consumer* turns into a string.++ The reason this exists rather than `:output` simply being a string: MCP builds its prose as+ `metabase.mcp.v2.message/msg` records and renders them at the boundary, deliberately, so that+ locale and untrusted interpolations are decided by whoever is sending the response rather than by+ whoever wrote the sentence. Metabot has no such need and uses plain English strings.++ Making the result carry a renderable instead of a string means neither surface has to give that up,+ and a tool does not have to know which one is consuming it. A string is the trivial case."+ (render-text [this]+ "This value as a string, for a consumer that is about to put it on the wire."))++(extend-protocol Renderable+ String+ (render-text [this] this))++(defn renderable?+ "Whether `x` can be [[render-text]]ed. Deliberately not satisfied by every object: a result whose+ `:output` is a map or a keyword is a bug, and `::result` should reject it."+ [x]+ (satisfies? Renderable x))++(mr/def ::renderable+ "Agent-facing text: a string, or anything extending [[Renderable]]."+ [:fn {:error/message "a string, or a value extending metabase.metabot.tools.core/Renderable"}+ renderable?])++;;; ------------------------------------------------ Schemas -------------------------------------------------------++(def ^:private DataPart+ "One entry of a result's `:data-parts`: `metabase.metabot.agent.streaming`'s `{:type :data, …}`+ constructors."+ [:map {:closed true}+ [:type [:= :data]]+ [:data-type :string]+ [:data {:optional true} [:maybe ::schema.v2/tool-io]]])++(mr/def ::declaration+ "What a tool tells the runtime and the providers about itself.++ Closed on purpose: a misspelled key (`:capability`, `:scopes`) would otherwise read as \"this tool+ needs nothing\" and quietly drop a gate.++ `:description` is the model-facing text. It is a field rather than a docstring because a tool that+ exists in several configurations should be able to build it — the four `search` tools each hardcode+ theirs today precisely because a docstring cannot be computed.++ `:name`, `:description`, `:args` and `:scope` are the neutral core: every consumer needs all four,+ and `:scope` is shared because both surfaces check strings from the same `api-scope` registry (MCP+ tools already declare `metabot.scope/agent-content-read`).++ Everything else is namespaced by the consumer it is for, and a consumer reads only its own+ namespace. That is what lets a tool be declared once and consumed by a surface it was not written+ for: MCP would read `:mcp/annotations`, `:mcp/required-extensions`, `:mcp/output-schema`,+ `:mcp/title` and `:mcp/_meta`, see no `:metabot/*` keys it cares about, and fall back to its own+ defaults.++ So this map cannot be closed — a closed map would make adding a consumer a change to this schema.+ The typo protection a closed map gave us is kept by a different rule, enforced in+ [[validate-tool!]]: every key outside the core must be namespaced. `:capability` is rejected,+ `:metabot/capabilities` is not, and a misspelling *within* a namespace is that consumer's to catch+ since it is the only thing that knows its own keys."+ [:map+ [:name :string]+ [:description :string]+ ;; `:any` rather than a schema-of-schemas: this is a Malli schema in any of its forms — a+ ;; registry keyword, a vector form, or a compiled Schema. `validate-tool!` checks it compiles.+ [:args :any]+ [:scope {:optional true} [:maybe :string]]+ [:metabot/capabilities {:optional true} [:maybe [:set :keyword]]]+ [:metabot/title-fn {:optional true} [:maybe fn?]]])++(mr/def ::result+ "What [[handle]] returns. Success only — a failure is thrown.++ `:output` is required and is the whole of what the model reads, so instructions belong in it rather+ than in a separate key. `:structured-output` is not a success signal and is not a second copy of+ the output: include it only when a named consumer reads it (the agent loop's query and chart memory+ and its markdown link buffer, `metabase.metabot.used-tables`, the document API's chart draft,+ `metabase.metabot.agent.user-context`, and EE analytics persistence)."+ [:map {:closed true}+ [:output ::renderable]+ [:structured-output {:optional true} ::schema.v2/tool-io]+ [:data-parts {:optional true} [:sequential DataPart]]])++(mr/def ::entry+ "One item's contribution, as [[compose]] sees it.++ Uniform whether the item loaded or failed: `:output` is always a string — the item's own text, or+ its failure rendered — and `:failed?` is always a boolean. A composer that concatenates therefore+ never asks which happened, and one that separates them asks a boolean rather than probing for a+ key."+ [:map {:closed true}+ [:item :any]+ [:output :string]+ [:failed? :boolean]+ [:error {:optional true} ::tools.error/recoverable]+ [:structured-output {:optional true} ::schema.v2/tool-io]+ [:data-parts {:optional true} [:sequential DataPart]]])++;;; ------------------------------------------------ Protocols -----------------------------------------------------++(defprotocol Tool+ "Every Metabot tool. One call, one unit of work."+ (declaration [this]+ "This tool's complete [[::declaration]] — what the model is told it is, and what a consumer+ gates it on.++ Written out as a literal map rather than derived from the record's fields, because it is the+ tool's contract with the model and a reader should be able to see all of it in one place.")+ (handle [this args ctx]+ "Do the work for one call. `args` have already been coerced and validated against the+ declaration's `:args`, so destructure them without re-checking.++ Returns a [[::result]] or throws."))++(defprotocol BatchedTool+ "A tool that can also be called for several items at once.++ The rule: for everything that differs between the single and the batched form, this protocol has a+ `batched-…` function that receives the single form and returns a **complete** batched form. Nothing+ is derived by the framework, so there are no special cases and no shape a tool cannot express.++ [[Tool]] stays the single-item tool. Take `BatchedTool` away and the record is still a working+ tool that reads one URI, loads one id, edits one query. That is the point: `handle` *is* the item+ loader, so there is no second per-item function to keep in step with it, and the single form can be+ tested and published on its own.++ The consumer orchestrates. It asks whether a tool satisfies this protocol, and if so calls+ [[run-batched]] instead of [[handle]]. That is one branch in each consumer, in exchange for the+ single form being independently real."+ (batched-declaration [this declaration]+ "The complete [[::declaration]] for the batched form, given the single one.++ Two things usually differ: `:args` becomes a map holding a sequence, and `:description` gains a+ sentence about the per-call limit. Everything else — name, scope, namespaced extras — is normally+ passed through.++ The tool composes `:args` itself rather than the framework wrapping the single schema. That is+ what lets `read_resource` publish `[:sequential :string]` while its single form takes+ `{:uri :string}`, and lets a tool with heterogeneous items embed the single schema whole. Share+ the item schema through a var so the two cannot drift.")+ (batched-args [this args]+ "The batched `args`, split into one single-form args map per item, in the order the agent asked.++ The inverse of what [[batched-declaration]] did to `:args`. The tool owns both, so the framework+ never has to guess how the plural shape maps onto the singular one.")+ (compose [this entries ctx]+ "The [[::result]] for the whole call, from one [[::entry]] per item in item order.++ The only thing that decides where a failure appears. [[concatenated]] leaves failures in position+ and is what most tools want: `(compose [_ entries _] (concatenated entries))`. A tool whose+ output is one document over the whole set has no positions to put them in and will separate them+ out by `:failed?`."))++;;; ------------------------------------------------ Composition ---------------------------------------------------++(defn concatenated+ "The ordinary composition: the entries' `:output`s joined in order, their `:structured-output`s+ collected into a vector, their `:data-parts` concatenated.++ Failures land in position, because a failed entry's `:output` is its rendered failure text and this+ joins what it is given."+ [entries]+ (cond-> {:output (str/join "\n" (map :output entries))}+ (some :structured-output entries) (assoc :structured-output (mapv :structured-output entries))+ (some :data-parts entries) (assoc :data-parts (vec (mapcat :data-parts entries)))))++(defn- entry+ "One item's [[::entry]]: the result of calling `tool`'s [[handle]] with `item-args`, or its declared+ failure rendered.++ A declared recoverable error becomes this item's contribution. Anything else is a fault, and by+ default it is rethrown so the whole call fails — a bug is not a partial result.++ `on-item-fault` is the one seam, for a consumer whose contract says otherwise: it takes the item's+ args and the throwable and returns that item's [[::entry]]. Only `/v1/read-resource` passes one+ (see [[with-batched-entries]]); it is nil everywhere else, which is the failing default."+ [tool item-args ctx on-item-fault]+ (try+ (let [result (handle tool item-args ctx)]+ (when-not (mr/validate ::result result)+ (throw (ex-info (str "handle returned an invalid result for " (pr-str item-args))+ {:item-args item-args :result result})))+ (assoc result :item item-args :failed? false :output (render-text (:output result))))+ (catch Throwable e+ (let [error (tools.error/classify e)]+ (cond+ (= :recoverable (:class error))+ {:item item-args+ :error error+ :output (tools.error/recoverable-text error (:tool-names ctx))+ :failed? true}++ on-item-fault (on-item-fault item-args e)+ :else (throw e))))))++(defrecoverable all-items-failed!+ "Every item in a batched call failed, so the call has nothing to report but its failures."+ {:payload [:map {:closed true}+ [:count :int]+ ;; What `compose` produced, rendered. Carried rather than rebuilt so the model reads+ ;; exactly what a call that lost all but one item would have shown it.+ [:output :string]]}+ [{:keys [output]}]+ ;; The composed text is the whole message. Each item's own recovery steps are already inside it —+ ;; `entry` rendered them through `recoverable-text` for this profile — so there is nothing to add+ ;; here, and a step of our own would be advice about a call rather than about any of its items.+ {:message output+ :recovery []})++(defn with-batched-entries+ "`f` applied to the entries of `tool`'s batched call — one [[::entry]] per item, in item order.+ Returns whatever `f` returns, with the permission cache held across both the item loading and `f`+ (see [[call]]).++ THE ONLY CALLER IS `metabase.agent-api.api`'s `POST /v1/read-resource`, and this function exists+ for it alone. That endpoint publishes a different contract from the agent loop's: one HTTP status+ for the whole call and an `:error` on each item that could not be read, so a single-URI request+ that missed is still a 200 carrying one failed item. [[run-batched]] cannot serve that — it answers+ with one [[::result]] and throws when nothing was delivered — and before this existed the endpoint+ got its per-item data by having `read_resource`'s own `compose` build it, which left a tool+ constructing one of its consumers' response shapes.++ So if that endpoint goes away, delete this with it. Nothing else should reach for it: a consumer+ that wants one result per call wants [[run-batched]], which is this with `compose` and the+ nothing-was-delivered check on top.++ `opts` may carry `:on-item-fault`, called when one item fails with something other than a declared+ recoverable error, with that item's args and the throwable; it returns that item's [[::entry]].+ Without it such a failure fails the whole call, which is what the agent loop wants and what the+ same endpoint must not do — its contract is one status for the call and an `:error` per item, so+ one URI hitting a bug cannot discard the four that read."+ [tool args ctx {:keys [on-item-fault]} f]+ (metabot.perms/with-cache+ (let [item-args (batched-args tool args)]+ (f (mapv (fn [one] (entry tool one ctx on-item-fault)) item-args)))))++(defn run-batched+ "Perform `tool`'s batched call and return one [[::result]].++ What a consumer calls in place of [[handle]] when a tool satisfies [[BatchedTool]].++ A declared recoverable error from one item becomes that item's contribution — unless every item+ failed, which is a failed call and throws [[all-items-failed!]]. A call that produced nothing must+ not report success: the agent loop decides whether a call worked by the absence of an `:error`, so+ five failures dressed as a result are counted as a success by the provider adapters, by+ `successful-tool-output?` and by telemetry alike. The model reads the same per-item text either+ way, so this changes who is told the call failed, not what it is told. A consumer whose contract+ says otherwise composes the entries itself through [[with-batched-entries]].++ Anything other than a declared recoverable error is rethrown, so an undeclared exception fails the+ whole call and discards the items that did load. That is deliberate: a bug is not a partial+ result."+ [tool args ctx]+ (with-batched-entries tool args ctx nil+ (fn [entries]+ (let [result (compose tool entries ctx)]+ (if (and (seq entries) (every? :failed? entries))+ ;; The composed output, rendered, rather than a sentence of our own: the model reads+ ;; exactly what a call that lost all but one item would have shown it.+ (all-items-failed! {:count (count entries)+ :output (render-text (:output result))})+ result)))))++(defn batched?+ "Whether `tool` can be called for several items at once.++ Read by [[call]], to decide which of the two protocols to go through, and by [[validate-tool!]],+ to decide whether there is a second declaration to check."+ [tool]+ (satisfies? BatchedTool tool))++(defn call+ "Call `tool` with `args` and `ctx`, and return one [[::result]].++ The entry point a consumer uses. One item or several, depending on the tool, so a consumer does not+ branch and does not need to know which kind it has. [[handle]] is the protocol method for one+ item's work; this is the function that performs a call.++ A consumer whose contract differs from `run-batched`'s — one that answers per item rather than per+ call — uses [[with-batched-entries]] instead of this.++ Every call runs inside `metabase.metabot.metadata-perms/with-cache`, so the table rows and+ per-table permission decisions a tool looks up are fetched once per call rather than once per+ lookup. It is here rather than in each tool because no tool is worse off for it: a tool that never+ reaches `metadata-perms` pays one dynamic binding and one empty atom, and `with-cache` nests, so+ the six places inside tool code that already wrap their own work now reuse this one instead of+ each opening a cache per item. That is what a batched tool gets out of it — five URIs through+ `read_resource` used to re-fetch the same table and the same permission once per URI.++ Nothing cached here is anything a tool mutates: table and field rows, and per-table `can-query?`,+ view-data, sandbox and routing decisions, all keyed by the current user. A tool that creates a+ card or an alert changes none of them."+ [tool args ctx]+ (metabot.perms/with-cache+ (if (batched? tool)+ (run-batched tool args ctx)+ (handle tool args ctx))))++;;; ------------------------------------------------ Registration --------------------------------------------------++(def ^:private tool-name-pattern+ "Model-facing tool names are snake_case. Providers differ on what they accept, and a name one+ rejects fails the whole turn, so the declaration is the place to find out."+ #"^[a-z][a-z0-9_]*$")++(def ^:private core-declaration-keys+ "The keys every consumer needs. Anything else must be namespaced for one; see [[::declaration]]."+ #{:name :description :args :scope})++(defn- validate-declaration!+ "Check one declaration, throwing on anything a load-time check can catch."+ [declared]+ (let [{tool-name :name :keys [args]} declared]+ (when-not (mr/validate ::declaration declared)+ (throw (ex-info (str "Invalid tool declaration: " (pr-str declared))+ {:declaration declared+ :explain (mr/explain ::declaration declared)})))+ ;; The declaration is open so a new consumer can add its own keys without editing the schema,+ ;; which costs us the typo protection a closed map gives. This buys it back: an unqualified key+ ;; outside the core is a misspelling of a core key or a consumer key someone forgot to namespace,+ ;; and either way it would be read by nobody and silently drop whatever it was meant to do.+ (when-let [stray (seq (remove #(or (contains? core-declaration-keys %) (qualified-keyword? %))+ (keys declared)))]+ (throw (ex-info (str "Tool " tool-name " declares unnamespaced key(s) " (vec stray)+ ". Only " (vec (sort core-declaration-keys)) " are consumer-neutral;"+ " anything else belongs to one consumer and must say which, e.g."+ " :metabot/capabilities.")+ {:name tool-name :stray (vec stray)})))+ (when-not (re-matches tool-name-pattern tool-name)+ (throw (ex-info (str "Tool name " (pr-str tool-name) " is not snake_case") {:name tool-name})))+ ;; Build the validator now rather than on the first model call. `mr/schema` on an unregistered+ ;; keyword comes back without complaint, so an `:args` schema with a typo'd registry reference+ ;; would pass a weaker check and then turn every call of this tool into an argument-validation+ ;; failure in production, with nothing to say the declaration was at fault. Building the+ ;; validator is what the runtime does, and it is cached, so this checks the real thing.+ (try+ (mr/validator args)+ (catch Throwable e+ (throw (ex-info (str "Tool " tool-name " has an :args schema that does not compile")+ {:name tool-name} e))))+ declared))++(defn validate-tool!+ "Check `tool`'s declaration — and its batched declaration, when it has one — and return the+ declaration a consumer publishes.++ Both are checked because both are published schemas somewhere: the single one by a consumer that+ calls `handle` directly, the batched one by every consumer of a [[BatchedTool]]. A batched `:args`+ the tool composed wrongly would otherwise fail on the first model call."+ [tool]+ (let [declared (validate-declaration! (declaration tool))]+ (if (batched? tool)+ (validate-declaration! (batched-declaration tool declared))+ declared)))++(defn entries+ "The runtime's `entries` map — tool name to `{:declaration … :tool …}` — for one profile's `tools`.++ The declaration is the published one, so a batched tool's entry carries its batched `:args` and the+ runtime validates the model's arguments against the shape it was actually offered.++ Rejects two tools claiming the same name: within a profile the name is how the model and the+ runtime address a tool, so a collision means one of them is unreachable and which one depends on+ the order of the seq. Across profiles a name legitimately belongs to several tools — `search` has+ four — which is why there is no global registry."+ [tools]+ (reduce (fn [acc tool]+ (let [{tool-name :name :as declared} (validate-tool! tool)]+ (when (contains? acc tool-name)+ (throw (ex-info (str "Two tools claim the tool name " tool-name)+ {:name tool-name})))+ (assoc acc tool-name {:declaration declared :tool tool})))+ {}+ tools))++;;; ------------------------------------------------ Converters ----------------------------------------------------++(def ^:private refusal-status-codes+ "The statuses that mean \"you may not see this\" or \"this is not here\". `api/read-check` raises a+ 403 for the first and a 404 for the second, and the converters collapse them."+ #{403 404})++(defn do-with-entity+ "Implementation of [[with-entity]]."+ [{:keys [kind id]} thunk]+ (try+ (thunk)+ (catch Throwable e+ (if (contains? refusal-status-codes (:status-code (ex-data e)))+ (tools.error/throw-recoverable! ::recoverable.common/not-found+ (cond-> {} kind (assoc :kind kind) (some? id) (assoc :id id))+ {:cause e})+ (throw e)))))++(defmacro with-entity+ "Convert a read refusal from `body` into the declared `not-found!` error for `entity`.++ (with-entity {:kind :timeline :id timeline-id}+ (timeline/include-events-singular (timeline/get-timeline timeline-id)))++ `entity` is `{:kind <keyword> :id <id>}`. A 403 and a 404 — the two things `api/read-check` raises+ — both become the same recoverable error; see `recoverable.common/not-found!` for why they are not+ distinguished. Every other exception passes through, so a genuine failure inside `body` stays+ unrecoverable instead of being reported to the model as a missing entity."+ {:style/indent [:defn]}+ [entity & body]+ `(do-with-entity ~entity (fn [] ~@body)))++(def ^:private pipeline-ns+ "The namespace holding the pipeline declarations.++ Read off one of the declarations rather than written as a string, because the conversion finds them+ through the catalog by code: renaming the namespace would otherwise leave this mapping pointing at+ codes nothing declares, and every pipeline error would quietly become unrecoverable with no failing+ test to say so."+ (str (ns-name (:ns (meta #'recoverable.pipeline/unknown-table!)))))++(defn- pipeline-error-code+ "The `recoverable.pipeline` code for a pipeline `:error` keyword, or nil when none is declared."+ [error]+ (when (keyword? error)+ (let [code (keyword pipeline-ns (name error))]+ (when (contains? (tools.error/recoverables) code)+ code))))++(defn do-with-pipeline-errors+ "Implementation of [[with-pipeline-errors]]."+ [thunk]+ (try+ (thunk)+ (catch Throwable e+ (let [{:keys [agent-error? status-code error entity-type entity-id]} (ex-data e)+ code (pipeline-error-code error)]+ (cond+ ;; `:agent-error?` *and* an `:error` key. The pipeline's `as-agent-input-error` stamps+ ;; `:agent-error?` onto foreign exceptions from lib, toucan2 and JDBC as well, and those+ ;; messages are not authored for anyone — only an `:error` code says "this sentence was+ ;; written for a model".+ (and agent-error? code)+ (tools.error/throw-recoverable!+ code+ (cond-> {:message (or (ex-message e) "")}+ entity-type (assoc :entity-type entity-type)+ (some? entity-id) (assoc :entity-id entity-id))+ {:cause e})++ (contains? refusal-status-codes status-code)+ (tools.error/throw-recoverable! ::recoverable.common/not-found {} {:cause e})++ :else+ (throw e))))))++(defmacro with-pipeline-errors+ "Convert the representations pipeline's agent errors from `body` into declared recoverable errors.++ (with-pipeline-errors+ (construct/execute-representations-query query))++ Three cases:+ - an `:agent-error?` exception whose ex-data carries an `:error` code declared in+ `metabase.metabot.tools.recoverable.pipeline` becomes that error, with the pipeline's own+ sentence as the message;+ - a 403 or 404 becomes `recoverable.common/not-found!`;+ - anything else passes through and is therefore unrecoverable, including an `:error` code with no+ declaration. `metabase.metabot.tools.recoverable.pipeline-test` scans the pipeline sources and+ fails when a code has none, so a new pipeline error cannot quietly start ending turns."+ {:style/indent [:defn]}+ [& body]+ `(do-with-pipeline-errors (fn [] ~@body)))diff --git a/src/metabase/metabot/tools/deftool.clj b/src/metabase/metabot/tools/deftool.cljdeleted file mode 100644index d5302b3220a..00000000000--- a/src/metabase/metabot/tools/deftool.clj+++ /dev/null@@ -1,99 +0,0 @@-(ns metabase.metabot.tools.deftool- "Macro for defining metabot tool endpoints with standard encoding/decoding behavior."- (:require- [malli.core :as mc]- [malli.transform :as mtx]- [metabase.api.macros :as api.macros]- [metabase.metabot.context :as metabot.context]- [metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]))--;;; ---------------------------------------------------- Schemas ------------------------------------------------------(mr/def ::tool-request- "Base schema for all tool requests. Contains the conversation ID and optional profile ID."- [:map- [:conversation_id ms/UUIDString]- [:metabot_id {:optional true} [:maybe :string]]- [:profile_id {:optional true} [:maybe :string]]])--(def request-transformer- "Transformer for encoding tool request arguments (snake_case -> kebab-case).- Converts snake_case keys to kebab-case and string enum values to keywords."- (mtx/transformer {:name :tool-api-request}))--(def ^:private response-transformer- "Transformer for decoding tool response data (kebab-case -> snake_case)."- (mtx/transformer {:name :tool-api-response}))--(defn invoke-tool- "Core tool invocation logic. Handles encoding, calling the handler, decoding, and logging.- This is the runtime implementation called by endpoints generated by `deftool`.-- Arguments:- - `body` - The request body containing `:arguments` and `:conversation_id`- - `request` - The Ring request map (used to extract `:metabot/metabot-id`)- - `opts` - A map with:- - `:api-name` - Keyword name for logging (e.g., `:field-values`)- - `:args-schema` - Malli schema for encoding arguments (optional)- - `:result-schema` - Malli schema for decoding results (optional)- - `:handler` - Function to call with encoded arguments (receives args map with :metabot-id)-- The handler receives a single map argument containing the encoded args plus `:metabot-id`- and `:profile-id` (extracted from the request body)."- [{:keys [arguments conversation_id metabot_id profile_id] :as body}- request- {:keys [api-name args-schema result-schema handler]}]- (metabot.context/log (assoc body :api api-name) :llm.log/llm->be)- (let [metabot-id (or (:metabot/metabot-id request) metabot_id)- encoded-args (cond-> (if args-schema- (mc/encode args-schema arguments request-transformer)- {})- metabot-id (assoc :metabot-id metabot-id)- profile_id (assoc :profile-id profile_id))- raw-result (handler encoded-args)- result (if result-schema- (mc/decode result-schema raw-result response-transformer)- raw-result)]- (doto (assoc result :conversation_id conversation_id)- (metabot.context/log :llm.log/be->llm))))--(defmacro deftool- "Define a tool endpoint with standard encoding/decoding and logging behavior.-- This macro generates a `defendpoint` with the boilerplate needed for tool endpoints:- - Logging incoming requests and outgoing responses- - Encoding arguments from snake_case to kebab-case (via `:tool-api-request` transformer)- - Decoding results from kebab-case to snake_case (via `:tool-api-response` transformer)- - Attaching `conversation_id` to responses- - Extracting `:metabot-id` and `:profile-id` from the request body and including them in the args map-- Options:- :args-schema - Malli schema for arguments (optional - omit for no-args tools)- :args-optional? - If true, arguments are marked as optional in the request body schema- :result-schema - Malli schema for result (required for response schema generation)- :handler - Function to call. Always receives an args map (may be empty for no-args tools)- with `:metabot-id` included when available from the request.-- Example:- (deftool \"/field-values\"- \"Return statistics and/or values for a given field.\"- {:args-schema ::field-values-arguments- :result-schema ::field-values-result- :handler metabot.tools.field-stats/field-values})"- [route docstring {:keys [args-schema args-optional? result-schema handler]}]- (let [api-name (keyword (subs route 1)) ; "/field-values" -> :field-values- body-schema (if args-schema- (if args-optional?- `[:merge [:map [:arguments {:optional true} ~args-schema]] ::tool-request]- `[:merge [:map [:arguments ~args-schema]] ::tool-request])- `::tool-request)- response-schema `[:merge ~result-schema ::tool-request]- tool-opts {:api-name api-name- :args-schema args-schema- :result-schema result-schema- :handler handler}]- `(api.macros/defendpoint :post ~route :- ~response-schema- ~docstring- [~'_route-params ~'_query-params ~'body :- ~body-schema ~'request]- (invoke-tool ~'body ~'request ~tool-opts))))diff --git a/src/metabase/metabot/tools/document.clj b/src/metabase/metabot/tools/document.cljindex a4c1511fca6..e6682d3833e 100644--- a/src/metabase/metabot/tools/document.clj+++ b/src/metabase/metabot/tools/document.clj@@ -4,6 +4,7 @@[metabase.metabot.scope :as scope][metabase.metabot.table-utils :as table-utils][metabase.metabot.tools.construct :as construct-tools]+ [metabase.metabot.tools.core :as tools][metabase.metabot.tools.shared :as shared][metabase.metabot.tools.shared.instructions :as instructions][metabase.metabot.tools.sql.create :as create-sql-query-tools]@@ -190,11 +191,15 @@[{:keys [name description query viz_settings]} :- model-chart-schema](try(let [chart-type (get viz_settings :chart_type)- result (construct-tools/construct-notebook-query-tool- {:query query- :title name- :description description- :visualization {:chart_type chart-type}})+ ;; `construct_notebook_query` is a record now, so this is a protocol call rather than a+ ;; function call. The nil ctx is what construct's `handle` already ignores; this tool is+ ;; still the old shape and has none to pass on.+ result (tools/call construct-tools/construct-notebook-query-tool+ {:query query+ :title name+ :description description+ :visualization {:chart_type chart-type}}+ nil)structured (or (:structured-output result) (:structured_output result))query-id (:query-id structured)dataset-query (:query structured)]diff --git a/src/metabase/metabot/tools/error.clj b/src/metabase/metabot/tools/error.cljnew file mode 100644index 00000000000..ea1b96c0f3c--- /dev/null+++ b/src/metabase/metabot/tools/error.clj@@ -0,0 +1,355 @@+(ns metabase.metabot.tools.error+ "The ToolError domain: what a Metabot tool failure *is*, before anything decides where it goes.++ A tool failure has exactly one class, and the class picks the audience:++ | Class | Produced by | Handled by | Carries |+ | ---------------- | -------------------------------- | ---------- | ---------------- |+ | `:validation` | the runtime only | the agent | `:message` |+ | `:recoverable` | a [[defrecoverable]] constructor | the agent | `:message`, `:recovery` |+ | `:unrecoverable` | everything else | the user | `:user-message`? |++ Recoverable is opt-in and unrecoverable is the default, so the safe path is the one you get by+ doing nothing: an exception nobody declared recoverable ends the turn rather than handing the+ model text that nobody wrote for it. An unrecoverable error has no `:message` key at all, which+ makes forwarding a foreign exception message to the agent impossible rather than merely+ discouraged.++ Each recoverable error is declared once with [[defrecoverable]], which records it in the catalog+ here. The catalog is what lets one test cover every declared error, and what lets a converter+ (see `metabase.metabot.tools.core`) turn a foreign error into a declared one by code.++ This namespace is the bottom of the tool-error stack: it knows about classes, codes and payload+ schemas, and nothing about tools, profiles or rendering. `metabase.metabot.tools.runtime` decides+ what text each audience actually receives."+ (:require+ [clojure.string :as str]+ [malli.error :as me]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.log :as log]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++;;; ----------------------------------------------- Schemas --------------------------------------------------------++(mr/def ::recovery-step+ "One alternative path offered to the agent after a recoverable failure.++ `:uses` is the set of tool names `:text` mentions. The runtime keeps a step only when the current+ profile has all of them, so a step naming `read_resource` silently disappears in a profile without+ it instead of sending the agent at a tool it cannot call."+ [:map {:closed true}+ [:uses [:set :string]]+ [:text :string]])++(mr/def ::tool-error+ "A tool failure as data. The `:class` decides the audience; see the namespace docstring.++ `:message` and recovery text are model-facing: write them in English, do not use `tru`.+ `:user-message` is user-facing and should use `tru`.++ `:data` on a recoverable error is the validated payload, which logs and evals read. `:data` on an+ unrecoverable error reaches the logs only."+ [:multi {:dispatch :class}+ [:validation [:map {:closed true}+ [:class [:= :validation]]+ [:code :keyword]+ [:message :string]]]+ [:recoverable [:map {:closed true}+ [:class [:= :recoverable]]+ [:code :qualified-keyword]+ [:message :string]+ [:recovery [:sequential ::recovery-step]]+ [:data :map]]]+ [:unrecoverable [:map {:closed true}+ [:class [:= :unrecoverable]]+ [:code :keyword]+ [:user-message {:optional true} :string]+ [:data {:optional true} :map]]]])++(mr/def ::recoverable+ "The recoverable branch of [[::tool-error]], on its own. Referenced where only a recoverable error+ is admissible — a batched tool's failed entry, for instance: a validation error cannot arise+ inside a handler, and an unrecoverable one by definition cannot be survived."+ [:map {:closed true}+ [:class [:= :recoverable]]+ [:code :qualified-keyword]+ [:message :string]+ [:recovery [:sequential ::recovery-step]]+ [:data :map]])++(mr/def ::recoverable-body+ "What a [[defrecoverable]] body returns: the model-facing text for this failure."+ [:map {:closed true}+ [:message :string]+ [:recovery [:sequential ::recovery-step]]])++(def error-key+ "The `ex-data` key a ToolError travels under.++ Spelled out as a var because three layers have to agree on it — the constructors here, the+ runtime's `classify`, and the tests — and a typo'd keyword would silently demote every error to+ `:internal`."+ ::error)++;;; ------------------------------------------ Throwing ------------------------------------------------------------++(defn- explanation+ "A human-readable account of how `value` violates `schema`, for the logs. Never model- or+ user-facing: it quotes the offending value verbatim."+ [schema value]+ (try+ (some-> (mr/explain schema value) me/humanize pr-str)+ (catch Throwable _+ "<unexplainable>")))++(defn unrecoverable-ex+ "The exception for an unrecoverable ToolError with `code`.++ `opts` may carry `:user-message` (the only text the user ever sees for this failure), `:data`+ (logs only) and `:cause`. The exception message is the `:user-message` when there is one, and the+ code otherwise — there is deliberately no `:message` key on the error itself, so nothing+ downstream can hand this text to the model.++ Unlike recoverable errors there is no `:agent-error?` flag: code outside the agent loop that+ catches these should treat them as the server faults they are."+ ^Throwable [code {:keys [user-message data cause]}]+ (let [error (cond-> {:class :unrecoverable :code code}+ user-message (assoc :user-message user-message)+ (seq data) (assoc :data data))]+ (ex-info (or user-message (str code))+ {error-key error}+ cause)))++(defn unrecoverable!+ "Throw an unrecoverable ToolError with `code`, ending the turn.++ Always throws; never returns. Tool code passes a qualified keyword, so the log and the+ model-facing template both say which namespace gave up; the runtime's own codes are an+ unqualified closed set (`metabase.metabot.tools.runtime/runtime-codes`).++ (unrecoverable! ::no-sql-permission)+ (unrecoverable! ::no-sql-permission+ {:user-message (tru \"You can''t write SQL for this database.\")+ :cause e+ :data {:database-id database-id}})++ `:user-message` is the only way to show the user something specific to this failure; without it+ they get the generic message. Unrecoverable errors are not declared anywhere, because the only+ authored text they carry is that one optional string."+ ([code] (unrecoverable! code nil))+ ([code opts]+ (throw (unrecoverable-ex code opts))))++;;; ------------------------------------------ Recoverable catalog -------------------------------------------------++(defonce ^:private recoverables*+ (atom {}))++(defn recoverables+ "The declared recoverable errors, as a map of code to catalog entry.++ An entry has `:code`, `:var`, `:doc`, `:payload-schema`, `:status-code` and `:build-fn`. Tests+ walk this to cover every declared error at once, and converters look an error up by code."+ []+ @recoverables*)++(defn declare-recoverable!+ "Record one recoverable error in the catalog. [[defrecoverable]] calls this; call it directly only+ if you are building another declaration macro on top.++ Rejects a second declaration of the same `code` from a *different* var, which would otherwise let+ load order decide which text the agent sees. Comparison is by the var's fully-qualified symbol+ rather than by identity, because reloading a namespace in the REPL mints a fresh var for the same+ name and an identity check would reject the reload."+ [{:keys [code var payload-schema] :as entry}]+ (when-not (qualified-keyword? code)+ (throw (ex-info "A recoverable error code must be a qualified keyword" {:code code})))+ (when-not (var? var)+ (throw (ex-info (str "Recoverable error " code " must be declared with its constructor var")+ {:code code :var var})))+ (when-not payload-schema+ (throw (ex-info (str "Recoverable error " code " declared without a payload schema") {:code code})))+ ;; Fail at load time rather than when the error first fires: a declaration whose schema does not+ ;; compile would otherwise turn every use of it into an `:internal` error in production.+ (mr/schema payload-schema)+ (when-let [existing (get @recoverables* code)]+ (when-not (= (symbol (:var existing)) (symbol var))+ (throw (ex-info (str "Recoverable error " code " is already declared by " (symbol (:var existing)))+ {:code code :existing (symbol (:var existing)) :duplicate (symbol var)}))))+ (swap! recoverables* assoc code entry)+ code)++(defn- recoverable-ex+ "The exception for a recoverable ToolError, given a validated `payload` and the `:message`/+ `:recovery` its declaration produced.++ The ex-data carries `:agent-error?` and `:status-code` as well as the ToolError, so the existing+ callers of shared tool helpers that live outside the agent loop — MCP v2's `search` calling+ `metabase.metabot.tools.search/search`, for instance — keep seeing the shape they handle today."+ ^Throwable [code {:keys [message recovery]} payload status-code cause]+ (ex-info message+ {error-key {:class :recoverable+ :code code+ :message message+ :recovery (vec recovery)+ :data payload}+ :agent-error? true+ :status-code status-code}+ cause))++(defn throw-recoverable!+ "Throw the declared recoverable error `code`, built from `payload`.++ Always throws. `opts` may carry `:cause`, which reaches the logs only. This is the catalog-driven+ entry point, for code that knows an error by its code rather than by its var — the converters in+ `metabase.metabot.tools.core`, which map a foreign error onto a declaration. Tool code calls the+ constructor var that [[defrecoverable]] defined instead.++ A payload that does not match the declaration's schema, or a body that returns something other+ than `::recoverable-body`, throws an unrecoverable `:internal` error instead: a malformed+ recoverable error must never reach the agent, and the alternative is unauthored text. Validation+ runs in every environment, not just dev and test like `mu/defn`, because that guarantee is the+ whole point."+ ([code payload] (throw-recoverable! code payload nil))+ ([code payload {:keys [cause]}]+ (let [{:keys [payload-schema status-code build-fn] :as entry} (get (recoverables) code)]+ (when-not entry+ (throw (unrecoverable-ex :internal {:data {:code code}+ :cause (ex-info (str "No recoverable error declared for " code)+ {:code code})})))+ (when-not (mr/validate payload-schema payload)+ (log/errorf "Recoverable error %s built with an invalid payload: %s"+ code (explanation payload-schema payload))+ (throw (unrecoverable-ex :internal {:data {:code code :payload payload}+ :cause cause})))+ (let [body (build-fn payload)]+ (when-not (mr/validate ::recoverable-body body)+ (log/errorf "Recoverable error %s produced an invalid body: %s"+ code (explanation ::recoverable-body body))+ (throw (unrecoverable-ex :internal {:data {:code code :payload payload}+ :cause cause})))+ (throw (recoverable-ex code body payload status-code cause))))))++(defn code-for+ "The error code [[defrecoverable]] gives a constructor named `sym` in namespace `ns-name`: the+ qualified keyword of the name without its trailing `!`."+ [ns-name sym]+ (keyword (str ns-name) (str/replace (name sym) #"!$" "")))++(defmacro defrecoverable+ "Declare one recoverable error and define its constructor.++ (defrecoverable unknown-query-id!+ \"The query id is not in this conversation's query state.\"+ {:payload [:map {:closed true}+ [:query-id :string]+ [:available [:sequential :string]]]}+ [{:keys [query-id available]}]+ {:message (str \"Query \" query-id \" not found. Available query ids: \"+ (str/join \", \" available) \".\")+ :recovery []})++ The name ends with `!` because the constructor always throws; it never returns a value to test+ against. The code is the qualified keyword of the name without the `!`, so the example above is+ `:metabase.metabot.tools.sql/unknown-query-id`.++ `opts` is a map of:+ - `:payload` - *required* - Malli schema for the payload the call site passes. Validated on every+ call, in every environment.+ - `:status-code` - *optional*, default 400 - the `:status-code` on the thrown `ex-info`, for the+ non-agent callers of shared tool helpers.++ The body receives the validated payload and returns `{:message ... :recovery [...]}`. Write both+ in English: they are model-facing, not user-facing. Only recovery steps name tools, and each step+ declares the tools its text mentions in `:uses` so the runtime can drop steps the current profile+ cannot act on.++ The argument vector holds the payload binding alone. The shape — name, docstring, options map,+ argument vector, body — is `defn`'s, which is what lets clj-kondo lint this as a `defn` without a+ hook, and matches `metabase.mcp.v2.registry/deftool`."+ {:style/indent [:defn]}+ [sym docstring opts argv & body]+ (assert (string? docstring) "defrecoverable requires a docstring")+ (assert (map? opts) "defrecoverable requires an options map")+ (assert (and (vector? argv) (= 1 (count argv)))+ "defrecoverable takes exactly one argument, the payload")+ (assert (str/ends-with? (name sym) "!") "a defrecoverable name must end with !")+ (let [code (code-for *ns* sym)]+ ;; The constructor takes the payload through untouched and lets `throw-recoverable!` validate it+ ;; against the catalog, so `argv`'s destructuring applies to the body only — one place decides+ ;; what a valid payload is, whether the error was raised through the var or by code.+ `(do+ (defn ~sym ~docstring [payload#]+ (throw-recoverable! ~code payload#))+ (declare-recoverable! {:code ~code+ :var (var ~sym)+ :doc ~docstring+ :payload-schema ~(:payload opts)+ :status-code ~(:status-code opts 400)+ :build-fn (fn ~argv ~@body)}))))++;;; ------------------------------------------ Reading a recoverable error -----------------------------------------++;;; A recoverable error becomes model-facing text in two places — a call that failed outright, and+;;; one item of a batched call that mostly worked. Both go through [[recoverable-text]], so the+;;; agent cannot tell the two apart from the wording, only from where it appears. Tool code does not+;;; call these; the framework does.++(defn recovery-steps-for-tools+ "The subset of `recovery` whose steps only name tools in `tool-names`.++ A step naming a tool the profile lacks is dropped, not rewritten: half a sentence about+ `read_resource` is worse than silence."+ [recovery tool-names]+ (let [available (set tool-names)]+ (filterv #(every? available (:uses %)) recovery)))++(defn names-a-tool?+ "Whether `text` names a tool in backticks, e.g. \"call `read_resource`\". Used by the runtime's+ dev/test assertions, which hold that only recovery steps name tools and only ones they declare."+ [text tool-name]+ (str/includes? (str text) (str "`" tool-name "`")))++(defn step-failure-text+ "A failed call as the text the UI shows for that step, and the conversation stores.++ A third audience, decided the way the other two are — by the class. The model's `:output` is not+ it: that text is written to be acted on (\"`uris` must be an array of 1 to 5 URI strings\", \"the+ user was shown the error (:internal)\"), and someone reading their own conversation is not the one+ acting on it.++ - `:unrecoverable` gets the `:user-message` the tool chose, because this is the failure the user+ has to act on, and the generic sentence when the tool chose none.+ - `:validation` and `:recoverable` get the generic sentence. What we told the model about its+ arguments, and which tool to call instead, is the agent's business; a reader sees that a step did+ not succeed.++ The code is deliberately absent: it is a keyword from our own namespaces and says nothing to a+ reader. It goes to the logs and to telemetry, which is where support looks."+ [{:keys [class user-message]}]+ (or (when (= class :unrecoverable) (not-empty user-message))+ (tru "Metabot could not complete this step.")))++(defn recoverable-text+ "A recoverable `error` as the lines the model reads: the message, then each recovery step the+ tools in `tool-names` can act on."+ [{:keys [message recovery]} tool-names]+ (->> (recovery-steps-for-tools recovery tool-names)+ (map :text)+ (cons message)+ (str/join "\n")))++;;; ------------------------------------------ Classification ------------------------------------------------------++(defn classify+ "The ToolError for `e`.++ An exception carrying [[error-key]] in its ex-data keeps the class its producer chose; everything+ else is unrecoverable `:internal`. Reads the top-level exception only and does not walk the cause+ chain, so wrapping a declared error in an undeclared one demotes it — which is the safe+ direction."+ [e]+ (or (get (ex-data e) error-key)+ {:class :unrecoverable :code :internal}))diff --git a/src/metabase/metabot/tools/legacy.clj b/src/metabase/metabot/tools/legacy.cljnew file mode 100644index 00000000000..31a61916c76--- /dev/null+++ b/src/metabase/metabot/tools/legacy.clj@@ -0,0 +1,200 @@+(ns metabase.metabot.tools.legacy+ "Makes a tool written against the old shape satisfy `metabase.metabot.tools.core/Tool`.++ A tool used to be an `mu/defn` var carrying `:tool-name`, `:schema` and friends in its metadata,+ called with one argument and returning a loose result: a string, or a map with any of `:output`,+ `:structured-output`, `:structured_output`, `:instructions`, `:terminal-error?`, `:status-code`,+ `:data-parts`. Errors came back as a success-shaped `{:output \"…\"}` or escaped as+ an `ex-info` with `:agent-error?` or `:terminal-error?` in its ex-data.++ [[adapt]] wraps such a var in a [[LegacyTool]], which implements `Tool`. A profile's tool list goes+ through `adapt` once, so converted and unconverted tools arrive at `tools.core/entries` as the same+ kind of thing: `tools/call` calls both, and the runtime knows neither. Tools are converted one at a+ time and nothing has to happen on a single day.++ A wrapper rather than `extend-protocol` on `clojure.lang.Var`, which was the first thing tried.+ Extending the protocol to `Var` makes *every* var satisfy `Tool` — `clojure.core/map` included — so+ `satisfies? Tool` stops meaning anything and a var passed in by mistake fails somewhere inside+ `declaration` rather than where it was registered. `adapt` refuses it by name, at the call site.++ Behaviour is preserved rather than improved. An unconverted tool that returns a success-shaped+ failure still looks like a success, because nothing here can tell `{:output \"Failed to read the+ card\"}` from `{:output \"<card>…</card>\"}`. That is the thing conversion fixes, one tool at a+ time.++ This namespace is deleted when the last tool is converted."+ (:require+ [clojure.string :as str]+ [metabase.metabot.tools.core :as tools]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.recoverable.legacy :as recoverable.legacy]))++(set! *warn-on-reflection* true)++;;; ------------------------------------------------ Declaration ---------------------------------------------------++(defn- description+ "`doc` with the `Inputs: …` / `Return: …` preamble `mu/defn` prepends to a docstring removed.++ The same strip `metabase.metabot.self.schema/tool-function` does today. It moves here because the+ description is part of the declaration, and a converted tool's description needs no stripping at+ all — so the adapters stop needing this once the last tool is converted."+ [doc]+ (let [doc (or doc "")]+ (if (str/starts-with? doc "Inputs: ")+ (or (second (str/split doc #"\n\n " 2)) doc)+ doc)))++(defn- args-schema+ "The argument schema out of an `mu/defn` var's `[:=> [:cat args] out]`."+ [schema]+ (let [[_:=> [_:cat args] _out] schema]+ args))++(defn legacy-tool?+ "Whether `v` is a var carrying an old-shape tool definition."+ [v]+ (boolean (and (var? v) (:tool-name (meta v)))))++;;; ------------------------------------------------ Results -------------------------------------------------------++(defn- with-instructions+ "`output` with `instructions` appended. The old shape carried them separately and every adapter+ concatenated them; the new one has one text channel, so they are joined here."+ [output instructions]+ (cond+ (str/blank? (str instructions)) (or output "")+ (str/blank? (str output)) instructions+ :else (str output "\n" instructions)))++(defn- adapt-result+ "One old-shape return value as a `tools.core/result`.++ `:structured_output` is folded into `:structured-output`, `:instructions` into `:output`, and+ `:status-code` is dropped — it described the exception a tool had already caught, and a result does+ not carry one. `:resources` is dropped too: `read_resource` was the only tool that returned one,+ and now that it is converted the only consumer of per-item data reads it from the entries."+ [tool-name result]+ (cond+ (nil? result) {:output ""}+ (string? result) {:output result}+ (map? result)+ (let [{:keys [output structured-output structured_output instructions data-parts]} result]+ (when (:terminal-error? result)+ ;; The old way to end a turn and show the user something. `:output` was the user-facing text,+ ;; which is exactly what `:user-message` is for.+ (tools.error/unrecoverable! ::terminal-error+ {:user-message (or (not-empty output) "Something went wrong")+ :data {:tool-name tool-name}}))+ (cond-> {:output (with-instructions output instructions)}+ (or structured-output structured_output) (assoc :structured-output (or structured-output+ structured_output))+ (seq data-parts) (assoc :data-parts (vec data-parts))))+ :else {:output (str result)}))++(defn- adapt-throw+ "Re-raise `e` from an old-shape tool as a declared error, or rethrow it.++ `:terminal-error?` and `:agent-error?` are the two flags the old shape used to say who the message+ was for. Anything without one is a failure nobody wrote text for, so it passes through and becomes+ unrecoverable — the same judgement `with-pipeline-errors` makes."+ [tool-name ^Throwable e]+ (let [{:keys [agent-error? terminal-error?]} (ex-data e)]+ (cond+ ;; Already a declared error: raised by a converted tool this one called, or by a shared+ ;; converter such as `with-pipeline-errors`. A declared recoverable carries `:agent-error?`+ ;; too, so without this it would be re-wrapped as a legacy agent error — losing its recovery+ ;; steps and re-attributing it to this tool.+ (contains? (ex-data e) tools.error/error-key)+ (throw e)++ terminal-error?+ (tools.error/unrecoverable! ::terminal-error+ {:user-message (or (not-empty (ex-message e)) "Something went wrong")+ :cause e+ :data {:tool-name tool-name}})++ agent-error?+ (tools.error/throw-recoverable! ::recoverable.legacy/agent-error+ {:message (or (not-empty (ex-message e)) "The call failed.")+ :tool-name tool-name}+ {:cause e})++ :else+ (throw e))))++;;; ------------------------------------------------ The wrapper ---------------------------------------------------++(defrecord LegacyTool [tool-var]+ tools/Tool+ (declaration [_]+ (let [{:keys [tool-name doc schema scope capabilities title-fn prompt system-instructions decode]}+ (meta tool-var)]+ (cond-> {:name tool-name+ :description (description doc)+ :args (args-schema schema)}+ scope (assoc :scope scope)+ capabilities (assoc :metabot/capabilities capabilities)+ title-fn (assoc :metabot/title-fn title-fn)+ ;; Carried so nothing is lost in the adaptation. No consumer reads them, and a converted+ ;; tool declares none of them.+ prompt (assoc :metabot/prompt prompt)+ system-instructions (assoc :metabot/system-instructions system-instructions)+ decode (assoc :metabot/decode decode))))++ (handle [_ args _ctx]+ (let [{:keys [tool-name decode]} (meta tool-var)+ ;; `:decode` ran before the schema check in the old runtime. No tool uses it, and it is not+ ;; part of the new contract, but honouring it here keeps the adaptation faithful.+ args (cond-> args decode decode)]+ (try+ ;; One argument, and no ctx: the old signature. The runtime has already bound+ ;; `shared/*memory-atom*`, `*metabot*` and `*profile-id*` from `ctx`, which is how an+ ;; unconverted tool still reaches its state.+ (adapt-result tool-name (tool-var args))+ (catch Throwable e+ (adapt-throw tool-name e))))))++(defn adapt+ "`tool` as something implementing `tools.core/Tool`.++ A tool that already implements the protocol is returned unchanged. A var carrying old-shape+ metadata is wrapped. Anything else is refused here, where it was registered, rather than failing+ later inside a protocol method.++ Put a profile's whole tool list through this. Each conversion then removes nothing from the call+ site — the list is uniform either way — and this call disappears when the last tool converts."+ [tool]+ (cond+ (var? tool)+ (cond+ ;; Old shape: the metadata says so, and the var itself is the handler.+ (legacy-tool? tool) (->LegacyTool tool)+ ;; Converted, but still named as a var — which is how profiles name every tool, so they do+ ;; not change as tools are converted one at a time.+ (satisfies? tools/Tool (deref tool)) (deref tool)+ :else+ (throw (ex-info (str tool " is not a tool: its var carries no :tool-name metadata, and its "+ "value does not implement metabase.metabot.tools.core/Tool")+ {:var tool})))++ (satisfies? tools/Tool tool)+ tool++ :else+ (throw (ex-info (str (pr-str tool) " is not a tool: it implements neither "+ "metabase.metabot.tools.core/Tool nor the old var shape")+ {:tool tool}))))++(defn adapt-all+ "Every tool in `tools` through [[adapt]], in order. What a profile's tool list goes through."+ [tools]+ (mapv adapt tools))++(defn declaration-of+ "The declaration for `tool`, converted or not.++ For code that reads a tool's name, scope or capabilities without calling it — the profile filters,+ for instance, which used to read those off the var's metadata."+ [tool]+ (tools/declaration (adapt tool)))diff --git a/src/metabase/metabot/tools/recoverable/common.clj b/src/metabase/metabot/tools/recoverable/common.cljnew file mode 100644index 00000000000..8d3b7e73f18--- /dev/null+++ b/src/metabase/metabot/tools/recoverable/common.clj@@ -0,0 +1,39 @@+(ns metabase.metabot.tools.recoverable.common+ "Recoverable errors that more than one tool raises.++ An error belongs here only once a second tool needs it. A recoverable error declared for one tool+ lives in that tool's own namespace, so its code says where it came from and its text can stay+ specific."+ (:require+ [clojure.string :as str]+ [metabase.metabot.tools.error :refer [defrecoverable]]))++(set! *warn-on-reflection* true)++(def ^:private entity-kinds+ "The entity kinds [[not-found!]] can report on. A closed set because the kind reaches the model as+ a noun in English — an unexpected keyword would read as gibberish, and the payload check turns+ that into an `:internal` error instead."+ [:enum :card :chart :collection :dashboard :database :document :field :metric :model :question+ :segment :measure :snippet :table :timeline :transform])++(defrecoverable not-found!+ "The entity does not exist, or the current user cannot read it."+ {:payload [:map {:closed true}+ ;; Both optional because the two converters know different amounts.+ ;; `with-entity` wraps a specific lookup and names the entity; a 403 or 404 that+ ;; surfaces from deep inside the representations pipeline often does not say which+ ;; reference failed, and inventing a kind would be worse than omitting it.+ [:kind {:optional true} entity-kinds]+ [:id {:optional true} [:or :string :int]]]+ :status-code 404}+ [{:keys [kind id]}]+ ;; A 403 and a 404 give the same sentence on purpose. Telling the agent that something exists but+ ;; is forbidden leaks the existence of content the user cannot see, and the agent's next move is+ ;; the same either way.+ {:message (str (if (and kind id)+ (str (str/capitalize (name kind)) " " id)+ "The entity referenced here")+ " was not found. It may not exist, or you may not have access to it.")+ :recovery [{:uses #{"search"}+ :text "Call `search` to find the entity you want and use an id from the results."}]})diff --git a/src/metabase/metabot/tools/recoverable/legacy.clj b/src/metabase/metabot/tools/recoverable/legacy.cljnew file mode 100644index 00000000000..6379ca23c62--- /dev/null+++ b/src/metabase/metabot/tools/recoverable/legacy.clj@@ -0,0 +1,27 @@+(ns metabase.metabot.tools.recoverable.legacy+ "The one recoverable error a not-yet-converted tool can raise.++ A tool written against the old shape signals \"relay this to the model\" by throwing with+ `:agent-error? true`, or by catching that itself and returning the message as `:output`. The flag+ is the author saying the sentence was written for a model, which is the same judgement+ `metabase.metabot.tools.recoverable.pipeline` relies on for pipeline errors, so the message is+ authored text and the payload may carry it.++ One declaration for all of them, because a tool that has not been converted has not said which+ error it raised. Converting a tool means replacing its uses of this with declarations of its own,+ and this namespace goes away when the last tool is converted."+ (:require+ [metabase.metabot.tools.error :refer [defrecoverable]]))++(set! *warn-on-reflection* true)++(defrecoverable agent-error!+ "A tool that has not been converted relayed a message to the model."+ {:payload [:map {:closed true}+ [:message :string]+ [:tool-name :string]]}+ [{:keys [message]}]+ ;; No recovery steps. The tool knows how to recover and has not been asked yet; a step invented+ ;; here would be a guess, and a wrong one sends the agent at the wrong tool.+ {:message message+ :recovery []})diff --git a/src/metabase/metabot/tools/recoverable/pipeline.clj b/src/metabase/metabot/tools/recoverable/pipeline.cljnew file mode 100644index 00000000000..3a4aa0c4b75--- /dev/null+++ b/src/metabase/metabot/tools/recoverable/pipeline.clj@@ -0,0 +1,345 @@+(ns metabase.metabot.tools.recoverable.pipeline+ "One declared recoverable error per `:error` code the representations pipeline raises.++ The pipeline (`metabase.agent-lib.representations*`, `metabase.metabot.tools.construct`,+ `metabase.models.serialization.resolve.mp`) throws a bare statement of what went wrong plus+ structured `ex-data` carrying an `:error` keyword. It deliberately knows nothing about which tools+ its caller has, so it cannot say how to recover. This namespace supplies that half: each `:error`+ code gets a declaration whose recovery steps are written in the tool vocabulary — `read_resource`,+ `metabase://` URIs, portable FKs, `portable_entity_id` — and `tools.core/with-pipeline-errors`+ converts a pipeline exception into the matching declaration.++ The pipeline's own message is authored text (it is built with `tru` and already reaches the model+ today), so it is the one foreign message a payload here may carry. Everything else about the+ exception stays in the logs.++ A code with no declaration is not converted and becomes unrecoverable, which is why+ `metabase.metabot.tools.recoverable.pipeline-test` scans the pipeline sources and fails when a+ code here is missing. Recovery steps start from `metabase.metabot.tools.recovery-hints`, with+ `tru` removed — these are model-facing, not user-facing. A code whose recovery would be guesswork+ gets no steps at all: a missing step reads as terse, a wrong one sends the agent at the wrong+ tool."+ (:require+ [metabase.metabot.tools.error :refer [defrecoverable]]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++(mr/def ::payload+ "The payload every pipeline-error declaration takes.++ `:message` is the pipeline's own sentence. `:entity-type` and `:entity-id` are present only for+ the codes whose recovery depends on what was referenced (see [[uri-in-source-table!]])."+ [:map {:closed true}+ [:message :string]+ [:entity-type {:optional true} [:maybe :string]]+ [:entity-id {:optional true} [:maybe [:or :string :int]]]])++;;; ------------------------------------------- Shared recovery steps ----------------------------------------------++;; Each step names the tools its text mentions in `:uses`, so a profile without `read_resource` gets+;; the error with that step dropped rather than advice it cannot follow.++(def ^:private list-tables-step+ {:uses #{"read_resource"}+ :text (str "Call `read_resource` with `metabase://database/<numeric id>/tables` to list the available "+ "tables and schemas, then retry with an exact portable FK from the response.")})++(def ^:private list-fields-step+ {:uses #{"read_resource"}+ :text "Call `read_resource` with `metabase://table/<numeric id>/fields` to list this table's columns."})++(def ^:private list-fks-step+ {:uses #{"read_resource"}+ :text (str "Call `read_resource` with `metabase://table/<numeric id>/fields` for the source table to list "+ "the available foreign-key columns.")})++(def ^:private metric-dimensions-step+ {:uses #{"read_resource"}+ :text (str "If a metric relates to that table, read its dimensions resource "+ "`metabase://metric/<metric_id>/dimensions`, which lists the exact `joins:` clause to paste "+ "and the columns it unlocks.")})++(def ^:private card-entity-id-step+ {:uses #{"read_resource"}+ :text (str "Do not invent or guess entity_ids: call `read_resource` with "+ "`metabase://question/<numeric id>` or `metabase://model/<numeric id>` first, then copy the "+ "exact `portable_entity_id` from the response into `source-card:`.")})++(def ^:private measure-entity-id-step+ {:uses #{"read_resource"}+ :text (str "Do not invent or guess entity_ids: read the table that owns the measure with `read_resource` "+ "(`metabase://table/<numeric id>`) and copy the exact `portable_entity_id` from its "+ "`<measure>` tag.")})++(def ^:private segment-entity-id-step+ {:uses #{"read_resource"}+ :text (str "Do not invent or guess entity_ids: read the table that owns the segment with `read_resource` "+ "(`metabase://table/<numeric id>`) and copy the exact `portable_entity_id` from its "+ "`<segment>` tag.")})++(def ^:private database-name-step+ ;; Names no tool, so it survives into every profile: the advice is about where the database name+ ;; comes from in data the agent already has, not about making another call.+ {:uses #{}+ :text (str "Use the exact database name as it appears in the data you already have — it is the first "+ "element of every portable FK, e.g. `source-table: [<db-name>, <schema>, <table>]`.")})++(def ^:private first-stage-source-step+ {:uses #{}+ :text (str "`source-table:` takes a portable FK `[<db-name>, <schema>, <table>]`; `source-card:` takes an "+ "entity_id string.")})++;;; ------------------------------------------- Declarations -------------------------------------------------------++(defmacro ^:private defpipeline-error+ "Declare the recoverable error for one pipeline `:error` code.++ The message is always the pipeline's own sentence, so a declaration only has to say how to+ recover: `recovery` is a vector of recovery steps, usually the shared ones above. Use+ `defrecoverable` directly for a code whose recovery depends on the payload."+ {:style/indent [:defn]}+ [sym docstring recovery]+ `(defrecoverable ~sym ~docstring {:payload ::payload} [payload#]+ {:message (:message payload#)+ :recovery ~recovery}))++;;; Table resolution++(defpipeline-error unknown-table!+ "A portable FK `[db, schema, table]` in `source-table:` matched no active table."+ [list-tables-step])++(defpipeline-error unknown-table-id!+ "A numeric table id did not resolve."+ ;; Not `list-tables-step`: this is a numeric-id miss, and pointing the agent at a portable FK+ ;; would be advice for the other failure. v1 authors portable FKs, so the move is to find the+ ;; table by name and use its portable FK.+ [{:uses #{"read_resource"}+ :text (str "That numeric table id does not resolve. Call `read_resource` with "+ "`metabase://database/<numeric id>/tables` to find the table, then use its portable FK "+ "`[<db-name>, <schema>, <table-name>]` in `source-table:`.")}])++(defpipeline-error ambiguous-table!+ "A portable FK matched more than one table."+ [{:uses #{"read_resource"}+ :text (str "Call `read_resource` with `metabase://database/<numeric id>/tables` to list the available "+ "tables and retry with a more specific portable FK.")}])++;;; Database resolution++(defpipeline-error unknown-database!+ "The database name in a portable FK matched no database."+ [database-name-step])++(defpipeline-error unknown-database-id!+ "A numeric database id did not resolve."+ [database-name-step])++(defpipeline-error ambiguous-database-name!+ "The database name in a portable FK matched more than one database."+ [database-name-step])++;;; Field resolution++(defpipeline-error unknown-field!+ "A field reference named no column of its source."+ [list-fields-step])++(defpipeline-error unknown-field-id!+ "A numeric field id did not resolve."+ [list-fields-step])++(defpipeline-error ambiguous-field!+ "A field reference matched more than one column."+ [list-fields-step])++(defpipeline-error invalid-field-fk!+ "A field's portable FK was not a well-formed `[db, schema, table, field]` path."+ [list-fields-step])++(defpipeline-error numeric-field-id!+ "A field was referenced by numeric id where a portable FK is required."+ [list-fields-step])++(defpipeline-error unresolved-cross-stage-field!+ "A later stage referenced a column no earlier stage returns."+ [list-fields-step])++;;; Joins++(defpipeline-error ambiguous-fk!+ "More than one foreign key connects the two tables, so the join path is ambiguous."+ [list-fks-step])++(defpipeline-error ambiguous-fk-via-join!+ "More than one foreign key connects the joined tables, so the join path is ambiguous."+ [list-fks-step])++(defpipeline-error no-fk-path!+ "No foreign key connects the two tables, so they cannot be joined implicitly."+ [metric-dimensions-step])++;;; Saved entities++(defpipeline-error unknown-card!+ "A `source-card:` entity_id matched no question or model."+ [card-entity-id-step])++(defpipeline-error unknown-card-id!+ "A numeric card id did not resolve."+ [card-entity-id-step])++(defpipeline-error missing-card-entity-id!+ "A card reference carried no entity_id."+ [card-entity-id-step])++(defpipeline-error cross-database-card!+ "The referenced card belongs to a different database than the query."+ ;; No step: the fix is to pick a different source entirely, and which one depends on the question+ ;; the agent is answering, not on anything it can look up.+ [])++(defpipeline-error unknown-measure!+ "A measure entity_id matched no measure."+ [measure-entity-id-step])++(defpipeline-error unknown-measure-id!+ "A numeric measure id did not resolve."+ [measure-entity-id-step])++(defpipeline-error missing-measure-entity-id!+ "A measure reference carried no entity_id."+ [measure-entity-id-step])++(defpipeline-error cross-database-measure!+ "The referenced measure belongs to a different database than the query."+ [])++(defpipeline-error unknown-segment!+ "A segment entity_id matched no segment."+ [segment-entity-id-step])++(defpipeline-error unknown-segment-id!+ "A numeric segment id did not resolve."+ [segment-entity-id-step])++(defpipeline-error missing-segment-entity-id!+ "A segment reference carried no entity_id."+ [segment-entity-id-step])++(defpipeline-error cross-database-segment!+ "The referenced segment belongs to a different database than the query."+ [])++;;; Query shape++(defpipeline-error missing-source-in-first-stage!+ "The first stage declared neither `source-table:` nor `source-card:`."+ [first-stage-source-step])++(defpipeline-error unknown-stage-key!+ "A stage carried a key the representations format does not define."+ [])++(defpipeline-error invalid-representations-query!+ "The query did not parse as a representations query."+ [])++(defpipeline-error invalid-external-query!+ "A query supplied from outside the pipeline was not a valid MBQL query."+ [])++(defpipeline-error query-not-runnable!+ "The query parsed but would not run — the editor's own run gate rejects it."+ [])++(defpipeline-error not-implemented-yet!+ "The query used a representations feature the pipeline does not support yet."+ ;; No step: nothing the agent does to this query will make the feature exist. It can still make+ ;; progress by answering a different way, which is why this is recoverable rather than a dead end.+ [])++;;; Aggregations and expressions++(defpipeline-error aggregation-entry-not-aggregation!+ "An entry under `aggregation:` was not an aggregation clause."+ [])++(defpipeline-error aggregation-ref-no-aggregations!+ "An aggregation reference appeared in a stage with no aggregations."+ [])++(defpipeline-error aggregation-ref-out-of-range!+ "An aggregation reference pointed past the stage's aggregation list."+ [])++(defpipeline-error blank-expression-ref!+ "An expression reference named no expression."+ [])++(defpipeline-error case-default-in-opts!+ "A `case` expression put its default in the options map instead of the clause."+ [])++(defpipeline-error sexp-legacy-op-as-clause!+ "A legacy MBQL operator was written where a representations s-expression belongs."+ [])++(defpipeline-error expression-editor-rejection!+ "The expression editor rejected the expression."+ [])++(defpipeline-error post-agg-filter-needs-multi-stage!+ "A filter on an aggregate needs its own stage after the aggregating one."+ [])++(defpipeline-error post-agg-filter-with-trailing-clauses!+ "A post-aggregation filter was combined with clauses that have to precede it."+ [])++;;; Temporal handling++(defpipeline-error invalid-temporal-literal!+ "A temporal literal was not in a format the pipeline can parse."+ [])++(defpipeline-error temporal-unit-on-non-temporal-column!+ "A temporal bucket was applied to a column that is not a date or time."+ [list-fields-step])++(defpipeline-error unencodable-temporal-clause!+ "A temporal clause has no representations encoding."+ [])++;;; Payload-dependent++(defrecoverable uri-in-source-table!+ "A `metabase://` URI was used where `source-table:` expects a portable FK."+ {:payload ::payload}+ [{:keys [message entity-type entity-id]}]+ ;; The right correction depends on what the URI pointed at: a metric is not a source at all, a+ ;; card goes in a different key, and a table needs its portable FK.+ {:message message+ :recovery [(case entity-type+ "metric"+ {:uses #{"read_resource"}+ :text (str "Metrics are aggregations, not sources. To use metric " entity-id+ ", put its base table into `source-table:` — combine the `database_name` and "+ "`base_table_fully_qualified_name` attributes from its search result or "+ "`read_resource metabase://metric/" entity-id "` — and reference the metric as "+ "`aggregation: [[metric, {}, \"<portable_entity_id>\"]]`.")}++ ("question" "model" "card")+ {:uses #{"read_resource"}+ :text (str "To reference a saved question or model as a query source, put its "+ "`portable_entity_id` (the 21-char string from its search result or "+ "`read_resource`) into `source-card:` — not a URI.")}++ "table"+ {:uses #{"read_resource"}+ :text (str "Use the portable FK `[<db-name>, <schema>, <table-name>]` in `source-table:` — "+ "not a URI. `read_resource metabase://table/" entity-id+ "` reports the exact names.")}++ first-stage-source-step)]})diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.cljindex ab5cdd4dc12..6955b696e0c 100644--- a/src/metabase/metabot/tools/resources.clj+++ b/src/metabase/metabot/tools/resources.clj@@ -75,20 +75,19 @@[metabase.metabot.query-export :as query-export][metabase.metabot.scope :as scope][metabase.metabot.tmpl :as te]+ [metabase.metabot.tools.core :as tools][metabase.metabot.tools.entity-details :as entity-details][metabase.metabot.tools.field-stats :as field-stats]+ [metabase.metabot.tools.recoverable.common :as recoverable.common][metabase.metabot.tools.shared :as shared][metabase.metabot.tools.shared.content-store :as shared.content-store][metabase.metabot.tools.shared.instructions :as instructions][metabase.metabot.tools.shared.llm-shape :as llm-shape]- [metabase.metabot.tools.util :as metabot.tools.u][metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.transforms.core :as transforms][metabase.util :as u][metabase.util.i18n :refer [tru]]- [metabase.util.log :as log]- [metabase.util.malli :as mu][metabase.util.match :as match][metabase.warehouses.core :as warehouses][ring.util.codec :as codec]))@@ -103,6 +102,139 @@"Page size for list responses."25)+;;; ------------------------------------------ Recoverable errors --------------------------------------------------++(def ^:private uri-templates+ "The supported URI shapes, by leading segment — what an agent that guessed a URI wrong is told.++ [[dispatch]]'s match table is what actually routes; this is the same information written for the+ model. `uri-templates-cover-dispatch-test` reads both out of this file's source and fails when they+ disagree, so a new URI shape cannot be added without the guidance following it."+ {"databases" ["metabase://databases"]+ "collections" ["metabase://collections"+ "metabase://collections?tree=true"]+ "user" ["metabase://user/recent-items"]+ "database" ["metabase://database/{id}"+ "metabase://database/{id}/tables"+ "metabase://database/{id}/models"+ "metabase://database/{id}/schemas"+ "metabase://database/{id}/schemas/{schema_name}/tables"]+ "collection" ["metabase://collection/{id}"+ "metabase://collection/{id}/items"+ "metabase://collection/{id}/subcollections"]+ "table" ["metabase://table/{id}"+ "metabase://table/{id}/fields"+ "metabase://table/{id}/fields/{field_id}"+ "metabase://table/{id}/derived"]+ "model" ["metabase://model/{id}"+ "metabase://model/{id}/fields"+ "metabase://model/{id}/fields/{field_id}"+ "metabase://model/{id}/sources"]+ "question" ["metabase://question/{id}"+ "metabase://question/{id}/fields"+ "metabase://question/{id}/fields/{field_id}"+ "metabase://question/{id}/sources"]+ "metric" ["metabase://metric/{id}"+ "metabase://metric/{id}/dimensions"+ "metabase://metric/{id}/dimensions/{dimension_id}"]+ "measure" ["metabase://measure/{id}"]+ "segment" ["metabase://segment/{id}"]+ "transform" ["metabase://transform/{id}"+ "metabase://transform/{id}/sources"+ "metabase://transform/{id}/target"]+ "dashboard" ["metabase://dashboard/{id}"+ "metabase://dashboard/{id}/items"]+ "document" ["metabase://document/{id}"]+ "chart" ["metabase://chart/{chart_id}"]+ "query" ["metabase://query/{query_id}"]})++(defn- templates-step+ "A recovery step listing the URI shapes served under `kind`, or nil when `kind` is not one we serve.++ Names no tool, so it survives every profile: the agent is already holding the tool that raised+ this, and the step tells it what to pass next time."+ [kind]+ (when-let [templates (seq (get uri-templates kind))]+ {:uses #{}+ :text (str "URIs under `" kind "` are: " (str/join ", " templates) ".")}))++(def ^:private kinds-step+ "A recovery step listing the leading segments we serve. The fallback when the agent's URI names+ nothing we recognise, so there is no kind to be specific about."+ {:uses #{}+ :text (str "The resource types served here are: "+ (str/join ", " (sort (keys uri-templates)))+ ". Read `metabase://databases` or `metabase://collections` to start navigating.")})++(def ^:private search-step+ "The step to offer whenever the agent composed a URI by hand. Dropped automatically in a profile+ without `search`."+ {:uses #{"search"}+ :text "Copy the `uri` attribute from a `search` result instead of composing a URI by hand."})++(tools/defrecoverable malformed-uri!+ "The string is not a metabase:// URI at all."+ {:payload [:map {:closed true} [:uri :string]]}+ [{:keys [uri]}]+ {:message (str (pr-str uri) " is not a Metabase resource URI. One starts with `metabase://` and"+ " has at least one path segment, for example `metabase://databases`.")+ :recovery [kinds-step search-step]})++(tools/defrecoverable unsupported-uri!+ "The URI parses, but no handler serves that shape."+ {:payload [:map {:closed true}+ [:uri :string]+ ;; The leading segment, when there is one. Absent for a URI whose first segment is+ ;; itself unknown — then there is no kind to list shapes for.+ [:kind {:optional true} [:maybe :string]]]}+ [{:keys [uri kind]}]+ {:message (str "No resource is served at " (pr-str uri) ".")+ :recovery (vec (keep identity [(templates-step kind) kinds-step search-step]))})++(tools/defrecoverable non-numeric-id!+ "An entity URI carried something other than a numeric id — usually a 21-character entity id."+ {:payload [:map {:closed true}+ [:uri :string]+ [:kind :string]+ [:id :string]]}+ [{:keys [kind id]}]+ {:message (str "Invalid id " (pr-str id) " in URI. Resource URIs use the numeric entity id, not"+ " an entity_id, a name or a slug.")+ :recovery (vec (keep identity+ [(templates-step kind)+ {:uses #{"search"}+ :text (str "Call `search` and build the URI from a result's numeric `id`"+ " attribute, or copy its `uri` attribute as-is.")}]))})++(tools/defrecoverable invalid-page!+ "A `?page=N` outside the list's range."+ {:payload [:map {:closed true}+ [:page :int]+ [:pages :int]]}+ [{:keys [page pages]}]+ {:message (str "There is no page " page ". This list has " pages (if (= 1 pages) " page." " pages."))+ :recovery [{:uses #{}+ :text (str "Request a page between 1 and " pages+ ", or re-read the list without `?page=` and follow the `next-page-uri`"+ " it gives you.")}]})++(tools/defrecoverable not-in-conversation!+ "A chart or query id that is not in this conversation's state."+ {:payload [:map {:closed true}+ [:id :string]+ [:available [:sequential :string]]]}+ [{:keys [id available]}]+ {:message (if (seq available)+ (str "No chart or query with id " (pr-str id) " exists in this conversation."+ " The ids that do: " (str/join ", " available) ".")+ (str "No chart or query with id " (pr-str id) " exists in this conversation, and"+ " none have been created in it yet."))+ :recovery [{:uses #{}+ :text (str "Charts and queries are per-conversation. If the user mentioned this one,"+ " ask them to paste it again; otherwise construct it here first.")}]})++;;; ------------------------------------------ Pagination ----------------------------------------------------------+(defn- paginate-list"Return one page of items. `page-str` is a 1-indexed string (from a URI query param), defaults to 1.Page size is always `page-size`. Throws if `page-str` parses to a page number outside [1, pages]@@ -113,9 +245,7 @@pages (max 1 (int (Math/ceil (/ (double total) page-size))))page (or (some-> page-str parse-long) 1)_ (when (or (< page 1) (> page pages))- (throw (ex-info (str "Invalid page " page ". This list has " pages- (if (= pages 1) " page." " pages."))- {:page page :pages pages})))+ (invalid-page! {:page page :pages pages}))start (* (dec page) page-size)]{:items (subvec items start (min total (+ start page-size))):total total@@ -185,16 +315,14 @@- :query-params - {keyword string} map (e.g. {:tree \"true\"}), or nil if no query string"[uri](when-not (str/starts-with? uri "metabase://")- (throw (ex-info (str "Invalid URI scheme. Expected 'metabase://' but got: " uri)- {:uri uri})))+ (malformed-uri! {:uri uri}))(let [stripped (subs uri 11)[path qs] (str/split stripped #"\?" 2)segments (->> (str/split path #"/")(remove str/blank?)(mapv codec/url-decode))](when (zero? (count segments))- (throw (ex-info (str "Invalid URI: " uri " — empty path")- {:uri uri})))+ (malformed-uri! {:uri uri})){:segments segments:query-params (parse-query-string qs)}))@@ -348,7 +476,7 @@tree? (->> (sort-by :path) vec))](list-result (if tree? :collections-tree :collections-root) items query-params)))-(defn- fetch-user-recents []+(defn- fetch-user-recents [query-params](let [recents (or (-> (activity-feed/get-recents api/*current-user-id* [:views]):recents)[])@@ -363,7 +491,7 @@:timestamp timestamp:uri (llm-shape/metabase-uri (keyword type) id)}))recents)]- (list-result :recent-items items)))+ (list-result :recent-items items query-params)));; ----- Database drill-down -----@@ -539,10 +667,10 @@:field-id field-id:limit 30})))-(defn- fetch-card-sources [id-str]+(defn- fetch-card-sources [id-str query-params](let [card (api/read-check :model/Card (parse-long id-str))](check-resource-database (:database_id card))- (list-result :card-sources (card-sources-items card))))+ (list-result :card-sources (card-sources-items card) query-params)));; ----- Metric -----@@ -587,7 +715,7 @@query-export/transform-with-exportable-source(assoc :result-type :entity :type :transform))})-(defn- fetch-transform-sources [id-str]+(defn- fetch-transform-sources [id-str query-params](let [transform (transforms/get-transform (parse-long id-str))source-table-ids (transform-source-table-ids transform)source-tables (when (seq source-table-ids)@@ -600,9 +728,9 @@:id db-id:uri (llm-shape/metabase-uri :database db-id)})source-tables (into source-tables))]- (list-result :transform-sources items)))+ (list-result :transform-sources items query-params)))-(defn- fetch-transform-target [id-str]+(defn- fetch-transform-target [id-str query-params](let [transform (transforms/get-transform (parse-long id-str));; The target table is hydrated by `transforms/get-transform` without a per-table;; permission check (the read-check on the Transform itself only verifies *source*@@ -616,7 +744,7 @@:id db-id:uri (llm-shape/metabase-uri :database db-id)})target-table (conj (present-table target-table)))]- (list-result :transform-target items)))+ (list-result :transform-target items query-params)));; ----- Dashboard -----@@ -627,7 +755,10 @@{:structured-output (assoc dashboard:result-type :entity:can_write (boolean (mi/can-write? :model/Dashboard dashboard-id)))}- {:status-code 404 :output (:output result)})))+ ;; `get-dashboard-details` reports a miss as a result rather than by throwing, so the+ ;; conversion is explicit here. Its `:output` is dropped on purpose: it reads+ ;; "Dashboard not found", which is what `not-found!` says with the id and a way forward.+ (recoverable.common/not-found! {:kind :dashboard :id dashboard-id}))))(defn- present-non-question-dashcard"Dashcards not rendered as a saved question — virtual cards (headings, text, links, ...) and@@ -752,9 +883,11 @@:id query-id:description (or (export-state-query query-id query)query-withheld-message)})- {:status-code 404- :output (str "No chart or query with id '" query-id "' exists in this conversation. "- "It may belong to another conversation; ask the user to paste or recreate it here.")}))+ ;; The ids are the agent's own — it minted them in this conversation — so echoing them back is+ ;; not instance content.+ (not-in-conversation! {:id query-id+ :available (vec (sort (concat (keys (shared/current-charts-state))+ (keys (shared/current-queries-state)))))})))(defn- fetch-conversation-chart"Present a chart stored in this conversation's agent state (created by chart tools or@@ -796,82 +929,110 @@(when (and (numeric-id-uri-types type-seg)(some? id-seg)(nil? (parse-long id-seg)))- (throw (ex-info- (str "Invalid id `" id-seg "` in URI. read_resource URIs use the numeric entity "- "id — copy the `uri` attribute from a search result, or build the URI from "- "its numeric `id` attribute, e.g. metabase://" type-seg "/42.")- {:agent-error? true- :status-code 400- :uri uri- :id-segment id-seg}))))+ (non-numeric-id! {:uri uri :kind type-seg :id id-seg})))++(def ^:private uri-entity-kinds+ "Leading URI segment -> the entity kind a refusal under it is about.++ Only the segments that address one entity. A list URI (`databases`, `collections`) and the+ conversation-state URIs are absent: a refusal there is not about an entity the agent named, and+ `not-found!` would invent a noun for it."+ {"database" :database+ "collection" :collection+ "table" :table+ "model" :model+ "question" :question+ "metric" :metric+ "measure" :measure+ "segment" :segment+ "transform" :transform+ "dashboard" :dashboard+ "document" :document})++(defn- uri-entity+ "The `{:kind … :id …}` that a read refusal under these segments is about, for [[tools/with-entity]].++ `{}` when the URI names no single entity, which still converts a 403 or 404 into the declared+ not-found error — just without a noun. The id comes from the URI rather than from the handler, so+ a refusal deep inside a presenter is still attributed to the thing the agent asked for."+ [[type-seg id-seg]]+ (if-let [kind (get uri-entity-kinds type-seg)]+ (cond-> {:kind kind}+ (some-> id-seg parse-long) (assoc :id (parse-long id-seg)))+ {}))(defn- dispatch"Route a parsed URI to the right fetch handler. The match-one table is the canonicallist of supported URI shapes — adding a new URI = adding a clause here + a handler.Pattern ordering: more-specific patterns (no rest-binding) must come before less-specific- ones (with rest-binding) so the exact-length match wins for the no-extra-segments case."+ ones (with rest-binding) so the exact-length match wins for the no-extra-segments case.++ Every handler runs inside [[tools/with-entity]], so the ~10 `api/read-check` calls below it — and+ any nested one in a presenter — report the entity the URI named instead of a bare \"Not found.\"+ This is the single 404/403 translator for every resource kind; see+ `metabase.metabot.tools.recoverable.common/not-found!` for why 403 and 404 collapse."[uri](let [{:keys [segments query-params]} (parse-uri uri)](check-numeric-id-segment! uri segments)- (->> (match/match-one segments- ;; Navigation- ["databases"] (fetch-databases-list query-params)- ["collections"] (fetch-collections-list query-params)- ["user" "recent-items"] (fetch-user-recents)-- ;; Database drill-down- ["database" id] (fetch-database id)- ["database" id "tables"] (fetch-database-tables id query-params)- ["database" id "models"] (fetch-database-models id query-params)- ["database" id "schemas"] (fetch-database-schemas id query-params)- ["database" id "schemas" schema "tables"] (fetch-database-schema-tables id schema query-params)-- ;; Collection drill-down- ["collection" id] (fetch-collection id)- ["collection" id "items"] (fetch-collection-items id query-params)- ["collection" id "subcollections"] (fetch-collection-subcollections id query-params)-- ;; Table- ["table" id] (fetch-table id)- ["table" id "fields"] (fetch-table-fields id)- ["table" id "fields" & rst] (fetch-table-field id (str/join "/" rst))- ["table" id "derived"] (fetch-table-derived id query-params)-- ;; Card (model / question — share handlers, dispatch on the type segment)- [(t :guard #{"model" "question"}) id] (fetch-card t id)- [(t :guard #{"model" "question"}) id "fields"] (fetch-card-fields t id)- [(t :guard #{"model" "question"}) id "fields" & rst] (fetch-card-field t id (str/join "/" rst))- [(t :guard #{"model" "question"}) id "sources"] (fetch-card-sources id)-- ;; Metric- ["metric" id] (fetch-metric id)- ["metric" id "dimensions"] (fetch-metric-dimensions id)- ["metric" id "dimensions" & rst] (fetch-metric-dimension id (str/join "/" rst))-- ;; Measure / Segment- ["measure" id] (fetch-measure id)- ["segment" id] (fetch-segment id)-- ;; Transform- ["transform" id] (fetch-transform id)- ["transform" id "sources"] (fetch-transform-sources id)- ["transform" id "target"] (fetch-transform-target id)-- ;; Dashboard- ["dashboard" id] (fetch-dashboard id)- ["dashboard" id "items"] (fetch-dashboard-items id query-params)-- ;; Document- ["document" id] (fetch-document id)-- ;; Conversation state- ["chart" id] (fetch-conversation-chart id)- ["query" id] (fetch-conversation-query id)-- ;; Default — required to make match non-recursive- _ (throw (ex-info (str "Unsupported URI: " uri)- {:uri uri :segments segments})))+ (->> (tools/with-entity (uri-entity segments)+ (match/match-one segments+ ;; Navigation+ ["databases"] (fetch-databases-list query-params)+ ["collections"] (fetch-collections-list query-params)+ ["user" "recent-items"] (fetch-user-recents query-params)++ ;; Database drill-down+ ["database" id] (fetch-database id)+ ["database" id "tables"] (fetch-database-tables id query-params)+ ["database" id "models"] (fetch-database-models id query-params)+ ["database" id "schemas"] (fetch-database-schemas id query-params)+ ["database" id "schemas" schema "tables"] (fetch-database-schema-tables id schema query-params)++ ;; Collection drill-down+ ["collection" id] (fetch-collection id)+ ["collection" id "items"] (fetch-collection-items id query-params)+ ["collection" id "subcollections"] (fetch-collection-subcollections id query-params)++ ;; Table+ ["table" id] (fetch-table id)+ ["table" id "fields"] (fetch-table-fields id)+ ["table" id "fields" & rst] (fetch-table-field id (str/join "/" rst))+ ["table" id "derived"] (fetch-table-derived id query-params)++ ;; Card (model / question — share handlers, dispatch on the type segment)+ [(t :guard #{"model" "question"}) id] (fetch-card t id)+ [(t :guard #{"model" "question"}) id "fields"] (fetch-card-fields t id)+ [(t :guard #{"model" "question"}) id "fields" & rst] (fetch-card-field t id (str/join "/" rst))+ [(t :guard #{"model" "question"}) id "sources"] (fetch-card-sources id query-params)++ ;; Metric+ ["metric" id] (fetch-metric id)+ ["metric" id "dimensions"] (fetch-metric-dimensions id)+ ["metric" id "dimensions" & rst] (fetch-metric-dimension id (str/join "/" rst))++ ;; Measure / Segment+ ["measure" id] (fetch-measure id)+ ["segment" id] (fetch-segment id)++ ;; Transform+ ["transform" id] (fetch-transform id)+ ["transform" id "sources"] (fetch-transform-sources id query-params)+ ["transform" id "target"] (fetch-transform-target id query-params)++ ;; Dashboard+ ["dashboard" id] (fetch-dashboard id)+ ["dashboard" id "items"] (fetch-dashboard-items id query-params)++ ;; Document+ ["document" id] (fetch-document id)++ ;; Conversation state+ ["chart" id] (fetch-conversation-chart id)+ ["query" id] (fetch-conversation-query id)++ ;; Default — required to make match non-recursive+ _ (unsupported-uri! {:uri uri :kind (first segments)})))(attach-next-page-uri uri))));; ----- Display titles -----@@ -929,15 +1090,14 @@extra queries. The entity plus any drilled-into aspect (`[Orders](…) columns`), anaspect noun alone when the result carries no entity name (`tables`), or anavigation noun (`databases`). nil when nothing fits."- [{:keys [uri content]}]+ [uri structured](let [{segments :segments} (parse-uri uri)[segment id-str & rst] segmentsid (some-> id-str parse-long);; tables carry a raw :name (ORDERS) and a friendly :display_name (Orders);;; prefer the latter so the label matches the search resultsentity-name (when (and id (or (link-models segment) (plain-models segment)))- (let [so (:structured-output content)]- (or (:display_name so) (:name so))))+ (or (:display_name structured) (:name structured)))title (when (string? entity-name)(if (link-models segment)(te/link entity-name "metabase://" segment "/" id)@@ -950,23 +1110,7 @@noun noun:else (nav-noun segments))))-;; ----- Tool entry points -------(defn- fetch-single-uri- "Fetch a single URI and return formatted content.-- Returns a map with either:- - {:uri uri :content result}- - {:uri uri :error error-message}"- [uri]- (try- (let [result (dispatch uri)]- (if (:status-code result)- {:uri uri :error (or (:output result) result)}- {:uri uri :content result}))- (catch Exception e- (log/warn "Error fetching resource" {:error (ex-message e)})- {:uri uri :error (or (ex-message e) "Unknown error")})))+;;; ------------------------------------------ The tool ------------------------------------------------------------(defn- format-with-instructions"Wrap content in `<result>` / `<instructions>` tags."@@ -975,123 +1119,162 @@"<instructions>\n" instruction-text "\n</instructions>"))(defn- format-content- "Format a tool result as an LLM-ready string.- Dispatches to the right llm-shape formatter based on :result-type.- Returns the :output string directly for error results (404s etc.)."- [content]- (if-let [structured (:structured-output content)]- (case (:result-type structured)- ;; NOTE: keep in sync with agent/tools/metadata.clj/format-field-metadata-output- :field-metadata (format-with-instructions- (llm-shape/field-metadata->xml structured)- instructions/field-metadata-instructions)- :entity (llm-shape/entity->xml structured)- :metabot-list (llm-shape/metabot-list->xml structured)- :metabot-entity (llm-shape/metabot-entity->xml structured)- ;; fallback — should not happen, but better than EDN- (llm-shape/entity->xml structured))- ;; error case — :output is already a string- (:formatted content)))--(defn- format-resources- "Format resources for LLM output."- [resources]- (str "<resources>\n"- (str/join "\n"- (for [{:keys [uri content error]} resources]- (str "<resource uri=\"" uri "\">"- (if content- (str "\n" (format-content content) "\n")- (str "\n**Error:** " error "\n"))- "</resource>")))- "\n</resources>"))--(defn read-resource- "Read one or more Metabase resources via URI patterns.-- Parameters:- - uris: List of metabase:// URIs to fetch (max 5)-- Returns a map with formatted resources or error details."- [{:keys [uris]}]- (log/info "Reading resources" {:uri-count (count uris)})-- ;; Validate URI count- (when (> (count uris) max-concurrent-uris)- (throw (ex-info- (str "Too many URIs provided (" (count uris) "). "- "Please limit to " max-concurrent-uris " URIs maximum. "- "Be more selective and focus on the most relevant items for the current task or fetch them in batches.")- {:agent-error? true :uri-count (count uris) :max max-concurrent-uris})))-- ;; Fetch all URIs (sequentially for now, could parallelize with pmap)- (let [resources (mapv fetch-single-uri uris)- formatted (format-resources resources)- labels (into []- (comp (filter :content)- (keep #(try (uri-label %) (catch Throwable _ nil)))- (distinct))- resources)]- (log/info "Fetched resources" {:total (count resources)- :successful (count (filter :content resources))- :errors (count (filter :error resources))})- (cond-> {:resources resources- :output formatted}- (seq labels)- ;; just the object (the entities/aspects) — the client wraps it in the verb- ;; + tense ("Reading …" while active, "Read …" once settled)- (assoc :data-parts [(streaming/tool-title-part (str/join ", " labels))]))))--(mu/defn ^{:tool-name "read_resource"- :scope scope/agent-resource-read}- read-resource-tool- "Read detailed information about Metabase resources via URI patterns. Use this to navigate- the instance and drill into specific entities. URIs returned by `search` can be fed directly- back here. Only numeric IDs accepted, never alphanumeric entity-id's.-- Up to 5 URIs may be requested in one call. List responses are capped at 25 items per page.- When :truncated is true, fetch the next page by requesting the :next-page-uri given in the- truncation note — don't build a page=N query param by hand. The response also includes :page- (current, 1-indexed) and :pages (total page count).-- NAVIGATION (top-level lists):- - metabase://databases - all databases- - metabase://collections - root collections- - metabase://collections?tree=true - flat list of all collections (use :location for hierarchy)- - metabase://user/recent-items - your recently-viewed items-- DATABASE DRILL-DOWN:- - metabase://database/{id}- - metabase://database/{id}/tables- - metabase://database/{id}/models- - metabase://database/{id}/schemas- - metabase://database/{id}/schemas/{schemaName}/tables-- COLLECTION DRILL-DOWN:- - metabase://collection/{id}- - metabase://collection/{id}/items - subcollections + leaves- - metabase://collection/{id}/subcollections-- ENTITY DRILL-DOWN:- - metabase://table/{id}[/fields[/{field_id}]] [/derived]- - metabase://model/{id}[/fields[/{field_id}]] [/sources]- - metabase://question/{id}[/fields[/{field_id}]] [/sources]- - metabase://metric/{id}[/dimensions[/{dim_id}]]- - metabase://measure/{id}- - metabase://segment/{id}- - metabase://transform/{id}[/sources|/target]- - metabase://dashboard/{id}[/items]- - metabase://document/{id} - name + indexed outline of the document's top-level blocks- (the indices are valid `position` values for `save_entity` document destinations)-- CONVERSATION STATE (charts and queries generated in or pasted into this conversation,- e.g. referenced in a user message as [name](metabase://chart/{id})):- - 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 {:error/message "must be an array of URI strings"}- [:string {:description "Metabase resource URIs to fetch"}]]]]]- (try- (read-resource {:uris uris})- (catch Exception e- (metabot.tools.u/handle-agent-error e))))+ "One read's structured output as the LLM-ready string, by `:result-type`.++ Every handler returns a `:structured-output`; a miss or a refusal is thrown rather than returned,+ so there is no error branch here and no result shape that renders as an empty `<resource>`."+ [structured]+ (case (:result-type structured)+ ;; NOTE: keep in sync with agent/tools/metadata.clj/format-field-metadata-output+ :field-metadata (format-with-instructions+ (llm-shape/field-metadata->xml structured)+ instructions/field-metadata-instructions)+ :entity (llm-shape/entity->xml structured)+ :metabot-list (llm-shape/metabot-list->xml structured)+ :metabot-entity (llm-shape/metabot-entity->xml structured)+ ;; fallback — should not happen, but better than EDN+ (llm-shape/entity->xml structured)))++(defn- resource-element+ "One `<resource>` element, for either outcome.++ `uri` goes through `pr-str` because it reaches the model inside an attribute and is the agent's+ own text — an unescaped `\"` would close the attribute early and the rest of the URI would read as+ markup."+ [uri body]+ (str "<resource uri=" (pr-str uri) ">\n" body "\n</resource>"))++(def ^:private uri-arg+ "The one thing a read takes. Both declarations below build their `:args` from this, so the single+ and batched forms cannot drift."+ [:string {:min 1 :description "A metabase:// resource URI"}])++(def ^:private tool-description+ "What the model is told `read_resource` is.++ A value rather than a docstring: the batched form has to add its own per-call limits to it, and a+ docstring cannot be computed."+ (str+ "Read detailed information about Metabase resources via URI patterns. Use this to navigate\n"+ "the instance and drill into specific entities. URIs returned by `search` can be fed directly\n"+ "back here. Only numeric IDs accepted, never alphanumeric entity-id's.\n"+ "\n"+ "NAVIGATION (top-level lists):\n"+ "- metabase://databases - all databases\n"+ "- metabase://collections - root collections\n"+ "- metabase://collections?tree=true - flat list of all collections (use :location for hierarchy)\n"+ "- metabase://user/recent-items - your recently-viewed items\n"+ "\n"+ "DATABASE DRILL-DOWN:\n"+ "- metabase://database/{id}\n"+ "- metabase://database/{id}/tables\n"+ "- metabase://database/{id}/models\n"+ "- metabase://database/{id}/schemas\n"+ "- metabase://database/{id}/schemas/{schemaName}/tables\n"+ "\n"+ "COLLECTION DRILL-DOWN:\n"+ "- metabase://collection/{id}\n"+ "- metabase://collection/{id}/items - subcollections + leaves\n"+ "- metabase://collection/{id}/subcollections\n"+ "\n"+ "ENTITY DRILL-DOWN:\n"+ "- metabase://table/{id}[/fields[/{field_id}]] [/derived]\n"+ "- metabase://model/{id}[/fields[/{field_id}]] [/sources]\n"+ "- metabase://question/{id}[/fields[/{field_id}]] [/sources]\n"+ "- metabase://metric/{id}[/dimensions[/{dim_id}]]\n"+ "- metabase://measure/{id}\n"+ "- metabase://segment/{id}\n"+ "- metabase://transform/{id}[/sources|/target]\n"+ "- metabase://dashboard/{id}[/items]\n"+ "- metabase://document/{id} - name + indexed outline of the document's top-level blocks\n"+ " (the indices are valid `position` values for `save_entity` document destinations)\n"+ "\n"+ "CONVERSATION STATE (charts and queries generated in or pasted into this conversation,\n"+ "e.g. referenced in a user message as [name](metabase://chart/{id})):\n"+ "- metabase://chart/{chart_id} - the chart's type and its query\n"+ "- metabase://query/{query_id} - a query from this conversation's state"))++(def ^:private batch-note+ "What the batched form adds to [[tool-description]]: the limits that exist only because one call+ can carry several URIs."+ (str "\n\n"+ "Up to " max-concurrent-uris " URIs may be requested in one call. List responses are capped\n"+ "at " page-size " items per page; when a list is truncated its structured output carries a\n"+ "ready-to-fetch `next-page-uri` — request that rather than building a `page=N` query param\n"+ "by hand. The response also includes `page` (current, 1-indexed) and `pages` (total)."))++(defrecord ReadResourceTool []+ tools/Tool+ (declaration [_]+ {:name "read_resource"+ :description tool-description+ :scope scope/agent-resource-read+ :args [:map {:closed true} [:uri uri-arg]]})++ (handle [_ {:keys [uri]} _ctx]+ (let [structured (:structured-output (dispatch uri))]+ (when-not structured+ ;; Two handlers still report a miss by returning `{:output … :status-code 404}` rather than+ ;; throwing — `entity-details/get-measure-details` and `get-segment-details`, whose other+ ;; callers depend on that shape. Their text is dropped rather than forwarded: it was not+ ;; written for a model, and `not-found!` already names the entity and says what to do next.+ ;; This also closes the case where a result carrying only `:output` rendered as an empty+ ;; `<resource>`, because the formatter read a `:formatted` key nothing ever set.+ (recoverable.common/not-found! (uri-entity (:segments (parse-uri uri)))))+ {:output (format-content structured)+ :structured-output structured}))++ tools/BatchedTool+ (batched-declaration [_ declared]+ (assoc declared+ :description (str (:description declared) batch-note)+ ;; A sequence of plain strings, not of `{:uri …}` maps: that is the shape the model has+ ;; been offered all along, and a mechanical derivation from the single form is not worth+ ;; invalidating every eval and prompt that uses it. The item schema is shared, so only+ ;; the container differs.+ :args [:map {:closed true}+ [:uris [:sequential {:min 1+ :max max-concurrent-uris+ :error/message (str "must be an array of 1 to "+ max-concurrent-uris " URI strings")}+ uri-arg]]]))++ (batched-args [_ {:keys [uris]}]+ ;; The reads run sequentially. Each URI resolves a different kind through a different presenter,+ ;; so there is no shared query to issue up front — what they do share is the permission cache,+ ;; which `tools/call` holds across the whole call. `pmap` over the fetches is worth measuring,+ ;; but it needs the request bindings carried onto the threads.+ (mapv (fn [uri] {:uri uri}) uris))++ (compose [_ entries _ctx]+ ;; Every entry is wrapped here rather than in `handle`, which is what puts a failed URI inside+ ;; its own `<resource uri=…>` instead of leaving its text loose in the envelope. A call that+ ;; asked for five URIs and lost one still says which one.+ (let [labels (into []+ (comp (remove :failed?)+ (keep (fn [{:keys [item structured-output]}]+ (uri-label (:uri item) structured-output)))+ (distinct))+ entries)]+ (cond-> {:output (str "<resources>\n"+ (str/join "\n"+ (for [{:keys [item output failed?]} entries]+ (resource-element (:uri item)+ (if failed?+ (str "**Error:** " output)+ output))))+ "\n</resources>")}+ (some :structured-output entries)+ (assoc :structured-output (mapv :structured-output entries))++ ;; The title describes the call, so only the thing that knows what the call covered can+ ;; build it. Take `BatchedTool` away and the single form keeps working but stops emitting+ ;; one, and the client falls back to its own label.+ (seq labels)+ ;; just the object (the entities/aspects) — the client wraps it in the verb+ ;; + tense ("Reading …" while active, "Read …" once settled)+ (assoc :data-parts [(streaming/tool-title-part (str/join ", " labels))])))))++(def read-resource-tool+ "`read_resource`: one URI through [[tools/handle]], several through [[tools/run-batched]]."+ (->ReadResourceTool))diff --git a/src/metabase/metabot/tools/runtime.clj b/src/metabase/metabot/tools/runtime.cljnew file mode 100644index 00000000000..0f73c8c59f7--- /dev/null+++ b/src/metabase/metabot/tools/runtime.clj@@ -0,0 +1,363 @@+(ns metabase.metabot.tools.runtime+ "Runs one tool call and decides where its failure goes.++ [[invoke]] is the single door into a tool: it resolves the name, coerces and validates the+ arguments, checks the scope, calls the handler, checks what came back, and turns any exception+ into an [[::outcome]]. Tool code says *what happened* by throwing a declared error; this namespace+ is the only thing that decides *who hears about it* and in what words.++ The text rule the whole design rests on: the agent and the user only ever receive authored text.+ Authored text is a `defrecoverable` body's `:message` and recovery steps, a `:user-message` passed+ to `unrecoverable!`, or a sentence built here. No foreign exception message, cause, ex-data or+ stack trace reaches either audience; the full exception goes to the logs instead. [[render]]+ asserts the first half of that in dev and test, because the rule is only as good as the thing that+ checks it.++ Codes come in two flavours. Tool code uses qualified keywords, so a code says which namespace+ raised it. The runtime's own codes are a closed, unqualified vocabulary — [[runtime-codes]] — and+ the agent loop adds one more (`:repeated-error`)."+ (:require+ [clojure.string :as str]+ [malli.core :as mc]+ [malli.error :as me]+ [malli.transform :as mtx]+ [metabase.api-scope.core :as api-scope]+ [metabase.config.core :as config]+ [metabase.metabot.tools.core :as tools]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.shared :as shared]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.log :as log]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++(def runtime-codes+ "Every error code the runtime itself produces, with the class each one takes.++ Written down as data so the agent loop, the adapters and the tests share one list rather than+ three sets of literal keywords. `:repeated-error` is the agent loop's and is not raised here."+ {:unknown-tool :validation+ :invalid-json :validation+ :invalid-arguments :validation+ :scope-denied :unrecoverable+ :internal :unrecoverable})++;;; ------------------------------------------------ Schemas -------------------------------------------------------++(mr/def ::ctx+ "What a tool is told about the call it is running in.++ `:tool-names` is the only key the framework itself reads — `tools.core/handle-each` passes it to+ the recovery-step filtering. Everything else here is Metabot's own context, which is why it is+ namespaced in a consumer-neutral world: another consumer supplies its own keys and the same tool+ reads whichever it was written against. MCP would pass `:tool-names` (every registered tool, since+ it has no profiles) plus its session id, token scopes and client info.++ `:tool-names` is the set of tools available *this turn*, which [[render]] uses to drop recovery+ steps the agent could not act on.++ `:memory-atom` is absent outside a conversation-backed run, not withheld from particular tools. A+ tool that reads memory when there is some and copes without is easier to reason about than a+ per-tool allowlist, which in practice only meant the memory accessors returned nil for anyone who+ forgot to add their tool to it."+ [:map {:closed true}+ [:profile-id :keyword]+ ;; The scope set granted to the user this turn. Passed rather than read from+ ;; `metabase.metabot.scope/*current-user-scope*` because requiring that namespace from here is a+ ;; load cycle: it reaches the provider adapters through `metabot.settings`, and those require+ ;; `metabase.metabot.self.core`, which requires this namespace. `tools/->entries` reads the var+ ;; once per turn, inside the request, and puts it here.+ [:user-scope [:set :string]]+ ;; The resolved Metabot row, not an id: `tools.shared/*metabot*` carries the row so a tool can+ ;; scope a query to that metabot's collection.+ [:metabot [:maybe :map]]+ [:tool-names [:set :string]]+ [:memory-atom {:optional true} :any]])++(mr/def ::outcome+ "What [[invoke]] returns to `self/` and the agent loop.++ A failure keeps `:output` — the text the model receives and the conversation history stores — next+ to the machine-readable `:error`. Success is the absence of `:error`; nothing has to inspect+ `:structured-output` to tell the two apart."+ [:multi {:dispatch #(if (:error %) :failure :success)}+ [:success ::tools/result]+ [:failure [:map {:closed true}+ [:output :string]+ [:error [:map {:closed true}+ [:class [:enum :validation :recoverable :unrecoverable]]+ [:code :keyword]+ [:user-message {:optional true} :string]]]]]])++;;; ------------------------------------------------ Arguments -----------------------------------------------------++;;; The argument-repair machinery below currently also lives in `metabase.metabot.self.core`. It is+;;; duplicated rather than shared because the dependency runs the other way once tools are migrated+;;; — `self.core/run-tool` will call [[invoke]] — and `self.core`'s copies go away with the checks+;;; they serve. Keep the wording identical until then: this is the text models have been repairing+;;; against.++(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."+ (mtx/transformer+ {:name :llm-stringified-scalars+ :decoders (select-keys (mtx/-string-decoders)+ [:int :double :float :boolean 'int? 'double? 'float? 'boolean?+ 'integer? 'nat-int? 'neg-int? 'pos-int? 'number? 'decimal?])}))++(defn- coerce-stringified-scalars+ "Coerce string `arguments` to the scalar types `args-schema` declares. Some models send numbers as+ JSON strings, e.g. `{\"limit\": \"15\"}`. Values that can't be parsed are left alone."+ [args-schema arguments]+ (or (try+ (mc/decode args-schema arguments stringified-scalar-transformer)+ (catch Throwable _ 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) "."))))))++(def raw-arguments-key+ "The key the stream collector leaves behind when a model's tool-call arguments were not valid JSON.++ Its *presence* is what [[invoke]] reports as `:invalid-json`; the value is the model's own+ malformed output and never reaches a message. Malformed JSON and schema-valid JSON that breaks the+ schema are separate codes because they are separate mistakes, and the repair differs: resend the+ call as an object, versus fix a named argument."+ :_raw_arguments)++(def ^:private invalid-json-message+ "Invalid tool arguments: the arguments were not valid JSON. Send the call again as a JSON object.")++;;; ------------------------------------------------ Rendering -----------------------------------------------------++(defn- unrecoverable-output+ "What the model is told about an unrecoverable failure: the code, and not to retry.++ Nothing else. The user is being shown the real error on another channel, so the model's job here+ is to stop rather than to explain. The code is safe to include because it is ours — a closed+ vocabulary we wrote — and it gives the model something stable to refer to if it says anything at+ all. Note that the model only ever sees this *within the turn*, to pair the remaining tool calls+ of the iteration with results; a turn that ends in an error event is dropped from history whole,+ so later turns never read it."+ [code]+ (str "This call failed and the user was shown the error (" code "). Don't retry it."))++(def ^:private leak-patterns+ "Shapes that mean a raw exception or EDN dump reached agent-bound text: a stack-trace frame,+ Clojure's `#error` printing, a class name, an ANSI escape sequence. Checked in dev and test only —+ in production [[render]] caps the length and trusts the tests."+ [[#"\tat " "a stack-trace frame"]+ [#"#error \{" "Clojure's #error printing"]+ [#"clojure\.lang\." "a Clojure class name"]+ [#"\u001b\[" "an ANSI escape sequence"]])++(defn- assert-authored!+ "Check `text` for the shapes that mean an unauthored message leaked through. Dev and test only."+ [text where]+ (doseq [[pattern description] leak-patterns]+ (when (re-find pattern (str text))+ (throw (ex-info (str "Agent-bound text from " where " contains " description+ ". Tool errors may only carry authored text; log the exception instead.")+ {:where where})))))++(def ^:private max-output-length+ "A cap on agent-bound failure text. A declared error should be nowhere near this; the cap is here+ so that a pathological payload cannot spend the turn's context on one failure."+ 4000)++(defn render+ "The failure [[::outcome]] for a ToolError, given the tool names available this turn.++ | Class | `:output` |+ | ---------------- | --------------------------------------------------------- |+ | `:validation` | the message |+ | `:recoverable` | the message, then each kept recovery step on its own line |+ | `:unrecoverable` | a fixed sentence carrying only the code |++ `:user-message` is copied onto the outcome for unrecoverable errors so the agent loop can show it+ to the user. It never becomes part of `:output`."+ [{:keys [class code message recovery user-message]} tool-names]+ (let [output (case class+ :validation message+ ;; The same assembly an item's failure gets, so a `not-found!` reads identically+ ;; whether it ended the call or was one of several things the call tried.+ :recoverable (tools.error/recoverable-text {:message message :recovery recovery}+ tool-names)+ (unrecoverable-output code))]+ (when (or config/is-dev? config/is-test?)+ ;; Only the authored-text check runs here. Whether a declaration's message names a tool is a+ ;; property of the declaration, not of this call, so it is checked once over the whole catalog+ ;; in `metabase.metabot.tools.error-test` rather than on every render — which also means this+ ;; path needs no exemption for `tools.core/all-items-failed`, whose message is not authored at+ ;; all but assembled from text each item already had filtered for this profile.+ (assert-authored! output (str class " " code)))+ {:output (cond-> output+ (< max-output-length (count output)) (subs 0 max-output-length))+ :error (cond-> {:class class :code code}+ user-message (assoc :user-message user-message))}))++;;; ------------------------------------------------ Invocation ----------------------------------------------------++(defn- validation-ex+ "The exception for one of the runtime's validation errors. Thrown rather than returned so that all+ seven steps of [[invoke]] leave by the same door."+ ^Throwable [code message]+ (ex-info message {tools.error/error-key {:class :validation :code code :message message}}))++(defn- unknown-tool-message+ [tool-name tool-names]+ (str "Tool `" tool-name "` does not exist. Available tools: "+ (str/join ", " (sort tool-names)) "."))++(defn- unknown-tool-ex+ ^Throwable [tool-name entries]+ (validation-ex :unknown-tool (unknown-tool-message tool-name (keys entries))))++(defn unknown-tool-outcome+ "The failure [[::outcome]] for a call to a tool that is not in `tool-names`.++ Public because the agent's `run-tool` resolves the entry before it has anything to invoke, so it+ reaches this directly rather than through [[invoke]]. One definition of the message either way."+ [tool-name tool-names]+ (render {:class :validation+ :code :unknown-tool+ :message (unknown-tool-message tool-name tool-names)}+ tool-names))++(defn- check-scope!+ "Throw an unrecoverable `:scope-denied` error when the current user's scope does not cover the+ tool's declaration.++ Unrecoverable rather than recoverable: the agent cannot acquire a scope, so there is no alternative+ path to offer it, and a profile that lists a tool the user may not call is a configuration problem+ the user needs to see. The message names the tool because that is the actionable part — it says+ which permission to ask for."+ [{tool-name :name :keys [scope]} user-scope]+ (when (and scope (not (api-scope/scope-matches? user-scope scope)))+ (log/warnf "Scope check failed for tool %s — required: %s, granted: %s"+ tool-name scope user-scope)+ (tools.error/unrecoverable! :scope-denied+ {:user-message (tru "You don''t have permission to use the {0} tool."+ tool-name)+ :data {:tool-name tool-name :scope scope}})))++(defn- validated-args+ "`args` coerced and checked against the declaration's `:args` schema. Throws a validation error+ otherwise."+ [{:keys [args]} arguments]+ (when (and (map? arguments) (contains? arguments raw-arguments-key))+ (throw (validation-ex :invalid-json invalid-json-message)))+ (let [coerced (coerce-stringified-scalars args arguments)]+ (when-let [message (invalid-arguments-message args coerced)]+ (throw (validation-ex :invalid-arguments message)))+ coerced))++(defn- call-tool+ "Call `tool` with `args` and `ctx`, with the dynamic vars bound from `ctx`.++ `tools.core/call` is the whole of it: whether this tool does one item or several is its own+ business, and the orchestration for the batched case lives in `tools.core` where every consumer+ shares it. This namespace never asks which kind it has.++ The vars are bound as well as the ctx passed because code a tool reaches *through* does not take a+ ctx — `metabase.metabot.tools.shared.content-store`, which the representations pipeline uses, reads+ the vars. Tools themselves read ctx."+ [tool args {:keys [metabot profile-id memory-atom] :as ctx}]+ (binding [shared/*metabot* metabot+ shared/*profile-id* profile-id+ shared/*memory-atom* memory-atom]+ (tools/call tool args ctx)))++(defn- rendered-output+ "`result` with its `:output` rendered to a string.++ The boundary where a renderable becomes text. A tool may return either; this consumer wants a+ string, and another consumer would render the same value its own way — that is the whole point of+ `tools.core/Renderable`."+ [result]+ (update result :output tools/render-text))++(defn- checked-result+ "`result` if it is a valid [[::handler-result]]; otherwise an unrecoverable `:internal` error.++ A handler that returns the wrong shape is a bug in our code, not something to teach the model+ about, so the explanation goes to the log and the model is told only that the call failed."+ [tool-name result]+ (if (mr/validate ::tools/result result)+ result+ (do+ (log/errorf "Tool %s returned an invalid result: %s"+ tool-name (some-> (mr/explain ::tools/result result) me/humanize pr-str))+ (tools.error/unrecoverable! :internal {:data {:tool-name tool-name}}))))++(defn- log-failure!+ "Log `e` in full, at the level its class deserves. Validation and recoverable errors are the agent+ working as designed; only unrecoverable ones are faults."+ [tool-name {:keys [class code]} ^Throwable e]+ (if (= class :unrecoverable)+ (log/error e "Tool call failed" {:tool-name tool-name :code code})+ (log/debugf "Tool %s: %s error %s: %s" tool-name (name class) code (ex-message e))))++(defn invoke+ "Run the tool `tool-name` from `entries` with `args`, and return an [[::outcome]].++ `entries` is one profile's map of tool name to `{:declaration … :tool …}` (see+ `tools.core/entries`); `args` are the arguments after JSON parsing. Never throws — every failure comes back as a failure outcome, because the caller has+ to pair each `tool_use` with a `tool_result` and an escaping exception would break that pairing.++ In order:+ 1. an unknown `tool-name` is a validation error listing what this profile does have;+ 2. arguments that were not valid JSON are a validation error (see [[raw-arguments-key]]);+ 3. stringified scalars are coerced, then the arguments are validated against `:args`;+ 4. the scope is checked, and a denial is unrecoverable;+ 5. the tool runs with the dynamic vars bound from `ctx`, through `tools.core/call`;+ 6. its result is validated against `tools.core/result` and its `:output` rendered to a string;+ 7. any exception is classified, logged in full, and rendered for its audience."+ [entries ctx tool-name args]+ (let [tool-names (:tool-names ctx)]+ (try+ (let [{:keys [declaration tool]} (or (get entries tool-name)+ (throw (unknown-tool-ex tool-name entries)))+ checked (validated-args declaration args)]+ (check-scope! declaration (:user-scope ctx))+ (-> (call-tool tool checked ctx)+ (->> (checked-result tool-name))+ rendered-output))+ (catch Throwable e+ (let [error (tools.error/classify e)]+ (log-failure! tool-name error e)+ (render error tool-names))))))diff --git a/src/metabase/metabot/tools/slackbot_query.clj b/src/metabase/metabot/tools/slackbot_query.cljindex 554a17e2deb..efbe6303499 100644--- a/src/metabase/metabot/tools/slackbot_query.clj+++ b/src/metabase/metabot/tools/slackbot_query.clj@@ -10,9 +10,7 @@[metabase.metabot.agent.streaming :as streaming][metabase.metabot.scope :as scope][metabase.metabot.tools.construct :as construct]- [metabase.metabot.tools.recovery-hints :as recovery-hints]- [metabase.metabot.tools.util :as metabot.tools.u]- [metabase.util.malli :as mu]))+ [metabase.metabot.tools.core :as tools]))(set! *warn-on-reflection* true)@@ -31,33 +29,50 @@:description "Visualization type for displaying the query results in Slack. Required in practice whenever the user asks for a chart or graph, and it must match any requested chart type. Valid values: 'table', 'bar', 'line', 'pie', 'area', 'row', 'scatter', 'funnel'. Use requested chart types like 'line', 'bar', 'area', 'pie', 'scatter', 'funnel', 'row', or 'table' when they fit the query. Omitting this field falls back to Metabase's default table display, so do not omit it for chart or graph requests. Only omit it when you intentionally want a plain table and the user did not request a chart type."}[:maybe [:enum "table" "bar" "line" "pie" "area" "row" "scatter" "funnel"]]]])-(mu/defn ^{:tool-name "construct_notebook_query"- :scope scope/agent-notebook-create}- slackbot-construct-notebook-query-tool- "Construct a notebook query from a metric, model, or table. The query results will be- rendered as a visualization in Slack.-- See `resources/metabot/prompts/tools/construct_notebook_query.md` for the JSON format the- `:query` argument must follow — the prompt is shared with the main `construct_notebook_query`- tool."- [{:keys [_reasoning query title display]} :- slackbot-query-schema]- (try- (let [query-result (construct/execute-representations-query- query- {:recovery-hint recovery-hints/recovery-hint})- structured (or (:structured-output query-result) (:structured_output query-result))]- (if (and structured (:query-id structured) (:query structured))- (let [metabase-link (streaming/query->question-url (:query structured) display)- adhoc-viz-value (cond-> {:query (:query structured)- :link metabase-link}- title (assoc :title title)- display (assoc :display display))]- {:structured-output structured- :instructions (str "Query created. The visualization will be posted as a separate "- "follow-up message in the thread with the query results. "- "Use future tense when referring to results — they haven't "- "appeared yet when the user sees your text.")- :data-parts [(streaming/adhoc-viz-part adhoc-viz-value)]})- query-result))- (catch Exception e- (metabot.tools.u/handle-agent-or-api-error e))))+(def ^:private tool-description+ "What the model is told this tool is. The `:query` contract is the main tool's; only what happens+ to the result differs."+ (str+ "Construct a notebook query from a metric, model, or table. The query results will be\n"+ "rendered as a visualization in Slack.\n"+ "\n"+ "See `resources/metabot/prompts/tools/construct_notebook_query.md` for the JSON format the\n"+ "`:query` argument must follow — the prompt is shared with the main `construct_notebook_query`\n"+ "tool."))++(def ^:private instruction-text+ "Slack posts the visualization as its own follow-up message, so the model has to write as though+ the results are not on screen yet."+ (str "Use future tense when referring to results — they haven't appeared yet when the user sees "+ "your text."))++(defrecord SlackbotConstructNotebookQueryTool []+ tools/Tool+ (declaration [_]+ {:name "construct_notebook_query"+ :description tool-description+ :scope scope/agent-notebook-create+ :args slackbot-query-schema})++ (handle [_ {:keys [query title display]} _ctx]+ (let [structured (:structured-output (tools/with-pipeline-errors+ (construct/execute-representations-query query)))+ viz (cond-> {:query (:query structured)+ :link (streaming/query->question-url (:query structured) display)}+ title (assoc :title title)+ display (assoc :display display))]+ ;; Before, this returned `:instructions` and no `:output`, so the adapters fell back to+ ;; printing the whole result map — the model was shown the EDN of the resolved query as well+ ;; as the sentence. `:output` is the only thing the model reads now.+ {:output (str "<result>\n"+ "Query created. The visualization will be posted as a separate "+ "follow-up message in the thread with the query results.\n"+ "</result>\n"+ "<instructions>\n" instruction-text "\n</instructions>")+ :structured-output structured+ :data-parts [(streaming/adhoc-viz-part viz)]})))++(def slackbot-construct-notebook-query-tool+ "`construct_notebook_query` for the Slackbot profile: same pipeline, no saved chart, and the+ visualization leaves as an adhoc-viz data part."+ (->SlackbotConstructNotebookQueryTool))diff --git a/src/metabase/metabot/tools/timelines.clj b/src/metabase/metabot/tools/timelines.cljindex 731ea4af601..0913ff1b845 100644--- a/src/metabase/metabot/tools/timelines.clj+++ b/src/metabase/metabot/tools/timelines.clj@@ -1,7 +1,14 @@(ns metabase.metabot.tools.timelines+ "`list_timelines` and `get_timeline_details`.++ `get_timeline_details` is converted: it is a record implementing+ `metabase.metabot.tools.core/Tool`. `list_timelines` is not yet, so it is still an `mu/defn` var.+ Both appear in the same profile; see `metabase.metabot.tools/->entries`."(:require[clojure.string :as str][metabase.metabot.scope :as scope]+ [metabase.metabot.tools.core :as tools]+ [metabase.metabot.tools.recoverable.common :as recoverable.common][metabase.metabot.tools.shared.llm-shape :as llm-shape][metabase.metabot.tools.util :as metabot.tools.u][metabase.timeline.core :as timeline]@@ -20,19 +27,16 @@(metabot.tools.u/handle-agent-error e))))(defn get-timeline-details- "Retrieve a specific timeline by ID, including its events."- [{:keys [timeline-id]}]- (try- {:structured_output- (when timeline-id- (when-let [tl (timeline/include-events-singular- (timeline/get-timeline timeline-id))]- (-> (select-keys tl [:id :name :description])- (assoc :events- (mapv #(select-keys % [:id :name :description :timestamp :time_matters :timezone])- (:events tl))))))}- (catch Exception e- (metabot.tools.u/handle-agent-error e))))+ "A timeline by id, including its events, or nil when there is no such timeline.++ Returns nil rather than throwing: `timeline/get-timeline` is `[:maybe ...]`, and the caller decides+ what a miss means. `get_timeline_details` reports it as a declared not-found error."+ [timeline-id]+ (when-let [tl (timeline/include-events-singular (timeline/get-timeline timeline-id))]+ (-> (select-keys tl [:id :name :description])+ (assoc :events+ (mapv #(select-keys % [:id :name :description :timestamp :time_matters :timezone])+ (:events tl))))))(defn- format-timeline-list-output[timelines]@@ -80,12 +84,27 @@[_args :- [:map {:closed true}]](add-output (get-timelines {}) format-timeline-list-output))-(mu/defn ^{:tool-name "get_timeline_details"- :scope scope/agent-timelines-read}- get-timeline-details-tool- "Get the full details of a timeline including its events.+(defrecord GetTimelineDetailsTool []+ tools/Tool+ (declaration [_]+ {:name "get_timeline_details"+ :description (str "Get the full details of a timeline including its events.\n\n"+ "Use this tool to retrieve the events on a timeline after identifying it "+ "with list_timelines. Events include timestamps, names, and descriptions.")+ :scope scope/agent-timelines-read+ :args [:map {:closed true} [:timeline_id :int]]})+ (handle [_ {:keys [timeline_id]} _ctx]+ ;; `with-entity` covers the 403 a read check raises. A nil is the other way this misses, and it+ ;; reports the same thing: before, a miss returned `{:structured_output nil}` with no `:output`,+ ;; so the model was shown the printed map.+ (let [timeline (tools/with-entity {:kind :timeline :id timeline_id}+ (or (get-timeline-details timeline_id)+ (recoverable.common/not-found! {:kind :timeline :id timeline_id})))]+ ;; No `:structured-output`: nothing reads it for a timeline. It is not one of+ ;; `persistence/persisted-structured-output-keys`, the agent loop keeps no timeline memory, and+ ;; `used-tables` does not look at it.+ {:output (format-timeline-details-output timeline)})))- Use this tool to retrieve the events on a timeline after identifying it with- list_timelines. Events include timestamps, names, and descriptions."- [{:keys [timeline_id]} :- [:map {:closed true} [:timeline_id :int]]]- (add-output (get-timeline-details {:timeline-id timeline_id}) format-timeline-details-output))+(def get-timeline-details-tool+ "The `get_timeline_details` tool."+ (->GetTimelineDetailsTool))diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex f5025a237b9..e85e68ba9a2 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -16,6 +16,8 @@[metabase.lib.metadata :as lib.metadata][metabase.lib.normalize :as lib.normalize][metabase.mcp.core :as mcp]+ [metabase.metabot.tools.core :as tools.core]+ [metabase.metabot.tools.resources :as metabot-resources][metabase.oauth-server.test-util :as oauth-server.tu][metabase.permissions.core :as perms][metabase.permissions.models.data-permissions :as data-perms]@@ -28,6 +30,7 @@[metabase.test.http-client :as client][metabase.util :as u][metabase.util.json :as json]+ [metabase.util.malli.registry :as mr][oidc-provider.util :as oidc.util][toucan2.core :as t2]))@@ -1950,6 +1953,32 @@(let [uris (vec (repeat 10 "metabase://databases"))](mt/user-http-request :crowberto :post 400 "agent/v1/read-resource"{:uris uris})))+ (testing "this endpoint publishes the tool's own argument schema, so its limits cannot drift from+ the ones the agent loop enforces. The hand-written copy this replaced had already lost+ the 5-URI cap."+ ;; Compared on the `:uris` entry: `mr/def` stamps its own docstring onto the map's properties,+ ;; so the outer form differs by a `:description` the endpoint never publishes.+ (is (= (nth (:args (tools.core/validate-tool! metabot-resources/read-resource-tool)) 2)+ (nth (mr/schema :metabase.agent-api.api/read-resource-request) 2))))+ (testing (str "a URI that faults is that item's error, and the ones that read are kept. The agent "+ "loop fails the whole call for an undeclared failure — a bug is not a partial "+ "result — but this endpoint publishes one status for the call and an `:error` per "+ "item, so it opts out with `:on-item-fault`.")+ (mt/with-dynamic-fn-redefs [metabot-resources/dispatch+ (fn [uri]+ (if (str/includes? uri "boom")+ (throw (ex-info "a bug nobody wrote text for" {}))+ {:structured-output {:result-type :metabot-list+ :list-type :databases+ :items [] :total 0 :page 1 :pages 1}}))]+ (let [resp (mt/user-http-request :crowberto :post 200 "agent/v1/read-resource"+ {:uris ["metabase://databases" "metabase://boom"]})]+ (is (= ["metabase://databases" "metabase://boom"] (mapv :uri (:resources resp))))+ (is (some? (-> resp :resources first :content))+ "the URI that read is not discarded by the one that faulted")+ (testing "and the faulting one carries an authored sentence, not the exception's message"+ (is (= "This resource could not be read." (-> resp :resources second :error)))+ (is (not (str/includes? (:output resp) "a bug nobody wrote text for")))))))(testing "Reports a per-URI error rather than failing the whole call"(let [resp (mt/user-http-request :crowberto :post 200 "agent/v1/read-resource"{:uris ["metabase://nonsense/path"]})]diff --git a/test/metabase/metabot/agent/core_test.clj b/test/metabase/metabot/agent/core_test.cljindex 84a5d8f1b78..cdec9694ad8 100644--- a/test/metabase/metabot/agent/core_test.clj+++ b/test/metabase/metabot/agent/core_test.clj@@ -105,7 +105,8 @@:query-id "q1"}}}]failure [{:type :tool-input :id "b" :function "edit_sql_query"}{:type :tool-output :id "b" :result {:output "validation error"- :instructions "fix it"}}]+ :error {:class :validation+ :code :invalid-arguments}}}]read [{:type :tool-input :id "c" :function "read_resource"}{:type :tool-output :id "c" :result {:output "<fields/>"}}]](testing "a successful terminal-tool call ends the turn"@@ -119,6 +120,17 @@(is (not (#'agent/terminal-tool-call? terminal read))))(testing "terminality is per-profile: an empty terminal set never ends the turn"(is (not (#'agent/terminal-tool-call? #{} success))))+ (testing (str "an unconverted tool's returned failure does not end the turn either. Every "+ "terminal tool catches its own exceptions and returns `{:output \"Query 3 not "+ "found\"}`, so there is no `:error` for the adapter to find — ending the turn on "+ "the absence of one would deliver that sentence to the user as the answer. The "+ "`:structured-output` it does not attach is what tells them apart until they are "+ "converted.")+ (let [legacy-failure [{:type :tool-input :id "d" :function "edit_sql_query"}+ {:type :tool-output :id "d" :result {:output "Query 3 not found"}}]]+ (is (not (#'agent/terminal-tool-call? terminal legacy-failure)))+ (is (#'agent/should-continue? 0 20 terminal legacy-failure)+ "the model gets another turn to fix the id")))(testing "finish-reason reports :terminal-tool"(is (= :terminal-tool (#'agent/finish-reason 0 20 terminal success))))))@@ -226,22 +238,34 @@(is (contains? tools "document_construct_sql_chart"))(is (contains? tools "document_schema_collect")))))))+(defn- unrecoverable-part+ [id user-message]+ {:type :tool-output+ :id id+ :result (cond-> {:output "This call failed and the user was shown the error (:x). Don't retry it."+ :error {:class :unrecoverable :code :x}}+ user-message (assoc-in [:error :user-message] user-message))})+(deftest terminal-error-message-test(let [denial [{:type :tool-input :id "a" :function "create_sql_query"}- {:type :tool-output :id "a" :result {:output "No native permission."- :terminal-error? true}}]]- (testing "reads the message off a tool result marked terminal"+ (unrecoverable-part "a" "No native permission.")]]+ (testing "reads the user-facing message off an unrecoverable failure"(is (= "No native permission." (#'agent/terminal-error-message denial))))- (testing "an ordinary tool failure is not terminal"+ (testing "a recoverable failure is not terminal — the model can still self-correct"(is (nil? (#'agent/terminal-error-message- [{:type :tool-output :id "b" :result {:output "syntax error"}}]))))- (testing "a terminal marker with no message yields nil so no empty text part is emitted"+ [{:type :tool-output :id "b" :result {:output "syntax error"+ :error {:class :recoverable :code :x}}}]))))+ (testing "and neither is a success"(is (nil? (#'agent/terminal-error-message- [{:type :tool-output :id "c" :result {:output "" :terminal-error? true}}]))))+ [{:type :tool-output :id "b" :result {:output "fine"}}]))))+ (testing "an unrecoverable failure with no :user-message gets the generic one, so the user is+ always told something"+ (is (= "Something went wrong."+ (#'agent/terminal-error-message [(unrecoverable-part "c" nil)]))))(testing "the first denial wins when an iteration produces several"(is (= "first" (#'agent/terminal-error-message- [{:type :tool-output :id "a" :result {:output "first" :terminal-error? true}}- {:type :tool-output :id "b" :result {:output "second" :terminal-error? true}}]))))+ [(unrecoverable-part "a" "first")+ (unrecoverable-part "b" "second")]))))(testing "should-continue? is unaffected — the gate lives in loop-step, per profile"(is (#'agent/should-continue? 0 20 #{} denial)))))@@ -294,14 +318,19 @@"the refusal is emitted as assistant text — a tool result is not rendered to the user")(is (some #(= :data (:type %)) parts)"state data part still closes the turn")))- (testing ":internal lets the model explain the denial itself, so the loop continues"+ (testing (str ":internal stops on the same denial. The class decides, not the profile: only "+ "the user can grant this permission, so there is nothing for the agent to do "+ "with the turn. This used to continue, and the model paraphrased the refusal "+ "in its own words — nicer wording, bought with an extra LLM call, a profile "+ "exception, and a model that might have said something else entirely.")(let [{:keys [llm-calls parts]} (run-sql-denial-turn! :internal builder-db)]- (is (= 2 llm-calls))- (is (= :stop (:finish-reason (last parts))))- (is (not-any? #(and (= :text (:type %))- (str/includes? (str (:text %)) "do not have permission"))- parts)- "no canned text — the model's own wording is used")))+ (is (= 1 llm-calls)+ "one call, where the profile gate used to allow a second")+ (is (= :terminal-error (:finish-reason (last parts))))+ (is (some #(and (= :text (:type %))+ (str/includes? (:text %) "do not have permission"))+ parts)+ "the tool's own `:user-message`, which is authored and specific")))(testing "a database the user cannot read at all stops the turn the same way"(let [{:keys [llm-calls parts]} (run-sql-denial-turn! :sql unreadable-db)](is (= 1 llm-calls)diff --git a/test/metabase/metabot/agent/profiles_test.clj b/test/metabase/metabot/agent/profiles_test.cljindex 80ef74c4700..2b82cba085d 100644--- a/test/metabase/metabot/agent/profiles_test.clj+++ b/test/metabase/metabot/agent/profiles_test.clj@@ -5,12 +5,14 @@[metabase.metabot.agent.profiles :as profiles][metabase.metabot.scope :as scope][metabase.metabot.tools :as tools]+ [metabase.metabot.tools.legacy :as tools.legacy][metabase.search.entity-retrieval.core :as entity-retrieval][metabase.test :as mt]))(deftest get-profile-test+ ;; The declaration, not the var's metadata: a converted tool is a record and carries none.(letfn [(tool-names [profile]- (set (map #(:tool-name (meta %)) (:tools profile))))]+ (set (map #(:name (tools.legacy/declaration-of %)) (:tools profile))))](testing "retrieves embedding_next profile with default provider"(let [profile (profiles/get-profile :embedding_next)](is (some? profile))@@ -265,3 +267,28 @@(is (contains? tools "read_resource")"precondition: read_resource is active (would otherwise match a skill)")(is (not (contains? tools "load_skill")))))))++(deftest terminal-tools-are-still-unconverted-test+ (testing (str "Every tool a profile can end a turn on is still an `mu/defn` var. "+ "`metabase.metabot.agent.core/answer-producing?` requires `:structured-output` "+ "from them on top of the absence of `:error`, because each one catches its own "+ "exceptions and returns `{:output \"Query 3 not found\"}` — a failure with no "+ "`:error` for the adapter to find, which would otherwise end the turn and deliver "+ "that sentence as the answer.\n\n"+ "When one of these is converted it throws instead, its failure carries an `:error`, "+ "and the extra requirement becomes wrong: a converted tool that answers without "+ "structured output would stop being terminal. So this test is the tripwire — if it "+ "fails because you converted one of these, delete the `:structured-output` clause "+ "in `answer-producing?` and this test with it.")+ (let [terminal (for [[profile-id profile] @@#'profiles/*profiles+ :let [by-name (into {} (map (juxt #(:name (tools.legacy/declaration-of %))+ identity))+ (:tools profile))]+ tool-name (:terminal-tools profile)]+ [profile-id tool-name (get by-name tool-name)])]+ (is (seq terminal) "no terminal tools found — has :terminal-tools moved?")+ (doseq [[profile-id tool-name tool-var] terminal]+ (testing (str profile-id " / " tool-name)+ (is (some? tool-var) "a profile lists a terminal tool it does not expose")+ (is (tools.legacy/legacy-tool? tool-var)+ (str tool-name " is converted now — see this test's docstring")))))))diff --git a/test/metabase/metabot/agent/scope_enforcement_test.clj b/test/metabase/metabot/agent/scope_enforcement_test.cljindex ed67286b246..34778bff8b2 100644--- a/test/metabase/metabot/agent/scope_enforcement_test.clj+++ b/test/metabase/metabot/agent/scope_enforcement_test.clj@@ -3,7 +3,8 @@[clojure.test :refer [deftest is testing]][metabase.api-scope.core :as api-scope][metabase.metabot.scope :as scope]- [metabase.metabot.tools :as tools]))+ [metabase.metabot.tools :as tools]+ [metabase.util.malli :as mu]));;; ──────────────────────────────────────────────────────────────────;;; Tool list filtering by scope (via profiles/filter-by-scope)@@ -29,52 +30,54 @@(is (nil? (:scope (meta no-scope))))))));;; ──────────────────────────────────────────────────────────────────-;;; Tool invocation scope check (via wrap-tools-with-state)+;;; Tool invocation scope check (in the runtime, from the declaration);;; ──────────────────────────────────────────────────────────────────-(deftest ^:parallel wrapped-tool-scope-enforcement-test- (let [tool-var (with-meta (fn [_args] {:output "success"})- {:tool-name "test_tool"- :schema [:=> [:cat :map] :map]- :scope "agent:sql:create"})- tools-map {"test_tool" tool-var}- memory-atom (atom {})- wrapped (tools/wrap-tools-with-state tools-map memory-atom nil :sql)- wrapped-fn (get-in wrapped ["test_tool" :fn])]- (testing "tool executes when scope is satisfied"- (binding [scope/*current-user-scope* api-scope/unrestricted]- (is (= {:output "success"} (wrapped-fn {})))))- (testing "tool executes with matching wildcard scope"- (binding [scope/*current-user-scope* #{"agent:sql:*"}]- (is (= {:output "success"} (wrapped-fn {})))))- (testing "tool executes with exact scope match"- (binding [scope/*current-user-scope* #{"agent:sql:create"}]- (is (= {:output "success"} (wrapped-fn {})))))- (testing "tool returns denial when scope is not satisfied"- (binding [scope/*current-user-scope* #{}]- (let [result (wrapped-fn {})]- (is (string? (:output result)))- (is (re-find #"do not have permission" (:output result)))- ;; scope string should NOT be leaked in the output- (is (not (re-find #"agent:sql" (:output result)))))))- (testing "tool returns denial with wrong scope"- (binding [scope/*current-user-scope* #{"agent:notebook:*"}]- (let [result (wrapped-fn {})]- (is (re-find #"do not have permission" (:output result))))))))+(mu/defn ^{:tool-name "scoped_test_tool"+ :scope "agent:sql:create"}+ scoped-test-tool+ "A tool that requires a scope."+ [_args :- [:map {:closed true}]]+ {:output "success"})-(deftest ^:parallel wrapped-tool-no-scope-test- (let [tool-var (with-meta (fn [_args] {:output "no-scope-tool"})- {:tool-name "legacy_tool"- :schema [:=> [:cat :map] :map]})- tools-map {"legacy_tool" tool-var}- memory-atom (atom {})- wrapped (tools/wrap-tools-with-state tools-map memory-atom nil :sql)- wrapped-fn (get-in wrapped ["legacy_tool" :fn])]- (testing "tool without :scope always executes regardless of current scope"- (binding [scope/*current-user-scope* #{}]- (is (= {:output "no-scope-tool"} (wrapped-fn {}))))- (binding [scope/*current-user-scope* api-scope/unrestricted]- (is (= {:output "no-scope-tool"} (wrapped-fn {})))))))+(mu/defn ^{:tool-name "unscoped_test_tool"}+ unscoped-test-tool+ "A tool that requires no scope."+ [_args :- [:map {:closed true}]]+ {:output "no-scope-tool"})++(defn- call-tool+ [tool-var tool-name]+ ((get-in (tools/->entries [tool-var] (atom {}) nil :sql) [tool-name :fn]) {}))++(deftest ^:parallel tool-scope-enforcement-test+ (doseq [[label granted] {"unrestricted" api-scope/unrestricted+ "wildcard" #{"agent:sql:*"}+ "exact" #{"agent:sql:create"}}]+ (testing (str "the tool runs with a " label " scope")+ (binding [scope/*current-user-scope* granted]+ (is (= {:output "success"} (call-tool #'scoped-test-tool "scoped_test_tool"))))))+ (testing "a denial is unrecoverable: the agent cannot acquire a scope, so the turn ends"+ (doseq [[label granted] {"no scope" #{}+ "wrong scope" #{"agent:notebook:*"}}]+ (testing label+ (binding [scope/*current-user-scope* granted]+ (let [outcome (call-tool #'scoped-test-tool "scoped_test_tool")]+ (is (= :unrecoverable (get-in outcome [:error :class])))+ (is (= :scope-denied (get-in outcome [:error :code])))+ (testing "the user is told which tool, and the scope string is not leaked"+ (is (re-find #"permission to use the scoped_test_tool tool"+ (get-in outcome [:error :user-message])))+ (is (not (re-find #"agent:sql" (get-in outcome [:error :user-message])))))+ (testing "and the model is told only that it failed"+ (is (re-find #"Don't retry it" (:output outcome)))+ (is (not (re-find #"agent:sql" (:output outcome)))))))))))++(deftest ^:parallel tool-without-a-scope-always-runs-test+ (doseq [granted [#{} api-scope/unrestricted]]+ (binding [scope/*current-user-scope* granted]+ (is (= {:output "no-scope-tool"}+ (call-tool #'unscoped-test-tool "unscoped_test_tool"))))))(deftest ^:parallel default-scope-is-empty-test(testing "*current-user-scope* defaults to empty set — denies all scoped tools"diff --git a/test/metabase/metabot/agent/tool_output_test.clj b/test/metabase/metabot/agent/tool_output_test.cljindex bb822895a8c..abbf6968e77 100644--- a/test/metabase/metabot/agent/tool_output_test.clj+++ b/test/metabase/metabot/agent/tool_output_test.clj@@ -8,6 +8,7 @@[clojure.test :refer :all][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.metabot.test-util :as test-util][metabase.metabot.tools.metadata :as metadata-tools][metabase.metabot.tools.resources :as resource-tools][metabase.metabot.tools.search :as search-tools]@@ -84,40 +85,40 @@(defn- read-resource-invocations! [][["read_resource: table (no fields)"- #(resource-tools/read-resource-tool- {:uris [(str "metabase://table/" (mt/id :orders))]})+ #(test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://table/" (mt/id :orders))]})#"<table\b"]["read_resource: table with fields"- #(resource-tools/read-resource-tool- {:uris [(str "metabase://table/" (mt/id :orders) "/fields")]})+ #(test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://table/" (mt/id :orders) "/fields")]})#"<table\b"]["read_resource: table field values"#(let [table-id (mt/id :orders)field-id (find-field-id table-id "QUANTITY")](ensure-fresh-field-values! (mt/id :orders :quantity))- (resource-tools/read-resource-tool- {:uris [(str "metabase://table/" table-id "/fields/" field-id)]}))+ (test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://table/" table-id "/fields/" field-id)]}))#"<field-metadata\b"]])(defn- read-resource-metric-invocations [metric-id][["read_resource: metric (no dimensions)"- #(resource-tools/read-resource-tool- {:uris [(str "metabase://metric/" metric-id)]})+ #(test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://metric/" metric-id)]})#"<metric\b"]["read_resource: metric with dimensions"- #(resource-tools/read-resource-tool- {:uris [(str "metabase://metric/" metric-id "/dimensions")]})+ #(test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://metric/" metric-id "/dimensions")]})#"<metric\b"]])(defn- read-resource-model-invocations [model-id][["read_resource: model (no fields)"- #(resource-tools/read-resource-tool- {:uris [(str "metabase://model/" model-id)]})+ #(test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://model/" model-id)]});; model->xml outputs <metabase-model> tag#"<metabase-model\b"]["read_resource: model with fields"- #(resource-tools/read-resource-tool- {:uris [(str "metabase://model/" model-id "/fields")]})+ #(test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://model/" model-id "/fields")]})#"<metabase-model\b"]]);; ---------------------------------------------------------------------------@@ -173,21 +174,24 @@(testing "read_resource with multiple URIs returns a single formatted :output string"(mt/test-driver :h2(mt/with-current-user (mt/user->id :crowberto)- (let [result (resource-tools/read-resource-tool- {:uris [(str "metabase://table/" (mt/id :orders))- (str "metabase://table/" (mt/id :products))]})]+ (let [result (test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://table/" (mt/id :orders))+ (str "metabase://table/" (mt/id :products))]})](assert-formatted-output result "multiple tables" #"<resources>"))))))(deftest read-resource-error-uri-test- (testing "read_resource with bad URI returns :output string, not an exception"+ (testing (str "read_resource with a bad URI gives the model authored text. The one URI could not "+ "be read, so the call failed — but what the model reads is still a string with no "+ "EDN in it.")(mt/test-driver :h2(mt/with-current-user (mt/user->id :crowberto)- (let [{:keys [output]} (resource-tools/read-resource-tool- {:uris ["metabase://table/999999999"]})]- (is (string? output) "error case must still return :output string")+ (let [{:keys [class text]} (test-util/tool-failure resource-tools/read-resource-tool+ {:uris ["metabase://table/999999999"]})]+ (is (= :recoverable class))+ (is (string? text) "a failure must still carry text for the model")(testing "Should not contain EDN patterns"(doseq [pattern edn-patterns]- (is (not (re-find pattern output)) (str "error output contains EDN pattern " pattern)))))))))+ (is (not (re-find pattern text)) (str "error output contains EDN pattern " pattern)))))))))(deftest search-tool-structured-output-formats-correctly-test(testing "search tool :structured-output formats to clean XML via format-structured-result"@@ -323,8 +327,8 @@:type :model}](ensure-fresh-field-values! (mt/id :orders :quantity))(let [field-id (mt/id :orders :quantity)- result (resource-tools/read-resource-tool- {:uris [(str "metabase://model/" model-id "/fields/" field-id)]})]+ result (test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://model/" model-id "/fields/" field-id)]})](assert-formatted-output result "model field values" #"<field-metadata\b"))))))))(deftest read-resource-metric-dimension-values-test@@ -342,6 +346,6 @@;; Use a real filterable field ID from the metric's source table;; Temp metrics may not have fingerprints — "No metadata available" is also valid(let [field-id (mt/id :orders :id)- result (resource-tools/read-resource-tool- {:uris [(str "metabase://metric/" metric-id "/dimensions/" field-id)]})]+ result (test-util/call-tool resource-tools/read-resource-tool+ {:uris [(str "metabase://metric/" metric-id "/dimensions/" field-id)]})](assert-formatted-output result "metric dimension values" #"(?:<field-metadata\b|No metadata available)"))))))))diff --git a/test/metabase/metabot/persistence_test.clj b/test/metabase/metabot/persistence_test.cljindex 4575bec6a89..f47296b351c 100644--- a/test/metabase/metabot/persistence_test.clj+++ b/test/metabase/metabot/persistence_test.clj@@ -1475,10 +1475,16 @@(is (= ""(tool-content [{:type :tool-input :id "c1" :function "search" :arguments {}}{:type :tool-output :id "c1" :result nil}]))))- (testing "errored tool output uses the error text"- (is (= "kaboom"+ (testing (str "a failed tool output replays the model-facing text from its result. The "+ "error lives in `:result`, not on the part, and `:errorText` is what the "+ "model reads again on replay — so it is the authored failure text, not the "+ "sentence the live UI channel shows.")+ (is (= "Table 7 was not found. Call `search` for a table id."(tool-content [{:type :tool-input :id "c1" :function "search" :arguments {}}- {:type :tool-output :id "c1" :error {:message "kaboom"}}]))))))))+ {:type :tool-output :id "c1"+ :result {:output "Table 7 was not found. Call `search` for a table id."+ :error {:class :recoverable+ :code :metabase.metabot.tools.recoverable.common/not-found}}}]))))))))(deftest history-drops-errored-turn-test(testing "a turn whose reply errored is dropped whole; surrounding turns survive"diff --git a/test/metabase/metabot/self/claude_test.clj b/test/metabase/metabot/self/claude_test.cljindex 00c8bc7bbdc..e518326bc5e 100644--- a/test/metabase/metabot/self/claude_test.clj+++ b/test/metabase/metabot/self/claude_test.clj@@ -539,12 +539,24 @@[{:type :tool-input :id "call-1" :function "todo_read" :arguments nil}])))))(deftest ^:parallel parts->claude-messages-error-result-test- (testing "tool error is formatted as error string"+ (testing "a failed call carries its text and is marked as a failure, so the model does not read+ it as an ordinary result"(is (=? [{:role "user"- :content [{:type "tool_result"- :content #"Error:.*failed"}]}]+ :content [{:type "tool_result"+ :tool_use_id "call-1"+ :content "Card 7 was not found."+ :is_error true}]}](claude/parts->claude-messages- [{:type :tool-output :id "call-1" :error {:message "Tool failed"}}])))))+ [{:type :tool-output :id "call-1"+ :result {:output "Card 7 was not found."+ :error {:class :recoverable :code :x}}}]))))+ (testing "a successful call is not marked"+ (is (= [{:role "user"+ :content [{:type "tool_result"+ :tool_use_id "call-1"+ :content "<card/>"}]}]+ (claude/parts->claude-messages+ [{:type :tool-output :id "call-1" :result {:output "<card/>"}}])))))(deftest ^:parallel parts->claude-messages-blank-content-test(testing "blank string content is filtered out during merge"diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.cljindex fc652b85feb..84f9c235cd6 100644--- a/test/metabase/metabot/self_test.clj+++ b/test/metabase/metabot/self_test.clj@@ -9,6 +9,7 @@[metabase.analytics.snowplow-test :as snowplow-test][metabase.llm.provider :as llm.provider][metabase.llm.test-util :as llm.tu]+ [metabase.metabot.persistence :as persistence][metabase.metabot.schema.v2 :as schema.v2][metabase.metabot.scope :as scope][metabase.metabot.self :as self]@@ -26,6 +27,10 @@[metabase.metabot.self.zai :as zai][metabase.metabot.settings :as metabot.settings][metabase.metabot.test-util :as test-util]+ [metabase.metabot.tools :as metabot.tools]+ [metabase.metabot.tools.core :as tools.core]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.runtime :as tools.runtime][metabase.metabot.usage :as usage][metabase.test :as mt][metabase.test.fixtures :as fixtures]@@ -495,11 +500,12 @@:toolName "search":result {:data []}::self.core/duration-ms 1234}]]+ ;; No `:error` key: a failed call carries its error inside `:result`, and a second copy on+ ;; the part is what let a failure read as a success downstream.(is (= [{:type :tool-output:id "call-1":function "search":result {:data []}- :error nil:duration-ms 1234}](into [] (self.core/lite-aisdk-xf) chunks)))))(testing "streams reasoning deltas and carries provider metadata on the end"@@ -656,22 +662,33 @@(is (=? {:type :tool-output-available:toolCallId "call-err":toolName "get-time"- :error {:message string?- :type string?}}+ :result {:output string?+ :error {:class :unrecoverable :code :internal}}}(last result))))))-(deftest ^:parallel tool-failure-log-level-test+(def ^:private failing-tool-exception+ "What `failing-tool` throws. An atom so the tool can be a real var, which is what `adapt` accepts."+ (atom nil))++(mu/defn ^{:tool-name "failing"}+ failing-tool+ "Always throws whatever `failing-tool-exception` holds."+ [_args :- [:map {:closed true}]]+ (throw @failing-tool-exception))++(deftest tool-failure-log-level-test(let [run-failing (fn [e]- (into [] (self.core/tool-executor-xf {"failing" {:fn (fn [_] (throw e))}})+ (reset! failing-tool-exception e)+ (into [] (self.core/tool-executor-xf+ (metabot.tools/->entries [#'failing-tool] (atom {}) nil nil))(test-util/parts->aisdk-chunks[{:type :tool-input :id "call-f" :function "failing" :arguments {}}])))]- (testing "an unexpected tool failure is logged at error with its exception"- (let [e (ex-info "boom" {})]- (log.capture/with-log-messages-for-level [messages [metabase.metabot.self.core :error]]- (run-failing e)- (is (= [[:error e]] (map (juxt :level :e) (messages)))))))- (testing "an agent error is not"- (log.capture/with-log-messages-for-level [messages [metabase.metabot.self.core :error]]+ (testing "an unexpected tool failure is logged at error"+ (log.capture/with-log-messages-for-level [messages [metabase.metabot.tools.runtime :error]]+ (run-failing (ex-info "boom" {}))+ (is (= [:error] (map :level (messages))))))+ (testing "a failure the tool wrote for the model is not"+ (log.capture/with-log-messages-for-level [messages [metabase.metabot.tools.runtime :error]](run-failing (ex-info "No such field" {:agent-error? true}))(is (empty? (messages)))))))@@ -697,8 +714,9 @@{:type :tool-output-available:toolCallId "call-1":toolName "analyze_chart"- :error {:message (str "Tool `analyze_chart` does not exist. "- "Available tools: convert-currency, get-time, mock-llm, no-arg.")}})+ :result {:output (str "Tool `analyze_chart` does not exist. "+ "Available tools: convert-currency, get-time, mock-llm, no-arg.")+ :error {:class :validation :code :unknown-tool}}})result)))))(deftest ^:parallel tool-executor-xf-stream-error-test@@ -716,19 +734,21 @@;;; 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+ "The text the model would see for `arguments` against `args-schema`, or nil when they are accepted."[args-schema arguments]- (let [tools {"validated" (schema-tool args-schema)}+ (let [tools (metabot.tools/->entries+ [(reify tools.core/Tool+ (declaration [_] {:name "validated" :description "validation test tool"+ :args args-schema})+ (handle [_ _args _ctx] {:output "ok"}))]+ (atom {}) nil nil)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)))+ {:type :tool-input :id "call-v" :function "validated" :arguments arguments}])+ result (-> (into [] (self.core/tool-executor-xf tools) chunks) last :result)]+ (when (:error result)+ (:output result))))(deftest ^:parallel tool-argument-validation-test(let [schema [:map {:closed true}@@ -759,12 +779,20 @@(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]]])}+ (let [tools (metabot.tools/->entries+ [(reify tools.core/Tool+ (declaration [_] {:name "validated" :description "validation test tool"+ :args [:map {:closed true}+ [:names {:optional true} [:sequential :string]]]})+ (handle [_ _args _ctx] {:output "ok"}))]+ (atom {}) nil nil)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"}])]+ [{:type :tool-input-available :toolName "validated" :toolCallId "call-j"}])+ result (-> (into [] (self.core/tool-executor-xf tools) chunks) last :result)](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))))))+ (:output result)))+ (is (= {:class :validation :code :invalid-json} (:error result))))))(deftest ^:parallel tool-non-object-arguments-test(let [received (atom ::not-called)@@ -778,29 +806,34 @@([raw] (run "open" raw))([tool-name raw](reset! received ::not-called)+ ;; `:result`, not a chunk-level `:error`: a non-object argument list is a+ ;; validation failure like any other, so it comes back classed, with its text+ ;; where every other failure's text is.(-> (into [] (self.core/tool-executor-xf tools)[{:type :tool-input-start :toolName tool-name :toolCallId "call-n"}{:type :tool-input-delta :toolCallId "call-n" :inputTextDelta raw}{:type :tool-input-available :toolName tool-name :toolCallId "call-n"}])- last :error :message)))]+ last :result)))+ message (fn [& args] (:output (apply run args)))](testing "valid JSON that isn't an object is rejected before it reaches a tool whose schema accepts any map"(is (= "Invalid tool arguments: expected an object of named arguments; received an array."- (run "[\"orders\"]")))+ (message "[\"orders\"]")))+ (is (= {:class :validation :code :invalid-arguments} (:error (run "[\"orders\"]"))))(is (= ::not-called @received)))(testing "a JSON string holding an object is reported as the string the model sent, not decoded into one"(is (= "Invalid tool arguments: expected an object of named arguments; received a string."- (run "\"{\\\"names\\\": [\\\"orders\\\"]}\"")))+ (message "\"{\\\"names\\\": [\\\"orders\\\"]}\"")))(is (= ::not-called @received)))(testing "a JSON boolean is rejected, not run as an empty argument map"(is (= "Invalid tool arguments: expected an object of named arguments; received a boolean."- (run "false")))+ (message "false")))(is (= ::not-called @received)))(testing "JSON null still runs the tool with an empty argument map"- (is (nil? (run "null")))+ (is (nil? (:error (run "null"))))(is (= {} @received)))(testing "a tool with no argument schema rejects a non-object too"(is (= "Invalid tool arguments: expected an object of named arguments; received an array."- (run "untyped" "[\"orders\"]")))+ (message "untyped" "[\"orders\"]")))(is (= ::not-called @received)))))(deftest ^:parallel tool-without-schema-is-not-validated-test@@ -814,137 +847,25 @@;;; tool :decode tests-(defn- make-decode-tool- "Create a wrapped tool map that records its received arguments and has an optional `:decode` fn.- Returns a map with `:fn`, `:doc`, `:schema` and optionally `:decode` — the same shape- that [[wrap-tools-with-state]] produces."- [tool-name received-atom decode-fn]- (let [f (fn [args]- (reset! received-atom args)- {:output "ok"})]- (cond-> {:fn f- :doc (str tool-name " test tool")- :schema [:=> [:cat [:map]] :any]}- decode-fn (assoc :decode decode-fn))))--(deftest ^:parallel tool-decode-var-test- (testing "tool definition map with :decode has decode applied before invocation"- (let [received (atom nil)- decode-fn (fn [args]- (update args :x inc))- tool-def {:fn (fn [args]- (reset! received args)- {:output "ok"})- :decode decode-fn- :schema [:=> [:cat [:map [:x :int]]] :any]- :doc "increment x"}- tools {"decode-inc" tool-def}- chunks (test-util/parts->aisdk-chunks- [{:type :start :id "msg-dec-1"}- {:type :tool-input :id "call-d1" :function "decode-inc" :arguments {:x 41}}])- result (into [] (self.core/tool-executor-xf tools) chunks)- tool-result (last result)]- (is (= 42 (:x @received))- "decode should have incremented x before the tool saw it")- (is (=? {:type :tool-output-available :toolCallId "call-d1"}- tool-result)))))--(deftest ^:parallel tool-decode-map-test- (testing "wrapped tool map with :decode has decode applied"- (let [received (atom nil)- tool (make-decode-tool "coerce-test" received- (fn [args]- (update args :x str)))- tools {"coerce-test" tool}- chunks (test-util/parts->aisdk-chunks- [{:type :start :id "msg-dec-2"}- {:type :tool-input :id "call-d2" :function "coerce-test" :arguments {:x 123}}])- result (into [] (self.core/tool-executor-xf tools) chunks)- tool-result (last result)]- (is (= "123" (:x @received))- "decode should have converted x to string before the tool saw it")- (is (=? {:type :tool-output-available :toolCallId "call-d2"}- tool-result)))))--(deftest ^:parallel tool-decode-error-test- (testing "decode that throws agent-error is returned to LLM"- (let [received (atom nil)- tool (make-decode-tool "bad-decode" received- (fn [_args]- (throw (ex-info "Value must be positive"- {:agent-error? true :status-code 400}))))- tools {"bad-decode" tool}- chunks (test-util/parts->aisdk-chunks- [{:type :start :id "msg-dec-3"}- {:type :tool-input :id "call-d3" :function "bad-decode" :arguments {:x -1}}])- result (into [] (self.core/tool-executor-xf tools) chunks)- tool-result (last result)]- (is (nil? @received)- "tool function should not have been called")- (is (=? {:type :tool-output-available- :toolCallId "call-d3"- :toolName "bad-decode"- :error {:message #"Value must be positive"}}- tool-result)))))--(deftest ^:parallel tool-without-decode-test- (testing "tool without :decode still works normally"- (let [received (atom nil)- tool (make-decode-tool "no-decode" received nil)- tools {"no-decode" tool}- chunks (test-util/parts->aisdk-chunks- [{:type :start :id "msg-dec-4"}- {:type :tool-input :id "call-d4" :function "no-decode" :arguments {:x 99}}])- result (into [] (self.core/tool-executor-xf tools) chunks)- tool-result (last result)]- (is (= 99 (:x @received))- "without decode, arguments pass through unchanged")- (is (=? {:type :tool-output-available :toolCallId "call-d4"}- tool-result)))))--(deftest ^:parallel tool-decode-coercion-test- (testing "decode can deeply transform nested arguments (simulating temporal filter coercion)"- (let [received (atom nil)- ;; Simulate the temporal filter decode: walk into query.filters and coerce values- decode-fn (fn [args]- (update-in args [:query :filters]- (fn [filters]- (mapv (fn [f]- (if (and (= "year-of-era" (:bucket f))- (string? (:value f)))- (assoc f :value (Integer/parseInt (subs (:value f) 0 4)))- f))- filters))))- tool (make-decode-tool "construct-test" received decode-fn)- tools {"construct-test" tool}- chunks (test-util/parts->aisdk-chunks- [{:type :start :id "msg-dec-5"}- {:type :tool-input :id "call-d5" :function "construct-test"- :arguments {:query {:filters [{:bucket "year-of-era" :value "2024-01-01"}- {:bucket nil :value "2024-06-15"}]}}}])- result (into [] (self.core/tool-executor-xf tools) chunks)]- (is (= 2024 (get-in @received [:query :filters 0 :value]))- "year-of-era filter value should be coerced to integer")- (is (= "2024-06-15" (get-in @received [:query :filters 1 :value]))- "filter without bucket should pass through unchanged")- (is (=? {:type :tool-output-available :toolCallId "call-d5"}- (last result))))))--;;; stringified scalar coercion tests-(defn- probe-tool- "A tool named `probe` that declares `args-schema` and records the arguments it is called with."+ "Entries for a tool named `probe` that declares `args-schema` and records the arguments it is+ called with.++ Built through `->entries` rather than by hand, because argument coercion and validation live in+ `metabase.metabot.tools.runtime` — a hand-made `:fn` would be called with the raw arguments."[args-schema received]- {"probe" {:tool-name "probe"- :doc "Records the arguments it was called with."- :schema [:=> [:cat args-schema] :any]- :fn (fn [args]- (reset! received args)- {:output "ok"})}})+ (metabot.tools/->entries+ [(reify tools.core/Tool+ (declaration [_] {:name "probe"+ :description "Records the arguments it was called with."+ :args (or args-schema :any)})+ (handle [_ args _ctx]+ (reset! received args)+ {:output "ok"}))]+ (atom {}) nil nil))(defn- run-probe- "Run one `probe` tool call with `arguments` against `tools`.- Returns the last output chunk."+ "Run one `probe` tool call with `arguments` against `tools`. Returns the last output chunk."[tools arguments](let [chunks (test-util/parts->aisdk-chunks[{:type :start :id "msg-coerce"}@@ -952,7 +873,7 @@(last (into [] (self.core/tool-executor-xf tools) chunks))))(defn- tool-received-args- "Run one `probe` tool call with `arguments` and return the arguments the tool function saw."+ "Run one `probe` tool call with `arguments` and return the arguments the tool saw."[args-schema arguments](let [received (atom nil)](run-probe (probe-tool args-schema received) arguments)@@ -1000,23 +921,16 @@(is (= {:limit "15"}(tool-received-args nil {:limit "15"})))))-(deftest ^:parallel tool-args-coercion-precedes-decode-test- (testing "coercion happens before the tool's own :decode fn, which sees a real integer"- (let [received (atom nil)- tools (update (probe-tool [:map [:limit :int]] received)- "probe" assoc :decode #(update % :limit inc))]- (run-probe tools {:limit "15"})- (is (= {:limit 16}- @received)))))-(deftest ^:parallel tool-args-stringified-int-satisfies-tool-validation-test(testing "a stringified integer no longer fails a tool that validates its own arguments"(let [args-schema [:map [:limit [:maybe [:int {:min 1 :max 50}]]]]- tools {"probe" {:tool-name "probe"- :doc "Validates its arguments."- :schema [:=> [:cat args-schema] :any]- :fn (mu/fn [args :- args-schema]- {:output (str "limit=" (:limit args))})}}]+ tools (metabot.tools/->entries+ [(reify tools.core/Tool+ (declaration [_] {:name "probe" :description "Validates its arguments."+ :args args-schema})+ (handle [_ args _ctx]+ {:output (str "limit=" (:limit (mc/coerce args-schema args nil)))}))]+ (atom {}) nil nil)](is (=? {:type :tool-output-available:result {:output "limit=15"}}(run-probe tools {:limit "15"}))))))@@ -1211,9 +1125,20 @@(is (= {:type "tool-output-available" :toolCallId "call-i" :output ""}output-event)"no :output key -> empty wire output; internal :instructions/:data-parts never leak")))- (testing "tool error becomes tool-output-error"- (is (= {:type "tool-output-error" :toolCallId "call-2" :errorText "Tool failed"}- (first (sse-events [{:type :tool-output :id "call-2" :error {:message "Tool failed"}}])))))+ (testing (str "a failed call becomes tool-output-error, read from the result and rendered for a "+ "reader rather than for the model")+ (is (= {:type "tool-output-error" :toolCallId "call-2"+ :errorText "Metabot could not complete this step."}+ (first (sse-events [{:type :tool-output :id "call-2"+ :result {:output "`n` should be an int; received a string."+ :error {:class :validation :code :invalid-arguments}}}]))))+ (testing "and an unrecoverable failure shows the message the tool chose for the user"+ (is (= {:type "tool-output-error" :toolCallId "call-5" :errorText "Ask an admin for access."}+ (first (sse-events [{:type :tool-output :id "call-5"+ :result {:output "This call failed and the user was shown the error."+ :error {:class :unrecoverable+ :code :scope-denied+ :user-message "Ask an admin for access."}}}]))))))(testing ":tool-input-start maps to tool-input-start"(is (= {:type "tool-input-start" :toolCallId "call-3" :toolName "search"}(first (sse-events [{:type :tool-input-start :id "call-3" :function "search"}])))))@@ -1228,12 +1153,10 @@"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")}}+ "coerced" {:tool-name "coerced"+ :title-fn (fn [{:keys [who]}]+ (str "Greeting " (str/join ", " (cond-> who+ (string? who) vector))))}}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"}@@ -1248,17 +1171,10 @@(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\"]"}+ (testing "a double-encoded argument is coerced, as it is before the tool runs"+ (is (= [{:type :tool-input :id "c7" :function "coerced" :arguments {:who "[\"Sam\",\"Kim\"]"}:title "Greeting Sam, Kim"}]- (stamp {:type :tool-input :id "c7" :function "decoded" :arguments {:who "[\"Sam\",\"Kim\"]"}}))))+ (stamp {:type :tool-input :id "c7" :function "coerced" :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"}))))))@@ -2921,3 +2837,124 @@(let [models (self/known-models provider)](is (seq models) provider)(is (every? (comp string? :display-name val) models) provider)))))++;;; ===== A failed call stays failed all the way out =====++(defn- throwing-tool+ "A tool whose one job is to fail with `error-class`."+ [tool-name thrower]+ (reify tools.core/Tool+ (declaration [_] {:name tool-name :description "Fails." :args [:map {:closed true}]})+ (handle [_ _args _ctx] (thrower))))++(defn- failed-outcome+ "What the runtime hands back for a failing call of each class, through the real `invoke`."+ [tool-name thrower]+ (let [tool (throwing-tool tool-name thrower)+ entries (tools.core/entries [tool])]+ (tools.runtime/invoke entries+ {:profile-id :nlq :metabot nil :user-scope #{"*"}+ :tool-names (set (keys entries))}+ tool-name+ {})))++(defn- tool-output-part+ "The `:tool-output` part the stream assembles for `outcome` — the shape every consumer downstream+ of the runtime actually reads."+ [outcome]+ (->> [{:type :tool-input-start :toolCallId "c1" :toolName "failer"}+ {:type :tool-input-available :toolCallId "c1" :toolName "failer"}+ {:type :tool-output-available :toolCallId "c1" :toolName "failer" :result outcome}]+ (into [] (self.core/aisdk-xf))+ (filter #(= :tool-output (:type %)))+ first))++(deftest a-failed-call-is-failed-at-every-consumer-test+ (testing (str "from `invoke` through the part to the SSE writer and persistence. Nothing spanned "+ "this before, which is how the error moving into `:result` left three consumers "+ "still reading it off the part and reporting every failure as a success.")+ (doseq [[label thrower expected-text]+ [["recoverable"+ #(tools.error/throw-recoverable! :metabase.metabot.tools.recoverable.common/not-found+ {:kind :table :id 7})+ "Metabot could not complete this step."]+ ["unrecoverable with a :user-message"+ #(tools.error/unrecoverable! ::nope {:user-message "Ask an admin for access."})+ "Ask an admin for access."]+ ["unrecoverable without one"+ #(tools.error/unrecoverable! ::nope {})+ "Metabot could not complete this step."]]]+ (testing label+ (let [outcome (failed-outcome "failer" thrower)+ part (tool-output-part outcome)]+ (testing "the outcome carries the error inside :result, and only there"+ (is (some? (:error outcome)))+ (is (not (contains? part :error))+ "a second copy on the part is what let a failure read as a success"))+ (testing "the SSE writer emits tool-output-error with text written for a reader"+ (let [events (into [] (self.core/parts->aisdk-sse-xf) [part])+ body (apply str events)]+ (is (str/includes? body "tool-output-error") body)+ (is (str/includes? body expected-text) body)+ (testing "and never the model's own text, nor the EDN of the error map"+ (is (not (str/includes? body "Don't retry")) body)+ (is (not (str/includes? body ":class")) body))))+ (testing (str "persistence stores it as a failed step, keeping the MODEL's text: "+ "`tool-part->llm-messages` replays `:errorText` to the model, so a generic "+ "sentence here would lose the authored failure on every replay")+ (let [stored (#'persistence/internal-parts->storable+ [{:type :tool-input :id "c1" :function "failer" :arguments {}}+ part])+ entry (first (filter #(= "tool-failer" (:type %)) stored))]+ (is (= "output-error" (:state entry)) (pr-str entry))+ (is (= (:output outcome) (:errorText entry)))+ (is (nil? (:output entry))+ "a failed step stores no :output; its text is the :errorText")+ (testing "and that text replays to the model verbatim"+ ;; a pair: the assistant's tool_call, then the `:tool` message the model reads+ (is (= (:output outcome)+ (:content (last (persistence/tool-part->llm-messages entry)))))))))))))++(deftest a-rejected-argument-is-failed-at-every-consumer-test+ (testing (str "the validation class takes the same path, and its message is the most "+ "model-facing text there is — it names the argument and the repair")+ (let [tool (reify tools.core/Tool+ (declaration [_] {:name "strict" :description "Takes an int."+ :args [:map {:closed true} [:n :int]]})+ (handle [_ _ _] {:output "unreachable"}))+ entries (tools.core/entries [tool])+ outcome (tools.runtime/invoke entries+ {:profile-id :nlq :metabot nil :user-scope #{"*"}+ :tool-names #{"strict"}}+ "strict" {:n "not an int"})+ part (tool-output-part outcome)+ body (apply str (into [] (self.core/parts->aisdk-sse-xf) [part]))]+ (is (= :validation (get-in outcome [:error :class])))+ (is (str/includes? (:output outcome) "`n`") "the model is told which argument")+ (is (str/includes? body "tool-output-error") body)+ (is (str/includes? body "Metabot could not complete this step.") body)+ (testing "and the argument message is not shown to the reader"+ (is (not (str/includes? body "`n`")) body))+ (testing "but it is what replays to the model"+ (let [stored (#'persistence/internal-parts->storable+ [{:type :tool-input :id "c1" :function "strict" :arguments {}} part])+ entry (first (filter #(= "tool-strict" (:type %)) stored))]+ (is (str/includes? (:errorText entry) "`n`") (pr-str entry)))))))++(deftest a-successful-call-is-still-successful-test+ (testing "the same path, with nothing to report"+ (let [tool (reify tools.core/Tool+ (declaration [_] {:name "fine" :description "Works." :args [:map {:closed true}]})+ (handle [_ _ _] {:output "all good"}))+ entries (tools.core/entries [tool])+ outcome (tools.runtime/invoke entries+ {:profile-id :nlq :metabot nil :user-scope #{"*"}+ :tool-names #{"fine"}}+ "fine" {})+ part (tool-output-part outcome)+ body (apply str (into [] (self.core/parts->aisdk-sse-xf) [part]))+ stored (#'persistence/internal-parts->storable+ [{:type :tool-input :id "c1" :function "failer" :arguments {}} part])]+ (is (nil? (:error outcome)))+ (is (str/includes? body "tool-output-available") body)+ (is (= "output-available" (:state (first (filter #(= "tool-failer" (:type %)) stored))))))))diff --git a/test/metabase/metabot/test_util.clj b/test/metabase/metabot/test_util.cljindex 54e31d590a3..fa638f4fac6 100644--- a/test/metabase/metabot/test_util.clj+++ b/test/metabase/metabot/test_util.clj@@ -4,6 +4,8 @@[clojure.string :as str][metabase.metabot.self.core :as self.core][metabase.metabot.tools :as metabot.tools]+ [metabase.metabot.tools.core :as tools.core]+ [metabase.metabot.tools.error :as tools.error][metabase.util.json :as json][metabase.util.log :as log]))@@ -95,16 +97,55 @@(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."+ return the error text the model would see, or nil when the call was accepted.++ The text is the outcome's `:output`, which is where a failure's message lives now; a failure also+ carries `:error` with its class and code."[tool-name tool-var arguments]- (let [tools (metabot.tools/wrap-tools-with-state {tool-name tool-var} (atom {}) nil nil)+ (let [tools (metabot.tools/->entries [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)))+ {:type :tool-input :id "call-boundary" :function tool-name :arguments arguments}])+ result (-> (into [] (self.core/tool-executor-xf tools) chunks) last :result)]+ (when (:error result)+ (:output result))))++(defn call-tool+ "Call `tool` with `arguments` and return its `tools.core/result`.++ What a test uses in place of invoking a tool var as a function. A converted tool is a record, so+ `(the-tool args)` no longer works and the caller should not have to know whether this one does one+ item or several — `tools.core/call` decides that. `tool` may be the record, or a var holding one.++ `tool-names` is the profile the recovery steps are filtered against; it defaults to a profile that+ has `search`, since most steps offer it. Pass a smaller set to assert a step disappears.++ This is not the agent boundary: arguments are not validated and the scope is not checked. Use+ [[tool-boundary-error]] for those."+ ([tool arguments] (call-tool tool arguments #{"search"}))+ ([tool arguments tool-names]+ (tools.core/call (cond-> tool (var? tool) deref) arguments {:tool-names tool-names})))++(defn tool-failure+ "Call `tool` expecting it to fail, and return what the failure is: `{:class :code}`, plus `:text`+ — the text a model in a profile holding `tool-names` would read — when it is recoverable.++ The counterpart to [[call-tool]]. Throws when the call succeeds, so a test cannot pass by the+ tool quietly working. This is the tool's own contract, not the agent boundary: the runtime's+ rendering of an unrecoverable error, and its dev assertions, are+ `metabase.metabot.tools.runtime-test`'s subject. Use [[tool-boundary-error]] for the boundary."+ ([tool arguments] (tool-failure tool arguments #{"search"}))+ ([tool arguments tool-names]+ (let [outcome (try+ (call-tool tool arguments tool-names)+ (catch Throwable e e))]+ (if-not (instance? Throwable outcome)+ (throw (ex-info "expected this tool call to fail, but it returned a result"+ {:result outcome}))+ (let [{:keys [class code] :as error} (tools.error/classify outcome)]+ (cond-> {:class class :code code}+ (= :recoverable class)+ (assoc :text (tools.error/recoverable-text error tool-names))))))))(defn mock-llm-response"Create a mock LLM response (reducible) from high-level parts."diff --git a/test/metabase/metabot/tools/charts/edit_test.clj b/test/metabase/metabot/tools/charts/edit_test.cljindex bc67cb54fd7..968fc521b00 100644--- a/test/metabase/metabot/tools/charts/edit_test.clj+++ b/test/metabase/metabot/tools/charts/edit_test.clj@@ -5,6 +5,7 @@[clojure.walk :as walk][metabase.lib.core :as lib][metabase.metabot.agent.core :as agent]+ [metabase.metabot.test-util :as test-util][metabase.metabot.tools.charts :as tools.charts][metabase.metabot.tools.charts.edit :as edit-chart][metabase.metabot.tools.construct :as tools.construct]@@ -134,8 +135,11 @@(mt/with-current-user (test.users/user->id :crowberto)(let [table-fields-uri (str "metabase://table/" (mt/id :products) "/fields")- {[{{table :structured-output} :content}] :resources}- (tools.resources/read-resource-tool {:uris [table-fields-uri]})+ ;; One URI, so the composed `:structured-output` is a one-element vector. The per-URI+ ;; `:resources` list this used to read is the Agent API's shape and the tool no longer+ ;; builds it.+ {[table] :structured-output}+ (test-util/call-tool tools.resources/read-resource-tool {:uris [table-fields-uri]});; Representations-format query: LLM-facing code should prefer the portable_fk path;; over numeric field ids. Take them straight from the read_resource response.@@ -154,11 +158,11 @@"aggregation" [["count" {}]]"breakout" [["field" {} category-field-fk]]}]}external-query (walk/keywordize-keys query-data)- construct-result (tools.construct/construct-notebook-query-tool- {:query external-query- :title "Counts by category"- :description "Counts by category."- :visualization {:chart_type "bar"}})+ construct-result (test-util/call-tool tools.construct/construct-notebook-query-tool+ {:query external-query+ :title "Counts by category"+ :description "Counts by category."+ :visualization {:chart_type "bar"}})query-id (get-in construct-result [:structured-output :query-id])query (get-in construct-result [:structured-output :query])chart-id (get-in construct-result [:structured-output :chart-id])]@@ -205,11 +209,11 @@["field" {}[db-name "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}external-query (walk/keywordize-keys query-data)- result (tools.construct/construct-notebook-query-tool- {:query external-query- :title "Test chart"- :description "Test chart description."- :visualization {:chart_type "bar"}})+ result (test-util/call-tool tools.construct/construct-notebook-query-tool+ {:query external-query+ :title "Test chart"+ :description "Test chart description."+ :visualization {:chart_type "bar"}})query (get-in result [:structured-output :query])](testing "order-by inner clause is now an aggregation reference, not :sum"(let [first-ord (first (get-in query [:stages 0 :order-by]))@@ -250,23 +254,21 @@["field" {}["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}external-query (walk/keywordize-keys query-data)- result (tools.construct/construct-notebook-query-tool- {:query external-query- :title "Test chart"- :description "Test chart description."- :visualization {:chart_type "bar"}})]- (testing "tool returns a clear, agent-targeted error rather than producing a chart"- ;; The outer `construct-notebook-query-tool` catches the ex-info and returns- ;; `{:output <message>}` (no `:structured-output`). That's the LLM-visible signal.- (is (nil? (:structured-output result))- (str "expected no structured-output, got: " (pr-str result)))- (is (string? (:output result)))- (is (re-find #"Sample" (:output result))- (str "error message should mention the offending DB name; got: "- (:output result)))- (is (re-find #"read_resource|Unknown database" (:output result))- (str "error message should hint at the recovery path; got: "- (:output result))))))))+ {:keys [class code text]}+ (test-util/tool-failure tools.construct/construct-notebook-query-tool+ {:query external-query+ :title "Test chart"+ :description "Test chart description."+ :visualization {:chart_type "bar"}}+ #{"read_resource"})]+ (testing "tool raises a declared, agent-targeted error rather than producing a chart"+ (is (= :recoverable class))+ (is (= :metabase.metabot.tools.recoverable.pipeline/unknown-database code))+ (is (re-find #"Sample" text)+ (str "error message should mention the offending DB name; got: " text))+ (testing "and the declaration's recovery step says where a database name comes from"+ (is (re-find #"portable FK" text)+ (str "error message should hint at the recovery path; got: " text))))))))(deftest construct-notebook-query-llm-uses-canonical-db-name-end-to-end-test(testing (str "Symmetric to the previous test: the LLM writes `database: Sample Database`\n"@@ -284,11 +286,11 @@"breakout" [["field" {}[db-name "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]}external-query (walk/keywordize-keys query-data)- result (tools.construct/construct-notebook-query-tool- {:query external-query- :title "Test chart"- :description "Test chart description."- :visualization {:chart_type "bar"}})+ result (test-util/call-tool tools.construct/construct-notebook-query-tool+ {:query external-query+ :title "Test chart"+ :description "Test chart description."+ :visualization {:chart_type "bar"}})query (get-in result [:structured-output :query])breakout-field (get-in query [:stages 0 :breakout 0])](testing "the chart was constructed successfully"@@ -310,13 +312,13 @@"a JOIN and executes successfully against the app DB.")(mt/with-current-user (test.users/user->id :crowberto)(let [;; Discover portable FKs the same way the LLM does: via read_resource /fields.- {[{{orders-details :structured-output} :content}] :resources}- (tools.resources/read-resource-tool- {:uris [(str "metabase://table/" (mt/id :orders) "/fields")]})+ {[orders-details] :structured-output}+ (test-util/call-tool tools.resources/read-resource-tool+ {:uris [(str "metabase://table/" (mt/id :orders) "/fields")]})- {[{{products-details :structured-output} :content}] :resources}- (tools.resources/read-resource-tool- {:uris [(str "metabase://table/" (mt/id :products) "/fields")]})+ {[products-details] :structured-output}+ (test-util/call-tool tools.resources/read-resource-tool+ {:uris [(str "metabase://table/" (mt/id :products) "/fields")]})orders-fk (:portable_fk orders-details)product-id-field (some (fn [{:keys [display_name] :as f}]@@ -340,11 +342,11 @@"breakout" [["field" {} category-field-fk]]}]}external-query (walk/keywordize-keys query-data)- construct-result (tools.construct/construct-notebook-query-tool- {:query external-query- :title "Test chart"- :description "Test chart description."- :visualization {:chart_type "bar"}})+ construct-result (test-util/call-tool tools.construct/construct-notebook-query-tool+ {:query external-query+ :title "Test chart"+ :description "Test chart description."+ :visualization {:chart_type "bar"}})query (get-in construct-result [:structured-output :query])breakout-field (get-in query [:stages 0 :breakout 0])field-opts (second breakout-field)]diff --git a/test/metabase/metabot/tools/core_test.clj b/test/metabase/metabot/tools/core_test.cljnew file mode 100644index 00000000000..8c2d0a8b711--- /dev/null+++ b/test/metabase/metabot/tools/core_test.clj@@ -0,0 +1,371 @@+(ns metabase.metabot.tools.core-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.metabot.metadata-perms :as metabot.perms]+ [metabase.metabot.tools.core :as tools]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++;;; A tool is a value, so a fixture is a record instance or a `reify` — no macro, no var metadata,+;;; no registry to register with.++(defrecord WidgetTool [tool-name description]+ tools/Tool+ (declaration [this]+ {:name (:tool-name this)+ :description (:description this)+ :args [:map {:closed true} [:id :int]]})+ (handle [_ {:keys [id]} _ctx]+ {:output (str "widget " id)}))++(def ^:private widget-tool (->WidgetTool "widget" "Reports a widget."))++(def ^:private scoped-tool+ (reify tools/Tool+ (declaration [_]+ {:name "scoped"+ :description "Needs a scope and a capability."+ :args [:map {:closed true}]+ :scope "agent:sql:create"+ :metabot/capabilities #{:permission-write-sql-queries}})+ (handle [_ _args _ctx] {:output "ok"})))++(def ^:private ctx {:profile-id :nlq :metabot nil :tool-names #{"search"}})++;;; ------------------------------------------------ Renderable ----------------------------------------------------++(defrecord Lines [lines]+ tools/Renderable+ (render-text [_] (str/join "\n" lines)))++(deftest ^:parallel renderable-test+ (testing "a string is the trivial case, so a tool author writes strings and never thinks about this"+ (is (tools/renderable? "plain"))+ (is (= "plain" (tools/render-text "plain"))))+ (testing "anything extending the protocol renders itself, which is how a consumer with its own+ text model — MCP renders prose at the boundary — avoids forcing a change in tool code"+ (let [output (->Lines ["<term>churn</term>" "<definition>…</definition>"])]+ (is (tools/renderable? output))+ (is (= "<term>churn</term>\n<definition>…</definition>" (tools/render-text output)))))+ (testing "and nothing else is renderable, so a result whose :output is a map or a keyword is+ rejected rather than coerced"+ (doseq [x [{:not :text} :keyword 42 nil]]+ (is (not (tools/renderable? x)) (pr-str x))+ (is (not (mr/validate ::tools/result {:output x}))))))++(deftest ^:parallel a-renderable-output-is-a-valid-result-test+ (is (mr/validate ::tools/result {:output (->Lines ["one"])}))+ (testing "and survives composition, where entries carry rendered strings"+ (is (= {:output "one\ntwo"}+ (tools/call (reify+ tools/Tool+ (declaration [_] {:name "r" :description "d" :args :any})+ (handle [_ {:keys [n]} _] {:output (->Lines [n])})+ tools/BatchedTool+ (batched-declaration [_ d] d)+ (batched-args [_ _] [{:n "one"} {:n "two"}])+ (compose [_ es _] (tools/concatenated es)))+ {} ctx)))))++;;; ------------------------------------------------ Tool ----------------------------------------------------------++(deftest ^:parallel a-tool-is-a-value-test+ (testing "nothing is registered and nothing is looked up — you call it"+ (is (= {:output "widget 4"} (tools/handle widget-tool {:id 4} {}))))+ (testing "and a test double needs no machinery"+ (is (= {:output "stub"}+ (tools/handle (reify tools/Tool+ (declaration [_] {:name "x" :description "d" :args :any})+ (handle [_ _ _] {:output "stub"}))+ {} {})))))++(deftest ^:parallel declaration-is-the-whole-contract-test+ (is (= {:name "widget" :description "Reports a widget."+ :args [:map {:closed true} [:id :int]]}+ (tools/declaration widget-tool)))+ (is (=? {:scope "agent:sql:create" :metabot/capabilities #{:permission-write-sql-queries}}+ (tools/declaration scoped-tool))))++(deftest ^:parallel configuration-lives-in-the-fields-test+ (testing "the reason for a record: two tools can be the same type under different configuration"+ (let [other (->WidgetTool "gadget" "Reports a gadget.")]+ (is (= "gadget" (:name (tools/declaration other))))+ (is (= {:output "gadget 1"} (update (tools/handle other {:id 1} {}) :output+ str/replace "widget" "gadget"))))))++;;; ------------------------------------------- Declaration checks -------------------------------------------------++(defn- declaring+ "A tool whose declaration is `declared` and which never runs."+ [declared]+ (reify tools/Tool+ (declaration [_] declared)+ (handle [_ _ _] {:output ""})))++(deftest ^:parallel validate-tool!-rejects-a-bad-declaration-test+ (testing "an unnamespaced key outside the neutral core fails at load time rather than silently+ dropping whatever it was meant to do"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"declares unnamespaced key"+ (tools/validate-tool! (declaring {:name "x" :description "d" :args :any+ :capability #{:typo}})))))+ (testing "but a namespaced one passes, because that is how a consumer adds its own keys without+ every other consumer's schema having to know about them"+ (is (=? {:mcp/annotations {:readOnlyHint true}}+ (tools/validate-tool! (declaring {:name "x" :description "d" :args :any+ :metabot/capabilities #{:permission-write-sql-queries}+ :mcp/annotations {:readOnlyHint true}})))))+ (testing "a missing :name, :description or :args fails"+ (doseq [declared [{:description "d" :args :any}+ {:name "x" :args :any}+ {:name "x" :description "d"}]]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Invalid tool declaration"+ (tools/validate-tool! (declaring declared))))))+ (testing "a name a provider might reject fails here, where it is cheap to find"+ (doseq [bad ["Widget" "read-resource" "2fast" "read resource"]]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"is not snake_case"+ (tools/validate-tool! (declaring {:name bad :description "d"+ :args :any}))))))+ (testing "an :args schema that does not resolve fails at load time, not on the first call"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #":args schema that does not compile"+ (tools/validate-tool! (declaring {:name "x" :description "d"+ :args ::nothing-registers-this}))))))++(deftest ^:parallel entries-test+ (is (= {"widget" {:declaration (tools/declaration widget-tool) :tool widget-tool}}+ (tools/entries [widget-tool])))+ (testing "two tools claiming one name is refused: one of them would be unreachable"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Two tools claim the tool name"+ (tools/entries [widget-tool (->WidgetTool "widget" "Another.")]))))+ (testing "across profiles a name legitimately belongs to several tools, so there is no registry"+ (is (= 1 (count (tools/entries [widget-tool]))))+ (is (= 1 (count (tools/entries [(->WidgetTool "widget" "Another.")]))))))++;;; -------------------------------------------- BatchedTool -------------------------------------------------------++(tools.error/defrecoverable odd-id! "Odd ids are not loadable."+ {:payload [:map {:closed true} [:id :int]]}+ [{:keys [id]}]+ {:message (str "Item " id " could not be loaded.")+ :recovery [{:uses #{"search"} :text "Call `search` for a loadable id."}]})++(defrecord ItemTool [compose-fn]+ tools/Tool+ (declaration [_]+ {:name "batched" :description "Loads one item."+ :args [:map {:closed true} [:id :int]]})+ (handle [_ {:keys [id]} _ctx]+ (if (even? id) {:output (str "item " id)} (odd-id! {:id id})))++ tools/BatchedTool+ (batched-declaration [_ declared]+ (-> declared+ (assoc :description "Loads several items.")+ (assoc :args [:map {:closed true} [:ids [:sequential {:min 1 :max 3} :int]]])))+ (batched-args [_ {:keys [ids]}] (mapv (fn [id] {:id id}) ids))+ (compose [_ entries _ctx] ((or compose-fn tools/concatenated) entries)))++(defn- item-tool [] (->ItemTool nil))++(deftest ^:parallel the-single-form-is-a-real-tool-test+ (testing "take BatchedTool away and this still works; handle is the item loader"+ (is (= {:output "item 2"} (tools/handle (item-tool) {:id 2} ctx)))+ (is (= {:name "batched" :description "Loads one item."+ :args [:map {:closed true} [:id :int]]}+ (tools/declaration (item-tool))))))++(deftest ^:parallel batched-declaration-is-complete-test+ (testing "the tool composes it; nothing is derived"+ (is (= {:name "batched" :description "Loads several items."+ :args [:map {:closed true} [:ids [:sequential {:min 1 :max 3} :int]]]}+ (tools/batched-declaration (item-tool) (tools/declaration (item-tool))))))+ (testing "and validate-tool! returns the published one"+ (is (= "Loads several items." (:description (tools/validate-tool! (item-tool)))))))++(deftest ^:parallel call-does-not-make-the-consumer-branch-test+ (testing "one entry point for both kinds of tool"+ (is (= {:output "item 2\nitem 4"} (tools/call (item-tool) {:ids [2 4]} ctx)))+ (is (= {:output "one"}+ (tools/call (reify tools/Tool+ (declaration [_] {:name "x" :description "d" :args :any})+ (handle [_ _ _] {:output "one"}))+ {} ctx))))+ (testing "and batched? is there for a consumer that needs to know for its own reasons"+ (is (tools/batched? (item-tool)))+ (is (not (tools/batched? (reify tools/Tool+ (declaration [_] {:name "x" :description "d" :args :any})+ (handle [_ _ _] {:output "one"})))))))++(deftest ^:parallel a-failed-item-is-rendered-in-position-test+ (is (= ["item 2"+ "Item 3 could not be loaded."+ "Call `search` for a loadable id."+ "item 4"]+ (str/split-lines (:output (tools/call (item-tool) {:ids [2 3 4]} ctx)))))+ (testing "with the step filtering a whole failed call would get"+ (is (= ["item 2" "Item 3 could not be loaded."]+ (str/split-lines+ (:output (tools/call (item-tool) {:ids [2 3]} (assoc ctx :tool-names #{}))))))))++(deftest ^:parallel one-permission-cache-per-call-test+ (testing "every call holds one `metadata-perms` cache, so a tool that looks the same table or the+ same permission up for several items pays for it once. This replaced an `around-batch`+ protocol method whose only implementation anywhere was `(run)`: the capability it existed+ for is the cache, and the cache is the same for every tool, so the framework holds it."+ (let [seen (atom [])+ tool (->ItemTool (fn [entries]+ (swap! seen conj metabot.perms/*cache*)+ (tools/concatenated entries)))]+ (is (nil? metabot.perms/*cache*) "no cache outside a call")+ (is (= {:output "item 2\nitem 4"} (tools/call tool {:ids [2 4]} ctx)))+ (is (= 1 (count @seen)))+ (is (some? (first @seen)) "a call binds one")+ (is (nil? metabot.perms/*cache*) "and unbinds it on the way out")))+ (testing "and a tool's own `with-cache` nests into it rather than opening a second one, which is+ what makes this free for the six places inside tool code that already wrap their work"+ (let [inner (atom nil)+ tool (->ItemTool (fn [entries]+ (metabot.perms/with-cache+ (reset! inner metabot.perms/*cache*))+ (tools/concatenated entries)))]+ (tools/call tool {:ids [2]} ctx)+ (is (some? @inner)))))++(deftest ^:parallel only-declared-recoverables-are-captured-test+ (testing "an undeclared exception ends the turn and discards the items that loaded"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"a real bug"+ (tools/call (reify+ tools/Tool+ (declaration [_] {:name "b" :description "d" :args :any})+ (handle [_ {:keys [id]} _] (if (= 2 id)+ (throw (ex-info "a real bug" {}))+ {:output "fine"}))+ tools/BatchedTool+ (batched-declaration [_ d] d)+ (batched-args [_ {:keys [ids]}] (mapv (fn [i] {:id i}) ids))+ (compose [_ es _] (tools/concatenated es)))+ {:ids [1 2]} ctx)))))++(deftest ^:parallel a-malformed-item-result-is-caught-test+ (testing "an item returns a complete ::result now — :output is required, as for any tool"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"invalid result"+ (tools/call (reify+ tools/Tool+ (declaration [_] {:name "b" :description "d" :args :any})+ (handle [_ _ _] {:outputs "typo"})+ tools/BatchedTool+ (batched-declaration [_ d] d)+ (batched-args [_ _] [{:id 1}])+ (compose [_ es _] (tools/concatenated es)))+ {} ctx)))))++(deftest ^:parallel concatenated-test+ (testing "outputs joined in order, structured outputs vectored, data parts concatenated"+ (is (= {:output "a\nb"+ :structured-output [{:n 1} {:n 2}]+ :data-parts [{:type :data :data-type "x"} {:type :data :data-type "y"}]}+ (tools/concatenated+ [{:item {} :failed? false :output "a" :structured-output {:n 1}+ :data-parts [{:type :data :data-type "x"}]}+ {:item {} :failed? false :output "b" :structured-output {:n 2}+ :data-parts [{:type :data :data-type "y"}]}]))))+ (testing "keys no entry produced are absent rather than empty"+ (is (= {:output "a"} (tools/concatenated [{:item {} :failed? false :output "a"}])))))++(deftest ^:parallel compose-owns-placement-test+ (testing "an entry is uniform — :output always a string, :failed? always a boolean"+ (is (= {:output "ok: item 2 | failed: 3"}+ (tools/call (->ItemTool (fn [entries]+ (let [{ok false failed true} (group-by :failed? entries)]+ {:output (str "ok: " (str/join ", " (map :output ok))+ " | failed: "+ (str/join ", " (map (comp :id :item) failed)))})))+ {:ids [2 3]} ctx)))))++;;; ------------------------------------------------ with-entity ---------------------------------------------------++(deftest ^:parallel with-entity-converts-read-refusals-test+ (doseq [status [403 404]]+ (testing (str "a " status " becomes the declared not-found error, naming the entity")+ (is (=? {:class :recoverable+ :code :metabase.metabot.tools.recoverable.common/not-found+ :message "Timeline 5 was not found. It may not exist, or you may not have access to it."+ :data {:kind :timeline :id 5}}+ (tools.error/classify+ (is (thrown? clojure.lang.ExceptionInfo+ (tools/with-entity {:kind :timeline :id 5}+ (throw (ex-info "nope" {:status-code status})))))))))))++(deftest ^:parallel with-entity-passes-everything-else-through-test+ (testing "a real failure inside the body stays unrecoverable instead of being reported as a miss"+ (doseq [data [{:status-code 500} {} {:status-code 400}]]+ (let [e (is (thrown? clojure.lang.ExceptionInfo+ (tools/with-entity {:kind :timeline :id 5}+ (throw (ex-info "a real bug" data)))))]+ (is (= "a real bug" (ex-message e)))+ (is (= :unrecoverable (:class (tools.error/classify e)))))))+ (testing "and a successful body is returned untouched"+ (is (= :fine (tools/with-entity {:kind :timeline :id 5} :fine)))))++;;; -------------------------------------------- with-pipeline-errors ----------------------------------------------++(defn- pipeline-failure+ "Raise `data` from inside `with-pipeline-errors` and return the resulting ToolError."+ [message data]+ (try+ (tools/with-pipeline-errors (throw (ex-info message data)))+ (catch Throwable e+ (assoc (tools.error/classify e) ::ex-message (ex-message e)))))++(deftest ^:parallel with-pipeline-errors-converts-declared-codes-test+ (testing "an :agent-error? with a declared :error code becomes that error, keeping the pipeline's+ own sentence as the message"+ (is (=? {:class :recoverable+ :code :metabase.metabot.tools.recoverable.pipeline/unknown-table+ :message "No table found matching portable FK [\"db\" nil \"t\"]."+ :recovery [{:uses #{"read_resource"}}]}+ (pipeline-failure "No table found matching portable FK [\"db\" nil \"t\"]."+ {:agent-error? true :status-code 400 :error :unknown-table}))))+ (testing "the payload carries the keys a declaration's recovery branches on"+ (let [error (pipeline-failure "A URI is not a source."+ {:agent-error? true :error :uri-in-source-table+ :entity-type "metric" :entity-id 7})]+ (is (=? {:code :metabase.metabot.tools.recoverable.pipeline/uri-in-source-table+ :data {:entity-type "metric" :entity-id 7}}+ error))+ (is (str/starts-with? (:text (first (:recovery error)))+ "Metrics are aggregations, not sources.")))))++(deftest ^:parallel with-pipeline-errors-converts-refusals-test+ (doseq [status [403 404]]+ (testing (str "a " status " from inside the pipeline becomes not-found, without inventing a kind")+ (is (=? {:class :recoverable+ :code :metabase.metabot.tools.recoverable.common/not-found+ :message (str "The entity referenced here was not found. It may not exist, or you "+ "may not have access to it.")+ :data {}}+ (pipeline-failure "no" {:status-code status}))))))++(deftest ^:parallel with-pipeline-errors-does-not-relay-foreign-messages-test+ (testing "`as-agent-input-error` stamps :agent-error? onto exceptions from lib, toucan2 and JDBC+ too. Without an :error code there is nothing to say the message was written for a model,+ so it stays unrecoverable and the model never sees it."+ (is (=? {:class :unrecoverable+ :code :internal+ ::ex-message "No matching clause: :whatever"}+ (pipeline-failure "No matching clause: :whatever"+ {:agent-error? true :status-code 400}))))+ (testing "an :error code with no declaration is not converted either — the pipeline-code test is+ what stops that case reaching production"+ (is (=? {:class :unrecoverable :code :internal}+ (pipeline-failure "a brand new pipeline failure"+ {:agent-error? true :error :no-declaration-for-this}))))+ (testing "and an ordinary exception passes straight through"+ (is (=? {:class :unrecoverable :code :internal} (pipeline-failure "boom" {}))))+ (testing "a successful body is returned untouched"+ (is (= :fine (tools/with-pipeline-errors :fine)))))diff --git a/test/metabase/metabot/tools/deftool_test.clj b/test/metabase/metabot/tools/deftool_test.cljdeleted file mode 100644index ca61fb12ece..00000000000--- a/test/metabase/metabot/tools/deftool_test.clj+++ /dev/null@@ -1,104 +0,0 @@-(ns metabase.metabot.tools.deftool-test- (:require- [clojure.set :as set]- [clojure.test :refer [deftest is testing]]- [metabase.metabot.tools.deftool :as deftool]- [metabase.util.malli.registry :as mr]))--;;; ---------------------------------------------------- invoke-tool tests ------------------------------------------------------(deftest ^:parallel invoke-tool-no-args-test- (testing "invoke-tool with no arguments schema passes metabot-id in args"- (let [received-args (atom nil)- handler (fn [args]- (reset! received-args args)- {:structured_output {:message "hello"}})- body {:conversation_id "conv-123"}- request {:metabot/metabot-id "bot-456"}- opts {:api-name :test-tool- :handler handler- :result-schema nil}- result (deftool/invoke-tool body request opts)]- (is (= {:metabot-id "bot-456"} @received-args) "Handler should receive metabot-id in args")- (is (= "conv-123" (:conversation_id result)))- (is (= {:message "hello"} (:structured_output result)))))- (testing "invoke-tool with no arguments schema and no metabot-id"- (let [received-args (atom nil)- handler (fn [args]- (reset! received-args args)- {:structured_output {:message "hello"}})- body {:conversation_id "conv-123"}- request {}- opts {:api-name :test-tool- :handler handler- :result-schema nil}- result (deftool/invoke-tool body request opts)]- (is (= {} @received-args) "Handler should receive empty args when no metabot-id")- (is (= "conv-123" (:conversation_id result))))))--(deftest ^:parallel invoke-tool-with-args-test- (testing "invoke-tool with arguments schema that encodes keys"- (mr/def ::test-args- [:map {:closed true, :encode/tool-api-request #(set/rename-keys % {:user_id :user-id})}- [:user_id :int]])- (let [received-args (atom nil)- handler (fn [args]- (reset! received-args args)- {:structured_output {:processed true}})- body {:arguments {:user_id 42}- :conversation_id "conv-456"}- request {:metabot/metabot-id "bot-789"}- opts {:api-name :test-tool- :args-schema ::test-args- :handler handler- :result-schema nil}- result (deftool/invoke-tool body request opts)]- (is (= {:user-id 42, :metabot-id "bot-789"} @received-args)- "Arguments should be encoded with schema transformer and include metabot-id")- (is (= "conv-456" (:conversation_id result))))))--(deftest ^:parallel invoke-tool-with-result-decoding-test- (testing "invoke-tool decodes results using result-schema"- (mr/def ::test-result- [:map {:decode/tool-api-response #(set/rename-keys % {:user-name :user_name})}- [:user_name :string]])- (let [handler (fn [_args]- {:user-name "Alice"})- body {:conversation_id "conv-789"}- request {}- opts {:api-name :test-tool- :handler handler- :result-schema ::test-result}- result (deftool/invoke-tool body request opts)]- (is (= "Alice" (:user_name result)) "Result should be decoded with schema transformer")- (is (= "conv-789" (:conversation_id result))))))--;;; ---------------------------------------------------- deftool macro tests ------------------------------------------------------(deftest ^:parallel deftool-macro-expansion-test- (testing "deftool macro expands to a defendpoint form"- (let [expansion (macroexpand-1 '(metabase.metabot.tools.deftool/deftool "/test-endpoint"- "Test docstring"- {:args-schema ::my-args- :result-schema ::my-result- :handler identity}))]- (is (seq? expansion) "Should expand to a form")- (is (= 'metabase.api.macros/defendpoint (first expansion)))- (is (= :post (second expansion)))- (is (= "/test-endpoint" (nth expansion 2)))))- (testing "deftool macro expands correctly for no-args tool"- (let [expansion (macroexpand-1 '(metabase.metabot.tools.deftool/deftool "/no-args"- "No args tool"- {:result-schema ::my-result- :handler identity}))]- (is (seq? expansion))- (is (= 'metabase.api.macros/defendpoint (first expansion)))))- (testing "deftool macro always includes request in binding vector"- (let [expansion (macroexpand-1 '(metabase.metabot.tools.deftool/deftool "/test"- "Test"- {:result-schema ::my-result- :handler identity}))]- (is (seq? expansion))- ;; The expansion should include 'request' in the binding vector- (let [binding-vec (nth expansion 6)]- (is (some #{'request} binding-vec) "Should include request binding")))))diff --git a/test/metabase/metabot/tools/document_test.clj b/test/metabase/metabot/tools/document_test.cljindex f8ec9576d04..7be082d172a 100644--- a/test/metabase/metabot/tools/document_test.clj+++ b/test/metabase/metabot/tools/document_test.clj@@ -4,6 +4,7 @@[metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.metabot.table-utils :as table-utils]+ [metabase.metabot.tools.charts.create :as create-chart-tools][metabase.metabot.tools.construct :as construct-tools][metabase.metabot.tools.document :as document-tools][metabase.metabot.tools.shared :as shared]@@ -149,11 +150,15 @@(deftest document-construct-model-chart-new-chart-types-test(testing "the tool schema accepts newly added chart types"- (mt/with-dynamic-fn-redefs [construct-tools/construct-notebook-query-tool- (fn [_]+ ;; Stubbed one layer below the tool: `construct_notebook_query` is a record now, and the+ ;; pipeline call and the chart creation are the two things inside it worth standing in for.+ (mt/with-dynamic-fn-redefs [construct-tools/execute-representations-query+ (fn [_ & _]{:structured-output {:query-id "3":query {:database 1- :type "query"}}})]+ :type "query"}}})+ create-chart-tools/create-chart+ (fn [args] {:chart-id "c-1" :chart-type (:chart-type args)})](doseq [chart-type ["treemap" "boxplot"]](let [result (document-tools/document-construct-model-chart-tool{:name "Test Name"@@ -173,7 +178,7 @@(mt/with-dynamic-fn-redefs [shared/current-context (fn [] {:references {"database:1" "Test Database"}})warehouses/get-database (fn [_] (throw (ex-info "boom" {})))create-sql-query-tools/create-sql-query (fn [_] (throw (ex-info "boom" {})))- construct-tools/construct-notebook-query-tool (fn [_] (throw (ex-info "boom" {})))]+ construct-tools/execute-representations-query (fn [_ & _] (throw (ex-info "boom" {})))](is (thrown-with-msg? clojure.lang.ExceptionInfo #"boom"(document-tools/document-schema-collect-tool {})))(is (thrown-with-msg? clojure.lang.ExceptionInfo #"boom"diff --git a/test/metabase/metabot/tools/error_test.clj b/test/metabase/metabot/tools/error_test.cljnew file mode 100644index 00000000000..47c6199b306--- /dev/null+++ b/test/metabase/metabot/tools/error_test.clj@@ -0,0 +1,272 @@+(ns metabase.metabot.tools.error-test+ (:require+ [clojure.set :as set]+ [clojure.test :refer :all]+ [malli.generator :as mg]+ [metabase.metabot.agent.profiles :as profiles]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.legacy :as tools.legacy]+ [metabase.metabot.tools.recoverable.common]+ [metabase.metabot.tools.recoverable.pipeline]+ [metabase.metabot.tools.runtime :as tools.runtime]+ [metabase.test :as mt]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++;;; The declarations these tests use live here rather than being generated per-test, so that the+;;; catalog test below covers them too — a declaration that only exists inside a `testing` block is+;;; a declaration the catalog test never sees.++(tools.error/defrecoverable test-no-widget!+ "There is no widget with that id."+ {:payload [:map {:closed true}+ [:id :int]+ [:available [:sequential :int]]]}+ [{:keys [id available]}]+ {:message (str "Widget " id " does not exist. Available ids: " (pr-str available) ".")+ :recovery [{:uses #{"search"} :text "Call `search` to find a widget id."}]})++(tools.error/defrecoverable test-custom-status!+ "A declaration that overrides the default status code."+ {:payload [:map {:closed true} [:id :int]]+ :status-code 404}+ [{:keys [id]}]+ {:message (str "Widget " id " is gone.") :recovery []})++(deftest ^:parallel constructor-throws-a-recoverable-tool-error-test+ (testing "the constructor throws, carrying the declared code and the body's text"+ (let [e (is (thrown? clojure.lang.ExceptionInfo+ (test-no-widget! {:id 7 :available [1 2]})))]+ (is (= {:class :recoverable+ :code ::test-no-widget+ :message "Widget 7 does not exist. Available ids: [1 2]."+ :recovery [{:uses #{"search"} :text "Call `search` to find a widget id."}]+ :data {:id 7 :available [1 2]}}+ (tools.error/classify e)))+ (testing "the exception message is the model-facing message"+ (is (= "Widget 7 does not exist. Available ids: [1 2]." (ex-message e))))+ (testing "and the ex-data keeps the shape non-agent callers of shared tool helpers handle"+ (is (=? {:agent-error? true :status-code 400} (ex-data e)))))))++(deftest ^:parallel status-code-is-declarable-test+ (is (=? {:status-code 404}+ (ex-data (is (thrown? clojure.lang.ExceptionInfo (test-custom-status! {:id 1})))))))++(deftest ^:parallel invalid-payload-becomes-internal-test+ (testing "a payload that does not match the declaration never reaches the agent"+ (doseq [[label payload] {"wrong type" {:id "7" :available []}+ "missing key" {:id 7}+ "extra key" {:id 7 :available [] :extra true}}]+ (testing label+ (is (= {:class :unrecoverable :code :internal+ :data {:code ::test-no-widget :payload payload}}+ (tools.error/classify+ (is (thrown? clojure.lang.ExceptionInfo (test-no-widget! payload))))))))))++(deftest ^:parallel body-result-is-validated-test+ (testing "a body that returns the wrong shape is an internal error, not a malformed agent message"+ ;; Redefined rather than declared, because the catalog is global: a deliberately broken+ ;; declaration registered here would be picked up by the catalog test below, where it belongs to+ ;; nobody and fails for the wrong reason.+ (mt/with-dynamic-fn-redefs [tools.error/recoverables+ (constantly {::bad-body {:code ::bad-body+ :var #'test-no-widget!+ :doc "A declaration whose body is wrong."+ :payload-schema [:map {:closed true}]+ :status-code 400+ :build-fn (constantly {:message "no recovery key"})}})]+ (is (= :internal+ (:code (tools.error/classify+ (is (thrown? clojure.lang.ExceptionInfo+ (tools.error/throw-recoverable! ::bad-body {}))))))))))++(deftest ^:parallel unknown-code-is-internal-test+ (is (= :internal+ (:code (tools.error/classify+ (is (thrown? clojure.lang.ExceptionInfo+ (tools.error/throw-recoverable! ::nothing-declares-this {}))))))))++(deftest ^:parallel unrecoverable-carries-no-model-facing-message-test+ (testing "the schema makes it impossible to attach agent-bound text to an unrecoverable error"+ (is (mr/validate ::tools.error/tool-error {:class :unrecoverable :code :internal}))+ (is (not (mr/validate ::tools.error/tool-error+ {:class :unrecoverable :code :internal :message "leaked"}))))+ (testing "a :user-message is the exception message, so nothing unauthored ends up there"+ (let [e (is (thrown? clojure.lang.ExceptionInfo+ (tools.error/unrecoverable! ::denied {:user-message "Ask an admin."})))]+ (is (= "Ask an admin." (ex-message e)))+ (is (= {:class :unrecoverable :code ::denied :user-message "Ask an admin."}+ (tools.error/classify e)))+ (testing "and it is not flagged as an agent error"+ (is (not (:agent-error? (ex-data e)))))))+ (testing "without one the message is the code, so logs still identify the failure"+ (is (= ":metabase.metabot.tools.error-test/denied"+ (ex-message (is (thrown? clojure.lang.ExceptionInfo+ (tools.error/unrecoverable! ::denied))))))))++(deftest ^:parallel classify-test+ (testing "an exception with no ToolError is unrecoverable :internal"+ (is (= {:class :unrecoverable :code :internal}+ (tools.error/classify (ex-info "a plain failure" {:status-code 500}))))+ (is (= {:class :unrecoverable :code :internal}+ (tools.error/classify (RuntimeException. "boom")))))+ (testing "classify reads the top-level exception only — wrapping a declared error demotes it,+ which is the safe direction"+ (let [declared (is (thrown? clojure.lang.ExceptionInfo (test-custom-status! {:id 1})))]+ (is (= :recoverable (:class (tools.error/classify declared))))+ (is (= :unrecoverable+ (:class (tools.error/classify (ex-info "wrapped" {} declared))))))))++;;; The two tests below write the global catalog, so they are not `^:parallel`.++(deftest duplicate-declaration-is-rejected-test+ (testing "a second var claiming an existing code fails loudly rather than shadowing by load order"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"already declared by"+ (tools.error/declare-recoverable! {:code ::test-no-widget+ :var #'test-custom-status!+ :doc "An impostor."+ :payload-schema [:map {:closed true}]+ :status-code 400+ :build-fn (constantly {:message "x" :recovery []})}))))+ (testing "but redeclaring the same var is fine, so namespace reloads work"+ (is (= ::test-no-widget+ (tools.error/declare-recoverable!+ (get (tools.error/recoverables) ::test-no-widget))))))++(deftest declaration-requires-a-var-and-a-schema-test+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"qualified keyword"+ (tools.error/declare-recoverable! {:code :unqualified :var #'test-no-widget!})))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"constructor var"+ (tools.error/declare-recoverable! {:code ::x :var 'not-a-var})))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"without a payload schema"+ (tools.error/declare-recoverable! {:code ::x :var #'test-no-widget!}))))++;;; ------------------------------------- Reading a recoverable error ----------------------------------------------++(deftest ^:parallel recovery-steps-for-tools-test+ (let [steps [{:uses #{} :text "Always applies."}+ {:uses #{"search"} :text "Call `search`."}+ {:uses #{"search" "read_resource"} :text "Call `search` then `read_resource`."}]]+ (is (= [(first steps)] (tools.error/recovery-steps-for-tools steps #{})))+ (is (= (take 2 steps) (tools.error/recovery-steps-for-tools steps #{"search"})))+ (is (= steps (tools.error/recovery-steps-for-tools steps #{"search" "read_resource" "widget"})))))++(deftest ^:parallel names-a-tool?-test+ (testing "only a backticked name counts, so prose mentioning a word is not a tool reference"+ (is (tools.error/names-a-tool? "Call `search` first." "search"))+ (is (not (tools.error/names-a-tool? "Use the search results." "search")))+ (is (not (tools.error/names-a-tool? nil "search")))))++(deftest ^:parallel recoverable-text-test+ (testing "one function for both places a recoverable error becomes text — a failed call, and one+ item of a batched call — so the wording cannot drift between them"+ (let [error {:message "Widget 7 does not exist."+ :recovery [{:uses #{"search"} :text "Call `search` to find one."}+ {:uses #{"read_resource"} :text "Or call `read_resource`."}]}]+ (is (= "Widget 7 does not exist.\nCall `search` to find one.\nOr call `read_resource`."+ (tools.error/recoverable-text error #{"search" "read_resource"})))+ (is (= "Widget 7 does not exist.\nCall `search` to find one."+ (tools.error/recoverable-text error #{"search"})))+ (is (= "Widget 7 does not exist." (tools.error/recoverable-text error #{}))))))++;;; ------------------------------------------- The catalog --------------------------------------------------------++(def ^:private catalog-sample-count+ "How many payloads to generate per declaration. Enough to exercise branching on payload values —+ `recoverable.pipeline/uri-in-source-table!` picks its recovery step from `:entity-type` — without+ making the suite's runtime depend on the size of the catalog."+ 20)++(def ^:private catalog-seed+ "Fixed so the generated payloads are the same on every run. Malli's string generator can emit+ control characters, which `render`'s authored-text assertions would (correctly) reject, and an+ unseeded generator would surface that as a test that fails one run in a few hundred. With a seed,+ either it fails every time and says something real, or it never does."+ 20261007)++(deftest ^:parallel every-declared-error-produces-a-valid-tool-error-test+ (testing "one test for the whole catalog: generate payloads from each declaration's own schema,+ raise it, and check what comes out"+ (doseq [[code {:keys [payload-schema var]}] (tools.error/recoverables)]+ (testing (str code " (" (symbol var) ")")+ (doseq [payload (mg/sample payload-schema {:size catalog-sample-count :seed catalog-seed})]+ (let [e (try+ (tools.error/throw-recoverable! code payload)+ (catch Throwable e e))+ error (tools.error/classify e)]+ (testing (str "payload " (pr-str payload))+ (is (= :recoverable (:class error))+ "a generated payload must satisfy its own declaration")+ (is (mr/validate ::tools.error/tool-error error))+ (is (= code (:code error)))+ (is (= payload (:data error)))+ (testing "and rendering it passes the authored-text assertions, for any profile"+ (doseq [tool-names [#{} #{"search"} #{"search" "read_resource"}]]+ (is (some? (:output (tools.runtime/render error tool-names)))))))))))))++(def ^:private every-tool-name+ "Every model-facing tool name in the product, from the registered profiles.++ The universe a declaration's text is checked against, rather than one profile's: a message naming+ a tool is wrong wherever that tool is missing, and which profiles exist is not this test's+ business."+ (delay (into #{} (comp (mapcat :tools)+ (keep #(:name (tools.legacy/declaration-of %))))+ (vals @@#'profiles/*profiles))))++(defn- tools-named-in+ "The tool names `text` names in backticks."+ [text]+ (into #{} (filter #(tools.error/names-a-tool? text %)) @every-tool-name))++(deftest a-declarations-text-is-profile-neutral-test+ (testing "checked once over the catalog rather than on every render, because it is a property of+ the declaration and nothing about it can change at runtime"+ (is (seq @every-tool-name) "no tool names to check against — are profiles registered?")+ (doseq [[code {:keys [payload-schema]}] (tools.error/recoverables)+ payload (mg/sample payload-schema {:size catalog-sample-count :seed catalog-seed})+ :let [{:keys [message recovery]} (-> (try (tools.error/throw-recoverable! code payload)+ (catch Throwable e e))+ tools.error/classify)]]+ (testing (str code " / payload " (pr-str payload))+ (testing "a message may not name a tool. The runtime can drop a recovery step for a profile+ that lacks its tool, but it cannot drop a message, so a message naming one would+ reach a profile where that tool does not exist."+ (is (= #{} (tools-named-in message))+ "move each of these into a recovery step that declares it in :uses"))+ (testing "and a step may name only the tools it declares in :uses, or it would survive into+ a profile that has no such tool"+ (doseq [{:keys [uses text]} recovery]+ (is (= #{} (set/difference (tools-named-in text) (set uses)))+ (str "add these to the :uses of the step " (pr-str text)))))))))++(deftest the-naming-check-finds-something-test+ (testing "a predicate that stopped matching would make the test above pass vacuously"+ (is (contains? @every-tool-name "read_resource"))+ (is (= #{"read_resource"}+ (tools-named-in "Call `read_resource` with `metabase://database/1/tables`.")))+ (testing "a step that names a tool it did not declare is what the check above catches"+ (is (= #{"read_resource"}+ (set/difference (tools-named-in "Call `read_resource`.") #{}))))+ (testing "and one that declares it is not"+ (is (= #{}+ (set/difference (tools-named-in "Call `read_resource`.") #{"read_resource"}))))+ (testing "and the catalog really does have steps that name tools, so the check above is+ exercised by real declarations and not only by the string on the line above"+ (is (seq (for [[code {:keys [payload-schema]}] (tools.error/recoverables)+ payload (mg/sample payload-schema {:size 1 :seed catalog-seed})+ step (:recovery (-> (try (tools.error/throw-recoverable! code payload)+ (catch Throwable e e))+ tools.error/classify))+ :when (seq (tools-named-in (:text step)))]+ [code (:uses step)]))))))++(deftest ^:parallel recoverable-codes-match-their-constructors-test+ (testing "a code is its constructor's name without the !, so a code says where to look"+ (doseq [[code {:keys [var]}] (tools.error/recoverables)]+ (testing (str code)+ (is (= code (tools.error/code-for (:ns (meta var)) (:name (meta var)))))+ (is (re-find #"!$" (name (:name (meta var))))+ "a constructor always throws, so its name ends with !")))))diff --git a/test/metabase/metabot/tools/legacy_test.clj b/test/metabase/metabot/tools/legacy_test.cljnew file mode 100644index 00000000000..8bffe97dc18--- /dev/null+++ b/test/metabase/metabot/tools/legacy_test.clj@@ -0,0 +1,237 @@+(ns metabase.metabot.tools.legacy-test+ "Converted and unconverted tools in one profile, called through one function."+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.metabot.scope :as scope]+ [metabase.metabot.tools.core :as tools]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.legacy :as tools.legacy]+ [metabase.metabot.tools.runtime :as tools.runtime]+ [metabase.metabot.tools.timelines :as tools.timelines]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++;;; ------------------------------------------- Unconverted tools --------------------------------------------------++;;; Written exactly as tools are written today: an `mu/defn` var with metadata, one argument, and a+;;; loose return value.++(mu/defn ^{:tool-name "old_plain"+ :scope "agent:content:read"}+ old-plain-tool+ "Returns a plain string, as several tools do."+ [{:keys [n]} :- [:map {:closed true} [:n :int]]]+ (str "plain " n))++(mu/defn ^{:tool-name "old_rich"+ :scope "agent:content:read"+ :capabilities #{:permission-write-sql-queries}}+ old-rich-tool+ "Returns the full old-shape map, including the keys that no longer exist."+ [{:keys [n]} :- [:map {:closed true} [:n :int]]]+ {:output (str "rich " n)+ :structured_output {:n n} ; snake_case variant+ :instructions "Show the user the result."+ :status-code 200 ; dropped+ :data-parts [{:type :data :data-type "viz"}]})++(mu/defn ^{:tool-name "old_agent_error"}+ old-agent-error-tool+ "Throws the old `:agent-error?` flag, meaning: relay this to the model."+ [_args :- [:map {:closed true}]]+ (throw (ex-info "Card 7 is not in this conversation." {:agent-error? true :status-code 400})))++(mu/defn ^{:tool-name "old_terminal_error"}+ old-terminal-error-tool+ "Throws the old `:terminal-error?` flag, meaning: show the user and stop."+ [_args :- [:map {:closed true}]]+ (throw (ex-info "You do not have permission to write SQL queries against this database."+ {:agent-error? true :terminal-error? true})))++(mu/defn ^{:tool-name "old_terminal_result"}+ old-terminal-result-tool+ "Returns `:terminal-error?` rather than throwing it, as the SQL tools do."+ [_args :- [:map {:closed true}]]+ {:output "You do not have permission to write SQL queries against this database."+ :terminal-error? true})++(mu/defn ^{:tool-name "old_crash"}+ old-crash-tool+ "Throws something nobody wrote text for."+ [_args :- [:map {:closed true}]]+ (throw (ex-info "H2 connection reset: user=mb_admin" {:sql "SELECT 1"})))++(mu/defn ^{:tool-name "old_quiet_failure"}+ old-quiet-failure-tool+ "Catches its own error and returns it as a success-shaped result, as `read_resource` does."+ [_args :- [:map {:closed true}]]+ {:output "Failed to read the card."})++;;; -------------------------------------------- A converted tool --------------------------------------------------++(tools.error/defrecoverable new-no-widget!+ "There is no widget with that id."+ {:payload [:map {:closed true} [:id :int]]}+ [{:keys [id]}]+ {:message (str "Widget " id " does not exist.")+ :recovery [{:uses #{"search"} :text "Call `search` to find a widget id."}]})++(defrecord NewWidgetTool []+ tools/Tool+ (declaration [_]+ {:name "new_widget"+ :description "Reports a widget."+ :scope "agent:content:read"+ :args [:map {:closed true} [:id :int]]})+ (handle [_ {:keys [id]} _ctx]+ (if (even? id)+ {:output (str "widget " id)}+ (new-no-widget! {:id id}))))++(def ^:private new-widget-tool (->NewWidgetTool))++;;; ------------------------------------------------- Fixtures -----------------------------------------------------++(def ^:private entries+ "One profile holding both kinds. `adapt-all` is the only place that knows the difference, and it+ leaves the converted tool untouched."+ (tools/entries+ (tools.legacy/adapt-all [#'old-plain-tool #'old-rich-tool #'old-agent-error-tool+ #'old-terminal-error-tool #'old-terminal-result-tool #'old-crash-tool+ #'old-quiet-failure-tool+ new-widget-tool])))++(defn- invoke+ ([tool-name args] (invoke #{"search"} tool-name args))+ ([extra-tool-names tool-name args]+ (binding [scope/*current-user-scope* #{"*"}]+ (tools.runtime/invoke entries+ {:profile-id :nlq :metabot nil :user-scope #{"*"}+ :tool-names (into extra-tool-names (keys entries))}+ tool-name args))))++;;; ------------------------------------------------ Coexistence ---------------------------------------------------++(deftest ^:parallel both-kinds-live-in-one-profile-test+ (testing "entries accepts a var and a record side by side"+ (is (= #{"old_plain" "old_rich" "old_agent_error" "old_terminal_error" "old_terminal_result"+ "old_crash" "old_quiet_failure" "new_widget"}+ (set (keys entries)))))+ (testing "and one call path reaches both"+ (is (= {:output "plain 1"} (invoke "old_plain" {:n 1})))+ (is (= {:output "widget 2"} (invoke "new_widget" {:id 2}))))+ (testing "after adapting, both are the same kind of thing"+ (is (every? #(satisfies? tools/Tool %)+ (tools.legacy/adapt-all [#'old-plain-tool new-widget-tool])))+ (is (not-any? tools/batched?+ (tools.legacy/adapt-all [#'old-plain-tool new-widget-tool])))))++(deftest ^:parallel a-real-unconverted-tool-adapts-test+ (let [adapted (tools.legacy/adapt #'tools.timelines/get-timeline-details-tool)]+ (testing "an untouched tool from the codebase needs no edit"+ (is (= {:name "get_timeline_details"+ :args [:map {:closed true} [:timeline_id :int]]+ :scope "agent:timelines:read"}+ (dissoc (tools/declaration adapted) :description))))+ (testing "with the mu/defn preamble stripped from its description"+ (let [{:keys [description]} (tools/declaration adapted)]+ (is (str/starts-with? description "Get the full details of a timeline"))+ (is (not (str/includes? description "Inputs:")))+ (is (not (str/includes? description "Return:")))))))++;;; -------------------------------------------- What is a tool ----------------------------------------------------++(deftest ^:parallel a-var-is-not-a-tool-test+ (testing "the protocol is not extended to clojure.lang.Var. Doing that would make every var in+ the codebase satisfy `Tool`, so the predicate would mean nothing and a var passed in by+ mistake would fail somewhere inside a protocol method instead of where it was registered."+ (is (not (satisfies? tools/Tool #'clojure.core/map)))+ (is (not (satisfies? tools/Tool #'old-plain-tool)))+ (testing "a wrapped one does"+ (is (satisfies? tools/Tool (tools.legacy/adapt #'old-plain-tool))))))++(deftest ^:parallel adapt-refuses-what-is-not-a-tool-test+ (testing "a var with no :tool-name is refused by name, at the call site"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"clojure.core/map is not a tool"+ (tools.legacy/adapt #'clojure.core/map))))+ (testing "and so is anything that is neither a tool nor a var"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"is not a tool"+ (tools.legacy/adapt 42)))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"is not a tool"+ (tools.legacy/adapt {:name "looks like a declaration"}))))+ (testing "a converted tool passes through untouched, so adapt-all is safe on a mixed list"+ (is (identical? new-widget-tool (tools.legacy/adapt new-widget-tool))))+ (testing "legacy-tool? answers the same question without wrapping"+ (is (tools.legacy/legacy-tool? #'old-plain-tool))+ (is (not (tools.legacy/legacy-tool? #'clojure.core/map)))+ (is (not (tools.legacy/legacy-tool? new-widget-tool)))))++;;; --------------------------------------------- Result adaptation ------------------------------------------------++(deftest ^:parallel a-loose-return-value-becomes-a-result-test+ (testing "a plain string"+ (is (= {:output "plain 3"} (invoke "old_plain" {:n 3}))))+ (testing "the full old map: snake_case folded, instructions appended, status-code dropped"+ (is (= {:output "rich 4\nShow the user the result."+ :structured-output {:n 4}+ :data-parts [{:type :data :data-type "viz"}]}+ (invoke "old_rich" {:n 4}))))+ (testing "and the result validates as a new-shape result"+ (is (mr/validate ::tools/result (invoke "old_rich" {:n 4})))))++;;; ----------------------------------------------- Error mapping --------------------------------------------------++(deftest ^:parallel an-agent-error-still-reaches-the-model-test+ (testing "the flag means the author wrote the sentence for a model, so it is relayed"+ (let [outcome (invoke "old_agent_error" {})]+ (is (= "Card 7 is not in this conversation." (:output outcome)))+ (is (=? {:class :recoverable+ :code :metabase.metabot.tools.recoverable.legacy/agent-error}+ (:error outcome))))))++(deftest ^:parallel a-terminal-error-still-ends-the-turn-test+ (doseq [[label tool] {"thrown" "old_terminal_error"+ "returned" "old_terminal_result"}]+ (testing label+ (let [outcome (invoke tool {})]+ (is (=? {:class :unrecoverable+ :user-message "You do not have permission to write SQL queries against this database."}+ (:error outcome)))+ (testing "and the model is told only that it failed"+ (is (str/starts-with? (:output outcome) "This call failed and the user was shown"))+ (is (not (str/includes? (:output outcome) "permission"))))))))++(deftest ^:parallel an-unflagged-exception-is-unrecoverable-test+ (testing "nobody wrote that text for anyone, so it does not reach the model"+ (let [outcome (invoke "old_crash" {})]+ (is (= {:class :unrecoverable :code :internal} (:error outcome)))+ (doseq [leak ["H2" "mb_admin" "SELECT"]]+ (is (not (str/includes? (:output outcome) leak)) (str "leaked " leak))))))++(deftest ^:parallel behaviour-is-preserved-not-improved-test+ (testing "a tool that catches its own error and returns it as `:output` still looks like a+ success. Nothing here can tell that string from a real result. Converting the tool is+ what fixes it — this test records the limitation rather than hiding it."+ (is (= {:output "Failed to read the card."} (invoke "old_quiet_failure" {})))+ (is (nil? (:error (invoke "old_quiet_failure" {}))))))++;;; ------------------------------------------- The runtime's checks -----------------------------------------------++(deftest ^:parallel unconverted-tools-get-the-new-checks-test+ (testing "arguments are validated against the schema from the var's metadata"+ (is (=? {:error {:class :validation :code :invalid-arguments}}+ (invoke "old_plain" {:m 1}))))+ (testing "and the scope is checked from the declaration"+ (is (=? {:error {:class :unrecoverable :code :scope-denied}}+ (tools.runtime/invoke entries+ {:profile-id :nlq :metabot nil :user-scope #{"agent:nothing"}+ :tool-names (set (keys entries))}+ "old_plain" {:n 1}))))+ (testing "a converted tool's recovery steps are filtered the same way"+ (is (= ["Widget 3 does not exist." "Call `search` to find a widget id."]+ (str/split-lines (:output (invoke "new_widget" {:id 3})))))+ (is (= ["Widget 3 does not exist."]+ (str/split-lines (:output (invoke #{} "new_widget" {:id 3})))))))diff --git a/test/metabase/metabot/tools/recoverable/pipeline_test.clj b/test/metabase/metabot/tools/recoverable/pipeline_test.cljnew file mode 100644index 00000000000..57daf75c2e2--- /dev/null+++ b/test/metabase/metabot/tools/recoverable/pipeline_test.clj@@ -0,0 +1,154 @@+(ns metabase.metabot.tools.recoverable.pipeline-test+ "Guards the one gap `with-pipeline-errors` cannot close by itself.++ The converter maps a pipeline `:error` code onto a declaration by name. A code with no declaration+ is not converted, so it becomes unrecoverable and ends the turn — silently, and only in production.+ This test reads the pipeline's own sources and fails while the gap is still cheap to close."+ (:require+ [clojure.java.io :as io]+ [clojure.set :as set]+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.mcp.v2.recovery-hints :as v2-hints]+ [metabase.metabot.tools.error :as tools.error]+ ;; loaded for its declarations; the codes are read out of the catalog, not off the vars+ [metabase.metabot.tools.recoverable.pipeline]+ [metabase.metabot.tools.recovery-hints :as v1-hints]))++(set! *warn-on-reflection* true)++(def ^:private pipeline-sources+ "The namespaces that raise representations-pipeline errors, as classpath resource paths.++ Listed rather than globbed: a glob would quietly stop covering a file that moved, which is the+ exact failure this test exists to catch."+ ["metabase/agent_lib/representations.clj"+ "metabase/agent_lib/representations/repair.clj"+ "metabase/agent_lib/representations/resolve.clj"+ "metabase/metabot/tools/construct.clj"+ "metabase/models/serialization/resolve/mp.clj"])++(def ^:private error-code-pattern+ "Matches `:error :some-code` in ex-data, which is how the pipeline tags an error for its caller."+ #":error\s+:([a-z0-9][a-z0-9-]*)")++(defn- codes-in-source+ [path]+ (let [resource (io/resource path)]+ (is (some? resource) (str "pipeline source " path " is not on the classpath — has it moved?"))+ (when resource+ (into #{} (map (comp keyword second)) (re-seq error-code-pattern (slurp resource))))))++(defn- pipeline-codes+ []+ (into #{} (mapcat codes-in-source) pipeline-sources))++(def ^:private declaration-ns+ "Where the declarations live. A literal, and self-guarding: if the namespace is renamed without+ this following, [[declared-codes]] comes back empty and the first test below fails naming every+ code as missing."+ "metabase.metabot.tools.recoverable.pipeline")++(defn- declared-codes+ []+ (into #{}+ (comp (filter #(= declaration-ns (namespace %)))+ (map (comp keyword name)))+ (keys (tools.error/recoverables))))++(deftest every-pipeline-error-code-has-a-declaration-test+ (let [missing (set/difference (pipeline-codes) (declared-codes))]+ (is (empty? missing)+ (str "These representations-pipeline :error codes have no declaration in "+ "metabase.metabot.tools.recoverable.pipeline, so `tools.core/with-pipeline-errors` "+ "will not convert them and they will end the turn instead of teaching the agent: "+ (pr-str (sort missing))+ ". Add a `defpipeline-error` for each, or decide it really is unrecoverable and say so "+ "in a comment there."))))++(deftest no-stale-declarations-test+ (testing "a declaration for a code the pipeline no longer raises is dead text that nobody will+ notice has drifted"+ (let [stale (set/difference (declared-codes) (pipeline-codes))]+ (is (empty? stale)+ (str "These declarations in metabase.metabot.tools.recoverable.pipeline match no `:error` "+ "code in the pipeline sources: " (pr-str (sort stale))+ ". Remove them, or add the source file that raises them to `pipeline-sources`.")))))++(deftest the-scan-finds-something-test+ (testing "a regex that stopped matching would make both tests above pass vacuously"+ (is (< 20 (count (pipeline-codes))))+ (is (contains? (pipeline-codes) :unknown-table))))++;;; ===== Can one declaration serve both surfaces? =====++;; The pipeline is shared by Metabot (portable FKs, `read_resource`) and MCP v2 (numeric ids,+;; `browse_data`), and each surface keeps its own hint table today — `tools/recovery_hints.clj` and+;; `mcp/v2/recovery_hints.clj`, the same error codes written twice. These tests establish what one+;; shared declaration could and could not replace, before anything is moved.++(tools.error/defrecoverable two-surface-error!+ "A stand-in for a pipeline error declared with both surfaces' recovery steps."+ {:payload [:map {:closed true} [:message :string]]}+ [{:keys [message]}]+ {:message message+ :recovery [{:uses #{"read_resource"}+ :text (str "Call `read_resource` with `metabase://database/<numeric id>/tables`, then "+ "retry with an exact portable FK.")}+ {:uses #{"browse_data"}+ :text (str "Call `browse_data` with action `list_tables`, then use a numeric table id "+ "as `source-table`.")}+ {:uses #{}+ :text "`source-table:` takes a portable FK `[<db-name>, <schema>, <table>]`."}]})++(defn- text-for!+ "The text a caller holding `tool-names` reads for this error. Named with `!` because it goes+ through the throwing constructor, which is the point — it reads the real declaration."+ [tool-names]+ (-> (try (two-surface-error! {:message "No table found."}) (catch Throwable e e))+ tools.error/classify+ (tools.error/recoverable-text tool-names)))++(deftest ^:parallel one-declaration-can-carry-both-surfaces-vocabularies-test+ (testing "`:uses` selects the right surface's step, so a single declaration can replace the two+ per-surface hint tables for every step that names a tool"+ (let [metabot (text-for! #{"read_resource" "search"})+ mcp (text-for! #{"browse_data" "search"})]+ (testing "the pipeline's own sentence reaches both"+ (is (str/includes? metabot "No table found."))+ (is (str/includes? mcp "No table found.")))+ (testing "each surface gets its own vocabulary and not the other's"+ (is (str/includes? metabot "portable FK"))+ (is (not (str/includes? metabot "browse_data")))+ (is (str/includes? mcp "numeric table id"))+ (is (not (str/includes? mcp "read_resource")))))))++(deftest ^:parallel a-step-naming-no-tool-cannot-be-told-apart-by-surface-test+ (testing "RECORDED, NOT SOLVED. `:uses` discriminates on which tools a caller has, which is not+ the same question as which dialect it writes. A step that names no tool survives into+ every surface — correct for advice about data the agent already holds, wrong for advice+ about argument format.++ Two of the declarations in this namespace have exactly that shape: `database-name-step`+ and `first-stage-source-step` both say `portable FK`, both name no tool, and would+ therefore reach an MCP v2 caller that writes numeric ids. Moving v2 onto these+ declarations needs those two steps keyed on something else — a `:dialect` on the step,+ or the dialect var the pipeline already binds."+ (is (str/includes? (text-for! #{"browse_data"}) "portable FK")+ "the dialect-specific, tool-free step reaches the numeric-id surface")))++(deftest ^:parallel the-two-hint-tables-cover-the-same-codes-test+ (testing "the per-surface hint tables answer the same set of codes, which is why one declaration+ per code is the right shape for them. A code one table answers and the other does not+ would mean the surfaces disagree about what is recoverable."+ (let [codes [:uri-in-source-table :unknown-table :unknown-table-id :ambiguous-table+ :unknown-field :unknown-field-id :ambiguous-fk :no-fk-path+ :unknown-card :unknown-card-id :unknown-measure :unknown-measure-id+ :unknown-segment :unknown-segment-id :unknown-database+ :missing-source-in-first-stage]]+ (doseq [code codes]+ (testing code+ (is (some? (v1-hints/recovery-hint {:error code :entity-type "table" :entity-id 1})))+ (is (some? (v2-hints/recovery-hint {:error code :entity-type "table" :entity-id 1})))))+ (testing "and every one of them is declared here"+ (is (= #{} (set/difference (set codes) (declared-codes))))))))diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.cljindex b9fb4c48107..75680390950 100644--- a/test/metabase/metabot/tools/resources_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -1,6 +1,8 @@(ns metabase.metabot.tools.resources-test"Tests for read_resource tool."(:require+ [clojure.java.io :as io]+ [clojure.set :as set][clojure.string :as str][clojure.test :refer :all][medley.core :as m]@@ -9,6 +11,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.metabot.test-util :as test-util][metabase.metabot.tools :as metabot.tools]+ [metabase.metabot.tools.core :as tools][metabase.metabot.tools.resources :as read-resource][metabase.metabot.tools.shared :as tools.shared][metabase.metabot.tools.shared.content-store :as shared.content-store]@@ -22,9 +25,41 @@[metabase.transforms.core :as transforms.core][toucan2.core :as t2]))+(def ^:private uri-arg+ "The tool's item schema, read off the tool so the assertions below compare against what it+ actually publishes."+ @#'read-resource/uri-arg)++(def ^:private read-ctx+ "A profile that has `search`, so the recovery steps naming it survive."+ {:tool-names #{"read_resource" "search"}})++(defn- read-uris+ "Read some URIs the way `POST /v1/read-resource` does: through `with-batched-entries`, with one+ item per URI.++ That consumer rather than the agent loop because the tests below are about what each URI produced,+ and most of them read a single URI — which through `tools/call` is `all-items-failed` the moment+ it misses, with no per-item list to assert on. The agent loop's path has its own test.++ The item shape is the endpoint's, repeated here rather than shared: the endpoint builds its own+ published response and should not export it for a test to lean on, and five lines of mirror is+ cheaper than making every assertion below reach into an entry."+ [{:keys [uris]}]+ (tools/with-batched-entries read-resource/read-resource-tool {:uris (vec uris)} read-ctx nil+ (fn [entries]+ {:resources (mapv (fn [{:keys [item output failed? structured-output]}]+ (cond-> {:uri (:uri item)}+ failed? (assoc :error output)+ (not failed?) (assoc :content {:structured-output structured-output})))+ entries)+ :output (tools/render-text+ (:output (tools/compose read-resource/read-resource-tool entries read-ctx)))})))+(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."+ (is (= (str "Invalid tool arguments: `uris` must be an array of 1 to 5 URI strings; "+ "received a string.")(test-util/tool-boundary-error "read_resource" #'metabot.tools/read-resource-tool{:uris "metabase://table/1"})))))@@ -79,20 +114,123 @@(is (= "metabase://database/1/schemas/weird%2Fname/tables" uri))(is (= ["database" "1" "schemas" "weird/name" "tables"] (:segments parsed)))))))-(deftest read-resource-validation-test- (testing "rejects too many URIs"- (let [uris (vec (repeat 10 "metabase://table/123"))]- (is (thrown-with-msg? Exception #"Too many URIs"- (read-resource/read-resource {:uris uris}))))))--(deftest read-resource-tool-errors-test- (testing "too many URIs go back to the agent as output"- (is (re-find #"^Too many URIs provided \(10\)"- (:output (read-resource/read-resource-tool {:uris (vec (repeat 10 "metabase://table/123"))})))))- (testing "an unexpected error propagates to the agent loop"- (mt/with-dynamic-fn-redefs [read-resource/read-resource (fn [_] (throw (ex-info "boom" {})))]+(deftest ^:parallel the-item-limit-is-a-schema-fact-test+ (testing "the 5-URI cap is in the batched `:args`, so the runtime rejects a sixth before the tool runs"+ (is (= (str "Invalid tool arguments: `uris` must be an array of 1 to 5 URI strings; "+ "received an array.")+ (test-util/tool-boundary-error "read_resource" #'metabot.tools/read-resource-tool+ {:uris (vec (repeat 10 "metabase://table/123"))})))))++(deftest ^:parallel single-and-batched-declarations-test+ (let [single (tools/declaration read-resource/read-resource-tool)+ batched (tools/batched-declaration read-resource/read-resource-tool single)]+ (testing "the single form takes one URI and is a complete tool on its own"+ (is (= [:map {:closed true} [:uri uri-arg]] (:args single)))+ (is (= "read_resource" (:name single)))+ (is (some? (:scope single))))+ (testing "the batched form publishes a sequence of plain strings, not of maps —+ the wire shape the model has always been offered"+ (is (= [:map {:closed true}+ [:uris [:sequential {:min 1 :max 5+ :error/message "must be an array of 1 to 5 URI strings"}+ uri-arg]]]+ (:args batched))))+ (testing "both forms share the item schema, so they cannot drift"+ (is (= uri-arg (get-in single [:args 2 1])))+ (is (= uri-arg (get-in batched [:args 2 1 2]))))+ (testing "only the description and the args differ"+ (is (= (dissoc single :description :args) (dissoc batched :description :args)))+ (is (str/starts-with? (:description batched) (:description single)))+ (is (str/includes? (:description batched) "Up to 5 URIs")))))++(deftest ^:parallel an-undeclared-failure-is-not-a-partial-result-test+ (testing "a bug inside one read fails the whole call rather than being reported as that item's+ text — five results and one Java message is a worse thing to hand a model than nothing"+ (mt/with-dynamic-fn-redefs [read-resource/dispatch (fn [_] (throw (ex-info "boom" {})))](is (thrown-with-msg? clojure.lang.ExceptionInfo #"boom"- (read-resource/read-resource-tool {:uris ["metabase://databases"]}))))))+ (read-uris {:uris ["metabase://databases"]}))))))++;; ===== The guidance an agent gets must match what the dispatch actually serves =====++(def ^:private dispatch-leading-segments+ "The leading path segments `dispatch` routes, read out of its own source.++ Read rather than listed: a list would drift the moment a URI shape is added, which is the drift+ this test exists to catch. The match table's patterns start with either a string literal+ (`[\"table\" id …]`) or a guard over a set of them (`[(t :guard #{\"model\" \"question\"}) …]`)."+ (delay+ (let [source (slurp (io/resource "metabase/metabot/tools/resources.clj"))+ table (subs source (str/index-of source "(match/match-one segments"))+ table (subs table 0 (str/index-of table "(unsupported-uri!"))+ literal (re-seq #"(?m)^\s+\[\"([a-z-]+)\"" table)+ guarded (re-seq #"\(t :guard #\{([^}]+)\}\)" table)]+ (into (set (map second literal))+ (comp (mapcat (fn [[_ names]] (re-seq #"\"([a-z-]+)\"" names)))+ (map second))+ guarded))))++(deftest ^:parallel uri-templates-cover-dispatch-test+ (testing "every resource type the dispatch serves has URI templates to offer an agent that+ guessed wrong. Without this, a new URI shape ships with an `unsupported-uri` error that+ does not mention it, and the agent has no way to discover it."+ (is (seq @dispatch-leading-segments) "the source scan found nothing — has the match table moved?")+ (is (contains? @dispatch-leading-segments "table") "the source scan is not reading the table")+ (is (= #{} (set/difference @dispatch-leading-segments+ (set (keys @#'read-resource/uri-templates))))))+ (testing "and no templates are offered for a shape nothing serves"+ (is (= #{} (set/difference (set (keys @#'read-resource/uri-templates))+ @dispatch-leading-segments)))))++(deftest ^:parallel unsupported-uri-lists-the-shapes-for-its-kind-test+ (mt/with-current-user (mt/user->id :crowberto)+ (testing "a known kind with an unknown aspect gets that kind's shapes, not the whole catalog"+ (let [{:keys [output]} (read-uris {:uris ["metabase://table/1/nonsense"]})]+ (is (str/includes? output "URIs under `table` are:"))+ (is (str/includes? output "metabase://table/{id}/fields/{field_id}"))))+ (testing "an unknown kind has no shapes to list, so it gets the kinds instead"+ (let [{:keys [output]} (read-uris {:uris ["metabase://nonsense/1"]})]+ (is (not (str/includes? output "URIs under")))+ (is (str/includes? output "The resource types served here are:"))))))++(deftest ^:parallel a-read-that-delivered-nothing-is-a-failed-call-test+ (mt/with-current-user (mt/user->id :crowberto)+ (let [ctx {:tool-names #{"read_resource" "search"}}]+ (testing "the agent loop's default: no URI could be read, so the call failed. The text is the+ same per-URI text a partially successful call shows; what changes is that the agent+ loop, the provider adapters and telemetry are told it failed instead of counting it+ a success."+ (let [{:keys [class code text]}+ (test-util/tool-failure read-resource/read-resource-tool+ {:uris ["metabase://bogus/1" "metabase://table/99999999"]}+ #{"read_resource" "search"})]+ (is (= :recoverable class))+ (is (= :metabase.metabot.tools.core/all-items-failed code))+ (testing "every URI is still named, so the agent can retry the ones worth retrying"+ (is (str/includes? text "metabase://bogus/1"))+ (is (str/includes? text "metabase://table/99999999")))))+ (testing "one URI surviving is a successful call with the failure in position"+ (is (nil? (:error (tools/call read-resource/read-resource-tool+ {:uris ["metabase://databases" "metabase://bogus/1"]}+ ctx)))))+ (testing "and a single URI that missed is a failed call too — there is nothing else in it"+ (is (= :metabase.metabot.tools.core/all-items-failed+ (:code (test-util/tool-failure read-resource/read-resource-tool+ {:uris ["metabase://table/99999999"]}+ #{"read_resource" "search"}))))))))++(deftest ^:parallel a-recovery-step-naming-a-missing-tool-is-dropped-test+ (mt/with-current-user (mt/user->id :crowberto)+ (testing "the `search` step survives in a profile that has search"+ (is (str/includes? (:text (test-util/tool-failure read-resource/read-resource-tool+ {:uris ["metabase://nonsense/1"]}+ #{"read_resource" "search"}))+ "`search` result")))+ (testing "and disappears in one that does not, rather than sending the agent at a tool it+ cannot call"+ (is (not (str/includes? (:text (test-util/tool-failure read-resource/read-resource-tool+ {:uris ["metabase://nonsense/1"]}+ #{"read_resource"}))+ "`search`"))))));; ===== Dispatch routing — every URI pattern routes to the expected handler =====@@ -107,7 +245,8 @@["metabase://collections?tree=true" :collections-list [{:tree "true"}]]["metabase://collections?tree=true&foo=bar" :collections-list [{:tree "true" :foo "bar"}]]["metabase://collections?page=2" :collections-list [{:page "2"}]]- ["metabase://user/recent-items" :user-recents []]+ ["metabase://user/recent-items" :user-recents [nil]]+ ["metabase://user/recent-items?page=2" :user-recents [{:page "2"}]];; ----- Database drill-down -----["metabase://database/1" :database ["1"]]["metabase://database/1/tables" :database-tables ["1" nil]]@@ -132,12 +271,13 @@["metabase://model/4/fields" :card-fields ["model" "4"]]["metabase://model/4/fields/99" :card-field ["model" "4" "99"]]["metabase://model/4/fields/c75/17" :card-field ["model" "4" "c75/17"]]- ["metabase://model/4/sources" :card-sources ["4"]]+ ["metabase://model/4/sources" :card-sources ["4" nil]]+ ["metabase://model/4/sources?page=2" :card-sources ["4" {:page "2"}]];; ----- Question (a card type) -----["metabase://question/5" :card ["question" "5"]]["metabase://question/5/fields" :card-fields ["question" "5"]]["metabase://question/5/fields/99" :card-field ["question" "5" "99"]]- ["metabase://question/5/sources" :card-sources ["5"]]+ ["metabase://question/5/sources" :card-sources ["5" nil]];; ----- Metric -----["metabase://metric/6" :metric ["6"]]["metabase://metric/6/dimensions" :metric-dimensions ["6"]]@@ -147,8 +287,9 @@["metabase://segment/10" :segment ["10"]];; ----- Transform -----["metabase://transform/7" :transform ["7"]]- ["metabase://transform/7/sources" :transform-sources ["7"]]- ["metabase://transform/7/target" :transform-target ["7"]]+ ["metabase://transform/7/sources" :transform-sources ["7" nil]]+ ["metabase://transform/7/sources?page=2" :transform-sources ["7" {:page "2"}]]+ ["metabase://transform/7/target" :transform-target ["7" nil]];; ----- Dashboard -----["metabase://dashboard/8" :dashboard ["8"]]["metabase://dashboard/8/items" :dashboard-items ["8" nil]]@@ -200,19 +341,19 @@(deftest dispatch-rejects-unknown-uri-test(testing "unknown top-level resource type throws"- (is (thrown-with-msg? Exception #"Unsupported URI"+ (is (thrown-with-msg? Exception #"No resource is served at"(#'read-resource/dispatch "metabase://nonsense/1"))))(testing "known type with unknown sub-resource throws"- (is (thrown-with-msg? Exception #"Unsupported URI"+ (is (thrown-with-msg? Exception #"No resource is served at"(#'read-resource/dispatch "metabase://table/1/nonsense"))))(testing "deep path that doesn't match any pattern throws"- (is (thrown-with-msg? Exception #"Unsupported URI"+ (is (thrown-with-msg? Exception #"No resource is served at"(#'read-resource/dispatch "metabase://database/1/schemas/PUBLIC/cards"))))(testing "extra-deep collection path throws"- (is (thrown-with-msg? Exception #"Unsupported URI"+ (is (thrown-with-msg? Exception #"No resource is served at"(#'read-resource/dispatch "metabase://collection/1/items/extra"))))(testing "user URI with unknown sub throws"- (is (thrown-with-msg? Exception #"Unsupported URI"+ (is (thrown-with-msg? Exception #"No resource is served at"(#'read-resource/dispatch "metabase://user/bookmarks"))))(testing "non-metabase scheme throws via parse-uri"(is (thrown? Exception@@ -237,7 +378,7 @@(is (= 400 (:status-code (ex-data e))))(is (true? (:agent-error? (ex-data e))))))(testing "the directive error text reaches read_resource output"- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://model/VZbHZIeqQ2HhZv5r0pO6a/fields"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://model/VZbHZIeqQ2HhZv5r0pO6a/fields"]})](is (str/includes? output "URIs use the numeric entity id"))))(testing "non-id segments are unaffected — schema names and field ids may be non-numeric"(is (= ["database" "1" "schemas" "PUBLIC" "tables"]@@ -247,7 +388,7 @@(comment(mt/with-current-user (mt/user->id :crowberto)- (read-resource/read-resource+ (read-uris{:uris [(str "metabase://table/" 1)]})))(deftest read-table-resource-test@@ -257,21 +398,21 @@:model/Table {table-id :id} {:db_id db-id :name "Test Table"}](testing "fetches basic table info"(is (=? {:resources [{:content {:structured-output map?}}]}- (read-resource/read-resource+ (read-uris{:uris [(str "metabase://table/" table-id)]}))))(testing "fetches table with fields"(is (=? {:resources [{:content {:structured-output map?}}]}- (read-resource/read-resource+ (read-uris{:uris [(str "metabase://table/" table-id "/fields")]}))))(testing "handles multiple URIs"(is (=? {:resources [{:content {:structured-output map?}}{:content {:structured-output map?}}]}- (read-resource/read-resource+ (read-uris{:uris [(str "metabase://table/" table-id)(str "metabase://table/" table-id "/fields")]}))))(testing "returns errors for invalid URIs"(is (=? {:resources [{:error string?}]}- (read-resource/read-resource+ (read-uris{:uris ["metabase://table/99999"]}))))))))(deftest read-dashboard-resource-test@@ -279,16 +420,16 @@(mt/with-temp [:model/Dashboard {dashboard-id :id dashboard-name :name}{:name "Sales Overview"}](testing "fetches dashboard info"- (let [result (read-resource/read-resource {:uris [(str "metabase://dashboard/" dashboard-id)]})]+ (let [result (read-uris {:uris [(str "metabase://dashboard/" dashboard-id)]})](is (=? {:resources [{:content {:structured-output map?}}]}result))(is (str/includes? (:output result) dashboard-name))))(testing "rejects sub-resources"(is (=? {:resources [{:error string?}]}- (read-resource/read-resource {:uris [(str "metabase://dashboard/" dashboard-id "/cards")]}))))+ (read-uris {:uris [(str "metabase://dashboard/" dashboard-id "/cards")]}))))(testing "returns error for unknown dashboard"(is (=? {:resources [{:error string?}]}- (read-resource/read-resource {:uris ["metabase://dashboard/99999"]})))))))+ (read-uris {:uris ["metabase://dashboard/99999"]})))))))(deftest read-document-resource-test(mt/with-current-user (mt/user->id :crowberto)@@ -303,7 +444,7 @@{:type "paragraph":content [{:type "text" :text "Detailed analysis"}]}]}}](testing "fetches an indexed outline of the document's top-level blocks"- (let [{:keys [output] :as result} (read-resource/read-resource+ (let [{:keys [output] :as result} (read-uris{:uris [(str "metabase://document/" document-id)]})](is (=? {:resources [{:content {:structured-output map?}}]}result))@@ -313,7 +454,7 @@(is (str/includes? output "[2] paragraph: Detailed analysis"))))(testing "returns error for unknown document"(is (=? {:resources [{:error string?}]}- (read-resource/read-resource {:uris ["metabase://document/99999"]})))))))+ (read-uris {:uris ["metabase://document/99999"]})))))))(deftest read-conversation-chart-resource-test(mt/with-current-user (mt/user->id :crowberto)@@ -331,27 +472,29 @@:queries [nil]:visualization_settings {:chart_type "bar"}}}}})](testing "resolves a conversation chart to its chart type and exported query"- (let [result (read-resource/read-resource {:uris ["metabase://chart/chart-1"]})]+ (let [result (read-uris {:uris ["metabase://chart/chart-1"]})](is (=? {:resources [{:content {:structured-output map?}}]}result))(is (str/includes? (:output result) "conversation-chart"))(is (str/includes? (:output result) "Chart type: line"))(is (str/includes? (:output result) "ORDERS"))))(testing "a chart with no query says so instead of claiming a permission denial"- (let [result (read-resource/read-resource {:uris ["metabase://chart/chart-2"]})]+ (let [result (read-uris {:uris ["metabase://chart/chart-2"]})](is (str/includes? (:output result) "Chart type: bar"))(is (str/includes? (:output result) "No query is attached to this chart."))(is (not (str/includes? (:output result) "cannot read")))))(testing "falls back to the queries state when the id is a query id"- (let [result (read-resource/read-resource {:uris ["metabase://chart/q-1"]})]+ (let [result (read-uris {:uris ["metabase://chart/q-1"]})](is (str/includes? (:output result) "conversation-query"))))(testing "resolves a conversation query"- (let [result (read-resource/read-resource {:uris ["metabase://query/q-1"]})]+ (let [result (read-uris {:uris ["metabase://query/q-1"]})](is (str/includes? (:output result) "conversation-query"))(is (str/includes? (:output result) "ORDERS"))))- (testing "errors clearly for ids that are in neither charts nor queries state"- (is (=? {:resources [{:error #"No chart or query with id 'nope'.*"}]}- (read-resource/read-resource {:uris ["metabase://chart/nope"]}))))))))+ (testing "an id in neither charts nor queries state is named, and so are the ids that+ do exist — the agent minted them itself, so echoing them back is its own text"+ (is (=? {:resources [{:error #"(?s)No chart or query with id \"nope\" exists in this conversation\. The ids that do: .*"}]}+ (read-uris {:uris ["metabase://chart/nope"]})))+ (is (str/includes? (:output (read-uris {:uris ["metabase://chart/nope"]})) "chart-1")))))))(defn- refusing-store"A ContentStore that records `tag` and refuses, the way the real stores do for a row the@@ -387,7 +530,7 @@(let [used (atom [])](with-redefs [shared.content-store/audited-store (refusing-store :audited used)shared.content-store/default-store (refusing-store :default used)]- (let [result (read-resource/read-resource {:uris [uri]})]+ (let [result (read-uris {:uris [uri]})](is (str/includes? (:output result)"references content the user cannot read"))(distinct @used)))))]@@ -413,7 +556,7 @@:type "query":query {:source-table 1}}}}})](mt/with-test-user :rasta- (let [result (read-resource/read-resource {:uris ["metabase://query/q-gone"]})]+ (let [result (read-uris {:uris ["metabase://query/q-gone"]})](is (not (str/includes? (:output result) "cannot read")))(is (str/includes? (:output result) "source-table")))))))@@ -433,7 +576,7 @@:type "query":query {:source-table (mt/id :orders)}})](doseq [uri ["metabase://query/q-1" "metabase://chart/chart-1"]]- (let [result (read-resource/read-resource {:uris [uri]})]+ (let [result (read-uris {:uris [uri]})](is (str/includes? (:output result) "references content the user cannot read") uri)(is (not (str/includes? (:output result) "ORDERS")) uri))))))))@@ -447,7 +590,7 @@(binding [tools.shared/*memory-atom* (doto (conversation-query-state query)(swap! assoc-in [:state :client-ids] client-ids))](doseq [uri ["metabase://query/q-1" "metabase://chart/chart-1"]]- (let [result (read-resource/read-resource {:uris [uri]})]+ (let [result (read-uris {:uris [uri]})](is (str/includes? (:output result) "references content the user cannot read") uri)(is (not (str/includes? (:output result) "SELECT")) uri)))))))))@@ -465,7 +608,7 @@:type :query:query {:source-table (str "card__" card-id)}})](doseq [uri ["metabase://query/q-1" "metabase://chart/chart-1"]]- (let [result (read-resource/read-resource {:uris [uri]})]+ (let [result (read-uris {:uris [uri]})](is (=? {:resources [{:content map?}]} result))(is (str/includes? (:output result) "source-card")))))))))))@@ -483,7 +626,7 @@:type :query:query {:source-table (str "card__" card-id)}})](doseq [uri ["metabase://query/q-1" "metabase://chart/chart-1"]]- (let [result (read-resource/read-resource {:uris [uri]})]+ (let [result (read-uris {:uris [uri]})](is (str/includes? (:output result) "references content the user cannot read") uri)(is (not (str/includes? (:output result) "ORDERS")) uri)))))))))@@ -496,16 +639,16 @@:query (lib/native-query (mt/metadata-provider)"SELECT * FROM products WHERE category = 'Gadget'")}}](testing "fetches transform info"- (let [result (read-resource/read-resource {:uris [(str "metabase://transform/" transform-id)]})]+ (let [result (read-uris {:uris [(str "metabase://transform/" transform-id)]})](is (=? {:resources [{:content {:structured-output map?}}]}result))(is (str/includes? (:output result) transform-name))))(testing "rejects sub-resources"(is (=? {:resources [{:error string?}]}- (read-resource/read-resource {:uris [(str "metabase://transform/" transform-id "/fields")]}))))+ (read-uris {:uris [(str "metabase://transform/" transform-id "/fields")]}))))(testing "returns error for unknown transform"(is (=? {:resources [{:error string?}]}- (read-resource/read-resource {:uris ["metabase://transform/99999"]}))))))))+ (read-uris {:uris ["metabase://transform/99999"]}))))))));; EE-only: the analyst reading here only can with `advanced-permissions`, which no OSS build can have(mt/when-ee-evailable@@ -523,19 +666,24 @@(perms/set-table-permission! (perms-group/all-users) (mt/id :venues) :perms/view-data :unrestricted)(perms/set-table-permission! (perms-group/all-users) (mt/id :venues) :perms/create-queries :query-builder)(mt/with-current-user (mt/user->id :rasta)- (is (=? {:resources [{:error "You don't have permissions to do that."}]}- (read-resource/read-resource {:uris [(str "metabase://transform/" transform-id)]}))))+ ;; A 403 and a 404 give the same sentence on purpose; see+ ;; `recoverable.common/not-found!`. Before, this was the bare+ ;; "You don't have permissions to do that." with no id and no next step.+ (is (=? {:resources [{:error #"(?s)^Transform \d+ was not found\..*"}]}+ (read-uris {:uris [(str "metabase://transform/" transform-id)]}))))(testing "and the query renders once the source table is granted"(perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/view-data :unrestricted)(perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/create-queries :query-builder)(mt/with-current-user (mt/user->id :rasta)- (let [result (read-resource/read-resource {:uris [(str "metabase://transform/" transform-id)]})]+ (let [result (read-uris {:uris [(str "metabase://transform/" transform-id)]})](is (some? (get-in result [:resources 0 :content :structured-output :source :query])))))))))))))(defn- read-title"The chain-of-thought title `read-resource` derives from what it read."[& uris]- (-> (read-resource/read-resource {:uris (vec uris)})+ ;; The agent loop's path, not the endpoint's: the title is a `:data-parts` entry on the composed+ ;; result, which is what `tools/call` returns and the endpoint drops.+ (-> (tools/call read-resource/read-resource-tool {:uris (vec uris)} read-ctx):data-parts first :data :title))(deftest read-resource-title-test@@ -585,11 +733,23 @@(testing "a navigation list names what's being browsed"(is (= "databases" (read-title "metabase://databases")))(is (= "recent items" (read-title "metabase://user/recent-items"))))- (testing "a missing entity -> no title"- (is (nil? (read-title "metabase://dashboard/99999"))))- (testing "an unreadable entity never leaks its name"+ (testing "a read that found nothing has no title because it is a failed call, not a call+ with an empty title"+ (is (= :metabase.metabot.tools.core/all-items-failed+ (:code (test-util/tool-failure read-resource/read-resource-tool+ {:uris ["metabase://dashboard/99999"]}+ (:tool-names read-ctx))))))+ (testing "an unreadable entity never leaks its name — same code, so the title cannot carry it+ and neither can the error"(with-redefs [mi/can-read? (constantly false)]- (is (nil? (read-title (str "metabase://dashboard/" dash-id)))))))))+ (let [{:keys [code text]} (test-util/tool-failure read-resource/read-resource-tool+ {:uris [(str "metabase://dashboard/" dash-id)]}+ (:tool-names read-ctx))]+ (is (= :metabase.metabot.tools.core/all-items-failed code))+ (is (not (str/includes? text "Sales Overview"))))))+ (testing "one readable entity beside an unreadable one still titles the readable one"+ (is (= (str "[Sales Overview](metabase://dashboard/" dash-id ")")+ (read-title (str "metabase://dashboard/" dash-id) "metabase://dashboard/99999")))))));; ===== Permission coverage — every branch =====;;@@ -651,7 +811,7 @@(with-redefs [mi/can-read? (constantly false)](doseq [uri uris](testing uri- (is (error? (read-resource/read-resource {:uris [uri]}))+ (is (error? (read-uris {:uris [uri]}))(str uri " should return an :error response when user lacks read perms"))))))))))(deftest read-check-throws-on-missing-perm-transform-test@@ -667,7 +827,7 @@(str "metabase://transform/" transform-id "/sources")(str "metabase://transform/" transform-id "/target")]](testing uri- (is (error? (read-resource/read-resource {:uris [uri]}))+ (is (error? (read-uris {:uris [uri]}))(str uri " should return an :error response when user can't read transform"))))))))))(deftest list-filters-databases-by-can-read-test@@ -681,7 +841,7 @@(if (= hidden-id (:id instance)) false (orig instance)))([model id](if (= hidden-id id) false (orig model id))))]- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://databases"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://databases"]})](is (str/includes? output "VISIBLE-DB"))(is (not (str/includes? output "HIDDEN-DB"))"unreadable database must not appear in the list"))))))))@@ -692,7 +852,7 @@(mt/with-temp [:model/Database {router-id :id} {:name "ROUTER-DB"}:model/Database _ {:name "DESTINATION-DB" :router_database_id router-id}](with-redefs [mi/can-read? (constantly true)]- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://databases"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://databases"]})](is (str/includes? output "ROUTER-DB"))(is (not (str/includes? output "DESTINATION-DB"))"destination database must not appear in the list")))))))@@ -708,7 +868,7 @@(if (= hidden-id (:id instance)) false (orig instance)))([model id](if (= hidden-id id) false (orig model id))))]- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://collections"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://collections"]})](is (str/includes? output "VISIBLE-COLL"))(is (not (str/includes? output "HIDDEN-COLL"))"unreadable collection must not appear in the list"))))))))@@ -732,7 +892,7 @@(and (= :model/Dashboard (t2/model instance)) (hidden-dashes (:id instance))) false:else (orig instance)))([model id] (orig model id)))]- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://collection/" coll-id "/items")]})](is (str/includes? output "VISIBLE-CARD"))(is (str/includes? output "VISIBLE-DASH"))@@ -755,7 +915,7 @@false(orig instance)))([model id] (orig model id)))]- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://database/" db-id "/tables")]})](is (str/includes? output "VISIBLE-TBL"))(is (not (str/includes? output "HIDDEN-TBL"))@@ -777,7 +937,7 @@false(orig instance)))([model id] (orig model id)))]- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "VISIBLE-DASHCARD"))(is (not (str/includes? output "HIDDEN-DASHCARD"))@@ -796,7 +956,7 @@:table target-table}](testing "when user CAN read the target, it appears in the output"(mt/with-dynamic-fn-redefs [transforms.core/get-transform (constantly stub-transform)]- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris ["metabase://transform/999/target"]})](is (str/includes? output "TARGET-TABLE")"target table name should appear when user has read perms")@@ -805,7 +965,7 @@(testing "when user CANNOT read the target, it's filtered out"(with-redefs [transforms.core/get-transform (constantly stub-transform)mi/can-read? (constantly false)]- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris ["metabase://transform/999/target"]})](is (not (str/includes? output "TARGET-TABLE"))"target table name must NOT appear when user lacks read perms")@@ -821,7 +981,7 @@(mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Database {db-id :id} {:name "Test DB"}](testing "metabase://databases returns the database with its drill-in URI"- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://databases"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://databases"]})](is (str/includes? output "Test DB"))(is (str/includes? output (str "uri=\"metabase://database/" db-id "\""))))))))@@ -830,7 +990,7 @@(mt/with-temp [:model/Database {db-id :id} {}:model/Table {t-id :id} {:db_id db-id :name "ORDERS" :active true}](testing "metabase://database/{id}/tables lists tables with drill-in URIs"- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://database/" db-id "/tables")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://database/" db-id "/tables")]})](is (str/includes? output "ORDERS"))(is (str/includes? output (str "uri=\"metabase://table/" t-id "\""))))))))@@ -840,10 +1000,10 @@:model/Card {card-id :id} {:name "Sales report" :collection_id coll-id}:model/Document {doc-id :id} {:name "Campaign plan" :collection_id coll-id}](testing "metabase://collections lists root collections (excluding trash)"- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://collections"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://collections"]})](is (str/includes? output "Marketing"))))(testing "metabase://collection/{id}/items lists members with drill-in URIs"- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://collection/" coll-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://collection/" coll-id "/items")]})](is (str/includes? output "Sales report"))(is (str/includes? output (str "uri=\"metabase://question/" card-id "\"")))(is (str/includes? output "Campaign plan"))@@ -860,7 +1020,7 @@:database_id db-id:table_id table-id}](testing "metabase://table/{id}/derived returns cards built on the table"- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://table/" table-id "/derived")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://table/" table-id "/derived")]})](is (str/includes? output "Derived"))(is (str/includes? output (str "uri=\"metabase://model/" card-id "\""))))))))@@ -877,7 +1037,7 @@:source {:type "query":query (lib/native-query (mt/metadata-provider) "SELECT 1")}}](testing "/derived for a table in db1 must exclude transforms whose source is in db2"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://table/" tbl1-id "/derived")]})](is (not (str/includes? output "Other-DB Transform"))"transforms not sourced from this table's database must not appear")@@ -889,7 +1049,7 @@:model/Table {table-id :id} {:db_id db-id}:model/Card {card-id :id} {:type :model :database_id db-id :table_id table-id}](testing "metabase://model/{id}/sources returns the FK-resolved sources"- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://model/" card-id "/sources")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://model/" card-id "/sources")]})](is (str/includes? output (str "uri=\"metabase://database/" db-id "\""))"should include the database URI")(is (str/includes? output (str "uri=\"metabase://table/" table-id "\""))@@ -915,14 +1075,14 @@:table_id table-id:source_card_id model-id}](testing "source_card_id pointing at a :metric emits a metric URI"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://question/" q-id "/sources")]})](is (str/includes? output (str "uri=\"metabase://metric/" metric-id "\""))"should resolve source-card of type :metric to a metric URI, not question")(is (not (str/includes? output (str "uri=\"metabase://question/" metric-id "\"")))"must NOT collapse the metric source-card to a question URI")))(testing "source_card_id pointing at a :model still emits a model URI (regression)"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://question/" q-from-model-id "/sources")]})](is (str/includes? output (str "uri=\"metabase://model/" model-id "\"")))))))))@@ -952,7 +1112,7 @@:creator_id (mt/user->id :crowberto):definition (measure-definition orders total)}](testing "metabase://measure/{id} returns the measure with parent-table context + portable entity id"- (let [result (read-resource/read-resource {:uris [(str "metabase://measure/" measure-id)]})+ (let [result (read-uris {:uris [(str "metabase://measure/" measure-id)]})structured (get-in result [:resources 0 :content :structured-output])output (:output result)](is (=? {:type :measure@@ -965,12 +1125,15 @@(testing "rendered XML carries the measure name and a portable entity id"(is (str/includes? output "Order Revenue"))(is (str/includes? output "portable_entity_id=")))))- (testing "returns an error for an unknown measure"- (is (=? {:resources [{:error string?}]}- (read-resource/read-resource {:uris ["metabase://measure/99999"]}))))+ (testing "an unknown measure is the declared not-found error. `get-measure-details`+ reports a miss by returning `{:output … :status-code 404}` rather than throwing,+ which used to render as an empty `<resource>` once the formatter stopped+ recognising the shape."+ (is (=? {:resources [{:error #"(?s)^Measure 99999 was not found\..*"}]}+ (read-uris {:uris ["metabase://measure/99999"]}))))(testing "errors when the user can't read the parent table"(with-redefs [mi/can-read? (constantly false)]- (is (error? (read-resource/read-resource {:uris [(str "metabase://measure/" measure-id)]}))))))))))+ (is (error? (read-uris {:uris [(str "metabase://measure/" measure-id)]}))))))))))(deftest read-segment-resource-test(mt/test-drivers #{:h2}@@ -983,7 +1146,7 @@:table_id orders:definition (segment-definition orders total 100)}](testing "metabase://segment/{id} returns the segment with parent-table context + portable entity id"- (let [result (read-resource/read-resource {:uris [(str "metabase://segment/" segment-id)]})+ (let [result (read-uris {:uris [(str "metabase://segment/" segment-id)]})structured (get-in result [:resources 0 :content :structured-output])output (:output result)](is (=? {:type :segment@@ -996,12 +1159,12 @@(testing "rendered XML carries the segment name and a portable entity id"(is (str/includes? output "Big Orders"))(is (str/includes? output "portable_entity_id=")))))- (testing "returns an error for an unknown segment"- (is (=? {:resources [{:error string?}]}- (read-resource/read-resource {:uris ["metabase://segment/99999"]}))))+ (testing "an unknown segment is the declared not-found error (see the measure case)"+ (is (=? {:resources [{:error #"(?s)^Segment 99999 was not found\..*"}]}+ (read-uris {:uris ["metabase://segment/99999"]}))))(testing "errors when the user can't read the parent table"(with-redefs [mi/can-read? (constantly false)]- (is (error? (read-resource/read-resource {:uris [(str "metabase://segment/" segment-id)]}))))))))))+ (is (error? (read-uris {:uris [(str "metabase://segment/" segment-id)]}))))))))))(deftest read-dashboard-items-test(mt/with-current-user (mt/user->id :crowberto)@@ -1009,7 +1172,7 @@:model/Card {card-id :id} {:name "Dash card"}:model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id}](testing "metabase://dashboard/{id}/items returns each dashcard with its dashcard_id"- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "Dash card"))(is (str/includes? output (str "uri=\"metabase://question/" card-id "\"")))(is (str/includes? output (str "dashcard_id=\"" dc-id "\""))))))))@@ -1035,7 +1198,7 @@:card_id nil :row 0 :col 0 :size_x 24 :size_y 1:visualization_settings {:virtual_card {:display "heading"}:text "Legacy Heading"}}]- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})idx #(str/index-of output %)](testing "a <tabs> block lists every tab in display order, empty ones included"(is (< (idx "Tab One") (idx "Tab Two") (idx "Empty Tab"))))@@ -1056,7 +1219,7 @@{:virtual_card {:display "heading"}:text "Revenue Section"}}](testing "virtual (heading/text) dashcards are listed with the dashcard_id that remove/move mutations take"- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "virtual_heading"))(is (str/includes? output "Revenue Section"))(is (str/includes? output (str "dashcard_id=\"" dc-id "\"")))))))@@ -1067,7 +1230,7 @@:card_id nil:row 0 :col 0 :size_x 4 :size_y 1:visualization_settings {}}]- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "virtual_dashcard"))(is (str/includes? output (str "dashcard_id=\"" dc-id "\"")))))))(testing "an action-button dashcard is listed as an action item with its dashcard_id"@@ -1082,7 +1245,7 @@:row 0 :col 0 :size_x 4 :size_y 1:visualization_settings{:virtual_card {:display "action"}}}]- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "type=\"action\""))(is (str/includes? output (str "dashcard_id=\"" dc-id "\""))))))))(testing "an action dashcard that also references its backing model card still reads as an action"@@ -1098,7 +1261,7 @@:row 0 :col 0 :size_x 4 :size_y 1:visualization_settings{:button.label "Create Row"}}]- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "type=\"action\""))(is (str/includes? output "name=\"Create Row\""))(is (str/includes? output (str "dashcard_id=\"" dc-id "\"")))@@ -1113,7 +1276,7 @@:visualization_settings{:virtual_card {:display "link"}:link {:url "https://status.example.com"}}}]- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "virtual_link"))(is (str/includes? output "https://status.example.com"))))))(testing "an entity link card does NOT leak the stored target snapshot (it bypasses read-checks)"@@ -1126,20 +1289,20 @@{:virtual_card {:display "link"}:link {:entity {:model "card" :id 12345:name "Secret Question"}}}}]- (let [{:keys [output]} (read-resource/read-resource {:uris [(str "metabase://dashboard/" dash-id "/items")]})]+ (let [{:keys [output]} (read-uris {:uris [(str "metabase://dashboard/" dash-id "/items")]})](is (str/includes? output "virtual_link"))(is (not (str/includes? output "Secret Question"))))))))(deftest read-user-recents-test(mt/with-current-user (mt/user->id :crowberto)(testing "metabase://user/recent-items returns a list shape (possibly empty)"- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://user/recent-items"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://user/recent-items"]})](is (str/includes? output "<list type=\"recent-items\""))))))(deftest read-list-shape-test(testing "list responses carry total/page/pages/showing/truncated attrs in the rendered XML"(mt/with-current-user (mt/user->id :crowberto)- (let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://databases"]})]+ (let [{:keys [output]} (read-uris {:uris ["metabase://databases"]})](is (str/includes? output "<list type=\"databases\""))(is (str/includes? output "total="))(is (str/includes? output "page="))@@ -1147,21 +1310,32 @@(is (str/includes? output "showing="))(is (str/includes? output "truncated="))))))-(deftest format-resources-test- (testing "formats resources with content"- (let [resources [{:uri "metabase://table/123"- :content {:formatted "Table details here"}}]- formatted (#'read-resource/format-resources resources)]- (is (str/includes? formatted "<resources>"))- (is (str/includes? formatted "<resource uri=\"metabase://table/123\">"))- (is (str/includes? formatted "Table details here"))- (is (str/includes? formatted "</resource>"))- (is (str/includes? formatted "</resources>"))))- (testing "formats resources with errors"- (let [resources [{:uri "metabase://table/123"- :error "Table not found"}]- formatted (#'read-resource/format-resources resources)]- (is (str/includes? formatted "**Error:** Table not found")))))+(deftest ^:parallel every-item-is-attributed-to-its-uri-test+ (mt/with-current-user (mt/user->id :crowberto)+ (let [{:keys [output resources]} (read-uris {:uris ["metabase://databases"+ "metabase://table/99999999"+ "metabase://nonsense/1"]})]+ (testing "a failed URI lands inside its own <resource> element, not loose in the envelope.+ Up to 5 reads share one result, so a failure the model cannot pin to a URI is a+ failure it cannot retry."+ (is (str/includes? output "<resource uri=\"metabase://table/99999999\">\n**Error:** "))+ (is (str/includes? output "<resource uri=\"metabase://nonsense/1\">\n**Error:** ")))+ (testing "a 404 names the entity the URI asked for, and says what to do next"+ (is (str/includes? output "Table 99999999 was not found"))+ (is (str/includes? output "Call `search`")))+ (testing "the successes are unaffected by the failures beside them"+ (is (str/includes? output "<list type=\"databases\"")))+ (testing "`:resources` carries every URI in order, which is the Agent API's published shape"+ (is (= ["metabase://databases" "metabase://table/99999999" "metabase://nonsense/1"]+ (mapv :uri resources)))+ (is (= [false true true] (mapv #(contains? % :error) resources)))))))++(deftest ^:parallel a-uri-attribute-is-escaped-test+ (mt/with-current-user (mt/user->id :crowberto)+ (testing "the URI is the agent's own text and reaches the model inside an attribute, so a quote+ in it must not be able to close that attribute early"+ (let [{:keys [output]} (read-uris {:uris ["metabase://table/\"><script>"]})]+ (is (str/includes? output "<resource uri=\"metabase://table/\\\"><script>\">"))))));; ===== Behavioral tests for patterns where the dispatch contract isn't enough =====@@ -1169,7 +1343,7 @@(mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Database {db-id :id} {:name "Detail DB" :engine :h2}](testing "metabase://database/{id} returns single-entity output with engine + uri"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://database/" db-id)]})](is (str/includes? output "Detail DB"))(is (str/includes? output (str "uri=\"metabase://database/" db-id "\"")))@@ -1181,7 +1355,7 @@(mt/with-temp [:model/Database {router-id :id} {}:model/Database {destination-id :id} {:router_database_id router-id}](with-redefs [mi/can-read? (constantly true)]- (is (error? (read-resource/read-resource+ (is (error? (read-uris{:uris [(str "metabase://database/" destination-id)]}))"destination database must not be readable by direct URI"))))))@@ -1223,10 +1397,12 @@(str "metabase://measure/" measure-id)(str "metabase://segment/" segment-id)]](testing uri- ;; Match the guard's 404 message exactly: a plain `error?` check can't tell the+ ;; Match the 404 text exactly: a plain `error?` check can't tell the;; destination-database guard from unrelated failures like "Field 42 not found".- (is (= "Not found."- (-> (read-resource/read-resource {:uris [uri]}) :resources first :error))+ ;; The guard raises a bare 404, which the URI's own kind and id now name — before,+ ;; every one of these said only "Not found." with nothing to act on.+ (is (re-find #"^\w+ \d+ was not found\. It may not exist, or you may not have access to it\."+ (-> (read-uris {:uris [uri]}) :resources first :error))"destination-backed entity resource must 404 via the destination-database guard"))))))))))(deftest read-database-models-test@@ -1235,7 +1411,7 @@:model/Card {model-id :id} {:type :model :database_id db-id :name "M-One"}:model/Card _ {:type :question :database_id db-id :name "Q-Skip"}](testing "metabase://database/{id}/models lists models only (not questions)"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://database/" db-id "/models")]})](is (str/includes? output "M-One"))(is (str/includes? output (str "uri=\"metabase://model/" model-id "\"")))@@ -1247,7 +1423,7 @@:model/Table _ {:db_id db-id :schema "PUBLIC" :name "t1" :active true}:model/Table _ {:db_id db-id :schema "PRIVATE" :name "t2" :active true}](testing "metabase://database/{id}/schemas emits a drill-in URI per schema"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://database/" db-id "/schemas")]})](is (str/includes? output "PUBLIC"))(is (str/includes? output "PRIVATE"))@@ -1260,7 +1436,7 @@:model/Table {pub-id :id} {:db_id db-id :schema "PUBLIC" :name "PUB-TABLE" :active true}:model/Table _ {:db_id db-id :schema "PRIVATE" :name "PRIV-TABLE" :active true}](testing "metabase://database/{id}/schemas/{name}/tables filters by schema"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://database/" db-id "/schemas/PUBLIC/tables")]})](is (str/includes? output "PUB-TABLE"))(is (str/includes? output (str "uri=\"metabase://table/" pub-id "\"")))@@ -1276,7 +1452,7 @@(testing "the URI builder emits an encoded segment"(is (str/includes? emitted-uri "weird%2Fname")))(testing "the encoded URI dispatches and filters to the right schema"- (let [{:keys [output]} (read-resource/read-resource {:uris [emitted-uri]})]+ (let [{:keys [output]} (read-uris {:uris [emitted-uri]})](is (str/includes? output "WEIRD-TABLE"))(is (str/includes? output (str "uri=\"metabase://table/" weird-id "\"")))(is (not (str/includes? output "OTHER-TABLE"))))))))))@@ -1285,7 +1461,7 @@(mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Collection {coll-id :id} {:name "Detail Coll" :location "/"}](testing "metabase://collection/{id} returns single-entity output with name + uri"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://collection/" coll-id)]})](is (str/includes? output "Detail Coll"))(is (str/includes? output (str "uri=\"metabase://collection/" coll-id "\""))))))))@@ -1295,7 +1471,7 @@(mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/"}:model/Collection {child-id :id} {:name "Child" :location (str "/" parent-id "/")}](testing "metabase://collection/{id}/subcollections lists direct children only"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://collection/" parent-id "/subcollections")]})](is (str/includes? output "Child"))(is (str/includes? output (str "uri=\"metabase://collection/" child-id "\"")))@@ -1306,7 +1482,7 @@(mt/with-temp [:model/Collection {parent-id :id} {:name "P" :location "/"}:model/Collection _ {:name "C" :location (str "/" parent-id "/")}](testing "metabase://collections?tree=true returns all collections with full path strings"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris ["metabase://collections?tree=true"]})](is (str/includes? output "<list type=\"collections-tree\""))(is (str/includes? output "P"))@@ -1325,7 +1501,7 @@(deftest read-table-field-partial-values-test(mt/with-current-user (mt/user->id :crowberto)(let [read-field (fn [table field]- (:output (read-resource/read-resource+ (:output (read-uris{:uris [(str "metabase://table/" (mt/id table) "/fields/" (mt/id table field))]})))](testing "a field with more values than the sample says how many it has"(let [output (read-field :people :state)]@@ -1342,11 +1518,11 @@:model/Card {q-id :id} {:type :question :database_id db-id :name "Q-card"}:model/Card {m-id :id} {:type :model :database_id db-id :name "M-card"}](testing "metabase://question/{id}/sources discriminates from model"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://question/" q-id "/sources")]})](is (str/includes? output (str "uri=\"metabase://database/" db-id "\"")))))(testing "metabase://model/{id}/sources for a model card"- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://model/" m-id "/sources")]})](is (str/includes? output (str "uri=\"metabase://database/" db-id "\""))))))))@@ -1364,7 +1540,7 @@:dataset_query query:result_metadata metadata}](mt/with-test-user :crowberto- (let [read-result (read-resource/read-resource-tool+ (let [read-result (read-uris{:uris [(str "metabase://question/" question-id "/fields")]})output (:output read-result)structured (get-in read-result [:resources 0 :content :structured-output])]@@ -1395,11 +1571,11 @@(is (= 50 (-> result :items last :id)))))(testing "out-of-range page throws instead of clamping"(let [items (mapv (fn [i] {:id i}) (range 1 11))]- (is (thrown-with-msg? Exception #"Invalid page 999\. This list has 1 page\."+ (is (thrown-with-msg? Exception #"There is no page 999\. This list has 1 page\."(#'read-resource/paginate-list items "999")))- (is (thrown-with-msg? Exception #"Invalid page 0\. This list has 1 page\."+ (is (thrown-with-msg? Exception #"There is no page 0\. This list has 1 page\."(#'read-resource/paginate-list items "0")))- (is (thrown-with-msg? Exception #"Invalid page -3\. This list has 1 page\."+ (is (thrown-with-msg? Exception #"There is no page -3\. This list has 1 page\."(#'read-resource/paginate-list items "-3")))))(testing "list shorter than one page"(let [items (mapv (fn [i] {:id i}) (range 1 6))@@ -1421,7 +1597,7 @@:db_id db-id:active true}))(testing "page 1 returns first 25 tables, with page/pages metadata"- (let [result (read-resource/read-resource+ (let [result (read-uris{:uris [(str "metabase://database/" db-id "/tables")]})so (get-in result [:resources 0 :content :structured-output])](is (= 1 (:page so)))@@ -1429,13 +1605,13 @@(is (= 30 (:total so)))(is (= 25 (count (:items so))))))(testing "page 2 returns remaining 5 tables"- (let [result (read-resource/read-resource+ (let [result (read-uris{:uris [(str "metabase://database/" db-id "/tables?page=2")]})so (get-in result [:resources 0 :content :structured-output])](is (= 2 (:page so)))(is (= 5 (count (:items so))))))(testing "out-of-range page surfaces as a resource error, not an uncaught exception"- (let [result (read-resource/read-resource+ (let [result (read-uris{:uris [(str "metabase://database/" db-id "/tables?page=999")]})](is (=? {:resources [{:error string?}]} result)))))))@@ -1447,7 +1623,7 @@(t2/insert! :model/Table {:name (format "TBL-%03d" i):db_id db-id:active true}))- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://database/" db-id "/tables")]})](is (str/includes? output "page=\"1\""))(is (str/includes? output "pages=\"2\""))@@ -1462,7 +1638,7 @@(t2/insert! :model/Table {:name (format "TBL-%03d" i):db_id db-id:active true}))- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://database/" db-id "/tables?page=1")]})](is (str/includes? output (str "metabase://database/" db-id "/tables?page=2")))(is (not (str/includes? output "page=1&page=2"))))))))@@ -1481,7 +1657,7 @@:model/Collection {a-root :id} {:name "A-Root" :location "/"}:model/Collection _ {:name "Z-Child" :location (str "/" z-root "/")}:model/Collection _ {:name "A-Child" :location (str "/" a-root "/")}]- (let [result (read-resource/read-resource {:uris ["metabase://collections?tree=true"]})+ (let [result (read-uris {:uris ["metabase://collections?tree=true"]})so (get-in result [:resources 0 :content :structured-output])paths (mapv :path (:items so))](testing "A-Root and its child appear before Z-Root and its child"@@ -1506,7 +1682,7 @@:model/Document _ {:name "SUMMARY-DOC":collection_id coll-id:exploration_id expl-id}]- (let [{:keys [output]} (read-resource/read-resource+ (let [{:keys [output]} (read-uris{:uris [(str "metabase://collection/" coll-id "/items")]})](is (str/includes? output "VISIBLE-DOC"))(is (not (str/includes? output "SUMMARY-DOC"))diff --git a/test/metabase/metabot/tools/runtime_test.clj b/test/metabase/metabot/tools/runtime_test.cljnew file mode 100644index 00000000000..21d9b850604--- /dev/null+++ b/test/metabase/metabot/tools/runtime_test.clj@@ -0,0 +1,377 @@+(ns metabase.metabot.tools.runtime-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.api-scope.core :as api-scope]+ [metabase.metabot.scope :as scope]+ [metabase.metabot.tools.core :as tools]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.runtime :as tools.runtime]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++;;; ------------------------------------------------ Fixtures ------------------------------------------------------++(tools.error/defrecoverable runtime-test-no-widget!+ "There is no widget with that id."+ {:payload [:map {:closed true} [:id :int]]}+ [{:keys [id]}]+ {:message (str "Widget " id " does not exist.")+ :recovery [{:uses #{"search"} :text "Call `search` to find a widget id."}+ {:uses #{"read_resource"} :text "Or call `read_resource` on the widget collection."}]})++(defn- tool+ "A one-off `Tool` with `declared` and a body of `f`, for the runtime to drive."+ [declared f]+ (reify tools/Tool+ (declaration [_] declared)+ (handle [_ args ctx] (f args ctx))))++(def ^:private happy-tool+ (tool {:name "happy" :description "Always works."+ :args [:map {:closed true} [:n :int]]}+ (fn [{:keys [n]} ctx] {:output (str "got " n " in " (:profile-id ctx))})))++(def ^:private recoverable-tool+ (tool {:name "boom" :description "Raises a declared recoverable error."+ :args [:map {:closed true} [:id :int]]}+ (fn [{:keys [id]} _] (runtime-test-no-widget! {:id id}))))++(def ^:private unrecoverable-tool+ (tool {:name "give_up" :description "Gives up in a way only the user can act on."+ :args [:map {:closed true}]}+ (fn [_ _] (tools.error/unrecoverable!+ ::out-of-cheese {:user-message "Out of cheese. Redo from start."}))))++(def ^:private silent-unrecoverable-tool+ (tool {:name "give_up_quietly" :description "Gives up without a user-facing message."+ :args [:map {:closed true}]}+ (fn [_ _] (tools.error/unrecoverable! ::no-comment))))++(def ^:private crashing-tool+ (tool {:name "crash" :description "Throws an undeclared exception."+ :args [:map {:closed true}]}+ (fn [_ _] (throw (ex-info "SELECT * FROM secrets failed: clojure.lang.ExceptionInfo at line 1"+ {:password "hunter2"})))))++(def ^:private bad-shape-tool+ (tool {:name "bad_shape" :description "Returns something that is not a result."+ :args [:map {:closed true}]}+ (fn [_ _] {:outputs "a typo for :output"})))++(def ^:private scoped-tool+ (tool {:name "scoped" :description "Needs a scope."+ :args [:map {:closed true}] :scope "agent:sql:create"}+ (fn [_ _] {:output "ok"})))++(def ^:private memory-tool+ (tool {:name "memory" :description "Reads the memory atom out of ctx."+ :args [:map {:closed true}]}+ (fn [_ ctx] {:output (str "memory: " (pr-str (some-> (:memory-atom ctx) deref)))})))++(def ^:private multi-item-tool+ "A single-card tool that can also take several. The runtime never asks which it is."+ (reify+ tools/Tool+ (declaration [_] {:name "read_many" :description "Reads one card."+ :args [:map {:closed true} [:id :int]]})+ (handle [_ {:keys [id]} _ctx]+ (tools/with-entity {:kind :card :id id}+ (if (even? id)+ {:output (str "card " id " contents")}+ (throw (ex-info "nope" {:status-code 404})))))+ tools/BatchedTool+ (batched-declaration [_ declared]+ (-> declared+ (assoc :description "Reads several cards.")+ (assoc :args [:map {:closed true} [:ids [:sequential {:min 1} :int]]])))+ (batched-args [_ {:keys [ids]}] (mapv (fn [id] {:id id}) ids))+ (compose [_ entries _ctx] (tools/concatenated entries))))++(def ^:private entries+ (tools/entries [happy-tool recoverable-tool unrecoverable-tool silent-unrecoverable-tool+ crashing-tool bad-shape-tool scoped-tool memory-tool multi-item-tool]))++(def ^:private all-tool-names+ (into #{"search" "read_resource"} (keys entries)))++(defn- ctx+ ([] (ctx {}))+ ([overrides]+ (merge {:profile-id :sql :metabot nil :tool-names all-tool-names+ ;; The runtime takes the user's scope from ctx rather than reading+ ;; `metabase.metabot.scope/*current-user-scope*` — see `::ctx`.+ :user-scope api-scope/unrestricted}+ overrides)))++(defn- invoke+ ([tool-name args] (invoke (ctx) tool-name args))+ ([ctx tool-name args]+ (binding [scope/*current-user-scope* #{"agent:content:read"}]+ (tools.runtime/invoke entries ctx tool-name args))))++;;; ------------------------------------------------ Success -------------------------------------------------------++(deftest ^:parallel success-is-the-absence-of-an-error-test+ (let [outcome (invoke "happy" {:n 3})]+ (is (= {:output "got 3 in :sql"} outcome))+ (is (nil? (:error outcome)))+ (is (mr/validate ::tools.runtime/outcome outcome))+ (testing "nothing has to look at :structured-output to tell success from failure"+ (is (nil? (:structured-output outcome))))))++(deftest ^:parallel ctx-is-passed-to-the-handler-test+ (is (= {:output "got 1 in :nlq"} (invoke (ctx {:profile-id :nlq}) "happy" {:n 1}))))++(deftest ^:parallel memory-reaches-every-tool-test+ (testing "there is no per-tool memory allowlist: a tool gets the atom when the run has one"+ (is (= {:output "memory: {:state {}}"}+ (invoke (ctx {:memory-atom (atom {:state {}})}) "memory" {}))))+ (testing "and nil outside a conversation-backed run"+ (is (= {:output "memory: nil"} (invoke "memory" {})))))++(deftest ^:parallel stringified-scalars-are-coerced-test+ (testing "models send numbers as JSON strings; the tool's own schema says what to parse"+ (is (= {:output "got 7 in :sql"} (invoke "happy" {:n "7"})))))++;;; ------------------------------------------------ Validation ----------------------------------------------------++(deftest ^:parallel unknown-tool-test+ (let [outcome (invoke "nope" {})]+ (is (= {:class :validation :code :unknown-tool} (:error outcome)))+ (testing "the message lists what this profile does have, so the model can pick one"+ (is (str/starts-with? (:output outcome) "Tool `nope` does not exist. Available tools: "))+ (is (str/includes? (:output outcome) "happy")))))++(deftest ^:parallel invalid-arguments-test+ (let [outcome (invoke "happy" {:m 1})]+ (is (= {:class :validation :code :invalid-arguments} (:error outcome)))+ (is (= "Invalid tool arguments: `m` is not a supported argument. `n` is required."+ (:output outcome)))))++(deftest ^:parallel invalid-json-is-its-own-code-test+ (testing "malformed JSON and schema-invalid JSON are different mistakes with different repairs"+ (let [outcome (invoke "happy" {tools.runtime/raw-arguments-key "{\"n\": "})]+ (is (= {:class :validation :code :invalid-json} (:error outcome)))+ (is (= (str "Invalid tool arguments: the arguments were not valid JSON. "+ "Send the call again as a JSON object.")+ (:output outcome)))+ (testing "and the model's own malformed output is not quoted back at it"+ (is (not (str/includes? (:output outcome) "{\"n\":")))))))++;;; ------------------------------------------------ Recoverable ---------------------------------------------------++(deftest ^:parallel recoverable-renders-message-then-steps-test+ (let [outcome (invoke "boom" {:id 9})]+ (is (= {:class :recoverable :code ::runtime-test-no-widget} (:error outcome)))+ (is (= ["Widget 9 does not exist."+ "Call `search` to find a widget id."+ "Or call `read_resource` on the widget collection."]+ (str/split-lines (:output outcome))))+ (is (mr/validate ::tools.runtime/outcome outcome))))++(deftest ^:parallel recovery-steps-are-filtered-by-profile-test+ (testing "a step naming a tool this turn does not have is dropped, not rewritten"+ (is (= ["Widget 9 does not exist."+ "Call `search` to find a widget id."]+ (str/split-lines+ (:output (invoke (ctx {:tool-names #{"boom" "search"}}) "boom" {:id 9}))))))+ (testing "and with neither tool only the message survives"+ (is (= ["Widget 9 does not exist."]+ (str/split-lines+ (:output (invoke (ctx {:tool-names #{"boom"}}) "boom" {:id 9})))))))++;;; ----------------------------------------------- Unrecoverable --------------------------------------------------++(deftest ^:parallel unrecoverable-tells-the-model-only-the-code-test+ (let [outcome (invoke "give_up" {})]+ (is (= "This call failed and the user was shown the error (:metabase.metabot.tools.runtime-test/out-of-cheese). Don't retry it."+ (:output outcome)))+ (testing "the user-facing message rides on :error and never becomes :output"+ (is (= {:class :unrecoverable+ :code ::out-of-cheese+ :user-message "Out of cheese. Redo from start."}+ (:error outcome)))+ (is (not (str/includes? (:output outcome) "Out of cheese"))))))++(deftest ^:parallel unrecoverable-without-a-user-message-test+ (testing "no :user-message means the frontend shows its generic error; nothing is invented here"+ (is (= {:class :unrecoverable :code ::no-comment}+ (:error (invoke "give_up_quietly" {}))))))++(deftest ^:parallel an-undeclared-exception-is-unrecoverable-and-leaks-nothing-test+ (let [outcome (invoke "crash" {})]+ (is (= {:class :unrecoverable :code :internal} (:error outcome)))+ (is (= "This call failed and the user was shown the error (:internal). Don't retry it."+ (:output outcome)))+ (testing "neither the exception message nor its ex-data reaches the model"+ (doseq [secret ["SELECT" "secrets" "clojure.lang" "hunter2"]]+ (is (not (str/includes? (:output outcome) secret))+ (str "leaked " secret))))))++(deftest ^:parallel a-wrong-handler-result-is-our-bug-not-the-models-test+ (is (= {:class :unrecoverable :code :internal} (:error (invoke "bad_shape" {})))))++(deftest ^:parallel scope-denial-is-unrecoverable-test+ (testing "the agent cannot acquire a scope, so there is no alternative path to offer it"+ (let [outcome (tools.runtime/invoke entries (ctx {:user-scope #{}}) "scoped" {})]+ (is (=? {:class :unrecoverable :code :scope-denied} (:error outcome)))+ (testing "and the user is told which tool to ask for"+ (is (str/includes? (get-in outcome [:error :user-message]) "scoped")))))+ (testing "a satisfied scope runs the tool"+ (is (= {:output "ok"}+ (tools.runtime/invoke entries (ctx {:user-scope #{"agent:sql:*"}}) "scoped" {})))))++(deftest ^:parallel invoke-never-throws-test+ (testing "every caller has to pair a tool_use with a tool_result, so nothing escapes"+ (doseq [[tool-name args] [["happy" {:n 1}] ["happy" {}] ["nope" {}] ["boom" {:id 1}]+ ["crash" {}] ["bad_shape" {}] ["give_up" {}] ["scoped" {}]+ ["happy" nil] ["happy" "not even a map"]]]+ (testing (str tool-name " " (pr-str args))+ (let [outcome (invoke tool-name args)]+ (is (mr/validate ::tools.runtime/outcome outcome)+ (pr-str outcome)))))))++;;; --------------------------------------------- Multiple items ---------------------------------------------------++(deftest ^:parallel the-runtime-does-not-branch-test+ (testing "it calls tools.core/call; one item or several is the tool's business"+ (let [outcome (invoke "read_many" {:ids [2 3 4]})]+ (is (nil? (:error outcome)) "a partial failure is not a failed call")+ (is (= ["card 2 contents"+ "Card 3 was not found. It may not exist, or you may not have access to it."+ "Call `search` to find the entity you want and use an id from the results."+ "card 4 contents"]+ (str/split-lines (:output outcome))))+ (is (mr/validate ::tools.runtime/outcome outcome)))))++(deftest ^:parallel the-batched-declaration-is-what-the-model-sees-test+ (testing "arguments are validated against the shape the tool was offered in"+ (is (= {:class :validation :code :invalid-arguments}+ (:error (invoke "read_many" {:id 2})))+ "the single form's args are not what this tool publishes")))++(deftest ^:parallel item-failures-are-profile-filtered-test+ (testing "the same step filtering as a failed call, in the same place"+ (is (= ["card 2 contents"+ "Card 3 was not found. It may not exist, or you may not have access to it."]+ (str/split-lines+ (:output (invoke (ctx {:tool-names #{"read_many"}}) "read_many" {:ids [2 3]})))))))++(deftest ^:parallel a-call-where-every-item-failed-is-a-failed-call-test+ (testing "nothing was delivered, so the call failed. The question this used to record was which+ error it could be — there is no code for \"your five items were five different kinds of+ missing\", and collapsing them would lose the attribution the agent needs to retry. The+ answer is that the text does not have to change: `all-items-failed` carries the composed+ per-item text as its message, so the model reads exactly what a call that lost all but+ one item would have shown it, and the `:error` is what changes."+ (let [outcome (invoke "read_many" {:ids [3 5]})]+ (is (= {:class :recoverable :code :metabase.metabot.tools.core/all-items-failed}+ (:error outcome)))+ (is (= ["Card 3 was not found. It may not exist, or you may not have access to it."+ "Call `search` to find the entity you want and use an id from the results."+ "Card 5 was not found. It may not exist, or you may not have access to it."+ "Call `search` to find the entity you want and use an id from the results."]+ (str/split-lines (:output outcome))))))+ (testing "one item surviving is still a successful call, with the failure in position"+ (is (nil? (:error (invoke "read_many" {:ids [2 3]})))))+ (testing "and the per-item steps are still filtered by profile, which is why the runtime does not+ apply its \"a message may not name a tool\" rule to this one error: the message was+ assembled from text this profile had already been filtered for."+ (is (= ["Card 3 was not found. It may not exist, or you may not have access to it."]+ (str/split-lines+ (:output (invoke (ctx {:tool-names #{"read_many"}}) "read_many" {:ids [3]})))))))++(deftest ^:parallel a-renderable-output-is-rendered-at-the-boundary-test+ (testing "a tool may return a non-string renderable; this consumer wants a string and renders it"+ (let [tool (tool {:name "lines" :description "Returns a renderable."+ :args [:map {:closed true}]}+ (fn [_ _] {:output (reify tools/Renderable+ (render-text [_] "line one\nline two"))}))+ outcome (binding [scope/*current-user-scope* #{"*"}]+ (tools.runtime/invoke (tools/entries [tool])+ (ctx {:tool-names #{"lines"}})+ "lines" {}))]+ (is (= {:output "line one\nline two"} outcome))+ (is (string? (:output outcome))))))++(defn- capped-tool+ "A batched-shaped tool whose item cap lives in its `:args`, with `opts` on the `:sequential`+ entry."+ [opts]+ (tool {:name "capped" :description "Takes at most 5."+ :args [:map {:closed true}+ [:uris [:sequential (merge {:min 1 :max 5} opts) :string]]]}+ (fn [_ _] {:output "ok"})))++(defn- over-the-cap+ [tool]+ (binding [scope/*current-user-scope* #{"*"}]+ (tools.runtime/invoke (tools/entries [tool])+ (ctx {:tool-names #{"capped"}})+ "capped" {:uris ["a" "b" "c" "d" "e" "f"]})))++(deftest ^:parallel an-item-limit-is-a-schema-fact-test+ (testing "an item cap belongs in `:args`, so the runtime rejects the call before the tool runs+ and the model is told how to repair it"+ (let [outcome (over-the-cap (capped-tool nil))]+ (is (= "Invalid tool arguments: `uris` should have at most 5 elements; received an array."+ (:output outcome)))+ (is (= {:class :validation :code :invalid-arguments} (:error outcome)))))+ (testing "the generated sentence is accurate but says nothing about what to do instead, so a tool+ with teaching to do writes its own with `:error/message`. This is what resolved the open+ question the branch recorded here: `read_resource` had a hand-written count check whose+ text was better than the generated one, and this is where that text now lives."+ (let [outcome (over-the-cap (capped-tool {:error/message "must be an array of 1 to 5 URIs"}))]+ (is (= "Invalid tool arguments: `uris` must be an array of 1 to 5 URIs; received an array."+ (:output outcome)))+ (is (= {:class :validation :code :invalid-arguments} (:error outcome))))))++;;; ------------------------------------------------- render -------------------------------------------------------++(deftest ^:parallel render-rejects-unauthored-text-test+ (testing "the dev/test assertions are what make the text rule more than a convention"+ (doseq [[label message] {"a stack-trace frame" "Failed:\n\tat clojure.core$foo.invoke(core.clj:1)"+ "#error printing" "Failed: #error {:cause \"boom\"}"+ "a class name" "Failed: clojure.lang.ExceptionInfo"+ "an ANSI escape" "Failed: \u001b[31mred\u001b[0m"}]+ (testing label+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"may only carry authored text"+ (tools.runtime/render {:class :validation :code :invalid-arguments :message message}+ all-tool-names)))))))++;; Whether a declaration's text names a tool it has not declared is a property of the declaration,+;; not of a render, so `render` no longer checks it — see+;; `metabase.metabot.tools.error-test/a-declarations-text-is-profile-neutral-test`, which checks the+;; whole catalog against every tool name in the product rather than one call against one profile.++(deftest ^:parallel render-caps-the-output-test+ (let [long-message (apply str (repeat 5000 "x"))+ outcome (tools.runtime/render {:class :validation :code :invalid-arguments+ :message long-message}+ all-tool-names)]+ (is (= 4000 (count (:output outcome))))))++(deftest ^:parallel runtime-codes-are-declared-test+ (testing "the agent loop and the adapters branch on these, so the list is shared rather than+ re-spelled in each place"+ (is (= {:unknown-tool :validation+ :invalid-json :validation+ :invalid-arguments :validation+ :scope-denied :unrecoverable+ :internal :unrecoverable}+ tools.runtime/runtime-codes))+ (testing "and every one of them is reachable through invoke"+ ;; The scoped case needs a ctx that grants nothing; the rest run under the default+ ;; unrestricted one.+ (is (= #{:unknown-tool :invalid-json :invalid-arguments :scope-denied :internal}+ (set (keep (fn [[tool-name args overrides]]+ (get-in (tools.runtime/invoke entries (ctx overrides) tool-name args)+ [:error :code]))+ [["nope" {}]+ ["happy" {tools.runtime/raw-arguments-key "{"}]+ ["happy" {:m 1}]+ ["scoped" {} {:user-scope #{}}]+ ["crash" {}]])))))))diff --git a/test/metabase/metabot/tools/slackbot_query_test.clj b/test/metabase/metabot/tools/slackbot_query_test.cljindex aa41a984713..211d1753303 100644--- a/test/metabase/metabot/tools/slackbot_query_test.clj+++ b/test/metabase/metabot/tools/slackbot_query_test.clj@@ -18,8 +18,8 @@[clojure.test :refer :all][malli.json-schema :as mjs][metabase.metabot.agent.streaming :as streaming]+ [metabase.metabot.test-util :as test-util][metabase.metabot.tools.construct :as construct]- [metabase.metabot.tools.recovery-hints :as recovery-hints][metabase.metabot.tools.slackbot-query :as slackbot-query][metabase.test :as mt][metabase.test.data.users :as test.users]@@ -82,7 +82,7 @@;; These tests stub `execute-representations-query` with a fake that returns a canned;; `:structured-output` so we can assert the slackbot-specific wrapping (link construction,-;; adhoc_viz data part, instructions text, error passthrough).+;; adhoc_viz data part, output text) without the pipeline.(defn- with-repr-stub! [stub-fn f](mt/with-dynamic-fn-redefs@@ -94,10 +94,14 @@(str "/question#fake" (when display (str "?d=" display))))](f)))+(defn- call+ [arguments]+ (test-util/call-tool slackbot-query/slackbot-construct-notebook-query-tool arguments))+(deftest slackbot-tool-happy-path-test(testing (str "Slackbot tool takes an external-query map, hands it verbatim to\n"- "execute-representations-query, wraps the result in an adhoc_viz data part\n"- "with the provided title + display, and returns structured-output + instructions.")+ "execute-representations-query, and wraps the result in an adhoc_viz data part\n"+ "with the provided title + display.")(let [captured-query (atom nil)captured-opts (atom :not-called)fake-query {:lib/type :mbql/query :database 1 :stages [{:source-table 10}]}]@@ -114,17 +118,17 @@:stages [{:lib/type "mbql.stage/mbql":source-table ["Sample" "PUBLIC" "ORDERS"]:aggregation [["count" {}]]}]}- result (slackbot-query/slackbot-construct-notebook-query-tool- {:reasoning "user asked for order count"- :query query-input- :title "Monthly order volume"- :display "bar"})]+ result (call {:reasoning "user asked for order count"+ :query query-input+ :title "Monthly order volume"+ :display "bar"})](testing "external-query passed through verbatim"(is (= query-input @captured-query)))- (testing "the v1 recovery-hint fn is threaded into the pipeline as `:recovery-hint`"- ;; Guards F1's regression class: without this, dropping the `:recovery-hint` arg from- ;; the caller would leave every stubbed test green while agent errors lose their hint.- (is (= recovery-hints/recovery-hint (:recovery-hint @captured-opts))))+ (testing "no `:recovery-hint` is threaded in. A pipeline error's recovery steps come+ from its declaration in `tools.recoverable.pipeline`, filtered by the tools+ the calling profile has — passing a hint as well would append a second copy+ of the same advice."+ (is (nil? @captured-opts)))(testing "structured-output is returned upstream"(is (= "q-1" (get-in result [:structured-output :query-id])))(is (= fake-query (get-in result [:structured-output :query]))))@@ -137,8 +141,13 @@(is (= "bar" (:display data)))(is (str/starts-with? (:link data) "/question#"))(is (= fake-query (:query data)))))- (testing "instructions text mentions follow-up visualization rendering"- (is (str/includes? (:instructions result) "follow-up message")))))))))+ (testing "the model is told the visualization follows in its own message. Before, this+ tool returned `:instructions` and no `:output`, so what actually reached the+ model was the printed result map — this sentence plus the EDN of the resolved+ query."+ (is (str/includes? (:output result) "follow-up message"))+ (is (str/includes? (:output result) "future tense"))+ (is (not (str/includes? (:output result) "source-table"))))))))))(deftest slackbot-tool-no-optional-fields-test(testing (str "When title/display are absent, the adhoc_viz data part omits them (doesn't\n"@@ -151,12 +160,11 @@:result-columns []}:instructions "ok"})(fn []- (let [result (slackbot-query/slackbot-construct-notebook-query-tool- {:reasoning "simple request"- :query {:lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/mbql"- :source-table ["Sample" "PUBLIC" "ORDERS"]- :aggregation [["count" {}]]}]}})+ (let [result (call {:reasoning "simple request"+ :query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table ["Sample" "PUBLIC" "ORDERS"]+ :aggregation [["count" {}]]}]}})data (get-in result [:data-parts 0 :data])](is (= "q-x" (get-in result [:structured-output :query-id])))(is (not (contains? data :title)))@@ -164,66 +172,87 @@(is (string? (:link data)))(is (= fake-query (:query data)))))))))-(deftest slackbot-tool-agent-error-surfaces-as-output-test- (testing (str "When `execute-representations-query` throws an :agent-error? ex-info (as it\n"- "does for unknown database, malformed YAML, etc.), the slackbot wrapper\n"- "returns `{:output <message>}` so the message reaches the LLM verbatim -\n"- "no stack trace, no data-parts.")+(deftest slackbot-tool-declared-pipeline-error-test+ (testing (str "A pipeline error carrying a declared `:error` code becomes that recoverable\n"+ "error: the pipeline's own sentence, plus the recovery steps its declaration\n"+ "supplies. The tool itself says nothing about recovery.")(with-repr-stub!(fn [_external-query & _]- (throw (ex-info "Unknown database: `Sample`. Use the exact database name as reported by search / read_resource."+ (throw (ex-info "Unknown database: `Sample`."{:agent-error? true:status-code 400:error :unknown-database:database "Sample"})))(fn []- (let [result (slackbot-query/slackbot-construct-notebook-query-tool- {:reasoning "test agent-error path"- :query {:lib/type "mbql/query" :stages []}})]- (testing "bare :output key with the agent message, no structured-output or data-parts"- (is (string? (:output result)))- (is (re-find #"Unknown database" (:output result)))- (is (re-find #"Sample" (:output result)))- (is (nil? (:structured-output result)))- (is (nil? (:data-parts result)))))))))+ (let [{:keys [class code text]}+ (test-util/tool-failure slackbot-query/slackbot-construct-notebook-query-tool+ {:reasoning "test agent-error path"+ :query {:lib/type "mbql/query" :stages []}})]+ (is (= :recoverable class))+ (is (= :metabase.metabot.tools.recoverable.pipeline/unknown-database code))+ (testing "the pipeline's sentence survives verbatim"+ (is (str/includes? text "Unknown database"))+ (is (str/includes? text "Sample")))+ (testing "and the declaration's recovery step is appended"+ (is (str/includes? text "first element of every portable FK"))))))))++(deftest slackbot-tool-undeclared-error-ends-the-turn-test+ (testing (str "An exception the pipeline stamped `:agent-error?` onto without authoring a\n"+ "sentence for it is unrecoverable. Its message was written for a developer, and\n"+ "before this it went to the model as the tool's whole output.")+ (with-repr-stub!+ (fn [_external-query & _]+ (throw (ex-info "No matching clause: :metabase.lib.schema/bogus" {:agent-error? true})))+ (fn []+ (is (= {:class :unrecoverable :code :internal}+ (test-util/tool-failure slackbot-query/slackbot-construct-notebook-query-tool+ {:reasoning "foreign failure"+ :query {:lib/type "mbql/query" :stages []}})))))))++(deftest slackbot-tool-refusal-is-a-not-found-test+ (testing (str "A 403 from inside the pipeline becomes the shared not-found error rather than\n"+ "`api/read-check`'s own sentence. Before, \"You don't have permissions to do\n"+ "that.\" was handed to the model as the tool's output, which named nothing and\n"+ "offered no next step.")+ (with-repr-stub!+ (fn [_external-query & _]+ (throw (ex-info "You don't have permissions to do that." {:status-code 403})))+ (fn []+ (let [{:keys [class code text]}+ (test-util/tool-failure slackbot-query/slackbot-construct-notebook-query-tool+ {:reasoning "refused"+ :query {:lib/type "mbql/query" :stages []}})]+ (is (= :recoverable class))+ (is (= :metabase.metabot.tools.recoverable.common/not-found code))+ (is (str/includes? text "was not found"))+ (testing "and says nothing about permissions, which would leak whether it exists"+ (is (not (str/includes? text "permission")))))))))-(deftest slackbot-tool-non-agent-errors-test- (let [tool-result-for-thrown #(with-repr-stub!- (fn [_external-query & _] (throw %))- (fn []- (slackbot-query/slackbot-construct-notebook-query-tool- {:reasoning "test non-agent error path"- :query {:lib/type "mbql/query" :stages []}})))]- (testing "a permission error goes back to the agent as output"- (is (= "You don't have permissions to do that."- (:output (tool-result-for-thrown- (ex-info "You don't have permissions to do that." {:status-code 403}))))))- (testing "an unexpected error, e.g. a programming bug, propagates to the agent loop"- (is (thrown-with-msg? RuntimeException #"something went sideways"- (tool-result-for-thrown (RuntimeException. "something went sideways")))))))+(deftest slackbot-tool-bug-propagates-test+ (testing "an unexpected error, e.g. a programming bug, is not converted"+ (with-repr-stub!+ (fn [_external-query & _] (throw (RuntimeException. "something went sideways")))+ (fn []+ (is (thrown-with-msg? RuntimeException #"something went sideways"+ (call {:reasoning "bug" :query {:lib/type "mbql/query" :stages []}})))))));;; ---------------------------------------- end-to-end test --------------------------------------------------------(deftest slackbot-tool-end-to-end-test- (testing (str "End-to-end: call the slackbot tool with a YAML query against the real\n"- "application sample DB. Exercises the full repr pipeline (parse-yaml \u2192\n"- "repair \u2192 validate \u2192 resolve) plus the slackbot-specific wrapping\n"- "(query->question-url, adhoc_viz data part). Serves as a safety net for\n"- "step 14 - any future regression in the slackbot contract should surface here\n"- "without needing a live LLM loop.")+ (testing (str "End-to-end: call the slackbot tool with a real query against the real\n"+ "application sample DB. Exercises the full repr pipeline (validate → repair →\n"+ "resolve) plus the slackbot-specific wrapping (query->question-url, adhoc_viz\n"+ "data part).")(mt/with-current-user (test.users/user->id :crowberto)(let [db-name (t2/select-one-fn :name :model/Database :id (mt/id))- ;; Canonical DB name (per `repr-plan.md` step 13); `Sample` alone would- ;; short-circuit with :unknown-database.external-query {:lib/type "mbql/query":stages [{:lib/type "mbql.stage/mbql":source-table [db-name "PUBLIC" "ORDERS"]:aggregation [["count" {}]]}]}- result (slackbot-query/slackbot-construct-notebook-query-tool- {:reasoning "count the orders"- :query external-query- :title "Total orders"- :display "bar"})]+ result (call {:reasoning "count the orders"+ :query external-query+ :title "Total orders"+ :display "bar"})](testing "structured-output carries a resolved MBQL 5 query with numeric ids"(let [q (get-in result [:structured-output :query])](is (= :mbql/query (:lib/type q)))@@ -238,31 +267,26 @@(is (= "bar" (:display data)))(is (str/starts-with? (:link data) "/question#"))(is (map? (:query data)))))- (testing "canonical-DB-name happy path returns a structured-output, not an error :output"- ;; A non-agent failure (or agent-error) would clear :structured-output and put the- ;; message under :output. Sanity-check the happy-path shape.- (is (some? (:structured-output result)) (pr-str result))- (is (nil? (:output result))))))))+ (testing "and an `:output` the model can read"+ (is (string? (:output result)))+ (is (str/includes? (:output result) "Query created")))))))(deftest slackbot-tool-end-to-end-unknown-database-test- (testing (str "End-to-end error path: if the LLM writes a DB name that doesn't match any\n"- "application database, the slackbot tool returns `{:output <message>}` with\n"- "a clear `Unknown database` message (no stack trace, no data-parts). This is\n"- "the post-step-13 loud-failure behaviour - the previous silent-rewrite pass\n"- "is gone.")+ (testing (str "End-to-end error path: a DB name matching no application database is the\n"+ "declared `unknown-database` error, with the pipeline's sentence and the\n"+ "recovery step that says where a database name comes from.")(mt/with-current-user (test.users/user->id :crowberto)- (let [;; Intentionally use an impossible name so we hit :unknown-database at lookup.- external-query {:lib/type "mbql/query"+ (let [external-query {:lib/type "mbql/query":stages [{:lib/type "mbql.stage/mbql":source-table ["DefinitelyNotARealDatabaseName" "PUBLIC" "ORDERS"]:aggregation [["count" {}]]}]}- result (slackbot-query/slackbot-construct-notebook-query-tool- {:reasoning "wrong db name"- :query external-query- :display "table"})]- (testing "no structured-output, no data-parts, clear message"- (is (nil? (:structured-output result)))- (is (nil? (:data-parts result)))- (is (string? (:output result)))- (is (re-find #"Unknown database" (:output result)))- (is (re-find #"DefinitelyNotARealDatabaseName" (:output result))))))))+ {:keys [class code text]}+ (test-util/tool-failure slackbot-query/slackbot-construct-notebook-query-tool+ {:reasoning "wrong db name"+ :query external-query+ :display "table"})]+ (is (= :recoverable class))+ (is (= :metabase.metabot.tools.recoverable.pipeline/unknown-database code))+ (is (str/includes? text "Unknown database"))+ (is (str/includes? text "DefinitelyNotARealDatabaseName"))+ (is (str/includes? text "portable FK"))))))diff --git a/test/metabase/metabot/tools/timelines_test.clj b/test/metabase/metabot/tools/timelines_test.cljindex 579474c54f6..e6ff29aed2b 100644--- a/test/metabase/metabot/tools/timelines_test.clj+++ b/test/metabase/metabot/tools/timelines_test.clj@@ -1,6 +1,9 @@(ns metabase.metabot.tools.timelines-test(:require+ [clojure.string :as str][clojure.test :refer :all]+ [metabase.metabot.tools.core :as tools.core]+ [metabase.metabot.tools.error :as tools.error][metabase.metabot.tools.timelines :as tools.timelines][metabase.test :as mt]))@@ -29,6 +32,11 @@names (set (map :name items))](is (not (contains? names "Archived TL")))))))))+(defn- details+ "Call the converted `get_timeline_details` tool for `timeline-id`."+ [timeline-id]+ (tools.core/handle tools.timelines/get-timeline-details-tool {:timeline_id timeline-id} {}))+(deftest get-timeline-details-tool-test(mt/with-current-user (mt/user->id :crowberto)(mt/with-temp [:model/Collection {coll-id :id} {:name "Events Coll"}@@ -40,25 +48,25 @@:timeline_id tl-id:timestamp #t "2025-06-01T00:00:00Z":icon "star"}]- (testing "returns timeline details with events"- (let [result (tools.timelines/get-timeline-details-tool {:timeline_id tl-id})- structured (:structured_output result)]- (is (= "Releases" (:name structured)))- (is (= "Release dates" (:description structured)))- (is (= 1 (count (:events structured))))- (is (= "v1.0" (-> structured :events first :name)))))- (testing "output contains XML-formatted text with events"- (let [{:keys [output]} (tools.timelines/get-timeline-details-tool {:timeline_id tl-id})]+ (testing "the details reach the model as XML, with its events"+ (let [{:keys [output]} (details tl-id)](is (re-find #"<timeline" output))(is (re-find #"<events>" output))(is (re-find #"v1.0" output))))(testing "events render as well-formed XML (closed attribute quote and opening tag)"- (let [{:keys [output]} (tools.timelines/get-timeline-details-tool {:timeline_id tl-id})]+ (let [{:keys [output]} (details tl-id)](is (re-find #"<event id=\"\d+\" name=\"v1\.0\" timestamp=\"[^\"]+\">Initial release</event>"output))))- (testing "throws for a nonexistent timeline (read-check 404)"- (is (thrown? Exception- (tools.timelines/get-timeline-details-tool {:timeline_id Integer/MAX_VALUE})))))))+ (testing "no :structured-output: nothing reads one for a timeline"+ (is (= [:output] (keys (details tl-id)))))+ (testing "a missing timeline is a declared recoverable error, not a bare throw"+ ;; Before conversion this returned `{:structured_output nil}` with no `:output`, so the model+ ;; was shown the printed map.+ (let [e (is (thrown? clojure.lang.ExceptionInfo (details Integer/MAX_VALUE)))]+ (is (=? {:class :recoverable+ :code :metabase.metabot.tools.recoverable.common/not-found+ :message #(str/starts-with? % "Timeline ")}+ (tools.error/classify e))))))))(deftest timeline-output-xml-escaping-test(mt/with-current-user (mt/user->id :crowberto)@@ -76,7 +84,7 @@(is (re-find #"name=\"Q&A <"Launches">\"" output))(is (re-find #"Tags: <b> & "quotes"" output))))(testing "details output escapes XML-special characters in timeline and event fields"- (let [{:keys [output]} (tools.timelines/get-timeline-details-tool {:timeline_id tl-id})]+ (let [{:keys [output]} (details tl-id)](is (re-find #"name=\"Q&A <"Launches">\"" output))(is (re-find #"name=\"R&D <event> "one"\"" output))(is (re-find #"a < b & c > d" output))diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.cljindex 5f4fbaeadcd..11ba97856a7 100644--- a/test/metabase/metabot/tools_test.clj+++ b/test/metabase/metabot/tools_test.clj@@ -1,13 +1,16 @@(ns metabase.metabot.tools-test(:require+ [clojure.string :as str][clojure.test :refer :all][metabase.api-scope.core :as api-scope][metabase.channel.settings :as channel.settings][metabase.metabot.agent.profiles :as profiles][metabase.metabot.scope :as scope]+ [metabase.metabot.test-util :as test-util][metabase.metabot.tools :as agent-tools][metabase.metabot.tools.charts.create :as create-chart-tools][metabase.metabot.tools.construct :as construct]+ [metabase.metabot.tools.legacy :as tools.legacy][metabase.metabot.tools.shared :as shared][metabase.notification.models :as models.notification][metabase.search.entity-retrieval.core :as entity-retrieval]@@ -15,21 +18,21 @@[toucan2.core :as t2]))(deftest all-tools-test- (testing "profile tools are vars with required metadata"+ (testing "every tool in every profile declares itself validly, converted or not"(let [tool-vars (mapcat :tools (vals @@#'profiles/*profiles))](is (seq tool-vars))(doseq [tool-var tool-vars]- (is (var? tool-var))- (let [m (meta tool-var)]- (is (string? (:tool-name m)))- (is (some? (:schema m))))))))+ (is (var? tool-var) "a profile names every tool as a var, whichever kind it is")+ (testing (str tool-var)+ (let [{:keys [name description args]} (tools.legacy/declaration-of tool-var)]+ (is (string? name))+ (is (string? description))+ (is (some? args))))))))-(deftest wrap-tools-with-state-carries-title-fn-test- (testing "a tool var's :title-fn metadata reaches the tool-def map"- (let [wrapped (agent-tools/wrap-tools-with-state- {"search" #'agent-tools/search-tool}- (atom {}) nil nil)]- (is (fn? (get-in wrapped ["search" :title-fn]))))))+(deftest entries-carry-title-fn-test+ (testing "a tool's title function reaches the entry the adapters read"+ (let [entries (agent-tools/->entries [#'agent-tools/search-tool] (atom {}) nil nil)]+ (is (fn? (get-in entries ["search" :title-fn]))))))(deftest filter-by-capabilities-test(testing "returns tools with no capability requirements when capabilities empty"@@ -41,7 +44,7 @@#'agent-tools/create-sql-query-tool]capabilities #{}result (#'profiles/filter-by-capabilities tool-vars capabilities)]- (is (= ["search"] (mapv #(:tool-name (meta %)) result)))))+ (is (= ["search"] (mapv #(:name (tools.legacy/declaration-of %)) result)))))(testing "includes tools when capabilities are provided"(let [tool-vars [#'agent-tools/search-tool #'agent-tools/create-sql-query-tool #'agent-tools/create-chart-tool]capabilities #{:permission-write-sql-queries}@@ -137,12 +140,18 @@(is (empty? tools))))(deftest ^:parallel get-tools-for-profile-metadata-test- (let [tools (tools-for-profile :embedding_next)]- (doseq [[tool-name tool-var] tools]- (is (var? tool-var))- (is (string? tool-name))- (is (= tool-name (:tool-name (meta tool-var))))- (is (some? (:schema (meta tool-var)))))))+ (testing "a profile's registry is keyed by the name each tool declares, whether that tool is a+ record or still an `mu/defn` var. The declaration is the source of truth either way —+ reading `:tool-name` off the var only worked while every tool was the second kind."+ (let [tools (tools-for-profile :embedding_next)]+ (is (seq tools))+ (doseq [[tool-name tool-var] tools]+ (is (var? tool-var))+ (is (string? tool-name))+ (let [{declared-name :name :keys [description args]} (tools.legacy/declaration-of tool-var)]+ (is (= tool-name declared-name))+ (is (string? description))+ (is (some? args)))))))(deftest search-tool-test(testing "search-tool var has valid metadata"@@ -175,12 +184,12 @@:source-table ["Sample" "PUBLIC" "ORDERS"]:aggregation [["count" {}]]}]}result (binding [shared/*profile-id* :nlq]- (agent-tools/construct-notebook-query-tool- {:reasoning "check seats"- :query query-input- :title "Seat check"- :description "Total order count."- :visualization {:chart_type "table"}}))]+ (test-util/call-tool agent-tools/construct-notebook-query-tool+ {:reasoning "check seats"+ :query query-input+ :title "Seat check"+ :description "Total order count."+ :visualization {:chart_type "table"}}))](is (= query-input @query-captured))(is (= "c-1" (get-in result [:structured-output :chart-id])))(is (= "q-1" (get-in result [:structured-output :query-id])))@@ -193,7 +202,7 @@(let [construct! (fn [tool-names show-chart-arg](let [chart-created? (atom false)](mt/with-dynamic-fn-redefs [construct/execute-representations-query- (fn [_ _]+ (fn [_ & _]{:structured-output {:query-id "q-1":query {:database 1}:result-columns []}})@@ -203,7 +212,8 @@{:chart-id "c-1", :chart-type :table})](let [result (binding [shared/*profile-id* :nlqshared/*memory-atom* (atom {:tool-names tool-names})]- (agent-tools/construct-notebook-query-tool+ (test-util/call-tool+ agent-tools/construct-notebook-query-tool(merge {:query {:lib/type "mbql/query", :stages []}:title "Seat check":description "Total order count."}@@ -223,87 +233,82 @@(is (= {:chart? true, :shown? true, :query-id "q-1", :run-it? false}(construct! #{"construct_notebook_query"} {:show_chart false}))))))-(defn- construct-tool-output-for-thrown- "Run `construct_notebook_query` with `execute-representations-query` throwing `e`.- Returns the `:output` the LLM would see when the tool handles `e`; otherwise `e` propagates."+(defn- construct-tool-failure-for-thrown+ "Run `construct_notebook_query` with `execute-representations-query` throwing `e`, and return the+ failure the model 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."})))))+ (mt/with-dynamic-fn-redefs [construct/execute-representations-query (fn [_ & _] (throw e))]+ (binding [shared/*profile-id* :nlq]+ (test-util/tool-failure agent-tools/construct-notebook-query-tool+ {:query {:lib/type "mbql/query" :stages []}+ :title "Seat check"+ :description "Total order count."}+ #{"read_resource" "search"}))))(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 "an unexpected error propagates to the agent loop"- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"something went sideways"- (construct-tool-output-for-thrown- (ex-info "something went sideways" {}))))))+ (testing (str "a 403 from inside the pipeline becomes the shared not-found error. Before, "+ "`api/read-check`'s own sentence went to the model as the tool's output, which "+ "named no entity and offered no next step — and told the model that something it "+ "could not see exists.")+ (let [{:keys [class code text]}+ (construct-tool-failure-for-thrown+ (ex-info "You don't have permissions to do that." {:status-code 403}))]+ (is (= :recoverable class))+ (is (= :metabase.metabot.tools.recoverable.common/not-found code))+ (is (str/includes? text "was not found"))+ (is (not (str/includes? text "permission")))))+ (testing (str "a declared pipeline code keeps the pipeline's sentence and gains its "+ "declaration's recovery step")+ (let [{:keys [class code text]}+ (construct-tool-failure-for-thrown+ (ex-info "No table found matching portable FK [\"Sample\" nil \"ORDRS\"]."+ {:agent-error? true :status-code 400 :error :unknown-table}))]+ (is (= :recoverable class))+ (is (= :metabase.metabot.tools.recoverable.pipeline/unknown-table code))+ (is (str/includes? text "No table found matching portable FK"))+ (is (str/includes? text "metabase://database/<numeric id>/tables"))))+ (testing (str "an exception nobody authored a model-facing sentence for ends the turn, whether "+ "or not the pipeline stamped `:agent-error?` onto it. `as-agent-input-error` "+ "stamps the flag on failures from lib, toucan2 and JDBC as well, so the flag alone "+ "never meant the message was written for anyone — only a declared `:error` code "+ "does.")+ (doseq [[what e] {"stamped by the pipeline, no :error code"+ (ex-info "No matching clause: :metabase.lib.schema/bogus" {:agent-error? true})-(deftest state-dependent-tools-test- (testing "state-dependent-tools set contains expected tools"- (is (contains? @#'agent-tools/state-dependent-tools "create_chart"))- (is (contains? @#'agent-tools/state-dependent-tools "edit_chart"))- (is (contains? @#'agent-tools/state-dependent-tools "create_sql_query"))- (is (contains? @#'agent-tools/state-dependent-tools "edit_sql_query"))- (is (contains? @#'agent-tools/state-dependent-tools "replace_sql_query"))- (is (contains? @#'agent-tools/state-dependent-tools "construct_notebook_query"))- (is (contains? @#'agent-tools/state-dependent-tools "todo_write"))- (is (contains? @#'agent-tools/state-dependent-tools "todo_read"))- (is (contains? @#'agent-tools/state-dependent-tools "create_autogenerated_dashboard"))- (is (contains? @#'agent-tools/state-dependent-tools "document_schema_collect"))- (is (contains? @#'agent-tools/state-dependent-tools "document_construct_sql_chart"))- (is (contains? @#'agent-tools/state-dependent-tools "document_construct_model_chart"))- (is (contains? @#'agent-tools/state-dependent-tools "create_alert"))- (is (contains? @#'agent-tools/state-dependent-tools "create_dashboard_subscription"))- (is (contains? @#'agent-tools/state-dependent-tools "static_viz"))- (is (contains? @#'agent-tools/state-dependent-tools "read_resource"))- (is (contains? @#'agent-tools/state-dependent-tools "run_query"))))+ "an ordinary bug"+ (ex-info "something went sideways" {})}]+ (testing what+ (is (= {:class :unrecoverable :code :internal}+ (construct-tool-failure-for-thrown e)))))))-(deftest wrap-tools-with-state-test- (testing "wraps state-dependent tools with state injection"- (let [memory-atom (atom {:state {:queries {"q1" {:database 1}}- :charts {"c1" {:query-id "q1"}}}})- base-tools {"create_sql_query" #'agent-tools/create-sql-query-tool- "search" #'agent-tools/search-tool}- wrapped-tools (agent-tools/wrap-tools-with-state base-tools memory-atom nil :nlq)]- ;; State-dependent tool should be wrapped into a tool-def map- (is (map? (get wrapped-tools "create_sql_query")))- (is (contains? (get wrapped-tools "create_sql_query") :fn))- (is (contains? (get wrapped-tools "create_sql_query") :doc))- (is (contains? (get wrapped-tools "create_sql_query") :schema))- ;; Non-state-dependent tool should also be a tool-def map- (is (map? (get wrapped-tools "search")))))- (testing "wrapped tools preserve original metadata"- (let [memory-atom (atom {:state {:queries {} :charts {}}})- base-tools {"create_chart" #'agent-tools/create-chart-tool}- wrapped-tools (agent-tools/wrap-tools-with-state base-tools memory-atom nil :nlq)- wrapped-tool (get wrapped-tools "create_chart")]- (is (= (:doc (meta #'agent-tools/create-chart-tool)) (:doc wrapped-tool)))- (is (= (:schema (meta #'agent-tools/create-chart-tool)) (:schema wrapped-tool)))))- (testing "wrapped function receives augmented args with state"- (let [memory-atom (atom {:state {:queries {"test-query" {:db 1}}- :charts {"test-chart" {:type :bar}}}})- wrapped (agent-tools/wrap-tools-with-state {"create_sql_query" #'agent-tools/create-sql-query-tool} memory-atom nil :nlq)- wrapped-fn (get-in wrapped ["create_sql_query" :fn])]- ;; Just verify the wrapped function is callable- (is (fn? wrapped-fn))))- (testing "non-state-dependent tools are also wrapped into tool-def maps"- (let [memory-atom (atom {:state {:queries {"q1" {:db 1}} :charts {}}})- base-tools {"search" #'agent-tools/search-tool- "construct_notebook_query" #'agent-tools/construct-notebook-query-tool}- wrapped-tools (agent-tools/wrap-tools-with-state base-tools memory-atom nil :nlq)]- ;; All tools are converted to tool-def maps- (is (map? (get wrapped-tools "search")))- (is (fn? (:fn (get wrapped-tools "search"))))- (is (map? (get wrapped-tools "construct_notebook_query")))- (is (fn? (:fn (get wrapped-tools "construct_notebook_query")))))))+(deftest ->entries-test+ (testing "an entry carries what the adapters and the system message read"+ (let [entries (agent-tools/->entries [#'agent-tools/create-sql-query-tool+ #'agent-tools/search-tool]+ (atom {:state {:queries {} :charts {}}}) nil :nlq)]+ (doseq [tool-name ["create_sql_query" "search"]]+ (testing tool-name+ (let [entry (get entries tool-name)]+ (is (map? entry))+ (is (= tool-name (:tool-name entry)))+ (is (string? (:doc entry)))+ (is (some? (:schema entry)))+ (is (fn? (:fn entry))))))))+ (testing "an unconverted tool's schema comes from its var metadata"+ (let [entries (agent-tools/->entries [#'agent-tools/create-chart-tool] (atom {}) nil :nlq)+ [_:=> [_:cat declared] _out] (:schema (get entries "create_chart"))+ [_:=> [_:cat original] _out] (:schema (meta #'agent-tools/create-chart-tool))]+ (is (= original declared))))+ (testing "a converted tool and an unconverted one sit side by side"+ (let [entries (agent-tools/->entries [#'agent-tools/list-timelines-tool ; mu/defn var+ #'agent-tools/get-timeline-details-tool] ; record+ (atom {}) nil :nlq)]+ (is (= #{"list_timelines" "get_timeline_details"} (set (keys entries))))+ (is (every? fn? (map :fn (vals entries))))))+ (testing "the entry's :fn goes through the runtime, so it reports rather than throws"+ (let [entries (agent-tools/->entries [#'agent-tools/search-tool] (atom {}) nil :nlq)+ outcome ((get-in entries ["search" :fn]) {:not_an_argument true})]+ (is (=? {:error {:class :validation :code :invalid-arguments}} outcome)))))(deftest tool-schemas-exclude-state-keys-test(testing "create_chart schema does not expose state keys"