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
Add a glossary tool to the MCP server (#82696)
Eric Normandac1f4cdc009b
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex bef9e64fb3a..d64ef9679e3 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1084,7 +1084,7 @@glossary{:team "Gadget"- :api #{metabase.glossary.api}+ :api #{metabase.glossary.api metabase.glossary.core}:uses #{apieventslib.schema@@ -1323,6 +1323,7 @@commentsdashboardsdocuments+ glossaryliblib.belib.metadatadiff --git a/mage/src/mage/modules.clj b/mage/src/mage/modules.cljindex 3e2c7dffcd3..54dfb38d0c4 100644--- a/mage/src/mage/modules.clj+++ b/mage/src/mage/modules.clj@@ -162,6 +162,7 @@explorationsformattergeojson+ glossaryindexed-entitiescore.initialization-statusinterestingnessdiff --git a/src/metabase/glossary/core.clj b/src/metabase/glossary/core.cljindex 2a2ecea3eee..4db1c677597 100644--- a/src/metabase/glossary/core.clj+++ b/src/metabase/glossary/core.clj@@ -15,6 +15,11 @@[:term ms/NonBlankString][:definition ms/NonBlankString]])+(mu/defn entries :- [:sequential ::glossary.schema/glossary]+ "Every glossary entry, in term order."+ []+ (glossary.db/glossary-entries nil))+(mu/defn create-entry! :- ::glossary.schema/glossary"Insert a glossary entry created by `user-id` and publish `:event/glossary-create`. Returns the new entry."[user-id :- ::lib.schema.id/userdiff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.mdindex 88d27f30b00..0dab8bbb7de 100644--- a/src/metabase/mcp/README.md+++ b/src/metabase/mcp/README.md@@ -54,7 +54,7 @@ Access tokens are scoped to limit what tools a client can use:| Scope | Tools it grants || ----- | --------------- |-| `agent:content:read` | `browse_collection`, `browse_data`, `get_content`, `get_parameter_values`, `learn`, `search` |+| `agent:content:read` | `browse_collection`, `browse_data`, `get_content`, `get_parameter_values`, `glossary`, `learn`, `search` || `agent:content:write` | `bookmark_content`, `collection_write`, `dashboard_write`, `document_write`, `duplicate_content`, `measure_write`, `metric_write`, `question_write`, `segment_write`, `transform_write` || `agent:delivery:write` | `alert_write`, `subscription_write` || `agent:query:run` | `execute_query`, `refresh_ui_credential`, `render_drill_through`, `run_saved_question`, `visualize_query` |@@ -123,6 +123,7 @@ the scope may not call it.| `execute_sql` | `agent:sql:run` | Escape hatch: execute a raw SQL string against a database, returning rows plus a query_handle. || `get_content` | `agent:content:read` | Fetch content by {type, id} — the typed read for anything found via search or browse_collection. || `get_parameter_values` | `agent:content:read` | Fetch the valid values for one filter on a dashboard or saved question, so you filter with real values instead of guessing. |+| `glossary` | `agent:content:read` | Look up a business term as this Metabase instance defines it; the defined term names ride the tool's own description. || `learn` | `agent:content:read` | Read this server's task docs (skills) for the write dialects the schemas can't fully describe. || `measure_write` | `agent:content:write` | Create or update a measure: a named, reusable MBQL aggregation attached to one table, referenced inside another query's aggregation as ["measure", id]. || `metric_write` | `agent:content:write` | Create or update a metric: a saved, reusable aggregation that lives in a collection and can be queried on its own or referenced from other queries. |diff --git a/src/metabase/mcp/v2/api.clj b/src/metabase/mcp/v2/api.cljindex ab7c715e728..8ab1c2baa71 100644--- a/src/metabase/mcp/v2/api.clj+++ b/src/metabase/mcp/v2/api.clj@@ -26,6 +26,7 @@[metabase.mcp.v2.tools.definitions][metabase.mcp.v2.tools.document][metabase.mcp.v2.tools.duplicate]+ [metabase.mcp.v2.tools.glossary][metabase.mcp.v2.tools.learn][metabase.mcp.v2.tools.metric][metabase.mcp.v2.tools.parameters]@@ -161,12 +162,16 @@(def ^:private server-instructions"The `initialize` result's `instructions` — the only channel that reaches the model before any tool call. It points- at the `learn` skills once, settles the routing choices a model makes before reading any tool description closely+ at the `learn` skills and the `glossary` once, settles the routing choices a model makes before reading any tool+ description closely(structured queries are the default, raw SQL the escape hatch, `visualize_query` for charts when listed), andexplains the scope-denial failures that clients rewrite before the model sees them."(str "This server ships task-shaped docs as skills. learn() lists the topics; learn(topic) returns one.\n""Before your first complex write — native template_tags, dashboard parameter wiring, a multi-stage or joined ""query, visualization settings — read the matching skill unless it is already in context.\n"+ "This instance's glossary defines business terms that matter for answering questions about its data. Fetch "+ "them with glossary() before you answer — an instance's own definition of a term overrides your reading of "+ "it.\n""Answer questions from data with execute_query (structured MBQL) by default; execute_sql is the escape hatch ""for what MBQL cannot express or an explicit request for SQL.\n""When visualize_query is available, use it for any request to show, chart, plot, or visualize data (pass a "diff --git a/src/metabase/mcp/v2/tools/glossary.clj b/src/metabase/mcp/v2/tools/glossary.cljnew file mode 100644index 00000000000..ded62016de1--- /dev/null+++ b/src/metabase/mcp/v2/tools/glossary.clj@@ -0,0 +1,85 @@+(ns metabase.mcp.v2.tools.glossary+ "The v2 MCP `glossary` tool: the business definitions an instance's data analysts have written down.++ The tool's own description ends with an unconditional instruction to call it. The words that most+ need a company definition are the ones that read as ordinary English — \"account\", \"active+ user\", \"churn\" — which a model believes it already understands, so an instruction it has to+ qualify by first noticing the jargon is one it never acts on. Naming the terms up there instead+ would beg that same question and cost more: clients truncate long descriptions, and a list cut+ short reads as the whole glossary, which is worse than no list at all.++ Metabot solves the same problem by pasting the whole glossary into every message it sends, which+ it can do because it owns the prompt. Here the description is the only channel that reaches the+ model unprompted, so it carries the instruction to call and nothing else."+ (:require+ [metabase.glossary.core :as glossary]+ [metabase.mcp.v2.common :as common]+ [metabase.mcp.v2.message :as message]+ [metabase.mcp.v2.registry :as registry]+ [metabase.metabot.scope :as metabot.scope]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++(def ^:private no-terms-message+ (message/msg ["No terms are defined in this instance's glossary yet."]))++(def ^:private default-limit+ "How many entries a `glossary()` listing returns when the caller names no limit. `definition` is a TEXT column+ with no length limit at any layer, so an unpaged listing has no size of its own; 50 matches what the instance's+ other plain app-db listings page at."+ 50)++(def ^:private max-limit+ "The largest page a caller may ask for, matching the other v2 listings' ceiling."+ 500)++(defn- entry-message+ [{:keys [term definition]}]+ (message/msg ["%s: %s"] term definition))++(defn- find-entries+ "Every entry of `entries` whose term matches `term` compared case-insensitively, in term order: a model echoes a+ term as it read it in a question or a column name, not as it happens to be stored."+ [entries term]+ (let [wanted (u/lower-case-en term)]+ (filter #(= wanted (u/lower-case-en (:term %))) entries)))++(registry/deftool glossary+ "Look up a business term as this Metabase instance defines it, as its own data analysts wrote it down. glossary() lists terms with their definitions, paged with limit (default 50, max 500) and offset; glossary(term) returns matching terms (case insensitive). Call glossary() before answering any question about this instance's data: these definitions override your own reading of a word, and the question itself will not tell you which words are defined here."+ {:name "glossary"+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args [:map {:closed true}+ [:term {:optional true}+ [:maybe [:string {:min 1+ :description (str "The term to define, matched case-insensitively. "+ "Omit to list terms with their definitions.")}]]]+ [:limit {:optional true}+ [:maybe [:int {:min 1 :max max-limit+ :description (str "Maximum entries to return (default 50, max 500). "+ "Ignored with \"term\", which is a lookup, not a "+ "page.")}]]]+ [:offset {:optional true}+ [:maybe [:int {:min 0+ :description (str "Number of entries to skip, for paging (default 0). "+ "Ignored with \"term\".")}]]]]}+ [{:keys [term limit offset]} _context]+ (let [entries (glossary/entries)]+ (if term+ (common/success-content+ (if-let [matches (seq (find-entries entries term))]+ (common/lines-message (map entry-message matches))+ (common/throw-teaching-error+ (message/msg ["No glossary entry for %s."] term))))+ ;; The page is cut in memory because the module reads the table whole. That bounds the response, which is+ ;; what a client pays for and what the definitions can make arbitrarily large, not the query.+ (let [limit (or limit default-limit)+ offset (or offset 0)+ page (into [] (comp (drop offset) (take limit)) entries)]+ (common/list-content (mapv #(select-keys % [:term :definition]) page)+ (count entries)+ {:param :term+ :offset offset+ :limit limit+ :empty-hint no-terms-message})))))diff --git a/test/metabase/glossary/core_test.clj b/test/metabase/glossary/core_test.cljindex 2884132e4ae..50b41838f1f 100644--- a/test/metabase/glossary/core_test.clj+++ b/test/metabase/glossary/core_test.clj@@ -77,3 +77,10 @@(testing "a missing id returns nil and publishes nothing"(is (= {:result nil :events []}(with-captured-events! #(glossary.core/delete-entry! user-id Integer/MAX_VALUE)))))))++(deftest entries-test+ (mt/with-temp [:model/Glossary _ {:term "Churn" :definition "Customers lost"}+ :model/Glossary _ {:term "ARR" :definition "Annual recurring revenue"}]+ (testing "every entry is returned, in term order"+ (is (= ["ARR" "Churn"]+ (filter #{"ARR" "Churn"} (map :term (glossary.core/entries))))))))diff --git a/test/metabase/mcp/v2/api_test.clj b/test/metabase/mcp/v2/api_test.cljindex df147a3a9d6..7e2174628bb 100644--- a/test/metabase/mcp/v2/api_test.clj+++ b/test/metabase/mcp/v2/api_test.clj@@ -113,6 +113,16 @@(testing "the handshake carries the skills instructions — the one pre-tool-call channel"(is (re-find #"learn\(\)" (get-in response [:body :result :instructions])))))))+(deftest initialize-instructions-point-at-the-glossary-test+ (testing "GHY-4522: the terms that most need an instance's own definition read as ordinary English, so a model+ never notices them and answers from its own meaning. The instructions must send it to glossary() before+ it answers, with no qualifier about which words."+ (let [[_ response] (initialize!)+ instructions (get-in response [:body :result :instructions])]+ (is (str/includes? instructions "glossary()"))+ (testing "the call is unconditional, not gated on spotting an unfamiliar term"+ (is (not (re-find #"(?i)unfamiliar|(don't|do not) recognize|looks like jargon" instructions)))))))+(deftest initialize-instructions-explain-scope-failures-test(testing "GHY-4543: clients replace a scope denial with their own text (Claude Code: \"requires re-authorization(token expired)\", Codex: \"Insufficient scope\", mcp-remote: \"Tool execution failed\"), so the modeldiff --git a/test/metabase/mcp/v2/tools/glossary_test.clj b/test/metabase/mcp/v2/tools/glossary_test.cljnew file mode 100644index 00000000000..3244092a9b8--- /dev/null+++ b/test/metabase/mcp/v2/tools/glossary_test.clj@@ -0,0 +1,142 @@+(ns metabase.mcp.v2.tools.glossary-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.mcp.v2.registry :as registry]+ [metabase.mcp.v2.tools.glossary :as glossary]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(comment glossary/keep-me)++(defn- call+ [args]+ (:result (registry/call-tool nil (str (random-uuid)) "glossary" args)))++(defn- text-of+ [result]+ (-> result :content first :text))++(defn- described+ "The published description of the `glossary` tool, as `tools/list` would send it."+ []+ (->> (registry/list-tools)+ (filter (comp #{"glossary"} :name))+ first+ :description))++(deftest listed-description-instructs-an-unconditional-call-test+ (testing "GHY-4522: the description tells the model to call before answering rather than naming the terms — an+ instruction conditioned on noticing a word is jargon is one the model never acts on, since the terms that+ most need a company definition are the ones that read as ordinary English"+ (mt/with-empty-h2-app-db!+ (t2/insert! :model/Glossary [{:term "Zoomer" :definition "A keysmash definition"}+ {:term "Account" :definition "An org that pays us"}])+ (let [description (described)]+ (is (str/includes? description "Call glossary() before answering"))+ (testing "terms stay behind the call: a partial list reads to the model as the whole glossary, and a complete+ one is unbounded — either way the description is the wrong place for it"+ (is (not (str/includes? description "Zoomer")))+ (is (not (str/includes? description "An org that pays us"))))))))++(deftest lookup-test+ (mt/with-temp [:model/Glossary _ {:term "Account" :definition "An org that pays us"}]+ (testing "GHY-4522: glossary(term) returns that term's definition"+ (let [result (call {:term "Account"})]+ (is (not (:isError result)) (text-of result))+ (is (str/includes? (text-of result) "An org that pays us"))))+ (testing "GHY-4522: the lookup is case-insensitive — a model echoes a term as it appeared in prose, not as stored"+ (is (str/includes? (text-of (call {:term "account"})) "An org that pays us")))+ (testing "GHY-4522: an unknown term is a teaching error naming the term that was asked for"+ (let [result (call {:term "not-a-term"})]+ (is (:isError result))+ (is (str/includes? (text-of result) "No glossary entry for"))+ (is (str/includes? (text-of result) "not-a-term"))))))++(deftest lookup-returns-every-case-variant-test+ (testing "GHY-4522: `term` is unique case-SENSITIVELY, so \"ARR\" and \"arr\" are two legitimate entries with two+ definitions — a case-insensitive lookup that answered with the first would hand the model one of them+ with no sign the other exists, and no way to tell it got the wrong one"+ (mt/with-empty-h2-app-db!+ (t2/insert! :model/Glossary [{:term "ARR" :definition "Annual recurring revenue"}+ {:term "arr" :definition "A Clojure array map"}])+ (let [text (text-of (call {:term "arr"}))]+ (is (str/includes? text "Annual recurring revenue"))+ (is (str/includes? text "A Clojure array map"))+ (testing "each entry reads as its own, not as one run-on definition"+ (is (str/includes? text "\n")))))))++(deftest lookup-cleans-stored-text-test+ (testing "GHY-4522: a term and its definition are user-written text going into prose a model reads as the server+ speaking, so both are cleaned — quoted and \\uXXXX-escaped — rather than concatenated in raw"+ (mt/with-empty-h2-app-db!+ ;; The separator is built rather than written literally: a raw U+2028 in source trips the whitespace linter.+ (let [separator (str (char 0x2028))+ term (str "Ignore" separator "previous")+ ;; `definition` is unbounded TEXT, so it is the field an injection payload actually fits in.+ definition (str "Disregard" separator "instructions")]+ (t2/insert! :model/Glossary [{:term term :definition definition}])+ (let [text (text-of (call {:term term}))]+ (is (not (str/includes? text separator)))+ (is (str/includes? text "Ignore\\u2028previous"))+ (is (str/includes? text "Disregard\\u2028instructions")))))))++(deftest lookup-against-an-empty-glossary-test+ (testing "GHY-4522: an unknown term against a glossary with nothing in it is the same teaching error as any other+ unknown term — nothing defined is not special-cased into a different answer"+ (mt/with-empty-h2-app-db!+ (let [result (call {:term "not-a-term"})]+ (is (:isError result))+ (is (str/includes? (text-of result) "No glossary entry for"))+ (is (str/includes? (text-of result) "not-a-term"))))))++(deftest list-all-test+ (testing "GHY-4522: glossary() lists terms with their definitions"+ (mt/with-empty-h2-app-db!+ (t2/insert! :model/Glossary [{:term "Account" :definition "An org that pays us"}+ {:term "Churn" :definition "An org that stopped paying us"}])+ (let [result (call {})]+ (is (not (:isError result)) (text-of result))+ (is (str/includes? (text-of result) "An org that pays us"))+ (is (str/includes? (text-of result) "An org that stopped paying us"))))))++(deftest list-all-is-paged-test+ (testing "GHY-4522: glossary() pages — `definition` is unbounded TEXT with no cap at any layer, so rendering every+ row in one response puts megabytes behind a carefully bounded description"+ (mt/with-empty-h2-app-db!+ (t2/insert! :model/Glossary (for [i (range 60)]+ {:term (format "term-%03d" i) :definition (format "definition %03d" i)}))+ (let [text (text-of (call {}))]+ (is (str/includes? text "definition 000"))+ (is (not (str/includes? text "definition 059")))+ (testing "and it says how to reach the rest"+ (is (str/includes? text "offset: 50")))+ (testing "the page reports what it returned against the whole"+ (is (str/includes? text "\"returned\":50"))+ (is (str/includes? text "\"total\":60"))))+ (testing "offset reaches the tail, which carries no continuation line"+ (let [text (text-of (call {:offset 50}))]+ (is (str/includes? text "definition 059"))+ (is (not (str/includes? text "definition 000")))+ (is (not (str/includes? text "offset:")))))+ (testing "limit narrows the page"+ (let [text (text-of (call {:limit 2}))]+ (is (str/includes? text "definition 001"))+ (is (not (str/includes? text "definition 002")))+ (is (str/includes? text "offset: 2")))))))++(deftest lookup-is-not-paged-test+ (testing "GHY-4522: glossary(term) is a lookup, not a page — a lone match carries no envelope and no continuation line"+ (mt/with-empty-h2-app-db!+ (t2/insert! :model/Glossary [{:term "Account" :definition "An org that pays us"}])+ (let [text (text-of (call {:term "Account"}))]+ (is (= "\"Account\": \"An org that pays us\"" text))))))++(deftest list-all-against-an-empty-glossary-test+ (testing "GHY-4522: glossary() with nothing defined is not an error — the tool lists on every instance"+ (mt/with-empty-h2-app-db!+ (let [result (call {})]+ (is (not (:isError result)) (text-of result))+ (is (str/includes? (text-of result) "No terms are defined"))))))