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
Do not return MCP Apps tools for clients without UI capability (#74743)
Phoomparin Manoef1d510edc2c
diff --git a/resources/migrations/062/20260526_mcp_query_handle_session_id_length.yaml b/resources/migrations/062/20260526_mcp_query_handle_session_id_length.yamlnew file mode 100644index 00000000000..1c32d91af81--- /dev/null+++ b/resources/migrations/062/20260526_mcp_query_handle_session_id_length.yaml@@ -0,0 +1,26 @@+## Widen mcp_query_handle.mcp_session_id for stateless MCP session ids with capability hints.++databaseChangeLog:+ - logicalFilePath: migrations/062_update_migrations.yaml++ - changeSet:+ id: v62.2026-05-26T00:00:00+ author: phoomparin+ comment: Widen mcp_query_handle.mcp_session_id for MCP session capability hints+ changes:+ - modifyDataType:+ tableName: mcp_query_handle+ columnName: mcp_session_id+ newDataType: varchar(254)+ rollback: []++ - changeSet:+ id: v62.2026-05-26T00:00:01+ author: phoomparin+ comment: Preserve NOT NULL on mcp_query_handle.mcp_session_id after widening+ changes:+ - addNotNullConstraint:+ tableName: mcp_query_handle+ columnName: mcp_session_id+ columnDataType: varchar(254)+ rollback: []diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.cljindex 66a864996b7..2c78b8f2cfd 100644--- a/src/metabase/mcp/api.clj+++ b/src/metabase/mcp/api.clj@@ -70,13 +70,30 @@:capabilities {:tools {:listChanged true} :resources {}}:serverInfo server-info}))-(defn- handle-tools-list [id _params token-scopes]- (jsonrpc-response id {:tools (mcp.tools/list-tools token-scopes)}))+(defn- mcp-app-ui-capability?+ "Return true if initialize params advertise support for MCP Apps HTML resources."+ [params]+ ;; `json/decode+kw` preserves the slash in the JSON extension key `"io.modelcontextprotocol/ui"` as the+ ;; namespaced keyword `:io.modelcontextprotocol/ui`.+ (contains?+ (set (get-in params [:capabilities :extensions :io.modelcontextprotocol/ui :mimeTypes]))+ "text/html;profile=mcp-app"))++(defn- handle-tools-list [id _params session-id token-scopes]+ (let [supports-mcp-ui? (mcp.session/supports-mcp-ui? session-id)]+ (jsonrpc-response id {:tools (mcp.tools/list-tools token-scopes {:supports-mcp-ui?+ supports-mcp-ui?})})))(defn- handle-tools-call [id params session-id token-scopes](let [tool-name (:name params)- arguments (or (:arguments params) {})]- (jsonrpc-response id (mcp.tools/call-tool token-scopes session-id tool-name arguments))))+ arguments (or (:arguments params) {})+ supports-mcp-ui? (mcp.session/supports-mcp-ui? session-id)]+ (jsonrpc-response id (mcp.tools/call-tool token-scopes+ session-id+ tool-name+ arguments+ {:supports-mcp-ui?+ supports-mcp-ui?}))))(defn- handle-resources-list [id _params token-scopes](jsonrpc-response id (mcp.resources/list-resources token-scopes)))@@ -103,7 +120,7 @@(try(case method"notifications/initialized" nil- "tools/list" (handle-tools-list id params token-scopes)+ "tools/list" (handle-tools-list id params session-id token-scopes)"tools/call" (handle-tools-call id params session-id token-scopes)"resources/list" (handle-resources-list id params token-scopes)"resources/read" (handle-resources-read id params session-id token-scopes)@@ -230,7 +247,10 @@;; Initialize: create session and return response with session header(and (not batch?) (= "initialize" (:method body)))- (let [session-id (mcp.session/create! user-id)+ (let [params (:params body)+ supports-mcp-ui? (mcp-app-ui-capability? params)+ session-id (mcp.session/create! user-id {:supports-mcp-ui?+ supports-mcp-ui?})init-response (handle-initialize (:id body) (:params body))](if (accepts-sse? request)(sse-response [init-response] {"Mcp-Session-Id" session-id})diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.cljindex 1f94eae1b27..2b0ba30e8eb 100644--- a/src/metabase/mcp/resources.clj+++ b/src/metabase/mcp/resources.clj@@ -203,7 +203,9 @@tool (-> tool(update :inputSchema malli->ui-input-schema)(cond-> (:outputSchema tool) (update :outputSchema malli->ui-output-schema))- (assoc :scope scope :_meta {:ui {:resourceUri uri}}))]+ (assoc :scope scope+ :required-extensions #{:mcp-app-ui}+ :_meta {:ui {:resourceUri uri}}))](swap! registry assoc-in [:tools (:name tool)] tool)tool)(throw (ex-info "Unknown resource" {:resource-key resource-key}))))diff --git a/src/metabase/mcp/session.clj b/src/metabase/mcp/session.cljindex 91983ddf470..6940b781dfa 100644--- a/src/metabase/mcp/session.clj+++ b/src/metabase/mcp/session.clj@@ -16,15 +16,18 @@its own TTL and will be reaped independently; if a subsequent resource readfinds it missing, `get-or-create-session-key!` will re-insert it."(:require+ [clojure.string :as str][metabase.app-db.core :as app-db][metabase.mcp.models.mcp-query-handle][metabase.mcp.settings :as mcp.settings][metabase.session.core :as session]+ [metabase.util.json :as json][metabase.util.log :as log][toucan2.core :as t2])(:import(java.nio ByteBuffer)- (java.util UUID)+ (java.nio.charset StandardCharsets)+ (java.util Base64 UUID)(javax.crypto Mac)(javax.crypto.spec SecretKeySpec)))@@ -77,17 +80,119 @@;;; -------------------------------------------------- Lifecycle --------------------------------------------------+(def ^:private session-payload-version+ "Version for the unsigned JSON client-capability hint encoded in new MCP session ids."+ 1)++(def ^:private max-session-id-length+ "Maximum persisted length for `mcp_query_handle.mcp_session_id`."+ 254)++(defn- encode-session-payload+ "Encode a small JSON map for the second segment of `Mcp-Session-Id`.++ MCP initialize capabilities are client-advertised hints, not authorization state. We include them in the+ server-created session id so later requests can make the same tools/list decision on any Metabase webserver+ without an in-memory cache or a DB row just for session metadata."+ [payload]+ (-> (json/encode payload)+ (.getBytes StandardCharsets/UTF_8)+ (->> (.encodeToString (.withoutPadding (Base64/getUrlEncoder))))))++(defn- decode-session-payload+ "Decode the optional client-capability hint from an `Mcp-Session-Id`.++ Invalid payloads return nil so the whole session id can be treated as invalid by [[session-parts]]."+ [encoded]+ (when-not (str/blank? encoded)+ (try+ (-> (Base64/getUrlDecoder)+ (.decode ^String encoded)+ (String. StandardCharsets/UTF_8)+ json/decode+kw)+ (catch Exception _+ nil))))++(defn- parse-session-payload+ "Parse the optional base64url JSON capability segment.++ Plain UUID session ids are legacy ids issued before capability-aware tools/list and remain valid. Two-part ids+ with a known payload version must include a supported payload shape so malformed capability hints do not silently+ fall back to legacy behavior. Unknown payload versions remain valid but default to no UI capability, so rolling+ deploy version skew does not invalidate the whole session."+ [payload]+ (cond+ (nil? payload)+ {:extended false}++ (str/blank? payload)+ (do+ (log/warn "MCP session id contains a blank capability payload")+ nil)++ :else+ (if-let [decoded-payload (decode-session-payload payload)]+ (let [payload-map? (map? decoded-payload)+ payload-version (when payload-map? (:v decoded-payload))+ has-payload-version? (and payload-map? (contains? decoded-payload :v))+ known-version? (and (integer? payload-version)+ (<= payload-version session-payload-version))+ unknown-version? (and (integer? payload-version)+ (> payload-version session-payload-version))]+ (cond+ (and payload-map?+ known-version?+ (boolean? (:ui decoded-payload)))+ {:extended true+ :payload decoded-payload}++ ;; During rolling deploys, a newer node may mint a capability payload version this node does not understand.+ ;; The payload is only a capability hint, so keep the session valid but fall back to no MCP Apps UI support.+ (and has-payload-version?+ unknown-version?)+ {:extended true+ :payload {:ui false}}))+ (log/warn "MCP session id contains an undecodable capability payload"))))++(defn- session-parts+ "Parse an MCP session id into a UUID correlator plus optional client-capability hint.++ New session ids have the form `<uuid>.<base64url-json>`, currently with payload `{\"v\":1,\"ui\":true}`.+ We keep the UUID as the first segment because existing MCP session behavior derives the embedding session key+ from this server-created id, while the JSON segment lets us remember initialize-time UI capability statelessly+ across multiple Metabase webservers."+ [session-id]+ (when (and (string? session-id)+ (<= (count session-id) max-session-id-length))+ (let [[uuid payload :as parts] (str/split session-id #"\." -1)]+ (when (#{1 2} (count parts))+ (when-let [uuid (parse-uuid uuid)]+ (some-> (parse-session-payload payload)+ (assoc :uuid uuid)))))))++(defn- create-session-id+ "Create a stateless MCP session id containing client capability hints.++ The server creates this id during initialize; clients only echo it back. The unsigned payload is intentionally+ limited to non-security-sensitive capability hints such as whether the client says it can render MCP Apps UI."+ [{:keys [supports-mcp-ui?]}]+ (let [session-id (str (UUID/randomUUID)+ "."+ (encode-session-payload {:v session-payload-version+ :ui (true? supports-mcp-ui?)}))]+ (assert (<= (count session-id) max-session-id-length)+ "MCP session id is too long")+ session-id))+(defn valid-id?- "Return true if `session-id` looks like a UUID (the format `create!` produces).+ "Return true if `session-id` has a UUID correlator (the format `create!` produces).Format check only — authentication is handled separately by cookie or bearer token,not by the session ID itself."[session-id]- (and (string? session-id)- (try (UUID/fromString session-id) true- (catch IllegalArgumentException _ false))))+ (some? (session-parts session-id)))(defn create!- "Create a new MCP session. Returns a UUID string.+ "Create a new MCP session. Returns a session id string.No database row is written — the session is just an opaque correlator untila resource read materializes it into a `core_session`.@@ -95,8 +200,19 @@stateless (no server-side token store), we don't validate the user againstfuture requests. This parameter exists so we can add durable, user-scopedsessions in the future without changing the call-site contract."- [_user-id]- (str (UUID/randomUUID)))+ ([user-id]+ (create! user-id nil))+ ([_user-id metadata]+ (create-session-id metadata)))++(defn supports-mcp-ui?+ "Return true if the client advertised MCP Apps UI support during initialize."+ [session-id]+ (when-let [{:keys [payload extended]} (session-parts session-id)]+ (if extended+ (true? (:ui payload))+ ;; Legacy plain UUID sessions were issued before capability-aware tools/list; keep old behavior for them.+ true)))(defn- get-or-create-embedding-session!"Materialize and return the `core_session` row backing this MCP session.diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.cljindex c9184ae464d..8f5d418f77a 100644--- a/src/metabase/mcp/tools.clj+++ b/src/metabase/mcp/tools.clj@@ -3,6 +3,7 @@tool calls to existing agent API endpoints."(:require[clojure.core.async :as a]+ [clojure.set :as set][clojure.string :as str][metabase.agent-api.api :as agent-api][metabase.api.common :as api]@@ -152,16 +153,40 @@(generate-manifest)@manifest-delay))+(def ^:private extension-labels+ "Human-readable labels for required-extension keywords in tool-call error messages."+ {:mcp-app-ui "MCP Apps UI"})++(defn- supported-extensions+ [{:keys [supports-mcp-ui?]}]+ (if supports-mcp-ui?+ #{:mcp-app-ui}+ #{}))++(defn- missing-required-extensions+ [tool supported-extensions]+ (seq (set/difference (:required-extensions tool #{}) supported-extensions)))++(defn- missing-extensions-error+ [tool-name missing-extensions]+ (let [extension-names (str/join ", " (map #(get extension-labels % (name %)) missing-extensions))]+ (str tool-name " requires a client that supports " extension-names ". "+ "Reconnect from a client that advertises text/html;profile=mcp-app.")))+(defn list-tools"Return the tool definitions suitable for MCP `tools/list` responses.When `token-scopes` is provided, only tools whose scope matches are included."- [token-scopes]- (let [{:keys [tools]} (manifest)]- (into []- (comp (filter #(mcp.scope/matches? token-scopes (:scope %)))- (map (fn [tool]- (select-keys tool [:name :title :description :inputSchema :outputSchema :annotations :_meta]))))- (concat tools (mcp.resources/list-ui-tools)))))+ ([token-scopes]+ (list-tools token-scopes {:supports-mcp-ui? true}))+ ([token-scopes options]+ (let [{:keys [tools]} (manifest)+ supported (supported-extensions options)]+ (into []+ (comp (filter #(mcp.scope/matches? token-scopes (:scope %)))+ (remove #(missing-required-extensions % supported))+ (map (fn [tool]+ (select-keys tool [:name :title :description :inputSchema :outputSchema :annotations :_meta]))))+ (concat tools (mcp.resources/list-ui-tools))))))(defn- pad-left[^String s width]@@ -450,22 +475,29 @@`defendpoint` middleware. UI tool response-fns receive `{:session-id session-id}`as opts in case a tool needs to scope reads to the calling MCP session.Returns MCP content on success, or error content on failure."- [token-scopes session-id tool-name arguments]- (let [arguments (drop-nil-args arguments)]- (if-let [ui-tool (some #(when (= tool-name (:name %)) %) (mcp.resources/list-ui-tools))]- (if-not (mcp.scope/matches? token-scopes (:scope ui-tool))- (error-content (str "Insufficient scope to call tool: " tool-name))- ((:response-fn ui-tool) arguments {:session-id session-id}))- (if-let [tool-def (get (tool-index) tool-name)]- (if-not (mcp.scope/matches? token-scopes (:scope tool-def))- (error-content (str "Insufficient scope to call tool: " tool-name))- (let [arguments (if (tools-accepting-query-handle tool-name)- (resolve-query-arg session-id tool-name arguments)- arguments)]- (if (= arguments ::handle-not-found)- (error-content "Query handle not found. The query may have expired — try running construct_query again.")- (try- (dispatch-via-agent-api tool-def arguments token-scopes session-id)- (catch Exception e- (error-content (or (ex-message e) "Internal error")))))))- (error-content (str "Unknown tool: " tool-name))))))+ ([token-scopes session-id tool-name arguments]+ (call-tool token-scopes session-id tool-name arguments {:supports-mcp-ui? true}))+ ([token-scopes session-id tool-name arguments options]+ (let [arguments (drop-nil-args arguments)+ supported (supported-extensions options)]+ (if-let [ui-tool (some #(when (= tool-name (:name %)) %) (mcp.resources/list-ui-tools))]+ (if-not (mcp.scope/matches? token-scopes (:scope ui-tool))+ (error-content (str "Insufficient scope to call tool: " tool-name))+ (if-let [missing-extensions (missing-required-extensions ui-tool supported)]+ (error-content (missing-extensions-error tool-name missing-extensions))+ ((:response-fn ui-tool) arguments {:session-id session-id})))+ (if-let [tool-def (get (tool-index) tool-name)]+ (if-not (mcp.scope/matches? token-scopes (:scope tool-def))+ (error-content (str "Insufficient scope to call tool: " tool-name))+ (if-let [missing-extensions (missing-required-extensions tool-def supported)]+ (error-content (missing-extensions-error tool-name missing-extensions))+ (let [arguments (if (tools-accepting-query-handle tool-name)+ (resolve-query-arg session-id tool-name arguments)+ arguments)]+ (if (= arguments ::handle-not-found)+ (error-content "Query handle not found. The query may have expired — try running construct_query again.")+ (try+ (dispatch-via-agent-api tool-def arguments token-scopes session-id)+ (catch Exception e+ (error-content (or (ex-message e) "Internal error"))))))))+ (error-content (str "Unknown tool: " tool-name)))))))diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex daa7c9b96c7..c0e81e73fa0 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -93,21 +93,38 @@([method params]{:jsonrpc "2.0" :method method :params params}))-(defn- initialize!- "Perform the full MCP initialize handshake (initialize + notifications/initialized).+(def ^:private mcp-app-ui-capabilities+ {:extensions {:io.modelcontextprotocol/ui {:mimeTypes ["text/html;profile=mcp-app"]}}})++(defn- initialize-with-params!+ "Perform the full MCP initialize handshake with custom initialize params.Returns [session-id init-response]."- []- (let [response (mcp-request (jsonrpc-request "initialize"))+ [params]+ (let [response (mcp-request (jsonrpc-request "initialize" params))session-id (get-in response [:headers "Mcp-Session-Id"])];; Complete the handshake so the session is marked initialized(mcp-request (jsonrpc-notification "notifications/initialized"){"mcp-session-id" session-id})[session-id response]))+(defn- initialize!+ "Perform the full MCP initialize handshake (initialize + notifications/initialized).+ Returns [session-id init-response]."+ []+ (initialize-with-params! {:capabilities mcp-app-ui-capabilities}))++(defn- initialize-without-ui!+ "Perform the full MCP initialize handshake without MCP Apps UI capability.+ Returns [session-id init-response]."+ []+ (initialize-with-params! {}))+(defn- initialize-as!"Like `initialize!` but authenticates as the given test username."[username]- (let [response (mcp-request-as username (jsonrpc-request "initialize") {})+ (let [response (mcp-request-as username+ (jsonrpc-request "initialize" {:capabilities mcp-app-ui-capabilities})+ {})session-id (get-in response [:headers "Mcp-Session-Id"])](mcp-request-as username(jsonrpc-notification "notifications/initialized")@@ -240,6 +257,12 @@"update_question""visualize_query"})+(deftest ui-tools-declare-required-extensions-test+ (testing "UI tools declare their own required client extensions"+ (doseq [{:keys [name required-extensions]} (mcp.resources/list-ui-tools)]+ (is (= #{:mcp-app-ui} required-extensions)+ (str name " should require MCP Apps UI support")))))+(deftest tools-list-all-tools-declare-required-hints-test(testing "every tool advertises readOnlyHint, destructiveHint, openWorldHint (some MCP clients reject tools that omit them)"(let [[session-id _] (initialize!)@@ -251,6 +274,36 @@(is (contains? annotations :destructiveHint) (str name " missing :destructiveHint"))(is (contains? annotations :openWorldHint) (str name " missing :openWorldHint"))))))+(deftest tools-list-omits-ui-tools-without-ui-capability-test+ (testing "clients that do not advertise MCP Apps UI support do not see UI-only tools"+ (let [[session-id _] (initialize-without-ui!)+ response (mcp-request (jsonrpc-request "tools/list") {"mcp-session-id" session-id})+ tool-names (set (map :name (get-in response [:body :result :tools])))]+ (is (= (disj all-tool-names "visualize_query" "render_drill_through") tool-names))+ (is (not (contains? tool-names "visualize_query")))+ (is (not (contains? tool-names "render_drill_through")))))+ (testing "clients that advertise MCP Apps UI support see UI-only tools"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/list") {"mcp-session-id" session-id})+ tool-names (set (map :name (get-in response [:body :result :tools])))]+ (is (contains? tool-names "visualize_query"))+ (is (contains? tool-names "render_drill_through")))))++(deftest ui-capability-detection-requires-mcp-ui-extension-test+ (testing "the MCP Apps UI extension path enables UI-only tools"+ (let [[session-id _] (initialize-with-params! {:capabilities mcp-app-ui-capabilities})+ response (mcp-request (jsonrpc-request "tools/list") {"mcp-session-id" session-id})+ tool-names (set (map :name (get-in response [:body :result :tools])))]+ (is (contains? tool-names "visualize_query"))+ (is (contains? tool-names "render_drill_through"))))+ (testing "an unrelated nested MCP Apps mimeType does not enable UI-only tools"+ (let [[session-id _] (initialize-with-params!+ {:capabilities {:experimental {:mimeTypes ["text/html;profile=mcp-app"]}}})+ response (mcp-request (jsonrpc-request "tools/list") {"mcp-session-id" session-id})+ tool-names (set (map :name (get-in response [:body :result :tools])))]+ (is (not (contains? tool-names "visualize_query")))+ (is (not (contains? tool-names "render_drill_through"))))))+(deftest text-content-includes-structured-content-for-maps-test(testing "text-content emits structuredContent for map values — MCP spec requires it for tools with outputSchema"(let [text-content (var-get #'mcp.tools/text-content)]@@ -652,6 +705,18 @@:structuredContent {:query "card__1"}}result)))))+(deftest tools-call-rejects-ui-tools-without-ui-capability-test+ (testing "direct calls to UI-only tools are rejected for clients without MCP Apps UI support"+ (let [[session-id _] (initialize-without-ui!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:name "visualize_query"+ :arguments {:query "card__1"}})+ {"mcp-session-id" session-id})]+ (is (=? {:status 200+ :body {:result {:isError true+ :content [{:text #(str/includes? % "requires a client that supports MCP Apps UI")}]}}}+ response)))))+(deftest tools-call-execute-query-test(testing "execute_query returns a streaming response captured as MCP text content"(let [streamed? (atom false)@@ -1244,7 +1309,14 @@{:id card-id :name "Nope"}))](is (=? {:isError true} result))(is (str/includes? (-> result :content first :text) "Insufficient scope")- "Scope enforcement error from defendpoint middleware")))))+ "Scope enforcement error from defendpoint middleware"))))+ (testing "scope failures take precedence over missing client extensions"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (mcp.tools/call-tool #{} nil "visualize_query" {:query "card__1"} {:supports-mcp-ui? false}))+ message (-> result :content first :text)]+ (is (=? {:isError true} result))+ (is (str/includes? message "Insufficient scope"))+ (is (not (str/includes? message "requires a client that supports MCP Apps UI"))))))(deftest check-resource-access-test(testing "returns :ok for a known URI with matching scope"diff --git a/test/metabase/mcp/session_test.clj b/test/metabase/mcp/session_test.cljindex 49bdc87a836..6747ed05b03 100644--- a/test/metabase/mcp/session_test.clj+++ b/test/metabase/mcp/session_test.clj@@ -1,12 +1,17 @@(ns metabase.mcp.session-test(:require+ [clojure.string :as str][clojure.test :refer :all][metabase.events.core :as events][metabase.mcp.session :as mcp.session][metabase.session.core :as session][metabase.test :as mt][metabase.test.fixtures :as fixtures]- [toucan2.core :as t2]))+ [metabase.util.json :as json]+ [toucan2.core :as t2])+ (:import+ (java.nio.charset StandardCharsets)+ (java.util Base64)))(set! *warn-on-reflection* true)@@ -17,14 +22,82 @@[session-id](session/hash-session-key (mcp.session/derive-embedding-session-key session-id)))+(defn- session-correlator+ [session-id]+ (first (str/split session-id #"\.")))++(defn- extended-session-id+ [payload]+ (str (random-uuid)+ "."+ (->> (.getBytes (json/encode payload) StandardCharsets/UTF_8)+ (.encodeToString (.withoutPadding (Base64/getUrlEncoder))))))+(deftest create-returns-uuid-string-test- (testing "create! returns a UUID string without writing to the database"+ (testing "create! returns a session id with a UUID correlator without writing to the database"(let [session-id (mcp.session/create! (mt/user->id :crowberto))](is (string? session-id))- (is (some? (parse-uuid session-id)))+ (is (some? (parse-uuid (session-correlator session-id))))(is (not (t2/exists? :core_session :key_hashed (derived-hash session-id)))"No core_session should exist yet"))))+(deftest session-ui-capability-is-stateless-test+ (testing "create! encodes MCP Apps UI support in an unsigned client capability hint"+ (let [ui-session-id (mcp.session/create! (mt/user->id :crowberto) {:supports-mcp-ui? true})+ plain-session-id (mcp.session/create! (mt/user->id :crowberto) {:supports-mcp-ui? false})]+ (is (= 2 (count (str/split ui-session-id #"\.")))+ "New MCP session ids should include a UUID correlator and a base64url JSON capability hint")+ (is (some? (parse-uuid (session-correlator ui-session-id))))+ (is (true? (mcp.session/supports-mcp-ui? ui-session-id)))+ (is (false? (mcp.session/supports-mcp-ui? plain-session-id)))+ (is (not (t2/exists? :core_session :key_hashed (derived-hash ui-session-id)))+ "Capability tracking should not materialize a core_session")+ (is (not (t2/exists? :core_session :key_hashed (derived-hash plain-session-id)))+ "Capability tracking should not materialize a core_session"))))++(deftest create-session-id-length-test+ (testing "generated session ids fit the persisted mcp_query_handle.mcp_session_id column"+ (is (<= (count (mcp.session/create! (mt/user->id :crowberto) {:supports-mcp-ui? true})) 254)))+ (testing "payload growth fails early in dev and tests"+ (mt/with-dynamic-fn-redefs [mcp.session/encode-session-payload (fn [_payload]+ (apply str (repeat 300 "x")))]+ (is (thrown-with-msg? AssertionError+ #"MCP session id is too long"+ (mcp.session/create! (mt/user->id :crowberto) {:supports-mcp-ui? true}))))))++(deftest legacy-session-ui-capability-test+ (testing "plain UUID sessions minted before capability hints keep the old tools/list behavior"+ (is (true? (mcp.session/supports-mcp-ui? (str (java.util.UUID/randomUUID)))))))++(deftest malformed-session-payload-test+ (testing "two-part session ids must include a decodable capability hint"+ (is (false? (mcp.session/valid-id? (str (java.util.UUID/randomUUID) ".not-base64")))))+ (testing "undecodable capability hints are logged"+ (mt/with-log-messages-for-level [messages [metabase.mcp.session :warn]]+ (is (false? (mcp.session/valid-id? (str (java.util.UUID/randomUUID) ".not-base64"))))+ (is (=? [{:level :warn+ :message "MCP session id contains an undecodable capability payload"}]+ (messages)))))+ (testing "blank capability hints are logged"+ (mt/with-log-messages-for-level [messages [metabase.mcp.session :warn]]+ (is (false? (mcp.session/valid-id? (str (java.util.UUID/randomUUID) "."))))+ (is (=? [{:level :warn+ :message "MCP session id contains a blank capability payload"}]+ (messages)))))+ (testing "two-part session ids must match the supported capability hint shape"+ (is (false? (mcp.session/valid-id? (extended-session-id {:v 1}))))+ (is (false? (mcp.session/valid-id? (extended-session-id {:v 1 :ui "true"})))))+ (testing "known payload versions preserve the UI capability hint"+ (let [session-id (extended-session-id {:v 1 :ui true})]+ (is (true? (mcp.session/valid-id? session-id)))+ (is (true? (mcp.session/supports-mcp-ui? session-id)))))+ (testing "unknown payload versions keep the session valid but disable UI capability"+ (let [session-id (extended-session-id {:v 2 :ui true})]+ (is (true? (mcp.session/valid-id? session-id)))+ (is (false? (mcp.session/supports-mcp-ui? session-id)))))+ (testing "two-part session ids must fit the persisted query-handle session id column"+ (is (false? (mcp.session/valid-id? (extended-session-id {:v 1 :ui true :padding (apply str (repeat 300 "x"))}))))))+(deftest derive-embedding-session-key-is-uuid-formatted-test(testing "derived key is UUID-formatted so it passes server.middleware.session/valid-session-key?";; If this regresses, the embedding SDK iframe will get 403s from /api when it sends the@@ -103,6 +176,8 @@(is (some? (parse-uuid h1)) "store-handle! must return a UUID string")(is (some? (parse-uuid h2)))(is (not= h1 h2) "successive calls must produce distinct handles")+ (is (= session-id (t2/select-one-fn :mcp_session_id :model/McpQueryHandle :id h1))+ "store-handle! stores the full MCP session id, including capability hints")(is (= "first" (mcp.session/read-handle session-id user-id h1)))(is (= "second" (mcp.session/read-handle session-id user-id h2)))(is (nil? (mcp.session/read-handle session-id user-id (str (random-uuid))))