Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Refresh MCP Apps UI credentials before expiry (#81041)

Phoomparin Manoc5e99eb3208e
diff --git a/frontend/src/metabase/app-embed-mcp.tsx b/frontend/src/metabase/app-embed-mcp.tsx
index ed8ffdea827..81f312bf9ea 100644
--- a/frontend/src/metabase/app-embed-mcp.tsx
+++ b/frontend/src/metabase/app-embed-mcp.tsx
@@ -7,7 +7,6 @@ import { createRoot } from "react-dom/client";
// Import the embedding SDK vendors side-effects (sets up global CSS vars, etc.)
import "metabase/embedding-sdk/vendors-side-effects";
-import { PLUGIN_API } from "metabase/api/client";
import { McpUiAppRoute } from "metabase/embedding/mcp/McpUiAppRoute";
import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
import { setBasename } from "metabase/utils/basename";
@@ -20,18 +19,10 @@ EMBEDDING_SDK_CONFIG.isMcpApp = true;
EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader = "mcp-apps";
EMBEDDING_SDK_CONFIG.tokenFeatureKey = "embedding_simple";
-// 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, uiCredential = "" } = window.metabaseConfig ?? {};
+const { instanceUrl } = window.metabaseConfig ?? {};
setBasename(instanceUrl);
-if (uiCredential) {
- PLUGIN_API.onBeforeRequestHandlers.setEmbeddingRequestAuthHeaders =
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- request header name
- async () => ({ headers: { "X-Metabase-Mcp-Ui-Auth": uiCredential } });
-}
-
function init() {
const rootElement = document.getElementById("root");
diff --git a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx
index 742d9275f33..1aa4477ed79 100644
--- a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx
+++ b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx
@@ -26,8 +26,10 @@ const FOOTER_HORIZONTAL_PADDING = 16;
interface McpUiAppRouteContentProps {
app: McpAppState["app"];
+ hostError: McpAppState["hostError"];
hostContext: McpAppState["hostContext"];
instanceUrl: string;
+ mcpSessionId: string;
prompt: McpAppState["prompt"];
query: McpAppState["query"];
uiCredential: string;
@@ -35,8 +37,6 @@ interface McpUiAppRouteContentProps {
interface McpMetabaseConfig {
instanceUrl: string;
- uiCredential: string;
- mcpSessionId: string;
}
// CSS for .mcp-loading and .mcp-spinner is defined globally in embed-mcp.html.
@@ -47,12 +47,20 @@ const SimpleLoader = () => (
);
export function McpUiAppRoute() {
- const { app, hostContext, prompt, query } = useMcpApp();
-
- const { instanceUrl = "", uiCredential = "" } =
+ const { instanceUrl = "" } =
// Unjustified type cast. FIXME
(window.metabaseConfig as McpMetabaseConfig) ?? {};
+ const {
+ app,
+ hostError,
+ hostContext,
+ mcpSessionId,
+ uiCredential,
+ prompt,
+ query,
+ } = useMcpApp();
+
const scheme: ResolvedColorScheme =
hostContext?.theme === "dark" ? "dark" : "light";
@@ -80,8 +88,10 @@ export function McpUiAppRoute() {
>
<McpUiAppRouteContent
app={app}
+ hostError={hostError}
hostContext={hostContext}
instanceUrl={instanceUrl}
+ mcpSessionId={mcpSessionId}
prompt={prompt}
query={query}
uiCredential={uiCredential}
@@ -92,21 +102,23 @@ export function McpUiAppRoute() {
function McpUiAppRouteContent({
app,
+ hostError,
hostContext,
instanceUrl,
+ mcpSessionId,
prompt,
query,
uiCredential,
}: McpUiAppRouteContentProps) {
- const handleDrillThrough = useHandleMcpDrillThrough(app);
const isHosted = useSetting("is-hosted?");
-
- const { mcpSessionId = "" } =
- // Unjustified type cast. FIXME
- (window.metabaseConfig as McpMetabaseConfig) ?? {};
-
const safeAreaInsets = hostContext?.safeAreaInsets ?? DEFAULT_INSETS;
+ const handleDrillThrough = useHandleMcpDrillThrough({
+ app,
+ uiCredential,
+ mcpSessionId,
+ });
+
const deserializedCard = useMemo(() => {
if (!query) {
return null;
@@ -126,16 +138,17 @@ function McpUiAppRouteContent({
instanceUrl &&
hostContext &&
isSettingsReady &&
+ uiCredential &&
deserializedCard
);
useEffect(() => {
// Remove the loading indicator on the HTML page once the app is ready or
// when initialization fails and the route can render its own error.
- if (isReady || userAndSettingsFetchError) {
+ if (isReady || hostError || userAndSettingsFetchError) {
document.getElementById("mcp-loading")?.remove();
}
- }, [isReady, userAndSettingsFetchError]);
+ }, [hostError, isReady, userAndSettingsFetchError]);
const height = `calc(${MCP_CONTENT_HEIGHT} + ${FOOTER_HEIGHT})`;
@@ -223,6 +236,10 @@ function McpUiAppRouteContent({
);
const renderContentView = () => {
+ if (hostError) {
+ return <SdkError message={hostError} />;
+ }
+
if (userAndSettingsFetchError) {
return <SdkError message={userAndSettingsFetchError} />;
}
diff --git a/frontend/src/metabase/embedding/mcp/auth/index.ts b/frontend/src/metabase/embedding/mcp/auth/index.ts
new file mode 100644
index 00000000000..72885bb17d1
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/auth/index.ts
@@ -0,0 +1 @@
+export { useMcpUiAuth } from "./useMcpUiAuth";
diff --git a/frontend/src/metabase/embedding/mcp/auth/mcpUiAuth.ts b/frontend/src/metabase/embedding/mcp/auth/mcpUiAuth.ts
new file mode 100644
index 00000000000..792cacd5f97
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/auth/mcpUiAuth.ts
@@ -0,0 +1,116 @@
+import type { App } from "@modelcontextprotocol/ext-apps/react";
+
+import { PLUGIN_API } from "metabase/api/client";
+import { retry } from "metabase/utils/retry";
+
+import {
+ MCP_APPS_METADATA_KEY,
+ UI_CREDENTIAL_REFRESH_MAX_FAILURES,
+ UI_CREDENTIAL_REFRESH_RETRY_MS,
+ UI_CREDENTIAL_REFRESH_TIMEOUT_MS,
+ UI_CREDENTIAL_REFRESH_TOOL,
+ UI_CREDENTIAL_VALIDITY_MS,
+} from "../constants";
+
+export interface McpUiAuth {
+ credential: string;
+ sessionId: string;
+}
+
+export function installMcpUiCredential(credential: string) {
+ PLUGIN_API.onBeforeRequestHandlers.setEmbeddingRequestAuthHeaders =
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- request header name
+ async () => ({ headers: { "X-Metabase-Mcp-Ui-Auth": credential } });
+}
+
+export async function refreshMcpUiAuth(
+ app: App,
+ abortController: AbortController,
+) {
+ let requestStartedAt = Date.now();
+
+ const auth = await retry(
+ () => {
+ requestStartedAt = Date.now();
+
+ return requestAuth(app, abortController.signal);
+ },
+ {
+ maxRetries: UI_CREDENTIAL_REFRESH_MAX_FAILURES - 1,
+ shouldRetry: (error) => {
+ if (abortController.signal.aborted) {
+ return false;
+ }
+
+ console.error("Error refreshing MCP UI credential:", error);
+
+ return true;
+ },
+ delayMs: () => UI_CREDENTIAL_REFRESH_RETRY_MS,
+ signal: abortController.signal,
+ },
+ );
+
+ abortController.signal.throwIfAborted();
+
+ return { auth, expiresAt: requestStartedAt + UI_CREDENTIAL_VALIDITY_MS };
+}
+
+async function requestAuth(
+ app: App,
+ effectSignal: AbortSignal,
+): Promise<McpUiAuth> {
+ const requestController = new AbortController();
+ const abortRequest = () => requestController.abort(effectSignal.reason);
+
+ effectSignal.addEventListener("abort", abortRequest, { once: true });
+
+ if (effectSignal.aborted) {
+ abortRequest();
+ }
+
+ try {
+ const result = await app.callServerTool(
+ {
+ name: UI_CREDENTIAL_REFRESH_TOOL,
+ arguments: {},
+ },
+ {
+ signal: requestController.signal,
+ timeout: UI_CREDENTIAL_REFRESH_TIMEOUT_MS,
+ },
+ );
+
+ const auth = getCredentialFromToolResultMetadata(result._meta);
+
+ if (!auth || result.isError) {
+ throw new Error("MCP UI credential refresh failed");
+ }
+
+ return auth;
+ } finally {
+ effectSignal.removeEventListener("abort", abortRequest);
+ }
+}
+
+/**
+ * Extract the UI credentials and session ID from tool result metadata.
+ */
+export function getCredentialFromToolResultMetadata(
+ metadata: Record<string, unknown> | undefined,
+): McpUiAuth | null {
+ const value = metadata?.[MCP_APPS_METADATA_KEY];
+
+ if (typeof value !== "object" || value === null) {
+ return null;
+ }
+
+ const credential = "credential" in value ? value.credential : null;
+ const sessionId = "sessionId" in value ? value.sessionId : null;
+
+ if (typeof credential !== "string" || typeof sessionId !== "string") {
+ return null;
+ }
+
+ return { credential, sessionId };
+}
diff --git a/frontend/src/metabase/embedding/mcp/auth/mcpUiAuth.unit.spec.ts b/frontend/src/metabase/embedding/mcp/auth/mcpUiAuth.unit.spec.ts
new file mode 100644
index 00000000000..edfff8c96c0
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/auth/mcpUiAuth.unit.spec.ts
@@ -0,0 +1,34 @@
+import { getCredentialFromToolResultMetadata } from "./mcpUiAuth";
+
+describe("getCredentialFromToolResultMetadata", () => {
+ it("reads the credential and session from the tool result metadata", () => {
+ expect(
+ getCredentialFromToolResultMetadata({
+ "com.metabase/mcp-apps": {
+ credential: "fresh-credential",
+ sessionId: "mcp-session-id",
+ },
+ }),
+ ).toEqual({
+ credential: "fresh-credential",
+ sessionId: "mcp-session-id",
+ });
+ });
+
+ it("ignores incorrect auth metadata", () => {
+ expect(getCredentialFromToolResultMetadata(undefined)).toBeNull();
+
+ expect(
+ getCredentialFromToolResultMetadata({ "com.metabase/mcp-apps": {} }),
+ ).toBeNull();
+
+ expect(
+ getCredentialFromToolResultMetadata({
+ "com.metabase/mcp-apps": {
+ credential: 123,
+ sessionId: "mcp-session-id",
+ },
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/auth/useMcpUiAuth.ts b/frontend/src/metabase/embedding/mcp/auth/useMcpUiAuth.ts
new file mode 100644
index 00000000000..7f6a4d6dc22
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/auth/useMcpUiAuth.ts
@@ -0,0 +1,129 @@
+import type { App } from "@modelcontextprotocol/ext-apps/react";
+import { useEffect, useRef, useState } from "react";
+
+import {
+ UI_CREDENTIAL_REFRESH_INTERVAL_MS,
+ UI_CREDENTIAL_REFRESH_RETRY_MS,
+} from "../constants";
+
+import { installMcpUiCredential, refreshMcpUiAuth } from "./mcpUiAuth";
+
+type UseMcpUiAuthOptions = {
+ app: App | null;
+ refreshKey: number;
+ onAuthenticated: () => void;
+};
+
+export function useMcpUiAuth({
+ app,
+ refreshKey,
+ onAuthenticated,
+}: UseMcpUiAuthOptions) {
+ const [uiCredential, setUiCredential] = useState("");
+ const [mcpSessionId, setMcpSessionId] = useState("");
+ const [error, setError] = useState<string | null>(null);
+
+ const authenticatedUntilRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ if (!app || refreshKey === 0) {
+ return;
+ }
+
+ if (!app.getHostCapabilities()?.serverTools) {
+ const hostName = app.getHostVersion()?.name.trim() || "Your MCP client";
+
+ setError(`${hostName} does not support query visualization.`);
+ return;
+ }
+
+ const connectedApp = app;
+ const abortController = new AbortController();
+
+ let credentialExpiryTimeout: number | undefined;
+ let refreshTimeout: number | undefined;
+
+ function clearAuth() {
+ authenticatedUntilRef.current = null;
+
+ setUiCredential("");
+ setMcpSessionId("");
+ }
+
+ function scheduleCredentialExpiry() {
+ window.clearTimeout(credentialExpiryTimeout);
+ const authenticatedUntil = authenticatedUntilRef.current;
+
+ if (authenticatedUntil === null) {
+ return;
+ }
+
+ const expiresIn = authenticatedUntil - Date.now();
+
+ if (expiresIn <= 0) {
+ clearAuth();
+ return;
+ }
+
+ credentialExpiryTimeout = window.setTimeout(() => {
+ if (authenticatedUntilRef.current === authenticatedUntil) {
+ clearAuth();
+ }
+ }, expiresIn);
+ }
+
+ function scheduleRefresh(delay: number) {
+ refreshTimeout = window.setTimeout(() => refreshAuth(), delay);
+ }
+
+ async function refreshAuth() {
+ try {
+ const { auth, expiresAt } = await refreshMcpUiAuth(
+ connectedApp,
+ abortController,
+ );
+
+ installMcpUiCredential(auth.credential);
+
+ setUiCredential(auth.credential);
+ setMcpSessionId(auth.sessionId);
+ setError(null);
+
+ authenticatedUntilRef.current = expiresAt;
+ onAuthenticated();
+
+ scheduleCredentialExpiry();
+ scheduleRefresh(UI_CREDENTIAL_REFRESH_INTERVAL_MS);
+ } catch {
+ if (abortController.signal.aborted) {
+ return;
+ }
+
+ const authenticatedUntil = authenticatedUntilRef.current;
+
+ if (authenticatedUntil === null || authenticatedUntil <= Date.now()) {
+ clearAuth();
+ setError(
+ "This visualization did not load. Ask your MCP client to show it again.",
+ );
+ return;
+ }
+
+ scheduleRefresh(UI_CREDENTIAL_REFRESH_RETRY_MS);
+ }
+ }
+
+ setError(null);
+ scheduleCredentialExpiry();
+ refreshAuth();
+
+ return () => {
+ abortController.abort();
+
+ window.clearTimeout(credentialExpiryTimeout);
+ window.clearTimeout(refreshTimeout);
+ };
+ }, [app, refreshKey, onAuthenticated]);
+
+ return { uiCredential, mcpSessionId, error };
+}
diff --git a/frontend/src/metabase/embedding/mcp/constants.ts b/frontend/src/metabase/embedding/mcp/constants.ts
new file mode 100644
index 00000000000..cd09c0fe50b
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/constants.ts
@@ -0,0 +1,32 @@
+/**
+ * Refresh three minutes after issue: two minutes before the server-side expiry
+ * and 90 seconds before the conservative client-side deadline below. Two
+ * 10-second attempts plus the 30-second backoff fit comfortably in that window.
+ * The lifetime is hard-coded in `ui-credential-lifetime-seconds` on `mcp/session.clj`
+ */
+export const UI_CREDENTIAL_REFRESH_INTERVAL_MS = 3 * 60 * 1000;
+
+/** Wait before retrying a failed credential refresh. */
+export const UI_CREDENTIAL_REFRESH_RETRY_MS = 30 * 1000;
+
+/** Credential minting is local and should fail quickly enough to retry safely. */
+export const UI_CREDENTIAL_REFRESH_TIMEOUT_MS = 10 * 1000;
+
+/**
+ * Treat a credential as expired 30 seconds before its server-side lifetime.
+ * The buffer covers request latency because the response does not expose its
+ * exact expiry timestamp.
+ */
+export const UI_CREDENTIAL_VALIDITY_MS = 4.5 * 60 * 1000;
+
+/**
+ * Initial authentication shows an error after this many failures. Background
+ * refreshes keep the current credential and begin another retry cycle instead.
+ */
+export const UI_CREDENTIAL_REFRESH_MAX_FAILURES = 2;
+
+/** Server tool that issues a fresh scoped credential for any Metabase MCP App. */
+export const UI_CREDENTIAL_REFRESH_TOOL = "refresh_ui_credential";
+
+/** Metadata key that stores UI credential for MCP Apps. */
+export const MCP_APPS_METADATA_KEY = "com.metabase/mcp-apps";
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts
index b7bd53f3f11..8a8543f2bc9 100644
--- a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts
+++ b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts
@@ -10,8 +10,6 @@ import { storeDrillQuery } from "../api";
interface McpGlobalConfig {
instanceUrl?: string;
- uiCredential?: string;
- mcpSessionId?: string;
}
type DrillThruName<T extends Lib.DrillThruType = Lib.DrillThruType> =
@@ -34,7 +32,7 @@ const isStayDrill = (drillName: string | undefined) =>
(prefix) => drillName === prefix || drillName.startsWith(`${prefix}.`),
);
-const isClaudeHost = (app: App) => {
+const isClaudeHost = (app: Pick<App, "getHostVersion">) => {
const hostVersion = app.getHostVersion();
return hostVersion?.name.toLowerCase().includes("claude");
@@ -45,7 +43,22 @@ type DrillThroughHandler = (
defaultNavigate: () => Promise<void>,
) => Promise<void>;
-export function useHandleMcpDrillThrough(app: App | null): DrillThroughHandler {
+type McpDrillThroughApp = Pick<
+ App,
+ "getHostVersion" | "openLink" | "sendMessage"
+>;
+
+interface UseHandleMcpDrillThroughParams {
+ app: McpDrillThroughApp | null;
+ uiCredential: string;
+ mcpSessionId: string;
+}
+
+export function useHandleMcpDrillThrough({
+ app,
+ uiCredential,
+ mcpSessionId,
+}: UseHandleMcpDrillThroughParams): DrillThroughHandler {
return useCallback(
async ({ drillName, nextCard }, defaultNavigate) => {
if (isStayDrill(drillName) || !app) {
@@ -53,7 +66,7 @@ export function useHandleMcpDrillThrough(app: App | null): DrillThroughHandler {
return;
}
- const { instanceUrl, uiCredential, mcpSessionId } =
+ const { instanceUrl } =
// Unjustified type cast. FIXME
(window.metabaseConfig as McpGlobalConfig | undefined) ?? {};
@@ -107,6 +120,6 @@ export function useHandleMcpDrillThrough(app: App | null): DrillThroughHandler {
],
});
},
- [app],
+ [app, mcpSessionId, uiCredential],
);
}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts
index 16b658fb209..058494df11e 100644
--- a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts
+++ b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts
@@ -19,8 +19,6 @@ describe("useHandleMcpDrillThrough", () => {
// Unjustified type cast. FIXME
(window as any).metabaseConfig = {
instanceUrl: "https://metabase.example",
- uiCredential: "ui-credential",
- mcpSessionId: "mcp-session-id",
};
fetchMock.post("path:/api/embed-mcp/drills", { handle: "drill-handle" });
@@ -39,8 +37,13 @@ describe("useHandleMcpDrillThrough", () => {
};
const defaultNavigate = jest.fn();
- // Unjustified type cast. FIXME
- const { result } = renderHook(() => useHandleMcpDrillThrough(app as any));
+ const { result } = renderHook(() =>
+ useHandleMcpDrillThrough({
+ app,
+ uiCredential: "ui-credential",
+ mcpSessionId: "mcp-session-id",
+ }),
+ );
await result.current(
{ drillName: "fk-details", nextCard: NEXT_CARD },
@@ -68,8 +71,13 @@ describe("useHandleMcpDrillThrough", () => {
};
const defaultNavigate = jest.fn();
- // Unjustified type cast. FIXME
- const { result } = renderHook(() => useHandleMcpDrillThrough(app as any));
+ const { result } = renderHook(() =>
+ useHandleMcpDrillThrough({
+ app,
+ uiCredential: "ui-credential",
+ mcpSessionId: "mcp-session-id",
+ }),
+ );
await result.current(
{ drillName: "fk-details", nextCard: NEXT_CARD },
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx
index de964939707..46c8ed1e654 100644
--- a/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx
+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx
@@ -6,11 +6,17 @@ import {
applyHostStyleVariables,
useApp,
} from "@modelcontextprotocol/ext-apps/react";
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+import { useMcpUiAuth } from "../auth";
export interface McpAppState {
query: string | null;
+ uiCredential: string;
+ mcpSessionId: string;
+ hostError: string | null;
+
/**
* Original user prompt that triggered this visualization, retrieved
* from `construct_query`, e.g. "visualize orders with Metabase".
@@ -21,10 +27,6 @@ export interface McpAppState {
app: App | null;
}
-type VisualizeQueryToolInput = {
- query?: string;
-};
-
type VisualizeQueryToolResult = {
query?: string;
prompt?: string;
@@ -46,9 +48,12 @@ function applyHostContext(ctx: McpUiHostContext) {
export function useMcpApp(): McpAppState {
const [query, setQuery] = useState<string | null>(null);
+ const [toolResultVersion, setToolResultVersion] = useState(0);
+ const pendingToolResultRef = useRef<VisualizeQueryToolResult | null>(null);
const [prompt, setPrompt] = useState<string | null>(null);
const [hostContext, setHostContext] = useState<McpUiHostContext | null>(null);
+ // `app` is stable across re-renders
const { app } = useApp({
appInfo: { name: "metabase-visualize-query", version: "1.0.0" },
capabilities: {},
@@ -60,20 +65,6 @@ export function useMcpApp(): McpAppState {
}
};
- app.ontoolinput = (params) => {
- const { query } =
- // Unjustified type cast. FIXME
- (params.arguments as VisualizeQueryToolInput | undefined) ?? {};
-
- if (query) {
- setQuery(query);
- setPrompt(null);
- }
- };
-
- // Fallback: ontoolinput may be missed if the tool returns instantly
- // (notification sent before the app finishes connecting).
- // Also the source of `prompt`, which visualize_query includes in structuredContent.
app.ontoolresult = (params) => {
const { query, prompt } =
// Unjustified type cast. FIXME
@@ -81,13 +72,35 @@ export function useMcpApp(): McpAppState {
{};
if (query) {
- setQuery(query);
- setPrompt(prompt ?? null);
+ pendingToolResultRef.current = { query, prompt };
+
+ setToolResultVersion((version) => version + 1);
}
};
},
});
+ const handleAuthenticated = useCallback(() => {
+ const toolResult = pendingToolResultRef.current;
+
+ if (!toolResult?.query) {
+ return;
+ }
+
+ setQuery(toolResult.query);
+ setPrompt(toolResult.prompt ?? null);
+ }, []);
+
+ const {
+ uiCredential,
+ mcpSessionId,
+ error: authError,
+ } = useMcpUiAuth({
+ app,
+ refreshKey: toolResultVersion,
+ onAuthenticated: handleAuthenticated,
+ });
+
// Read host context once connected and apply styles immediately
useEffect(() => {
if (app) {
@@ -100,5 +113,13 @@ export function useMcpApp(): McpAppState {
}
}, [app]);
- return { query, prompt, hostContext, app };
+ return {
+ query,
+ prompt,
+ uiCredential,
+ mcpSessionId,
+ hostError: authError,
+ hostContext,
+ app,
+ };
}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.unit.spec.tsx b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.unit.spec.tsx
new file mode 100644
index 00000000000..d841176d868
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.unit.spec.tsx
@@ -0,0 +1,386 @@
+import type {
+ App,
+ McpUiToolResultNotification,
+} from "@modelcontextprotocol/ext-apps/react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+
+import { MCP_APPS_METADATA_KEY } from "../constants";
+
+import { useMcpApp } from "./useMcpApp";
+
+const mockUseApp = jest.fn();
+
+interface TestMcpApp {
+ callServerTool: jest.MockedFunction<App["callServerTool"]>;
+ getHostCapabilities: jest.MockedFunction<App["getHostCapabilities"]>;
+ getHostContext: jest.MockedFunction<App["getHostContext"]>;
+ getHostVersion: jest.MockedFunction<App["getHostVersion"]>;
+
+ ontoolresult: (params: McpUiToolResultNotification["params"]) => void;
+}
+
+const QUERY_RESULT: McpUiToolResultNotification["params"] = {
+ content: [],
+ structuredContent: { query: "encoded-query" },
+};
+
+const NEXT_QUERY_RESULT: McpUiToolResultNotification["params"] = {
+ content: [],
+ structuredContent: { query: "next-encoded-query" },
+};
+
+const createAuthResult = (
+ credential = "refreshed-credential",
+ sessionId = "mcp-session-id",
+): Awaited<ReturnType<App["callServerTool"]>> => ({
+ content: [],
+ _meta: {
+ [MCP_APPS_METADATA_KEY]: { credential, sessionId },
+ },
+});
+
+const createTestApp = (overrides: Partial<TestMcpApp> = {}): TestMcpApp => ({
+ callServerTool: jest.fn(),
+ getHostCapabilities: jest.fn(() => ({})),
+ getHostContext: jest.fn(() => undefined),
+ getHostVersion: jest.fn(() => undefined),
+ ontoolresult: jest.fn(),
+ ...overrides,
+});
+
+const setup = (overrides: Partial<TestMcpApp> = {}) => {
+ const app = createTestApp(overrides);
+ let appCreated = false;
+
+ mockUseApp.mockImplementation(({ onAppCreated }) => {
+ if (!appCreated) {
+ appCreated = true;
+ onAppCreated(app);
+ }
+
+ return { app };
+ });
+
+ return { app, ...renderHook(() => useMcpApp()) };
+};
+
+jest.mock("@modelcontextprotocol/ext-apps/react", () => ({
+ applyDocumentTheme: jest.fn(),
+ applyHostFonts: jest.fn(),
+ applyHostStyleVariables: jest.fn(),
+ useApp: (...args: unknown[]) => mockUseApp(...args),
+}));
+
+describe("useMcpApp", () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ jest.restoreAllMocks();
+
+ mockUseApp.mockReset();
+ });
+
+ it("gets auth from the server tool instead of the visualization result", async () => {
+ const { app, result } = setup({
+ callServerTool: jest.fn().mockResolvedValue(createAuthResult()),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ act(() => {
+ app.ontoolresult({
+ ...QUERY_RESULT,
+ _meta: {
+ [MCP_APPS_METADATA_KEY]: {
+ credential: "tool-result-credential",
+ sessionId: "tool-result-session-id",
+ },
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(app.callServerTool).toHaveBeenCalledWith(
+ {
+ name: "refresh_ui_credential",
+ arguments: {},
+ },
+ {
+ signal: expect.any(AbortSignal),
+ timeout: 10 * 1000,
+ },
+ );
+
+ expect(result.current.query).toBe("encoded-query");
+ expect(result.current.uiCredential).toBe("refreshed-credential");
+ expect(result.current.mcpSessionId).toBe("mcp-session-id");
+ });
+ });
+
+ it("reports an unsupported host when server tools are unavailable", () => {
+ // callServerTool is unavailable here
+ const { app, result } = setup({
+ getHostVersion: jest.fn(() => ({
+ name: "Codex Desktop",
+ version: "1.0.0",
+ })),
+ });
+
+ act(() => app.ontoolresult(QUERY_RESULT));
+
+ expect(result.current.hostError).toBe(
+ "Codex Desktop does not support query visualization.",
+ );
+ });
+
+ it("gets fresh auth when the host reuses the same query", async () => {
+ const { app } = setup({
+ callServerTool: jest.fn().mockResolvedValue(createAuthResult()),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(app.callServerTool).toHaveBeenCalledTimes(1);
+ const firstSignal = app.callServerTool.mock.calls[0][1]?.signal;
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(app.callServerTool).toHaveBeenCalledTimes(2);
+ const secondSignal = app.callServerTool.mock.calls[1][1]?.signal;
+
+ expect(firstSignal).not.toBe(secondSignal);
+ expect(firstSignal?.aborted).toBe(false);
+ });
+
+ it("keeps the previous query and auth while a new tool result authenticates", async () => {
+ let resolveRefresh!: (result: ReturnType<typeof createAuthResult>) => void;
+ const pendingRefresh = new Promise<ReturnType<typeof createAuthResult>>(
+ (resolve) => {
+ resolveRefresh = resolve;
+ },
+ );
+ const { app, result } = setup({
+ callServerTool: jest
+ .fn()
+ .mockResolvedValueOnce(
+ createAuthResult("initial-credential", "initial-session-id"),
+ )
+ .mockReturnValueOnce(pendingRefresh),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(result.current.uiCredential).toBe("initial-credential");
+ expect(result.current.mcpSessionId).toBe("initial-session-id");
+ expect(result.current.query).toBe("encoded-query");
+
+ act(() => app.ontoolresult(NEXT_QUERY_RESULT));
+ expect(result.current.uiCredential).toBe("initial-credential");
+ expect(result.current.mcpSessionId).toBe("initial-session-id");
+ expect(result.current.query).toBe("encoded-query");
+
+ await act(async () => {
+ resolveRefresh(createAuthResult("next-credential", "next-session-id"));
+ await pendingRefresh;
+ });
+ expect(result.current.uiCredential).toBe("next-credential");
+ expect(result.current.mcpSessionId).toBe("next-session-id");
+ expect(result.current.query).toBe("next-encoded-query");
+ });
+
+ it("aborts an in-flight auth request when a newer tool result arrives", async () => {
+ let resolveFirstRefresh!: (
+ result: ReturnType<typeof createAuthResult>,
+ ) => void;
+ const firstRefresh = new Promise<ReturnType<typeof createAuthResult>>(
+ (resolve) => {
+ resolveFirstRefresh = resolve;
+ },
+ );
+ const { app, result } = setup({
+ callServerTool: jest
+ .fn()
+ .mockReturnValueOnce(firstRefresh)
+ .mockResolvedValueOnce(
+ createAuthResult("next-credential", "next-session-id"),
+ ),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ act(() => app.ontoolresult(QUERY_RESULT));
+ const firstSignal = app.callServerTool.mock.calls[0][1]?.signal;
+
+ await act(async () => app.ontoolresult(NEXT_QUERY_RESULT));
+
+ expect(firstSignal?.aborted).toBe(true);
+ expect(result.current.query).toBe("next-encoded-query");
+ expect(result.current.uiCredential).toBe("next-credential");
+
+ await act(async () => {
+ resolveFirstRefresh(
+ createAuthResult("stale-credential", "stale-session-id"),
+ );
+ await firstRefresh;
+ });
+
+ expect(result.current.query).toBe("next-encoded-query");
+ expect(result.current.uiCredential).toBe("next-credential");
+ });
+
+ it("reports an error after two initial credential refresh failures", async () => {
+ jest.useFakeTimers();
+ jest.spyOn(console, "error").mockImplementation();
+
+ const { app, result } = setup({
+ callServerTool: jest.fn().mockRejectedValue(new Error("Refresh failed")),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(result.current.hostError).toBeNull();
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(30 * 1000);
+ });
+
+ expect(app.callServerTool).toHaveBeenCalledTimes(2);
+
+ expect(result.current.hostError).toBe(
+ "This visualization did not load. Ask your MCP client to show it again.",
+ );
+ });
+
+ it("keeps retrying after background credential refresh failures", async () => {
+ jest.useFakeTimers();
+ jest.spyOn(console, "error").mockImplementation();
+
+ const { app, result } = setup({
+ callServerTool: jest
+ .fn()
+ .mockResolvedValueOnce(createAuthResult("initial-credential"))
+ .mockRejectedValueOnce(new Error("Refresh failed"))
+ .mockRejectedValueOnce(new Error("Refresh failed"))
+ .mockResolvedValueOnce(createAuthResult("recovered-credential")),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(result.current.uiCredential).toBe("initial-credential");
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(3 * 60 * 1000);
+ await jest.advanceTimersByTimeAsync(30 * 1000);
+ });
+
+ expect(app.callServerTool).toHaveBeenCalledTimes(3);
+ expect(result.current.hostError).toBeNull();
+ expect(result.current.uiCredential).toBe("initial-credential");
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(30 * 1000);
+ });
+
+ expect(app.callServerTool).toHaveBeenCalledTimes(4);
+ expect(result.current.hostError).toBeNull();
+ expect(result.current.uiCredential).toBe("recovered-credential");
+ });
+
+ it("keeps retrying when auth refresh fails for a repeated tool result", async () => {
+ jest.useFakeTimers();
+ jest.spyOn(console, "error").mockImplementation();
+
+ const { app, result } = setup({
+ callServerTool: jest
+ .fn()
+ .mockResolvedValueOnce(createAuthResult("initial-credential"))
+ .mockRejectedValueOnce(new Error("Refresh failed"))
+ .mockRejectedValueOnce(new Error("Refresh failed"))
+ .mockResolvedValueOnce(createAuthResult("recovered-credential")),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(result.current.uiCredential).toBe("initial-credential");
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(30 * 1000);
+ });
+
+ expect(app.callServerTool).toHaveBeenCalledTimes(3);
+ expect(result.current.hostError).toBeNull();
+ expect(result.current.uiCredential).toBe("initial-credential");
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(30 * 1000);
+ });
+
+ expect(app.callServerTool).toHaveBeenCalledTimes(4);
+ expect(result.current.hostError).toBeNull();
+ expect(result.current.uiCredential).toBe("recovered-credential");
+ });
+
+ it("does not reuse expired auth for a repeated tool result", async () => {
+ jest.useFakeTimers();
+ jest.spyOn(console, "error").mockImplementation();
+
+ const { app, result } = setup({
+ callServerTool: jest
+ .fn()
+ .mockResolvedValueOnce(createAuthResult("initial-credential"))
+ .mockRejectedValue(new Error("Refresh failed")),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(result.current.uiCredential).toBe("initial-credential");
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(4.5 * 60 * 1000);
+ });
+ expect(result.current.uiCredential).toBe("");
+ expect(result.current.mcpSessionId).toBe("");
+
+ await act(async () => app.ontoolresult(QUERY_RESULT));
+ expect(result.current.uiCredential).toBe("");
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(30 * 1000);
+ });
+ expect(result.current.hostError).toBe(
+ "This visualization did not load. Ask your MCP client to show it again.",
+ );
+ });
+
+ it("measures credential validity from the successful request start", async () => {
+ jest.useFakeTimers();
+ jest.spyOn(console, "error").mockImplementation();
+
+ let resolveRefresh!: (result: ReturnType<typeof createAuthResult>) => void;
+ const delayedRefresh = new Promise<ReturnType<typeof createAuthResult>>(
+ (resolve) => {
+ resolveRefresh = resolve;
+ },
+ );
+ const { app, result } = setup({
+ callServerTool: jest
+ .fn()
+ .mockReturnValueOnce(delayedRefresh)
+ .mockRejectedValue(new Error("Refresh failed")),
+ getHostCapabilities: jest.fn(() => ({ serverTools: {} })),
+ });
+
+ act(() => app.ontoolresult(QUERY_RESULT));
+ expect(app.callServerTool).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(60 * 1000);
+ resolveRefresh(createAuthResult("delayed-credential"));
+ await delayedRefresh;
+ });
+ expect(result.current.uiCredential).toBe("delayed-credential");
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(3.5 * 60 * 1000);
+ });
+ expect(result.current.uiCredential).toBe("");
+ expect(result.current.mcpSessionId).toBe("");
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts
index 4fe8a716ea0..68a598ac1c8 100644
--- a/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts
+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts
@@ -34,6 +34,10 @@ export function useMcpUserAndSettingsFetch({
// selectors like getTokenFeature has populated settings.
// We also no-op the EE auth flow (auth.ts) when in MCP Apps route.
useEffect(() => {
+ if (isSettingsReady) {
+ return;
+ }
+
let isMounted = true;
const setErrorByType = (type: McpAppsUserAndSettingsFetchErrorType) =>
@@ -45,7 +49,6 @@ export function useMcpUserAndSettingsFetch({
setFetchError(null);
if (!uiCredential) {
- setErrorByType("auth");
return;
}
@@ -80,7 +83,7 @@ export function useMcpUserAndSettingsFetch({
return () => {
isMounted = false;
};
- }, [instanceUrl, uiCredential, store]);
+ }, [instanceUrl, isSettingsReady, uiCredential, store]);
return { isSettingsReady, userAndSettingsFetchError: fetchError };
}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.unit.spec.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.unit.spec.ts
new file mode 100644
index 00000000000..b44cdf71d27
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.unit.spec.ts
@@ -0,0 +1,43 @@
+import { renderHook, waitFor } from "@testing-library/react";
+
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+
+import { useMcpUserAndSettingsFetch } from "./useMcpUserAndSettingsFetch";
+
+jest.mock("metabase/current-user", () => ({
+ refetchCurrentUser: jest.fn(() => ({ type: "refetch-current-user" })),
+}));
+
+jest.mock("metabase/settings", () => ({
+ refetchSiteSettings: jest.fn(() => ({ type: "refetch-site-settings" })),
+}));
+
+describe("useMcpUserAndSettingsFetch", () => {
+ it("keeps settings ready state even when the ui credential changes", async () => {
+ const unwrap = jest.fn().mockResolvedValue(undefined);
+ const dispatch = jest.fn(() => ({ unwrap }));
+
+ // The hook only uses dispatch
+ const store = { dispatch } as unknown as SdkStore;
+
+ const { result, rerender } = renderHook(
+ ({ uiCredential }) =>
+ useMcpUserAndSettingsFetch({
+ instanceUrl: "http://localhost:3000",
+ store,
+ uiCredential,
+ }),
+ { initialProps: { uiCredential: "credential-1" } },
+ );
+
+ await waitFor(() => {
+ expect(result.current.isSettingsReady).toBe(true);
+ });
+
+ expect(dispatch).toHaveBeenCalledTimes(2);
+
+ rerender({ uiCredential: "credential-2" });
+ expect(result.current.isSettingsReady).toBe(true);
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/resources/frontend_client/mcp_apps_template.html b/resources/frontend_client/mcp_apps_template.html
index e767de8a629..442eb8ab56d 100644
--- a/resources/frontend_client/mcp_apps_template.html
+++ b/resources/frontend_client/mcp_apps_template.html
@@ -88,9 +88,7 @@
<script>
window.metabaseConfig = {
- instanceUrl: {{{instanceUrl}}},
- uiCredential: {{{uiCredential}}},
- mcpSessionId: {{{mcpSessionId}}}
+ instanceUrl: {{{instanceUrl}}}
};
</script>
</body>
diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.clj
index 93721eb07ef..e7cf54b2ad5 100644
--- a/src/metabase/mcp/api.clj
+++ b/src/metabase/mcp/api.clj
@@ -95,14 +95,11 @@
(defn- handle-resources-list [id _params token-scopes]
(jsonrpc-response id (mcp.resources/list-resources token-scopes)))
-(defn- handle-resources-read [id params session-id token-scopes]
+(defn- handle-resources-read [id params token-scopes]
(let [uri (:uri params)]
(if (or (not (string? uri)) (str/blank? uri))
(jsonrpc-error id -32602 "Missing required parameter: uri")
- (let [user-id api/*current-user-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)]
+ (let [result (mcp.resources/read-resource uri token-scopes {})]
(case (:status result)
(:not-found :scope-denied) (jsonrpc-error id -32602 "Resource not found")
:ok (jsonrpc-response id {:contents (:contents result)}))))))
@@ -134,7 +131,7 @@
"tools/list" (handle-tools-list id params session-id token-scopes)
"tools/call" (handle-tools-call id params session-id token-scopes request-context)
"resources/list" (handle-resources-list id params token-scopes)
- "resources/read" (handle-resources-read id params session-id token-scopes)
+ "resources/read" (handle-resources-read id params token-scopes)
"ping" (handle-ping id params)
(if id
(jsonrpc-error id -32601 (str "Method not found: " method))
@@ -167,7 +164,11 @@
:mcp/scopes token-scopes}
(let [response (dispatch-method id method params session-id token-scopes request-context)]
;; record the materialized JSON-RPC result/error (the request's output)
- (ait/record! {:mcp/response response})
+ (when (ait/capture-active?)
+ (ait/record! {:mcp/response
+ (cond-> response
+ (contains? response :result)
+ (update :result mcp.resources/redact-ui-credential))}))
response))))
;;; ----------------------------------------------------- SSE ------------------------------------------------------
diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.clj
index 223f0b06f66..a2ad92d0392 100644
--- a/src/metabase/mcp/resources.clj
+++ b/src/metabase/mcp/resources.clj
@@ -36,8 +36,7 @@
(def ^:private test-fallback-template
(str "<!doctype html><html><head><base href=\"{{{instanceUrlRaw}}}/\"></head><body><script>"
"window.metabaseConfig = {"
- "instanceUrl: {{{instanceUrl}}},"
- "uiCredential: {{{uiCredential}}}"
+ "instanceUrl: {{{instanceUrl}}}"
"};</script></body></html>"))
;; An atom rather than a dynamic var because `resources/read` is invoked from the
@@ -63,13 +62,14 @@
(defn render-embed-mcp-template
"Render the embed-mcp.html Mustache template with the given vars map.
- Expected keys: :instanceUrl (JSON-encoded), :instanceUrlRaw, :uiCredential (JSON-encoded or nil),
- :mcpSessionId (JSON-encoded or nil)."
+ Expected keys: :instanceUrl (JSON-encoded) and :instanceUrlRaw."
[vars]
(cond
(io/resource embed-mcp-template-path)
(stencil/render-file embed-mcp-template-path vars)
+ ;; Backend-only tests install this stub when the frontend build is absent. A
+ ;; real build must win so tests and shared REPL JVMs exercise production HTML.
@fallback-template
(stencil/render-string @fallback-template vars)
@@ -188,27 +188,39 @@
[schema]
(tools-manifest/malli->json-schema schema))
-(mu/defn- register-ui-tool!
+(mu/defn- register-ui-tool-for-resources!
+ [resource-keys :- [:sequential :keyword]
+ tool :- [:map
+ [:name :string]
+ [:description :string]
+ [:inputSchema :any]
+ [:outputSchema {:optional true} :any]
+ [:annotations {:optional true} :map]
+ [:visibility {:optional true} [:sequential [:enum "model" "app"]]]
+ [:response-fn fn?]]]
+ (let [resources (mapv (fn [resource-key]
+ (if-let [uri (get-in @registry [:key->uri resource-key])]
+ (get-in @registry [:uri->resource uri])
+ (throw (ex-info "Unknown resource" {:resource-key resource-key}))))
+ resource-keys)
+ scopes (into #{} (map :scope) resources)
+ ui-meta (cond-> {}
+ (= 1 (count resources)) (assoc :resourceUri (:uri (first resources)))
+ (:visibility tool) (assoc :visibility (:visibility tool)))
+ tool (-> tool
+ (dissoc :visibility)
+ (update :inputSchema malli->ui-input-schema)
+ (cond-> (:outputSchema tool) (update :outputSchema malli->ui-output-schema))
+ (assoc :scope (if (= 1 (count scopes)) (first scopes) scopes)
+ :required-extensions #{:mcp-app-ui}
+ :_meta {:ui ui-meta}))]
+ (swap! registry assoc-in [:tools (:name tool)] tool)
+ tool))
+
+(defn- register-ui-tool!
"Register a UI tool. `inputSchema` and `outputSchema` are Malli schemas (not JSON Schema)."
- [resource-key :- :keyword
- tool :- [:map
- [:name :string]
- [:description :string]
- [:inputSchema :any]
- [:outputSchema {:optional true} :any]
- [:annotations {:optional true} :map]
- [:response-fn fn?]]]
- (if-let [uri (get-in @registry [:key->uri resource-key])]
- (let [scope (get-in @registry [:uri->resource uri :scope])
- tool (-> tool
- (update :inputSchema malli->ui-input-schema)
- (cond-> (:outputSchema tool) (update :outputSchema malli->ui-output-schema))
- (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}))))
+ [resource-key tool]
+ (register-ui-tool-for-resources! [resource-key] tool))
(defn resource-scopes
"Return the distinct set of scopes registered across all UI resources."
@@ -230,11 +242,31 @@
(:ui? resource) (assoc :_meta (ui-meta resource))))))
(vals (:uri->resource @registry)))})
+(def ^:private compatible-mcp-app-uri-pattern
+ #"^ui://metabase/(visualize-query|render-drill-through)(?:-v2|\.[0-9a-f]+)?\.html$")
+
+(def ^:private mcp-app-name->resource-key
+ {"visualize-query" :visualize-query
+ "render-drill-through" :render-drill-through})
+
+(defn- resource-for-uri
+ "Resolve current resource URIs exactly. Known MCP App URI variants resolve to
+ the corresponding current resource. This compatibility step must ship before
+ build-versioned URIs are advertised so rolling upgrades remain safe."
+ [uri]
+ (let [snapshot @registry]
+ (or (get-in snapshot [:uri->resource uri])
+ (when-let [[_ app-name] (re-matches compatible-mcp-app-uri-pattern uri)]
+ (let [resource-key (get mcp-app-name->resource-key app-name)
+ current-uri (get-in snapshot [:key->uri resource-key])]
+ (some-> (get-in snapshot [:uri->resource current-uri])
+ (assoc :uri uri)))))))
+
(defn check-resource-access
"Check whether `uri` exists and is accessible under `token-scopes`.
Returns :ok, :not-found, or :scope-denied."
[uri token-scopes]
- (if-let [{:keys [scope]} (get-in @registry [:uri->resource uri])]
+ (if-let [{:keys [scope]} (resource-for-uri uri)]
(if (mcp.scope/public-or-matches? token-scopes scope)
:ok
:scope-denied)
@@ -243,14 +275,14 @@
(defn read-resource
"Read a registered resource by URI, gated by `token-scopes`. Returns one of
`{:status :ok :contents [...]}`, `{:status :scope-denied}`, or
- `{:status :not-found}`. Single registry lookup keeps the gate atomic with the
- render, so callers cannot bypass the scope check."
+ `{:status :not-found}`. Resource resolution and scope enforcement use the same
+ immutable registry snapshot, so aliases cannot bypass the scope check."
[uri token-scopes opts]
- (if-let [{:keys [render-fn scope ui?] :as resource} (get-in @registry [:uri->resource uri])]
+ (if-let [{:keys [render-fn scope ui?] :as resource} (resource-for-uri uri)]
(if (mcp.scope/public-or-matches? token-scopes scope)
{:status :ok
:contents [(cond-> (select-keys resource [:uri :mimeType])
- true (assoc :text (render-fn opts))
+ true (assoc :text (render-fn (assoc opts :resource-uri uri)))
ui? (assoc :_meta (ui-meta resource)))]}
{:status :scope-denied})
{:status :not-found}))
@@ -286,19 +318,15 @@
(notably ChatGPT, which otherwise skips rendering a new iframe for a tool
whose `_meta.ui.resourceUri` already has one mounted) treat them as distinct.
`tag` is a per-URI marker embedded in the rendered HTML so the bytes hash
- differently — ChatGPT's asset CDN appears to dedupe by body hash, and without
+ differently — ChatGPT's asset CDN appears to dedupe by body hash, and without
distinct bodies the second URI's asset is silently dropped and the widget 404s."
[tag]
- (fn [opts]
- (let [site-url (system/site-url)
- ui-credential (:ui-credential opts)
- session-id (:session-id opts)]
- (str "<!-- metabase-mcp-asset: " tag " -->\n"
+ (fn [{:keys [resource-uri]}]
+ (let [site-url (system/site-url)]
+ (str "<!-- metabase-mcp-asset: " tag " " resource-uri " -->\n"
(render-embed-mcp-template
{:instanceUrl (json/encode site-url)
- :instanceUrlRaw site-url
- :uiCredential (when ui-credential (json/encode ui-credential))
- :mcpSessionId (when session-id (json/encode session-id))})))))
+ :instanceUrlRaw site-url})))))
(register-ui-resource!
:visualize-query
@@ -318,6 +346,37 @@
:prefersBorder true
:render-fn (visualize-query-render-fn "render-drill-through")})
+(defn- with-ui-credential
+ [result session-id]
+ (if (and session-id api/*current-user-id*)
+ (assoc result :_meta {:com.metabase/mcp-apps
+ {:credential (mcp.session/issue-ui-credential session-id api/*current-user-id*)
+ :sessionId session-id}})
+ {:content [{:type "text"
+ :text "MCP UI credential refresh requires an authenticated MCP session."}]
+ :isError true}))
+
+(defn redact-ui-credential
+ "Remove the private MCP UI credential from a tool result before tracing it."
+ [result]
+ (cond-> result
+ (map? (:_meta result)) (update :_meta dissoc :com.metabase/mcp-apps)))
+
+(register-ui-tool-for-resources!
+ [:visualize-query :render-drill-through]
+ {:name "refresh_ui_credential"
+ :description "Refresh the scoped credential used by a Metabase MCP App."
+ :inputSchema [:map]
+ :annotations {:readOnlyHint true
+ :destructiveHint false
+ :idempotentHint true
+ :openWorldHint false}
+ :visibility ["app"]
+ :response-fn (fn [_arguments {:keys [session-id]}]
+ (with-ui-credential
+ {:content [{:type "text" :text "MCP UI credential refreshed."}]}
+ session-id))})
+
(register-ui-tool!
:visualize-query
{:name "visualize_query"
diff --git a/src/metabase/mcp/scope.clj b/src/metabase/mcp/scope.clj
index 96728ae61d1..8fef085a1f8 100644
--- a/src/metabase/mcp/scope.clj
+++ b/src/metabase/mcp/scope.clj
@@ -8,17 +8,21 @@
[metabase.api.macros.scope :as api.scope]))
(defn matches?
- "Does `token-scopes` grant access to an entity with the given `required-scope`?
+ "Does `token-scopes` grant access to an entity with the given `required-scope`, or any member of a set of
+ alternative scopes?
- nil `token-scopes` always matches (internal callers).
- `::api.scope/unrestricted` in `token-scopes` always matches.
+ - A set of required scopes matches when any member matches.
- nil `required-scope` only matches the two cases above (callers that want
\"public to any authenticated MCP user\" should use [[public-or-matches?]]).
- Otherwise delegates wildcard/exact matching to [[api.scope/scope-satisfied?]]."
[token-scopes required-scope]
(or (nil? token-scopes)
(contains? token-scopes ::api.scope/unrestricted)
- (boolean (and (some? required-scope)
- (api.scope/scope-satisfied? token-scopes required-scope)))))
+ (if (set? required-scope)
+ (boolean (some #(matches? token-scopes %) required-scope))
+ (boolean (and (some? required-scope)
+ (api.scope/scope-satisfied? token-scopes required-scope))))))
(defn public-or-matches?
"Like [[matches?]] but treats a nil `required-scope` as \"public to any caller\"
diff --git a/src/metabase/mcp/session.clj b/src/metabase/mcp/session.clj
index 224df909c7e..bbb59d0c838 100644
--- a/src/metabase/mcp/session.clj
+++ b/src/metabase/mcp/session.clj
@@ -78,8 +78,8 @@
(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."
+ "Lifetime of an MCP Apps UI credential. The server sends the credential in
+ private tool-result metadata."
300)
(defn- base64url-encode [^String value]
diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.clj
index 2b928eb7d15..b64b76cde32 100644
--- a/src/metabase/mcp/tools.clj
+++ b/src/metabase/mcp/tools.clj
@@ -573,7 +573,8 @@
(when error? (some-> result :content first :text)))
;; `::error-code` is an internal classification marker — never expose it to the client.
(let [result (dissoc result ::error-code)]
- (ait/record! {:ai/tool-output result})
+ (when (ait/capture-active?)
+ (ait/record! {:ai/tool-output (mcp.resources/redact-ui-credential result)}))
result))
(catch Throwable e
;; A handler that throws instead of returning error content (notably a UI tool
diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.clj
index fbcdfe6e2ae..2a5d06b29dd 100644
--- a/src/metabase/server/middleware/session.clj
+++ b/src/metabase/server/middleware/session.clj
@@ -323,9 +323,8 @@
[: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."
+ "Resolve the short-lived credential from an MCP App tool result.
+ Accept it only for [[mcp-ui-request-surface]]."
[request]
(when (and (init-status/complete?)
(contains? mcp-ui-request-surface [(:request-method request) (:uri request)]))
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index b765640e28e..fabd9aecbac 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -315,6 +315,7 @@
"execute_sql"
"query"
"read_resource"
+ "refresh_ui_credential"
"render_drill_through"
"search"
"update_dashboard"
@@ -344,7 +345,11 @@
(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 (= (apply disj all-tool-names
+ ["visualize_query"
+ "render_drill_through"
+ "refresh_ui_credential"])
+ 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"
@@ -703,8 +708,9 @@
(deftest tools-call-smoke-test-covers-all-agent-api-backed-tools-test
(testing "every Agent API-backed tool is exercised by the smoke test"
- (is (= (apply disj (set (map :name (mcp.tools/list-tools nil)))
- ["visualize_query" "render_drill_through"])
+ (is (= (apply disj
+ (set (map :name (mcp.tools/list-tools nil)))
+ (map :name (mcp.resources/list-ui-tools)))
smoke-tested-tools)
"Add the missing tool to `smoke-tested-tools` and the call sequence below.")))
@@ -806,6 +812,74 @@
:structuredContent {:query "card__1"}}
result)))))
+(deftest ui-tools-do-not-return-ui-credentials-test
+ (testing "visualization tools leave credential minting to their app-only refresh tools"
+ (let [[session-id _] (initialize!)
+ visualize-result (get-in (mcp-request (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {:query "card__1"}})
+ {"mcp-session-id" session-id})
+ [:body :result])
+ handle (mt/with-current-user (mt/user->id :crowberto)
+ (mcp.session/store-handle! session-id
+ (mt/user->id :crowberto)
+ "card__2"))
+ drill-result (get-in (mcp-request (jsonrpc-request "tools/call"
+ {:name "render_drill_through"
+ :arguments {:handle handle}})
+ {"mcp-session-id" session-id})
+ [:body :result])]
+ (is (nil? (get-in visualize-result [:_meta :com.metabase/mcp-apps])))
+ (is (nil? (get-in drill-result [:_meta :com.metabase/mcp-apps]))))))
+
+(deftest mcp-ui-auth-refresh-tools-test
+ (testing "UI auth refresh tools are app-only and inherit their resource scopes"
+ (let [[session-id _] (initialize!)
+ tools (get-in (mcp-request (jsonrpc-request "tools/list")
+ {"mcp-session-id" session-id})
+ [:body :result :tools])
+ tools-by-name (into {} (map (juxt :name identity)) tools)
+ refresh-tool (get tools-by-name "refresh_ui_credential")]
+ (is (=? {:_meta {:ui {:visibility ["app"]}}}
+ refresh-tool))
+ (is (nil? (get-in refresh-tool [:_meta :ui :resourceUri]))))
+ (let [query-tools (into #{} (map :name)
+ (mcp.tools/list-tools #{"agent:viz:mcp-ui:query"}))
+ drill-tools (into #{} (map :name)
+ (mcp.tools/list-tools #{"agent:viz:mcp-ui:drill-through"}))]
+ (is (contains? query-tools "refresh_ui_credential"))
+ (is (contains? drill-tools "refresh_ui_credential"))))
+ (testing "a refresh call returns session-bound auth only in private metadata"
+ (let [[session-id _] (initialize!)
+ result (get-in (mcp-request
+ (jsonrpc-request "tools/call"
+ {:name "refresh_ui_credential"
+ :arguments {}})
+ {"mcp-session-id" session-id})
+ [:body :result])
+ credential (get-in result [:_meta :com.metabase/mcp-apps :credential])]
+ (is (string? credential))
+ (is (= session-id (get-in result [:_meta :com.metabase/mcp-apps :sessionId])))
+ (is (not (str/includes? (pr-str (select-keys result [:content :structuredContent]))
+ credential))))))
+
+(deftest refresh-ui-credential-is-redacted-from-tool-traces-test
+ (testing "refresh_ui_credential returns private credentials without storing it in AI traces"
+ (let [session-id (str (random-uuid))
+ {:keys [result trace]}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (ait/capturing
+ (mcp.tools/call-tool #{::scope/unrestricted}
+ session-id
+ "refresh_ui_credential"
+ {})))
+ credential (get-in result [:_meta :com.metabase/mcp-apps :credential])
+ tool-output (get-in trace [0 :attributes :ai/tool-output])]
+ (is (string? credential))
+ (is (= session-id (get-in result [:_meta :com.metabase/mcp-apps :sessionId])))
+ (is (= (assoc result :_meta {}) tool-output))
+ (is (not (str/includes? (pr-str trace) credential))))))
+
(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!)
@@ -1639,7 +1713,7 @@
;;; -------------------------------------------- Session Lifecycle -------------------------------------------------
(deftest resources-read-renders-ui-configuration-test
- (testing "multiple resources/read calls within one session render a usable UI configuration"
+ (testing "UI resources contain stable configuration without a short-lived credential"
(let [[session-id _] (initialize!)
read1 (mcp-request (jsonrpc-request "resources/read"
{:uri "ui://metabase/visualize-query.html"} 1)
@@ -1649,15 +1723,19 @@
{"mcp-session-id" session-id})]
(is (= 200 (:status read1)))
(is (= 200 (:status read2)))
- ;; Each resource response contains an independently short-lived UI credential.
+ ;; The resource is safe to cache because it contains only stable configuration.
(let [html1 (-> (get-in read1 [:body :result :contents]) first :text)
html2 (-> (get-in read2 [:body :result :contents]) first :text)]
(is (some? html1))
- (is (str/includes? html1 "uiCredential"))
- (is (str/includes? html2 "uiCredential"))))))
+ (is (not (str/includes? html1 "uiCredential")))
+ (is (not (str/includes? html2 "uiCredential")))
+ (is (not (str/includes? html1 "mcpSessionId")))
+ (is (not (str/includes? html2 "mcpSessionId")))
+ (is (not (str/includes? html1 "refreshTool")))
+ (is (not (str/includes? html2 "refreshTool")))))))
(deftest mcp-ui-credential-validation-test
- (testing "a scoped MCP Apps resource provides the UI request surface, but not general API access"
+ (testing "an app-only refresh tool provides the scoped 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!)
@@ -1666,11 +1744,12 @@
_ (save-access-token! token (mt/user->id :crowberto) client-id #{"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"})
+ tool-result (mcp-request-with-bearer token 200
+ (jsonrpc-request "tools/call"
+ {:name "refresh_ui_credential"
+ :arguments {}})
{"mcp-session-id" session-id})
- html (-> resource :body :result :contents first :text)
- credential (second (re-find #"uiCredential:\s*\"([^\"]+)\"" html))
+ credential (get-in tool-result [:body :result :_meta :com.metabase/mcp-apps :credential])
headers {"x-metabase-mcp-ui-auth" credential}]
(is (string? credential))
(is (= 200 (:status (client/client-full-response :get 200 "user/current"
diff --git a/test/metabase/mcp/resources_test.clj b/test/metabase/mcp/resources_test.clj
index 157702e1cbd..e952e76fed7 100644
--- a/test/metabase/mcp/resources_test.clj
+++ b/test/metabase/mcp/resources_test.clj
@@ -74,6 +74,38 @@
(is (=? {:status :not-found}
(mcp.resources/read-resource "test://nope" #{::scope/unrestricted} {})))))
+(deftest redact-ui-credential-test
+ (testing "the top-level UI credential is removed without walking or removing other metadata"
+ (is (= {:_meta {:ui {:resourceUri "ui://metabase/example.html"}}}
+ (mcp.resources/redact-ui-credential
+ {:_meta {:ui {:resourceUri "ui://metabase/example.html"}
+ :com.metabase/mcp-apps {:credential "secret"}}}))))
+ (testing "a result without private metadata is unchanged"
+ (is (= {:content [{:type "text", :text "large result"}]}
+ (mcp.resources/redact-ui-credential
+ {:content [{:type "text", :text "large result"}]})))))
+
+(deftest register-ui-tool-validates-visibility-test
+ (testing "the multi-resource registration path rejects misspelled visibility values"
+ (is (thrown?
+ Exception
+ (#'mcp.resources/register-ui-tool-for-resources!
+ [:visualize-query :render-drill-through]
+ {:name "invalid_visibility_test"
+ :description "Never registered"
+ :inputSchema [:map]
+ :visibility ["apps"]
+ :response-fn (constantly {})})))))
+
+(deftest refresh-ui-credential-requires-authenticated-session-test
+ (testing "missing authentication context is returned as a tool error"
+ (is (= {:content [{:type "text"
+ :text "MCP UI credential refresh requires an authenticated MCP session."}]
+ :isError true}
+ (#'mcp.resources/with-ui-credential
+ {:content [{:type "text", :text "MCP UI credential refreshed."}]}
+ nil)))))
+
(deftest builtin-construct-query-resource-test
(testing "the construct-query reference is registered as a public markdown resource"
(is (=? {:uri "metabase://docs/construct-query.md"
@@ -84,20 +116,46 @@
(deftest builtin-ui-resource-prefers-border-test
(testing "the visualize query UI resource explicitly asks the host to provide a border"
+ (let [uri "ui://metabase/visualize-query.html"]
+ (mcp.resources/with-fallback-template
+ (is (=? {:status :ok
+ :contents [{:uri uri
+ :mimeType "text/html;profile=mcp-app"
+ :_meta {:ui {:prefersBorder true}}}]}
+ (mcp.resources/read-resource uri
+ #{"agent:viz:mcp-ui:query"}
+ {})))))
+ (is (= :scope-denied
+ (mcp.resources/check-resource-access
+ "ui://metabase/visualize-query.deadbeef.html"
+ #{"agent:search"})))))
+
+(deftest builtin-ui-resource-supports-compatible-uris-test
+ (testing "legacy and future build-hashed URIs resolve without being advertised"
+ (doseq [uri ["ui://metabase/visualize-query-v2.html"
+ "ui://metabase/visualize-query.deadbeef.html"]]
+ (mcp.resources/with-fallback-template
+ (is (=? {:status :ok
+ :contents [{:uri uri}]}
+ (mcp.resources/read-resource uri
+ #{"agent:viz:mcp-ui:query"}
+ {}))))))
+ (testing "canonical and compatible URIs produce byte-distinct HTML"
(mcp.resources/with-fallback-template
- (is (=? {:status :ok
- :contents [{:uri "ui://metabase/visualize-query.html"
- :mimeType "text/html;profile=mcp-app"
- :_meta {:ui {:prefersBorder true}}}]}
- (mcp.resources/read-resource "ui://metabase/visualize-query.html"
- #{"agent:viz:mcp-ui:query"}
- {}))))))
+ (let [read-html (fn [uri]
+ (-> (mcp.resources/read-resource uri
+ #{"agent:viz:mcp-ui:query"}
+ {})
+ :contents first :text))]
+ (is (not= (read-html "ui://metabase/visualize-query.html")
+ (read-html "ui://metabase/visualize-query.deadbeef.html")))))))
(deftest drill-through-ui-resource-is-distinct-from-visualize-query-test
(testing "render_drill_through has its own UI resource URI (ChatGPT dedupes the iframe by `_meta.ui.resourceUri`; sharing the URI prevents a fresh widget from mounting on drill)"
(let [uris (set (map :uri (:resources (mcp.resources/list-resources #{"agent:viz:*"}))))]
(is (contains? uris "ui://metabase/visualize-query.html"))
- (is (contains? uris "ui://metabase/render-drill-through.html"))))
+ (is (contains? uris "ui://metabase/render-drill-through.html"))
+ (is (not (contains? uris "ui://metabase/visualize-query.deadbeef.html")))))
(testing "the two UI resources return byte-distinct HTML (ChatGPT's asset CDN appears to dedupe by body hash, so identical bodies cause the second asset to silently 404)"
(mcp.resources/with-fallback-template
(let [viz-html (-> (mcp.resources/read-resource "ui://metabase/visualize-query.html"
@@ -163,7 +221,7 @@
html (stencil/render-file
"frontend_client/mcp_apps_template.html"
{:instanceUrl "\"https://metabase.example.com/sub/path\""
- :instanceUrlRaw site-url
- :uiCredential nil
- :mcpSessionId nil})]
- (is (str/includes? html "<base href=\"https://metabase.example.com/sub/path/\"")))))
+ :instanceUrlRaw site-url})]
+ (is (str/includes? html "<base href=\"https://metabase.example.com/sub/path/\""))
+ (is (not (str/includes? html "uiCredential")))
+ (is (not (str/includes? html "mcpSessionId"))))))
diff --git a/test/metabase/mcp/scope_test.clj b/test/metabase/mcp/scope_test.clj
index 2f354c9133b..a586a6455c3 100644
--- a/test/metabase/mcp/scope_test.clj
+++ b/test/metabase/mcp/scope_test.clj
@@ -21,6 +21,10 @@
(is (true? (mcp.scope/matches? #{"agent:*"} "agent:read")))
(is (true? (mcp.scope/matches? #{"agent:*"} "agent:write")))
(is (false? (mcp.scope/matches? #{"other:*"} "agent:read"))))
+ (testing "any required scope match"
+ (is (true? (mcp.scope/matches? #{"agent:read"} #{"agent:read" "agent:write"})))
+ (is (true? (mcp.scope/matches? #{"agent:write"} #{"agent:read" "agent:write"})))
+ (is (false? (mcp.scope/matches? #{"other:read"} #{"agent:read" "agent:write"}))))
(testing "no match"
(is (false? (mcp.scope/matches? #{"foo:bar"} "agent:read")))
(is (false? (mcp.scope/matches? #{} "agent:read")))))