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
MCP: signal tool-list changes to clients (GHY-3661) (#74679)
bryan07cf45934574
diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.cljindex e9d8b13058e..66a864996b7 100644--- a/src/metabase/mcp/api.clj+++ b/src/metabase/mcp/api.clj@@ -67,7 +67,7 @@(jsonrpc-responseid{:protocolVersion protocol-version- :capabilities {:tools {} :resources {}}+ :capabilities {:tools {:listChanged true} :resources {}}:serverInfo server-info}))(defn- handle-tools-list [id _params token-scopes]@@ -256,10 +256,18 @@:else(json-response 200 responses))))))))+(def ^:private tools-list-changed-notification+ {:jsonrpc "2.0" :method "notifications/tools/list_changed"})+(defn- handle-get- "Handle a GET request for SSE stream (keepalive for server-initiated notifications)."+ "Handle a GET request for SSE stream (keepalive for server-initiated notifications).+ Polls the tool manifest hash on each keepalive tick — if the visible tool set has+ changed since the previous tick, emits an MCP `notifications/tools/list_changed`+ message so the client knows to refetch `tools/list`. Stateless: each connection+ tracks its own last-seen hash; no shared registry."[user-id request respond raise](let [session-id (get-in request [:headers "mcp-session-id"])+ token-scopes (:token-scopes request){:keys [error]} (require-valid-session user-id session-id)](cond(some? error)@@ -272,12 +280,16 @@:status 200}[os canceled-chan](let [writer (BufferedWriter. (OutputStreamWriter. os StandardCharsets/UTF_8))]- (loop []+ (loop [last-hash (mcp.tools/tools-hash token-scopes)](when-not (a/poll! canceled-chan)(.write writer ": keepalive\n\n")(.flush writer)(Thread/sleep 30000)- (recur)))))]+ (let [current-hash (mcp.tools/tools-hash token-scopes)]+ (when (not= current-hash last-hash)+ (.write writer ^String (sse-body [tools-list-changed-notification]))+ (.flush writer))+ (recur current-hash))))))](compojure.response/send* resp request respond raise)))))(defn- handle-deletediff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.cljindex 806dc554c23..a5a7d9ec2ef 100644--- a/src/metabase/mcp/tools.clj+++ b/src/metabase/mcp/tools.clj@@ -163,6 +163,29 @@(select-keys tool [:name :title :description :inputSchema :outputSchema :annotations :_meta]))))(concat tools (mcp.resources/list-ui-tools)))))+(defn- pad-left+ [^String s width]+ (if (>= (count s) width)+ s+ (str (apply str (repeat (- width (count s)) \0)) s)))++(defn tools-hash+ "Return a stable hash of the tool list visible to `token-scopes`, formatted as+ an 8-character unsigned hex string. Used by the SSE keepalive loop to detect+ manifest changes and emit `notifications/tools/list_changed`. Hashes the JSON+ encoding of `[name inputSchema outputSchema]` per tool, sorted by name, so the+ result is determined purely by the wire-visible schema bytes — no reliance on+ Clojure's `hash` of map values (which can be unstable for non-data leaves+ like functions, and is order-sensitive for some collection types)."+ [token-scopes]+ (-> (->> (list-tools token-scopes)+ (map (juxt :name :inputSchema :outputSchema))+ (sort-by first)+ json/encode+ hash)+ (Integer/toUnsignedString 16)+ (pad-left 8)))+(defn- build-tool-index"Build name->tool lookup from manifest tools."[tools]diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex 624553d5bb2..0b87d4e268e 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -198,7 +198,7 @@(is (= 1 (get-in response [:body :id])))(let [result (get-in response [:body :result])](is (= "2025-03-26" (:protocolVersion result)))- (is (= {:tools {} :resources {}} (:capabilities result)))+ (is (= {:tools {:listChanged true} :resources {}} (:capabilities result)))(is (= {:name "metabase" :version "0.1.0"} (:serverInfo result)))))))(deftest notifications-initialized-testdiff --git a/test/metabase/mcp/tools_test.clj b/test/metabase/mcp/tools_test.cljindex e03fd55150e..2bbeecaa3da 100644--- a/test/metabase/mcp/tools_test.clj+++ b/test/metabase/mcp/tools_test.clj@@ -2,11 +2,14 @@"scope-matches? tests moved to [[metabase.mcp.scope-test]]."(:require[clojure.test :refer :all]- [metabase.mcp.tools]))+ [clojure.walk :as walk]+ [metabase.api.macros.scope :as api.scope]+ [metabase.mcp.tools :as mcp.tools]+ [metabase.util.json :as json]))(deftest ^:parallel drop-nil-args-test(testing "strips nil-valued top-level keys so 'missing' and 'explicit nil' are equivalent at the MCP boundary"- (let [drop-nil-args (var-get #'metabase.mcp.tools/drop-nil-args)]+ (let [drop-nil-args (var-get #'mcp.tools/drop-nil-args)](testing "removes top-level nils"(is (= {:id 42 :flag false}(drop-nil-args {:id 42 :flag false :extra nil}))))@@ -27,11 +30,68 @@;; the override would otherwise be dropped on the floor and the wire-shape schema would be published;; in place of the intended MCP shape. Lives as a test (not a runtime check at manifest generation);; so prod startup isn't burdened with a check that only catches developer mistakes.- (let [manifest-fn (#'metabase.mcp.tools/manifest)+ (let [manifest-fn (#'mcp.tools/manifest)tool-names (into #{} (map :name) (:tools manifest-fn))]- (doseq [[label override-map-var] [["mcp-input-overrides" #'metabase.mcp.tools/mcp-input-overrides]- ["mcp-output-overrides" #'metabase.mcp.tools/mcp-output-overrides]]]+ (doseq [[label override-map-var] [["mcp-input-overrides" #'mcp.tools/mcp-input-overrides]+ ["mcp-output-overrides" #'mcp.tools/mcp-output-overrides]]](testing label(let [unknown (remove tool-names (keys @override-map-var))](is (empty? unknown)(str label " has keys that don't match any tool name: " (vec unknown)))))))))++(defn- data-node?+ "True if `x` is a value type our published JSON-Schema-shaped tool schemas+ are allowed to contain. Visited via `walk/postwalk`, which traverses every+ node (branches and leaves), so this predicate must accept both scalars and+ the container types that hold them. Excludes functions, vars, atoms —+ anything that would blow up `json/encode` or whose JSON encoding isn't+ byte-stable.++ `java.util.regex.Pattern` is allowed: `mjs/transform` lowers `[:re #\"...\"]`+ to `{:type \"string\" :pattern #\"...\"}`, leaving the compiled Pattern in+ the schema. Note that `(hash Pattern)` is identity-based and unstable, but+ `(json/encode Pattern)` writes the regex source string — which is stable.+ `tools-hash` hashes the JSON bytes, never the Pattern object, so Pattern+ nodes are safe in practice."+ [x]+ (or (nil? x) (boolean? x) (number? x) (string? x)+ (keyword? x) (symbol? x)+ (map? x) (vector? x) (seq? x) (set? x)+ (instance? java.util.regex.Pattern x)))++(deftest ^:parallel tool-schemas-are-pure-data-test+ (testing "published tool schemas must be JSON-encodable pure data so `tools-hash` is stable"+ ;; The MCP SSE keepalive emits `notifications/tools/list_changed` when `tools-hash` changes.+ ;; That hash is only meaningful if `inputSchema` / `outputSchema` are pure data: a stray fn+ ;; (e.g. a Malli predicate that leaked through `mjs/transform`) would either blow up+ ;; `json/encode` or, if hashed directly, produce an identity-hash that's stable within a JVM+ ;; but not across builds — silently breaking the list-changed contract.+ (let [tools (mcp.tools/list-tools #{::api.scope/unrestricted})]+ (is (seq tools) "list-tools should return some tools under the unrestricted scope")+ (doseq [{tool-name :name :keys [inputSchema outputSchema]} tools+ [label schema] [[:inputSchema inputSchema] [:outputSchema outputSchema]]+ :when schema]+ (testing (str tool-name " " label)+ (testing "every node is a pure-data type"+ (walk/postwalk+ (fn [x]+ (is (data-node? x)+ (str "Non-data node in " tool-name " " label ": " (pr-str x) " (" (type x) ")"))+ x)+ schema))+ (testing "json-encodes without error"+ (is (string? (json/encode schema))))+ (testing "json encoding is deterministic"+ (is (= (json/encode schema) (json/encode schema)))))))))++(deftest ^:parallel tools-hash-test+ (testing "tools-hash is deterministic across calls"+ (let [scopes #{::api.scope/unrestricted}]+ (is (= (mcp.tools/tools-hash scopes) (mcp.tools/tools-hash scopes)))))+ (testing "tools-hash differs when the visible toolset differs"+ ;; Different scope set yields a different (possibly smaller) tool list, so the hash should change.+ ;; If this ever flakes because two scope filters happen to produce identical lists, narrow the+ ;; second scope to one that we know filters tools out.+ (let [unrestricted (mcp.tools/tools-hash #{::api.scope/unrestricted})+ empty-scopes (mcp.tools/tools-hash #{})]+ (is (not= unrestricted empty-scopes)))))