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
Use scoped credentials for MCP UI (#79312)
Chris Truteracba9a1d24c2
diff --git a/frontend/src/metabase/api/client/request-handlers.ts b/frontend/src/metabase/api/client/request-handlers.tsindex f4dca94b27f..aad04bd30a4 100644--- a/frontend/src/metabase/api/client/request-handlers.ts+++ b/frontend/src/metabase/api/client/request-handlers.ts@@ -52,10 +52,10 @@ const getDefaultPluginApi = () => ({// which tags requests when running inside an embed preview (see// `embedding-request-auth`).setEmbedPreviewHeader: noop,- // Emit the embedding auth header (`X-Api-Key` or `X-Metabase-Session`). A- // no-op slot: the embedding auth flow installs exactly one strategy here —- // `setApiKeyHeader` or `setSessionTokenHeader` — based on the auth method in- // use (see `embedding-request-auth`).+ // Emit the embedding auth header (`X-Api-Key`, `X-Metabase-Session`, or+ // `X-Metabase-Mcp-Ui-Auth`). A no-op slot: the embedding auth flow installs+ // exactly one strategy here based on the auth method in use (see+ // `embedding-request-auth` and the MCP Apps entry point).setEmbeddingRequestAuthHeaders: noop,// Resolve and emit the SDK session token, refreshing it when expired.// Installed by SDK auth (`embedding-sdk-ee/auth`).diff --git a/frontend/src/metabase/app-embed-mcp.tsx b/frontend/src/metabase/app-embed-mcp.tsxindex 6718072aad1..ed8ffdea827 100644--- a/frontend/src/metabase/app-embed-mcp.tsx+++ b/frontend/src/metabase/app-embed-mcp.tsx@@ -14,22 +14,22 @@ import { setBasename } from "metabase/utils/basename";// Load EE plugins (whitelabeling, etc.) - no-op in OSSimport "sdk-iframe-embedding-ee-plugins";-import { setSessionTokenHeader } from "./embedding/lib/auth/set-session-token-header";EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;EMBEDDING_SDK_CONFIG.isMcpApp = true;EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader = "mcp-apps";EMBEDDING_SDK_CONFIG.tokenFeatureKey = "embedding_simple";-// Set session token immediately so all SDK API calls include X-Metabase-Session.+// Set the MCP UI credential immediately so all SDK API calls carry the purpose-bound header.// @ts-expect-error -- this is ONLY set in the MCP Apps route-const { instanceUrl, sessionToken = "" } = window.metabaseConfig ?? {};+const { instanceUrl, uiCredential = "" } = window.metabaseConfig ?? {};setBasename(instanceUrl);-if (sessionToken) {+if (uiCredential) {PLUGIN_API.onBeforeRequestHandlers.setEmbeddingRequestAuthHeaders =- setSessionTokenHeader(sessionToken);+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- request header name+ async () => ({ headers: { "X-Metabase-Mcp-Ui-Auth": uiCredential } });}function init() {diff --git a/frontend/src/metabase/embedding/lib/auth/set-api-key-header.ts b/frontend/src/metabase/embedding/lib/auth/set-api-key-header.tsindex d3cbb78f349..9d156ff62cd 100644--- a/frontend/src/metabase/embedding/lib/auth/set-api-key-header.ts+++ b/frontend/src/metabase/embedding/lib/auth/set-api-key-header.ts@@ -5,11 +5,12 @@ import type { OnBeforeRequestHandler } from "metabase/api/client";* over its value, so there's no shared mutable state — the embedding setup flow* installs the handlers it needs onto the plugin slots:*- * - `setApiKeyHeader` / `setSessionTokenHeader` onto `setEmbeddingRequestAuthHeaders`- * for static auth (an API key, or a session token that never refreshes — e.g.- * MCP). A refreshing SSO session instead emits its header from- * `getOrRefreshSessionHandler` via `getSessionTokenHeaders`, so the refreshed- * token applies to the request that triggered the refresh.+ * - `setApiKeyHeader` onto `setEmbeddingRequestAuthHeaders` for static auth+ * (an API key; the MCP Apps entry point installs its own inline handler for+ * the purpose-bound MCP UI credential). A refreshing SSO session instead+ * emits its header from `getOrRefreshSessionHandler` via+ * `getSessionTokenHeaders`, so the refreshed token applies to the request+ * that triggered the refresh.* - `setRequestClientHeaders` onto its own slot* - `setEmbedPreviewHeader` onto its own slot (public + SDK flows only)*diff --git a/frontend/src/metabase/embedding/lib/auth/set-session-token-header.ts b/frontend/src/metabase/embedding/lib/auth/set-session-token-header.tsdeleted file mode 100644index 0abb88e4ea7..00000000000--- a/frontend/src/metabase/embedding/lib/auth/set-session-token-header.ts+++ /dev/null@@ -1,8 +0,0 @@-import type { OnBeforeRequestHandler } from "metabase/api/client";--import { getSessionTokenHeaders } from "./get-session-token-headers";--export const setSessionTokenHeader =- (sessionToken: string): OnBeforeRequestHandler =>- async () =>- getSessionTokenHeaders(sessionToken);diff --git a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsxindex d5c4a383667..4904b269152 100644--- a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx+++ b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx@@ -31,12 +31,12 @@ interface McpUiAppRouteContentProps {instanceUrl: string;prompt: McpAppState["prompt"];query: McpAppState["query"];- sessionToken: string;+ uiCredential: string;}interface McpMetabaseConfig {instanceUrl: string;- sessionToken: string;+ uiCredential: string;mcpSessionId: string;}@@ -50,7 +50,7 @@ const SimpleLoader = () => (export function McpUiAppRoute() {const { app, hostContext, prompt, query } = useMcpApp();- const { instanceUrl = "", sessionToken = "" } =+ const { instanceUrl = "", uiCredential = "" } =// Unjustified type cast. FIXME(window.metabaseConfig as McpMetabaseConfig) ?? {};@@ -85,7 +85,7 @@ export function McpUiAppRoute() {instanceUrl={instanceUrl}prompt={prompt}query={query}- sessionToken={sessionToken}+ uiCredential={uiCredential}/></ComponentProvider>);@@ -97,7 +97,7 @@ function McpUiAppRouteContent({instanceUrl,prompt,query,- sessionToken,+ uiCredential,}: McpUiAppRouteContentProps) {const handleDrillThrough = useHandleMcpDrillThrough(app);const isHosted = useSelector(getIsHosted);@@ -119,7 +119,7 @@ function McpUiAppRouteContent({const { isSettingsReady, userAndSettingsFetchError } =useMcpUserAndSettingsFetch({instanceUrl,- sessionToken,+ uiCredential,store,});@@ -170,7 +170,7 @@ function McpUiAppRouteContent({mcpSessionId,prompt,query,- sessionToken,+ uiCredential,});const renderSdkQuestionContent = () => {diff --git a/frontend/src/metabase/embedding/mcp/api.ts b/frontend/src/metabase/embedding/mcp/api.tsindex 1b06392f018..e80ee0205dd 100644--- a/frontend/src/metabase/embedding/mcp/api.ts+++ b/frontend/src/metabase/embedding/mcp/api.ts@@ -5,7 +5,7 @@ import type { SubmitMcpAppsFeedbackRequest } from "metabase-types/api";type StoreDrillQueryRequest = {instanceUrl: string;- sessionToken: string;+ uiCredential: string;mcpSessionId: string;encodedQuery: string;};@@ -16,7 +16,7 @@ type StoreDrillQueryResponse = {type SubmitMcpFeedbackPayload = SubmitMcpAppsFeedbackRequest & {instanceUrl: string;- sessionToken: string;+ uiCredential: string;};/**@@ -28,7 +28,7 @@ type SubmitMcpFeedbackPayload = SubmitMcpAppsFeedbackRequest & {*/export async function storeDrillQuery({instanceUrl,- sessionToken,+ uiCredential,mcpSessionId,encodedQuery,}: StoreDrillQueryRequest): Promise<StoreDrillQueryResponse> {@@ -37,7 +37,7 @@ export async function storeDrillQuery({headers: {"Content-Type": "application/json","X-Metabase-Client": EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,- "X-Metabase-Session": sessionToken,+ "X-Metabase-Mcp-Ui-Auth": uiCredential,"Mcp-Session-Id": mcpSessionId,},body: JSON.stringify({ encodedQuery }),@@ -54,7 +54,7 @@ export async function storeDrillQuery({export async function submitMcpFeedback({instanceUrl,- sessionToken,+ uiCredential,mcpSessionId,payload,}: SubmitMcpFeedbackPayload): Promise<void> {@@ -63,7 +63,7 @@ export async function submitMcpFeedback({headers: {"Content-Type": "application/json","X-Metabase-Client": EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,- "X-Metabase-Session": sessionToken,+ "X-Metabase-Mcp-Ui-Auth": uiCredential,"Mcp-Session-Id": mcpSessionId,},body: JSON.stringify(payload),diff --git a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.tsindex 3f95d5c846d..b7bd53f3f11 100644--- a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts+++ b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts@@ -10,7 +10,7 @@ import { storeDrillQuery } from "../api";interface McpGlobalConfig {instanceUrl?: string;- sessionToken?: string;+ uiCredential?: string;mcpSessionId?: string;}@@ -53,7 +53,7 @@ export function useHandleMcpDrillThrough(app: App | null): DrillThroughHandler {return;}- const { instanceUrl, sessionToken, mcpSessionId } =+ const { instanceUrl, uiCredential, mcpSessionId } =// Unjustified type cast. FIXME(window.metabaseConfig as McpGlobalConfig | undefined) ?? {};@@ -70,7 +70,7 @@ export function useHandleMcpDrillThrough(app: App | null): DrillThroughHandler {return;}- if (!instanceUrl || !sessionToken || !mcpSessionId) {+ if (!instanceUrl || !uiCredential || !mcpSessionId) {await defaultNavigate();return;}@@ -85,7 +85,7 @@ export function useHandleMcpDrillThrough(app: App | null): DrillThroughHandler {// can fetch the payload without the LLM ever seeing it.({ handle } = await storeDrillQuery({instanceUrl,- sessionToken,+ uiCredential,mcpSessionId,encodedQuery,}));diff --git a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.tsindex 9685bd452b7..16b658fb209 100644--- a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts+++ b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts@@ -19,7 +19,7 @@ describe("useHandleMcpDrillThrough", () => {// Unjustified type cast. FIXME(window as any).metabaseConfig = {instanceUrl: "https://metabase.example",- sessionToken: "session-token",+ uiCredential: "ui-credential",mcpSessionId: "mcp-session-id",};diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.tsindex 38b74abe0e8..a34bad288e4 100644--- a/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.ts+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.ts@@ -23,8 +23,8 @@ interface UseMcpFeedbackProps {/** Ad-hoc query that is being shown, captured from construct_query */query: string | null;- /** Metabase session tokens for authenticating feedback requests */- sessionToken: string;+ /** Purpose-bound MCP UI credential for feedback requests */+ uiCredential: string;}export function useMcpFeedback({@@ -32,7 +32,7 @@ export function useMcpFeedback({mcpSessionId,prompt,query,- sessionToken,+ uiCredential,}: UseMcpFeedbackProps) {const [selectedFeedback, setSelectedFeedback] =useState<McpFeedbackChoice | null>(null);@@ -73,7 +73,7 @@ export function useMcpFeedback({await submitMcpFeedback({instanceUrl,- sessionToken,+ uiCredential,mcpSessionId,payload,});diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.unit.spec.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.unit.spec.tsindex 96fc03484a6..11803ed3534 100644--- a/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.unit.spec.ts+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.unit.spec.ts@@ -18,7 +18,7 @@ describe("useMcpFeedback", () => {mcpSessionId: "mcp-session-id",prompt: "visualize customers",query: "encoded-query",- sessionToken: "session-token",+ uiCredential: "ui-credential",}),{},);diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.tsindex 5fe94df6d77..2d26f8a52fe 100644--- a/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts@@ -13,7 +13,7 @@ import {interface UseMcpUserAndSettingsFetchOptions {instanceUrl: string;- sessionToken: string;+ uiCredential: string;store: SdkStore;}@@ -24,7 +24,7 @@ interface UseMcpUserAndSettingsFetchResult {export function useMcpUserAndSettingsFetch({instanceUrl,- sessionToken,+ uiCredential,store,}: UseMcpUserAndSettingsFetchOptions): UseMcpUserAndSettingsFetchResult {const [isSettingsReady, setIsSettingsReady] = useState(false);@@ -45,7 +45,7 @@ export function useMcpUserAndSettingsFetch({setIsSettingsReady(false);setFetchError(null);- if (!sessionToken) {+ if (!uiCredential) {setErrorByType("auth");return;}@@ -84,7 +84,7 @@ export function useMcpUserAndSettingsFetch({return () => {isMounted = false;};- }, [instanceUrl, sessionToken, store]);+ }, [instanceUrl, uiCredential, store]);return { isSettingsReady, userAndSettingsFetchError: fetchError };}diff --git a/resources/frontend_client/mcp_apps_template.html b/resources/frontend_client/mcp_apps_template.htmlindex e1bcfdd4b0a..e767de8a629 100644--- a/resources/frontend_client/mcp_apps_template.html+++ b/resources/frontend_client/mcp_apps_template.html@@ -89,7 +89,7 @@<script>window.metabaseConfig = {instanceUrl: {{{instanceUrl}}},- sessionToken: {{{sessionToken}}},+ uiCredential: {{{uiCredential}}},mcpSessionId: {{{mcpSessionId}}}};</script>diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.cljindex 652ea599b60..f3671ecedb6 100644--- a/src/metabase/mcp/api.clj+++ b/src/metabase/mcp/api.clj@@ -99,9 +99,8 @@(if (or (not (string? uri)) (str/blank? uri))(jsonrpc-error id -32602 "Missing required parameter: uri")(let [user-id api/*current-user-id*- session-key (when user-id (mcp.session/get-or-create-session-key! session-id user-id))- options {:session-key session-key- :session-id session-id}+ options {:ui-credential (when user-id (mcp.session/issue-ui-credential session-id user-id))+ :session-id session-id}result (mcp.resources/read-resource uri token-scopes options)](case (:status result)(:not-found :scope-denied) (jsonrpc-error id -32602 "Resource not found")diff --git a/src/metabase/mcp/callback_api.clj b/src/metabase/mcp/callback_api.cljindex 21e783e5175..0500a0771c1 100644--- a/src/metabase/mcp/callback_api.clj+++ b/src/metabase/mcp/callback_api.clj@@ -22,13 +22,18 @@(defn- check-session-header!"Validate the `Mcp-Session-Id` header against `user-id`. Throws an api/checkexception on failure so defendpoint surfaces the right status code."- [session-id user-id]+ [session-id user-id request](api/check (not (str/blank? session-id))[400 (tru "Missing Mcp-Session-Id header")])(api/check (mcp.session/valid-id? session-id)[404 (tru "Invalid or expired session")])(api/check (mcp.session/owned-by-user? session-id user-id)- [404 (tru "Invalid or expired session")]))+ [404 (tru "Invalid or expired session")])+ ;; A UI credential carries the session it was minted for. Normal browser+ ;; sessions intentionally continue to use the existing ownership check alone.+ (when-let [credential-session-id (:mcp-ui-session-id request)]+ (api/check (= credential-session-id session-id)+ [404 (tru "Invalid or expired session")])))(def ^:private feedback-text-max-length10000)@@ -56,7 +61,7 @@{:keys [encodedQuery]} :- [:map [:encodedQuery ms/NonBlankString]]request](let [session-id (mcp-session-id-from-headers request)]- (check-session-header! session-id api/*current-user-id*)+ (check-session-header! session-id api/*current-user-id* request){:handle (mcp.session/store-handle! session-id api/*current-user-id* encodedQuery)}))(api.macros/defendpoint :post "/feedback" :- [:map@@ -76,7 +81,7 @@[:query {:optional true} OptionalFeedbackText]]]]request](let [session-id (mcp-session-id-from-headers request)- _ (check-session-header! session-id api/*current-user-id*)]+ _ (check-session-header! session-id api/*current-user-id* request)](metabot.config/check-metabot-enabled!)(persist-mcp-feedback! body))api/generic-204-no-content)diff --git a/src/metabase/mcp/core.clj b/src/metabase/mcp/core.cljindex f8a707b4df9..f73c1d1b368 100644--- a/src/metabase/mcp/core.clj+++ b/src/metabase/mcp/core.clj@@ -5,6 +5,7 @@[clojure.string :as str][metabase.api.macros :as api.macros][metabase.mcp.resources :as mcp.resources]+ [metabase.mcp.session :as mcp.session][metabase.mcp.settings :as mcp.settings]))(set! *warn-on-reflection* true)@@ -19,6 +20,11 @@[](mcp.settings/mcp-enabled?))+(defn resolve-ui-credential+ "Resolves a credential issued for an MCP UI resource."+ [credential]+ (mcp.session/resolve-ui-credential credential))+(defn vscode-webview-enabled?"Returns true if vscode/cursor is enabled in common MCP apps."[]diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.cljindex fc86ccb97f6..223f0b06f66 100644--- a/src/metabase/mcp/resources.clj+++ b/src/metabase/mcp/resources.clj@@ -37,7 +37,7 @@(str "<!doctype html><html><head><base href=\"{{{instanceUrlRaw}}}/\"></head><body><script>""window.metabaseConfig = {""instanceUrl: {{{instanceUrl}}},"- "sessionToken: {{{sessionToken}}}"+ "uiCredential: {{{uiCredential}}}""};</script></body></html>"));; An atom rather than a dynamic var because `resources/read` is invoked from the@@ -63,7 +63,7 @@(defn render-embed-mcp-template"Render the embed-mcp.html Mustache template with the given vars map.- Expected keys: :instanceUrl (JSON-encoded), :instanceUrlRaw, :sessionToken (JSON-encoded or nil),+ Expected keys: :instanceUrl (JSON-encoded), :instanceUrlRaw, :uiCredential (JSON-encoded or nil),:mcpSessionId (JSON-encoded or nil)."[vars](cond@@ -290,14 +290,14 @@distinct bodies the second URI's asset is silently dropped and the widget 404s."[tag](fn [opts]- (let [site-url (system/site-url)- session-key (:session-key opts)- session-id (:session-id opts)]+ (let [site-url (system/site-url)+ ui-credential (:ui-credential opts)+ session-id (:session-id opts)](str "<!-- metabase-mcp-asset: " tag " -->\n"(render-embed-mcp-template{:instanceUrl (json/encode site-url):instanceUrlRaw site-url- :sessionToken (when session-key (json/encode session-key))+ :uiCredential (when ui-credential (json/encode ui-credential)):mcpSessionId (when session-id (json/encode session-id))})))))(register-ui-resource!diff --git a/src/metabase/mcp/session.clj b/src/metabase/mcp/session.cljindex acfb80525c0..a08ed1a4ab0 100644--- a/src/metabase/mcp/session.clj+++ b/src/metabase/mcp/session.clj@@ -2,19 +2,15 @@"Lightweight MCP session management.An MCP session ID is just a random UUID handed out on `initialize` — no database- row is created. When a resource read needs an embedding session, we HMAC-derive a- separate session key from an instance-wide signing secret and lazily upsert a- `core_session` row keyed by its hash.-- The derivation (rather than using the MCP session id directly as the session key)- is so that the id we put on the wire in the `Mcp-Session-Id` header is *not* itself- a live embedding session secret: capturing the header should not be enough to- impersonate the embedded SDK iframe. Any webserver can recompute the same derived- key on demand without any per-session plaintext sitting at rest.-- MCP sessions themselves do not expire. The underlying `core_session` row has- its own TTL and will be reaped independently; if a subsequent resource read- finds it missing, `get-or-create-session-key!` will re-insert it."+ row is created. Query handles may lazily materialize a `core_session` row, keyed+ by the hash of a deterministic value derived from the MCP session id.++ The backing value is derived rather than reusing the MCP session id directly, so+ the correlation id on the wire remains distinct from any stored session material.+ Any webserver can recompute the same value without per-session plaintext at rest.++ MCP sessions themselves do not expire. Any backing `core_session` has its own+ TTL and is re-created on demand for query-handle lifecycle management."(:require[clojure.string :as str][metabase.app-db.core :as app-db]@@ -27,6 +23,8 @@(:import(java.nio ByteBuffer)(java.nio.charset StandardCharsets)+ (java.security MessageDigest)+ (java.time Instant)(java.util Base64 UUID)(javax.crypto Mac)(javax.crypto.spec SecretKeySpec)))@@ -78,6 +76,53 @@(unchecked-long 0x8000000000000000))] ; set RFC 4122 variant (10)(str (UUID. high low))))+(def ^:private ui-credential-lifetime-seconds+ "Lifetime of a rendered MCP Apps UI credential. This is deliberately short: the+ credential is delivered to an iframe through a resource response."+ 300)++(defn- base64url-encode [^String value]+ (.encodeToString (.withoutPadding (Base64/getUrlEncoder)) (.getBytes value StandardCharsets/UTF_8)))++(defn- base64url-encode-bytes [^bytes value]+ (.encodeToString (.withoutPadding (Base64/getUrlEncoder)) value))++(defn- base64url-decode [^String value]+ (String. (.decode (Base64/getUrlDecoder) value) StandardCharsets/UTF_8))++(defn- ui-credential-signature [^String payload]+ (base64url-encode-bytes+ (hmac-sha256 (mcp.settings/unobfuscated-mcp-embedding-signing-secret)+ (str "mcp-ui-v1." payload))))++(declare valid-id?)++(defn issue-ui-credential+ "Create a short-lived credential for the MCP Apps UI. It authenticates only+ the narrow server-side UI request surface, never as a core Metabase session."+ [session-id user-id]+ (let [payload (base64url-encode+ (json/encode {:v 1 :uid user-id :sid session-id+ :exp (+ (.getEpochSecond (Instant/now)) ui-credential-lifetime-seconds)}))]+ (str payload "." (ui-credential-signature payload))))++(defn resolve-ui-credential+ "Validate a rendered MCP Apps UI credential and return its claims, or nil.+ Invalid and expired inputs intentionally have the same result and are never logged."+ [credential]+ (try+ (let [[payload ^String signature & extra] (str/split (or credential "") #"\." -1)+ ^String expected (when (and payload signature (empty? extra)) (ui-credential-signature payload))]+ (when (and expected+ (MessageDigest/isEqual (.getBytes expected StandardCharsets/UTF_8)+ (.getBytes signature StandardCharsets/UTF_8)))+ (let [{:keys [v uid sid exp] :as claims} (json/decode+kw (base64url-decode payload))]+ (when (and (= v 1) (integer? uid) (string? sid) (integer? exp)+ (valid-id? sid)+ (> exp (.getEpochSecond (Instant/now))))+ claims))))+ (catch Exception _ nil)))+;;; -------------------------------------------------- Lifecycle --------------------------------------------------(def ^:private session-payload-versiondiff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex 02eb96c2c78..6ed17be4595 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -26,6 +26,7 @@[metabase.app-db.core :as mdb][metabase.config.core :as config][metabase.initialization-status.core :as init-status]+ [metabase.mcp.core :as mcp][metabase.oauth-server.core :as oauth-server][metabase.premium-features.core :as premium-features][metabase.request.core :as request]@@ -304,27 +305,59 @@(m/update-existing :is-group-manager? boolean)(assoc :token-scopes (oauth-token->token-scopes scopes)))))))+(def ^:private mcp-ui-request-surface+ "The complete API surface used by the MCP visualization iframe. A UI credential+ is deliberately not a general Metabase API credential."+ #{[:get "/api/user/current"]+ [:get "/api/session/properties"]+ [:post "/api/dataset"]+ [:post "/api/dataset/pivot"]+ [:post "/api/dataset/query_metadata"]+ [:post "/api/dataset/parameter/remapping"]+ [:post "/api/embed-mcp/drills"]+ [:post "/api/embed-mcp/feedback"]})++(defn- current-user-info-for-mcp-ui-credential+ "Resolve the short-lived credential rendered into an MCP visualization iframe.+ It is accepted only for [[mcp-ui-request-surface]], so possession never+ authenticates arbitrary API routes."+ [request]+ (when (and (init-status/complete?)+ (contains? mcp-ui-request-surface [(:request-method request) (:uri request)]))+ (when-let [{:keys [uid sid] :as claims}+ (mcp/resolve-ui-credential (get-in request [:headers "x-metabase-mcp-ui-auth"]))]+ (some-> (t2/query-one (cons (user-data-for-id-query (premium-features/enable-advanced-permissions?)) [uid]))+ (m/update-existing :is-group-manager? boolean)+ ;; Endpoint scope middleware treats this as session-like auth, but the+ ;; route allowlist above is the actual authorization boundary.+ (assoc :token-scopes #{::scope/unrestricted}+ :mcp-ui-session-id sid+ :mcp-ui-credential claims)))))+(defn- auth-method- [session-info api-key-info oauth-info embedding-route]+ [session-info api-key-info oauth-info mcp-ui-info embedding-route](or ({"guest-embed" "guest"} embedding-route embedding-route)(cond session-info (or (:auth-provider session-info) "session")api-key-info "api-key"- oauth-info "oauth")))+ oauth-info "oauth"+ mcp-ui-info "mcp-ui")))(defn- merge-current-user-info[{:keys [metabase-session-key anti-csrf-token], {:strs [x-metabase-locale x-api-key]} :headers, :as request}](let [session-info (current-user-info-for-session metabase-session-key anti-csrf-token)api-key-info (when-not session-info (current-user-info-for-api-key x-api-key))- ;; Bearer is the lowest-precedence path: only consulted when there's no session or API key.+ ;; Bearer and MCP UI credentials are consulted only when no normal session/API key authenticated.oauth-info (when-not (or session-info api-key-info)(current-user-info-for-oauth-token request))+ mcp-ui-info (when-not (or session-info api-key-info oauth-info)+ (current-user-info-for-mcp-ui-credential request))embedding-route (analytics/get-route)- auth-method (auth-method session-info api-key-info oauth-info embedding-route)]+ auth-method (auth-method session-info api-key-info oauth-info mcp-ui-info embedding-route)](mergerequest;; oauth-info carries `:token-scopes` in addition to the standard current-user-info keys, so;; merging it whole both authenticates the request and records the granted scopes.- (dissoc (or session-info api-key-info oauth-info) :auth-provider)+ (dissoc (or session-info api-key-info oauth-info mcp-ui-info) :auth-provider)(when auth-method {:embedding/auth-method auth-method})(when x-metabase-locale(log/tracef "Found X-Metabase-Locale header: using %s as user locale" (pr-str x-metabase-locale))@@ -332,8 +365,8 @@(defn wrap-current-user-info"Add `:metabase-user-id`, `:is-superuser?`, `:is-group-manager?` and `:user-locale` to the request if a valid session- token, API key, OR OAuth bearer access token was passed. A bearer token additionally sets `:token-scopes` (the access- it was granted); precedence is session > API key > bearer."+ token, API key, OAuth bearer access token, OR MCP UI credential was passed. A bearer token additionally sets+ `:token-scopes` (the access it was granted); precedence is session > API key > bearer > MCP UI credential."[handler](fn [request respond raise](let [request' (tracing/with-span :db-app "db-app.session-lookup" {}diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex 23553114cc9..cd3f05fa45d 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -1631,8 +1631,8 @@;;; -------------------------------------------- Session Lifecycle --------------------------------------------------(deftest session-embedding-reuse-test- (testing "multiple resources/read calls within one session reuse the same embedding session"+(deftest resources-read-renders-ui-configuration-test+ (testing "multiple resources/read calls within one session render a usable UI configuration"(let [[session-id _] (initialize!)read1 (mcp-request (jsonrpc-request "resources/read"{:uri "ui://metabase/visualize-query.html"} 1)@@ -1642,12 +1642,33 @@{"mcp-session-id" session-id})](is (= 200 (:status read1)))(is (= 200 (:status read2)))- ;; Both responses should contain the same session token in the rendered HTML+ ;; Each resource response contains an independently short-lived UI credential.(let [html1 (-> (get-in read1 [:body :result :contents]) first :text)html2 (-> (get-in read2 [:body :result :contents]) first :text)](is (some? html1))- (is (= html1 html2)- "Same embedding session should produce identical HTML output")))))+ (is (str/includes? html1 "uiCredential"))+ (is (str/includes? html2 "uiCredential"))))))++(deftest mcp-ui-credential-validation-test+ (testing "a scoped MCP Apps resource provides the UI request surface, but not general API access"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (oauth-server/reset-provider!)+ (let [token (str (random-uuid))+ _ (save-access-token! token (mt/user->id :crowberto) #{"agent:viz:mcp-ui:query"})+ initialize (mcp-request-with-bearer token 200 (jsonrpc-request "initialize" {:capabilities mcp-app-ui-capabilities}) {})+ session-id (get-in initialize [:headers "Mcp-Session-Id"])+ resource (mcp-request-with-bearer token 200+ (jsonrpc-request "resources/read" {:uri "ui://metabase/visualize-query.html"})+ {"mcp-session-id" session-id})+ html (-> resource :body :result :contents first :text)+ credential (second (re-find #"uiCredential:\s*\"([^\"]+)\"" html))+ headers {"x-metabase-mcp-ui-auth" credential}]+ (is (string? credential))+ (is (= 200 (:status (client/client-full-response :get 200 "user/current"+ {:request-options {:headers headers}}))))+ (is (= 401 (:status (client/client-full-response :get 401 "collection"+ {:request-options {:headers headers}})))))))))(deftest batch-initialized-then-resources-read-test(testing "batch containing notifications/initialized + resources/read succeeds"diff --git a/test/metabase/mcp/callback_api_test.clj b/test/metabase/mcp/callback_api_test.cljindex e7af42923ec..ecc3d77c75f 100644--- a/test/metabase/mcp/callback_api_test.clj+++ b/test/metabase/mcp/callback_api_test.clj@@ -34,6 +34,13 @@:post expected-status "embed-mcp/feedback"body)))+(defn- post-drill-with-ui-credential+ [expected-status credential session-id]+ (client/client-full-response :post expected-status "embed-mcp/drills"+ {:request-options {:headers {"x-metabase-mcp-ui-auth" credential+ "mcp-session-id" session-id}}}+ {:encodedQuery "ZW5jb2RlZA=="}))+(deftest drills-post-stores-handle-test(testing "POST returns a UUID handle"(let [user-id (mt/user->id :crowberto)@@ -60,6 +67,23 @@(post-drill :rasta 404 {:encodedQuery "ZW5jb2RlZA=="}{"mcp-session-id" session}))))))+(deftest ui-credential-session-binding-test+ (let [user-id (mt/user->id :crowberto)+ credential-id (mcp.session/create! user-id)+ other-session-id (mcp.session/create! user-id)+ credential (mcp.session/issue-ui-credential credential-id user-id)]+ (testing "a credential can use the callback surface for its own MCP session"+ (is (= 200 (:status (post-drill-with-ui-credential 200 credential credential-id)))))+ (testing "a credential cannot be reused with another MCP session"+ (is (= 404 (:status (post-drill-with-ui-credential 404 credential other-session-id)))))+ (testing "invalid and expired credentials are rejected"+ (is (= 401 (:status (post-drill-with-ui-credential 401 "not-a-credential" credential-id))))+ (with-redefs [mcp.session/ui-credential-lifetime-seconds -1]+ (is (= 401 (:status (post-drill-with-ui-credential+ 401+ (mcp.session/issue-ui-credential credential-id user-id)+ credential-id))))))))+(deftest drills-post-rejects-blank-body-test(testing "blank encodedQuery returns 400"(let [user-id (mt/user->id :crowberto)diff --git a/test/metabase/mcp/resources_test.clj b/test/metabase/mcp/resources_test.cljindex ff682209ef9..157702e1cbd 100644--- a/test/metabase/mcp/resources_test.clj+++ b/test/metabase/mcp/resources_test.clj@@ -164,6 +164,6 @@"frontend_client/mcp_apps_template.html"{:instanceUrl "\"https://metabase.example.com/sub/path\"":instanceUrlRaw site-url- :sessionToken nil+ :uiCredential nil:mcpSessionId nil})](is (str/includes? html "<base href=\"https://metabase.example.com/sub/path/\"")))))diff --git a/test/metabase/mcp/session_test.clj b/test/metabase/mcp/session_test.cljindex 6747ed05b03..a9e1eff0f61 100644--- a/test/metabase/mcp/session_test.clj+++ b/test/metabase/mcp/session_test.clj@@ -112,6 +112,20 @@(is (= 2 (.variant ^java.util.UUID parsed))"should carry the RFC 4122 variant (10xx)"))))+(deftest ui-credential-validation-test+ (let [user-id (mt/user->id :crowberto)+ session-id (mcp.session/create! user-id)+ credential (mcp.session/issue-ui-credential session-id user-id)]+ (testing "a fresh credential resolves to its user and MCP session"+ (is (=? {:uid user-id :sid session-id}+ (mcp.session/resolve-ui-credential credential))))+ (testing "invalid credentials are rejected"+ (is (nil? (mcp.session/resolve-ui-credential (str credential "x")))))+ (testing "expired credentials are rejected"+ (with-redefs [mcp.session/ui-credential-lifetime-seconds -1]+ (is (nil? (mcp.session/resolve-ui-credential+ (mcp.session/issue-ui-credential session-id user-id))))))))+(deftest get-or-create-session-key-test(testing "first call creates a core_session and returns the derived embedding key"(let [user-id (mt/user->id :crowberto)diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.cljindex 8c631a73493..43c6cabe387 100644--- a/test/metabase/server/middleware/session_test.clj+++ b/test/metabase/server/middleware/session_test.clj@@ -518,23 +518,25 @@(deftest auth-method-test(testing "auth-method prefers route-based override on special routes"(let [f #'mw.session/auth-method]- (are [session-info api-key-info oauth-info embedding-route expected]- (= expected (f session-info api-key-info oauth-info embedding-route))+ (are [session-info api-key-info oauth-info mcp-ui-info embedding-route expected]+ (= expected (f session-info api-key-info oauth-info mcp-ui-info embedding-route));; session-based auth on non-special routes- {:auth-provider "password"} nil nil nil "password"- {:auth-provider "saml"} nil nil nil "saml"- {:auth-provider "jwt"} nil nil nil "jwt"- {:auth-provider "ldap"} nil nil nil "ldap"- {} nil nil nil "session"+ {:auth-provider "password"} nil nil nil nil "password"+ {:auth-provider "saml"} nil nil nil nil "saml"+ {:auth-provider "jwt"} nil nil nil nil "jwt"+ {:auth-provider "ldap"} nil nil nil nil "ldap"+ {} nil nil nil nil "session";; api-key on non-special route- nil {} nil nil "api-key"+ nil {} nil nil nil "api-key";; oauth bearer on non-special route- nil nil {:metabase-user-id 1} nil "oauth"+ nil nil {:metabase-user-id 1} nil nil "oauth"+ ;; mcp-ui credential on non-special route+ nil nil nil {:metabase-user-id 1} nil "mcp-ui";; route override: special routes win over credentials- nil {} nil "guest-embed" "guest" ; api-key + embed -> guest- nil nil nil "guest-embed" "guest" ; anon guest embed- nil nil nil "public" "public"- nil nil nil "metabot" "metabot"- nil nil nil "agent-api" "agent-api"+ nil {} nil nil "guest-embed" "guest" ; api-key + embed -> guest+ nil nil nil nil "guest-embed" "guest" ; anon guest embed+ nil nil nil nil "public" "public"+ nil nil nil nil "metabot" "metabot"+ nil nil nil nil "agent-api" "agent-api";; fully anonymous, non-special route- nil nil nil nil nil))))+ nil nil nil nil nil nil))))