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
Revise the MCP question card design and layout (#74332)
Phoomparin Mano4f1864255711
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.module.css b/frontend/src/metabase/embedding/mcp/ChartTypePicker/ChartTypePicker.module.csssimilarity index 100%rename from frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.module.cssrename to frontend/src/metabase/embedding/mcp/ChartTypePicker/ChartTypePicker.module.cssdiff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.tsx b/frontend/src/metabase/embedding/mcp/ChartTypePicker/ChartTypePicker.tsxsimilarity index 84%rename from frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.tsxrename to frontend/src/metabase/embedding/mcp/ChartTypePicker/ChartTypePicker.tsxindex c60b8faca97..eade5b1c218 100644--- a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.tsx+++ b/frontend/src/metabase/embedding/mcp/ChartTypePicker/ChartTypePicker.tsx@@ -1,17 +1,17 @@import { ActionIcon, Flex, Icon } from "metabase/ui";-import type { IconName } from "metabase-types/api";+import type { CardDisplayType, IconName } from "metabase-types/api";import S from "./ChartTypePicker.module.css";type ChartTypeOption = {- type: string;+ type: CardDisplayType;icon: IconName;};type ChartTypePickerProps = {chartTypes: ChartTypeOption[];- value: string;- onChange: (type: string) => void;+ value: CardDisplayType | null;+ onChange: (type: CardDisplayType) => void;};export function ChartTypePicker({diff --git a/frontend/src/metabase/embedding/mcp/McpCardFooter.tsx b/frontend/src/metabase/embedding/mcp/McpCardFooter.tsxnew file mode 100644index 00000000000..d5dcc11e328--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/McpCardFooter.tsx@@ -0,0 +1,44 @@+import type { App } from "@modelcontextprotocol/ext-apps/react";+import type { CSSProperties } from "react";++import { Flex } from "metabase/ui";++import { McpExploreButton } from "./McpExploreButton";+import type { McpFeedbackChoice } from "./McpFeedbackArea";+import { McpFeedbackButtons } from "./McpFeedbackButtons";++export interface McpCardFooterProps {+ app: App | null;+ footerStyle: CSSProperties;+ instanceUrl: string;+ isSubmittingFeedback: boolean;+ onSelectFeedback: (feedback: McpFeedbackChoice) => void;+ submittedFeedback: McpFeedbackChoice | null;+}++export const McpCardFooter = ({+ app,+ footerStyle,+ instanceUrl,+ isSubmittingFeedback,+ onSelectFeedback,+ submittedFeedback,+}: McpCardFooterProps) => (+ <Flex+ h="50px"+ align="center"+ justify="space-between"+ bg="background-secondary"+ style={footerStyle}+ >+ <Flex align="center" gap="xs">+ <McpFeedbackButtons+ isSubmitting={isSubmittingFeedback}+ submittedFeedback={submittedFeedback}+ onSelectFeedback={onSelectFeedback}+ />+ </Flex>++ <McpExploreButton app={app} instanceUrl={instanceUrl} />+ </Flex>+);diff --git a/frontend/src/metabase/embedding/mcp/McpExploreButton.tsx b/frontend/src/metabase/embedding/mcp/McpExploreButton.tsxnew file mode 100644index 00000000000..5cdd43530bf--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/McpExploreButton.tsx@@ -0,0 +1,40 @@+import type { App } from "@modelcontextprotocol/ext-apps/react";+import { t } from "ttag";++import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";+import { UnstyledButton } from "metabase/ui";+import * as Urls from "metabase/urls";++interface McpExploreButtonProps {+ app: App | null;+ instanceUrl: string;+}++export function McpExploreButton({ app, instanceUrl }: McpExploreButtonProps) {+ const { question } = useSdkQuestionContext();++ async function handleExploreClicked() {+ if (!instanceUrl || !question || !app) {+ return;+ }++ const url = instanceUrl + Urls.serializedQuestion(question.card());++ await app.openLink({ url });+ }++ return (+ <UnstyledButton+ onClick={handleExploreClicked}+ disabled={!app || !question || !instanceUrl}+ c="text-primary"+ fz={12}+ fw={400}+ lh="normal"+ p={0}+ >+ {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- no whitelabel needed */}+ {t`Explore in Metabase`}+ </UnstyledButton>+ );+}diff --git a/frontend/src/metabase/embedding/mcp/McpQueryBar.unit.spec.tsx b/frontend/src/metabase/embedding/mcp/McpExploreButton.unit.spec.tsxsimilarity index 64%rename from frontend/src/metabase/embedding/mcp/McpQueryBar.unit.spec.tsxrename to frontend/src/metabase/embedding/mcp/McpExploreButton.unit.spec.tsxindex 0f83fedb0ab..50751c14df2 100644--- a/frontend/src/metabase/embedding/mcp/McpQueryBar.unit.spec.tsx+++ b/frontend/src/metabase/embedding/mcp/McpExploreButton.unit.spec.tsx@@ -1,3 +1,5 @@+import userEvent from "@testing-library/user-event";+import {setupAlertsEndpoints,setupCardEndpoints,@@ -5,11 +7,12 @@ import {setupCardQueryMetadataEndpoint,setupDatabaseEndpoints,} from "__support__/server-mocks";-import { screen } from "__support__/ui";+import { screen, waitFor } from "__support__/ui";import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";+import * as Urls from "metabase/urls";import {createMockCard,createMockCardQueryMetadata,@@ -25,7 +28,7 @@ import {createSampleDatabase,} from "metabase-types/api/mocks/presets";-import { McpQueryBar } from "./McpQueryBar";+import { McpExploreButton } from "./McpExploreButton";const TEST_USER = createMockUser();const TEST_DATABASE = createSampleDatabase();@@ -38,17 +41,11 @@ const TEST_CARD = createMockCard({"source-table": ORDERS_ID,aggregation: [["count"]],breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "quarter" }]],- filter: [- "between",- ["field", ORDERS.CREATED_AT, null],- "2024-01-01",- "2024-12-31",- ],},},});-const ONE_POINT_RESULT = createMockDataset({+const QUERY_RESULT = createMockDataset({data: createMockDatasetData({cols: [createMockNumericColumn({@@ -64,6 +61,7 @@ const ONE_POINT_RESULT = createMockDataset({function setup() {const { state } = setupSdkState({ currentUser: TEST_USER });const app = { openLink: jest.fn() };+ const instanceUrl = "https://metabase.example";setupCardEndpoints(TEST_CARD);setupCardQueryMetadataEndpoint(@@ -73,7 +71,7 @@ function setup() {setupDatabaseEndpoints(TEST_DATABASE);setupAlertsEndpoints(TEST_CARD, []);- setupCardQueryEndpoints(TEST_CARD, ONE_POINT_RESULT);+ setupCardQueryEndpoints(TEST_CARD, QUERY_RESULT);renderWithSDKProviders(<SdkQuestion@@ -82,7 +80,7 @@ function setup() {withEditorButton={false}withChartTypeSelector={false}>- <McpQueryBar app={app as any} instanceUrl="https://metabase.example" />+ <McpExploreButton app={app as any} instanceUrl={instanceUrl} /></SdkQuestion>,{componentProviderProps: {@@ -92,28 +90,27 @@ function setup() {},);- return { app };+ return { app, instanceUrl };}-describe("McpQueryBar", () => {- it("renders remaining query controls when a one-point result has no MCP chart types", async () => {- setup();+describe("McpExploreButton", () => {+ it("opens the current question in Metabase", async () => {+ const user = userEvent.setup();+ const { app, instanceUrl } = setup();++ await user.click(+ await screen.findByRole("button", { name: /explore in metabase/i }),+ );- expect(await screen.findByTestId("query-explorer-bar")).toBeInTheDocument();- expect(- screen.getByRole("button", { name: /explore/i }),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "line" }),- ).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "bar" }),- ).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "area" }),- ).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "table" }),- ).not.toBeInTheDocument();+ await waitFor(() => {+ expect(app.openLink).toHaveBeenCalledWith({+ url:+ instanceUrl ++ Urls.serializedQuestion({+ ...TEST_CARD,+ original_card_id: TEST_CARD.id,+ }),+ });+ });});});diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackArea.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackArea.tsxnew file mode 100644index 00000000000..9953bdd789b--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/McpFeedbackArea.tsx@@ -0,0 +1,117 @@+import { t } from "ttag";++import { Form, FormProvider } from "metabase/forms";+import { FormSelect } from "metabase/forms/components/FormSelect";+import { FormTextarea } from "metabase/forms/components/FormTextarea";+import { Button, Flex, Stack, Text, UnstyledButton } from "metabase/ui";++export type McpFeedbackChoice = "positive" | "negative";++export interface McpFeedbackAreaValues {+ issue_type?: string;+ freeform_feedback: string;+}++interface McpFeedbackAreaProps {+ feedback: McpFeedbackChoice;+ isSubmitting: boolean;+ onCancel: () => void;+ onSubmit: (values: McpFeedbackAreaValues) => void;+}++export function McpFeedbackArea({+ feedback,+ isSubmitting,+ onCancel,+ onSubmit,+}: McpFeedbackAreaProps) {+ const isPositive = feedback === "positive";++ const feedbackAreaTitle = isPositive+ ? t`Give positive feedback for this result`+ : t`Give negative feedback for this result`;++ return (+ <Flex h="100%" w="100%" direction="column" data-testid="mcp-feedback-area">+ <Flex+ h={65}+ px="lg"+ align="center"+ justify="space-between"+ flex="0 0 auto"+ >+ <Text c="text-primary" fw={700} fz="md">+ {feedbackAreaTitle}+ </Text>++ <UnstyledButton+ c="text-primary"+ fz="md"+ disabled={isSubmitting}+ onClick={onCancel}+ >+ {t`Cancel`}+ </UnstyledButton>+ </Flex>++ <Flex flex={1} w="100%" align="center" justify="center" px="xl" py="lg">+ <FormProvider+ initialValues={{+ issue_type: isPositive ? undefined : "",+ freeform_feedback: "",+ }}+ onSubmit={onSubmit}+ >+ <Form w="100%">+ <Stack w="100%" maw={350} mx="auto" gap="md">+ {!isPositive && (+ <Stack gap="xs">+ <Text c="text-secondary" fw={700} fz="md">+ {t`What went wrong?`}+ </Text>++ <FormSelect+ name="issue_type"+ placeholder={t`Select your problem`}+ data={[+ { label: t`Incorrect data`, value: "incorrect-data" },+ {+ label: t`Wrong visualization`,+ value: "wrong-visualization",+ },+ {+ label: t`Did not follow request`,+ value: "did-not-follow-request",+ },+ { label: t`Other`, value: "other" },+ ]}+ />+ </Stack>+ )}++ <FormTextarea+ name="freeform_feedback"+ placeholder={+ isPositive+ ? t`Any additional thoughts?`+ : t`Any additional thoughts?`+ }+ minRows={8}+ resize="vertical"+ />++ <Button+ fullWidth+ variant="filled"+ type="submit"+ loading={isSubmitting}+ >+ {t`Submit`}+ </Button>+ </Stack>+ </Form>+ </FormProvider>+ </Flex>+ </Flex>+ );+}diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackArea.unit.spec.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackArea.unit.spec.tsxnew file mode 100644index 00000000000..87e3d0df194--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/McpFeedbackArea.unit.spec.tsx@@ -0,0 +1,53 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen, waitFor } from "__support__/ui";++import { McpFeedbackArea } from "./McpFeedbackArea";++describe("McpFeedbackArea", () => {+ it("submits negative feedback details", async () => {+ const user = userEvent.setup();+ const onSubmit = jest.fn();++ renderWithProviders(+ <McpFeedbackArea+ feedback="negative"+ isSubmitting={false}+ onCancel={jest.fn()}+ onSubmit={onSubmit}+ />,+ );++ await user.type(+ screen.getByPlaceholderText("Any additional thoughts?"),+ "Needs a better chart",+ );++ await user.click(screen.getByRole("button", { name: "Submit" }));++ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));++ expect(onSubmit.mock.calls[0][0]).toEqual({+ issue_type: "",+ freeform_feedback: "Needs a better chart",+ });+ });++ it("cancels feedback entry", async () => {+ const user = userEvent.setup();+ const onCancel = jest.fn();++ renderWithProviders(+ <McpFeedbackArea+ feedback="positive"+ isSubmitting={false}+ onCancel={onCancel}+ onSubmit={jest.fn()}+ />,+ );++ await user.click(screen.getByRole("button", { name: "Cancel" }));++ expect(onCancel).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.tsxindex 0cd755adb76..1da77bb235b 100644--- a/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.tsx+++ b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.tsx@@ -1,15 +1,10 @@-import { forwardRef, useEffect, useRef, useState } from "react";+import { forwardRef } from "react";import { t } from "ttag";-import { useToast } from "metabase/common/hooks";import { ActionIcon, Icon, Tooltip } from "metabase/ui";import type { IconName } from "metabase-types/api";-import {- McpFeedbackModal,- type McpFeedbackModalValues,-} from "./McpFeedbackModal";-import { submitMcpFeedback } from "./api";+import type { McpFeedbackChoice } from "./McpFeedbackArea";interface FeedbackButtonProps {"data-testid": string;@@ -19,87 +14,17 @@ interface FeedbackButtonProps {hasBeenClicked: boolean;}-interface McpFeedbackButtonsProps {- instanceUrl: string;- sessionToken: string;- mcpSessionId: string;- prompt: string | null;- query: string | null;+export interface McpFeedbackButtonsProps {+ isSubmitting: boolean;+ submittedFeedback: McpFeedbackChoice | null;+ onSelectFeedback: (feedback: McpFeedbackChoice) => void;}-type FeedbackChoice = "positive" | "negative";-type FeedbackContext = Pick<McpFeedbackButtonsProps, "prompt" | "query">;--const isSameFeedbackContext = (- first: FeedbackContext,- second: FeedbackContext,-) => first.prompt === second.prompt && first.query === second.query;-export function McpFeedbackButtons({- instanceUrl,- sessionToken,- mcpSessionId,- prompt,- query,+ isSubmitting,+ submittedFeedback,+ onSelectFeedback,}: McpFeedbackButtonsProps) {- const [selectedFeedback, setSelectedFeedback] =- useState<FeedbackChoice | null>(null);-- // Used for icon highlighting based on last submitted feedback- const [submittedFeedback, setSubmittedFeedback] =- useState<FeedbackChoice | null>(null);-- const [isSubmitting, setIsSubmitting] = useState(false);-- const [sendToast] = useToast();- const feedbackContext = { prompt, query };-- const feedbackContextRef = useRef<FeedbackContext>(feedbackContext);- feedbackContextRef.current = feedbackContext;-- useEffect(() => {- setSubmittedFeedback(null);- setSelectedFeedback(null);- }, [prompt, query]);-- const handleFeedback = async (- values: McpFeedbackModalValues & { positive: boolean },- ) => {- const submittedContext = feedbackContextRef.current;- const payload = {- feedback: {- positive: values.positive,- message_id: crypto.randomUUID(),- issue_type: values.issue_type || undefined,- freeform_feedback: values.freeform_feedback || undefined,- },- conversation_data: { source: "mcp", ...submittedContext },- } as const;-- try {- setIsSubmitting(true);-- await submitMcpFeedback({- instanceUrl,- sessionToken,- mcpSessionId,- payload,- });-- if (isSameFeedbackContext(submittedContext, feedbackContextRef.current)) {- sendToast({ icon: "check", message: t`Feedback submitted` });- setSubmittedFeedback(values.positive ? "positive" : "negative");- setSelectedFeedback(null);- }- } catch {- if (isSameFeedbackContext(submittedContext, feedbackContextRef.current)) {- sendToast({ icon: "warning", message: t`Failed to submit feedback` });- }- } finally {- setIsSubmitting(false);- }- };-return (<><Tooltip label={t`Give positive feedback`}>@@ -108,7 +33,7 @@ export function McpFeedbackButtons({icon="thumbs_up"hasBeenClicked={submittedFeedback === "positive"}disabled={isSubmitting}- onClick={() => setSelectedFeedback("positive")}+ onClick={() => onSelectFeedback("positive")}/></Tooltip>@@ -118,23 +43,9 @@ export function McpFeedbackButtons({icon="thumbs_down"hasBeenClicked={submittedFeedback === "negative"}disabled={isSubmitting}- onClick={() => setSelectedFeedback("negative")}+ onClick={() => onSelectFeedback("negative")}/></Tooltip>-- {selectedFeedback != null && (- <McpFeedbackModal- isSubmitting={isSubmitting}- positive={selectedFeedback === "positive"}- onClose={() => setSelectedFeedback(null)}- onSubmit={(values) =>- handleFeedback({- positive: selectedFeedback === "positive",- ...values,- })- }- />- )}</>);}diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.unit.spec.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.unit.spec.tsxindex 5274f168509..2ae50c69d84 100644--- a/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.unit.spec.tsx+++ b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.unit.spec.tsx@@ -1,176 +1,40 @@-import { act, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";-import { renderWithProviders } from "__support__/ui";+import { renderWithProviders, screen } from "__support__/ui";import { McpFeedbackButtons } from "./McpFeedbackButtons";-const POSITIVE_FEEDBACK_MESSAGE_ID = "00000000-0000-4000-8000-000000000001";-const NEGATIVE_FEEDBACK_MESSAGE_ID = "00000000-0000-4000-8000-000000000002";-describe("McpFeedbackButtons", () => {- beforeEach(() => {- jest- .spyOn(crypto, "randomUUID")- .mockReturnValueOnce(POSITIVE_FEEDBACK_MESSAGE_ID)- .mockReturnValueOnce(NEGATIVE_FEEDBACK_MESSAGE_ID);- });-- afterEach(() => {- jest.restoreAllMocks();- });-- const findFeedbackRequests = async () => {- await fetchMock.callHistory.flush();-- return fetchMock.callHistory.calls("path:/api/embed-mcp/feedback", {- method: "POST",- });- };-- const getRequestBody = (- request: ReturnType<typeof fetchMock.callHistory.calls>[number],- ) => JSON.parse(request.options.body?.toString() ?? "{}");-- const getRequestHeaders = (- request: ReturnType<typeof fetchMock.callHistory.calls>[number],- ) => request.options.headers as Record<string, string>;-- it("submits separate MCP feedback events to the feedback endpoint", async () => {+ it("notifies when a feedback choice is selected", async () => {const user = userEvent.setup();- const instanceUrl = "http://localhost:3000";-- fetchMock.post("path:/api/embed-mcp/feedback", 204);+ const onSelectFeedback = jest.fn();renderWithProviders(<McpFeedbackButtons- instanceUrl={instanceUrl}- sessionToken="metabase-session-token"- mcpSessionId="mcp-session-id"- prompt="show me orders"- query="encoded-query"+ isSubmitting={false}+ submittedFeedback={null}+ onSelectFeedback={onSelectFeedback}/>,);await user.click(screen.getByTestId("mcp-feedback-thumbs-up"));-- await user.type(- screen.getByPlaceholderText("Tell us what you liked!"),- "Useful chart",- );-- await user.click(screen.getByRole("button", { name: "Submit" }));-- await waitFor(() =>- expect(- fetchMock.callHistory.calls("path:/api/embed-mcp/feedback", {- method: "POST",- }),- ).toHaveLength(1),- );-- const [request] = await findFeedbackRequests();-- expect(request.url).toBe(`${instanceUrl}/api/embed-mcp/feedback`);- expect(getRequestHeaders(request)).toEqual(- expect.objectContaining({- "x-metabase-client": "mcp-apps",- "x-metabase-session": "metabase-session-token",- "mcp-session-id": "mcp-session-id",- }),- );-- expect(getRequestBody(request)).toEqual({- feedback: {- positive: true,- message_id: POSITIVE_FEEDBACK_MESSAGE_ID,- freeform_feedback: "Useful chart",- },- conversation_data: {- source: "mcp",- prompt: "show me orders",- query: "encoded-query",- },- });-await user.click(screen.getByTestId("mcp-feedback-thumbs-down"));- await user.click(screen.getByRole("button", { name: "Submit" }));- await waitFor(async () =>- expect(await findFeedbackRequests()).toHaveLength(2),- );-- const [, secondRequest] = await findFeedbackRequests();-- expect(getRequestBody(secondRequest)).toEqual({- feedback: {- positive: false,- message_id: NEGATIVE_FEEDBACK_MESSAGE_ID,- },- conversation_data: {- source: "mcp",- prompt: "show me orders",- query: "encoded-query",- },- });+ expect(onSelectFeedback).toHaveBeenCalledTimes(2);+ expect(onSelectFeedback).toHaveBeenNthCalledWith(1, "positive");+ expect(onSelectFeedback).toHaveBeenNthCalledWith(2, "negative");});- it("keeps an in-flight submission tied to the visualization it was submitted for", async () => {- const user = userEvent.setup();- const instanceUrl = "http://localhost:3000";- let resolveFeedback!: (status: number) => void;- const feedbackSubmission = new Promise<number>((resolve) => {- resolveFeedback = resolve;- });-- fetchMock.post("path:/api/embed-mcp/feedback", () => feedbackSubmission);-- const { rerender } = renderWithProviders(- <McpFeedbackButtons- instanceUrl={instanceUrl}- sessionToken="metabase-session-token"- mcpSessionId="mcp-session-id"- prompt="show me orders"- query="encoded-query"- />,- );-- await user.click(screen.getByTestId("mcp-feedback-thumbs-up"));- await user.click(screen.getByRole("button", { name: "Submit" }));-- await waitFor(() =>- expect(- fetchMock.callHistory.calls("path:/api/embed-mcp/feedback", {- method: "POST",- }),- ).toHaveLength(1),- );-- rerender(+ it("disables feedback choices while feedback is submitting", () => {+ renderWithProviders(<McpFeedbackButtons- instanceUrl={instanceUrl}- sessionToken="metabase-session-token"- mcpSessionId="mcp-session-id"- prompt="show me products"- query="new-encoded-query"+ isSubmitting+ submittedFeedback={null}+ onSelectFeedback={jest.fn()}/>,);- await waitFor(() =>- expect(- screen.queryByRole("button", { name: "Submit" }),- ).not.toBeInTheDocument(),- );expect(screen.getByTestId("mcp-feedback-thumbs-up")).toBeDisabled();-- await act(async () => {- resolveFeedback(204);- await feedbackSubmission;- });-- await waitFor(() =>- expect(screen.getByTestId("mcp-feedback-thumbs-up")).toBeEnabled(),- );+ expect(screen.getByTestId("mcp-feedback-thumbs-down")).toBeDisabled();});});diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackModal.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackModal.tsxdeleted file mode 100644index 60f4cb3752c..00000000000--- a/frontend/src/metabase/embedding/mcp/McpFeedbackModal.tsx+++ /dev/null@@ -1,104 +0,0 @@-import { t } from "ttag";--import { Form, FormProvider } from "metabase/forms";-import { FormSelect } from "metabase/forms/components/FormSelect";-import { FormTextarea } from "metabase/forms/components/FormTextarea";-import { Button, Group, Modal, Stack, Text } from "metabase/ui";--export interface McpFeedbackModalValues {- issue_type?: string;- freeform_feedback: string;-}--interface McpFeedbackModalProps {- isSubmitting: boolean;- positive: boolean;- onClose: () => void;- onSubmit: (values: McpFeedbackModalValues) => void;-}--export function McpFeedbackModal({- isSubmitting,- positive,- onClose,- onSubmit,-}: McpFeedbackModalProps) {- return (- <Modal- opened- onClose={onClose}- size="md"- title={t`Visualization feedback`}- data-testid="mcp-feedback-modal"- >- <FormProvider- initialValues={{- issue_type: positive ? undefined : "",- freeform_feedback: "",- }}- onSubmit={onSubmit}- >- <Form>- <Stack gap="md">- {!positive && (- <Stack gap="xs">- <Text>{t`What kind of issue are you reporting? (optional)`}</Text>- <FormSelect- name="issue_type"- placeholder={t`Select issue type`}- data={[- { label: t`Incorrect data`, value: "incorrect-data" },- {- label: t`Wrong visualization`,- value: "wrong-visualization",- },- {- label: t`Did not follow request`,- value: "did-not-follow-request",- },- { label: t`Other`, value: "other" },- ]}- />- </Stack>- )}-- <Stack gap="xs">- <Text>- {positive- ? t`Any details that you'd like to share? (optional)`- : t`What could be improved? (optional)`}- </Text>-- <FormTextarea- name="freeform_feedback"- placeholder={- positive- ? t`Tell us what you liked!`- : t`What could be improved about this result?`- }- minRows={4}- maxRows={10}- resize="vertical"- autosize- />- </Stack>-- <Group justify="flex-end" gap="md" mt="md">- <Button- variant="subtle"- disabled={isSubmitting}- onClick={onClose}- >- {t`Cancel`}- </Button>-- <Button variant="filled" type="submit" loading={isSubmitting}>- {t`Submit`}- </Button>- </Group>- </Stack>- </Form>- </FormProvider>- </Modal>- );-}diff --git a/frontend/src/metabase/embedding/mcp/McpQuestionTitle.tsx b/frontend/src/metabase/embedding/mcp/McpQuestionTitle.tsxindex 1901eb12b3c..064bb967a30 100644--- a/frontend/src/metabase/embedding/mcp/McpQuestionTitle.tsx+++ b/frontend/src/metabase/embedding/mcp/McpQuestionTitle.tsx@@ -45,7 +45,7 @@ export function McpQuestionTitle() {}return (- <Text fw={700} fz="h3" px="md" py="sm" truncate>+ <Text fw={700} truncate>{title}</Text>);diff --git a/frontend/src/metabase/embedding/mcp/McpQuestionView.tsx b/frontend/src/metabase/embedding/mcp/McpQuestionView.tsxnew file mode 100644index 00000000000..839c242073c--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/McpQuestionView.tsx@@ -0,0 +1,118 @@+import type { CSSProperties } from "react";++import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";+import { Box, Divider, Flex } from "metabase/ui";++import { ChartTypePicker } from "./ChartTypePicker/ChartTypePicker";+import { McpQuestionTitle } from "./McpQuestionTitle";+import { TimeGranularityControl } from "./TimeControlBar/TimeGranularityControl";+import { TimeRangeControl } from "./TimeControlBar/TimeRangeControl";+import { useMcpQueryControls } from "./hooks/useMcpQueryControls";++export const MCP_CONTENT_HEIGHT = "500px";++const QUERY_BAR_RESERVED_HEIGHT = "calc(2rem + var(--mantine-spacing-sm))";+const RECLAIMED_CONTENT_BOTTOM_PADDING = "var(--mantine-spacing-lg)";++export interface McpQuestionViewProps {+ safeAreaPaddingTop: number;+}++export function McpQuestionView({ safeAreaPaddingTop }: McpQuestionViewProps) {+ const {+ hasChartTypeSelector,+ hasTimeControls,+ timeGranularity,+ timeRange,+ chartTypes,+ currentChartType,+ onChartTypeChange,+ } = useMcpQueryControls();++ const isTableVisualization = currentChartType === "table";++ // When table has no time controls, we can remove vertical padding and increase height.+ const shouldUseFullHeightTable = isTableVisualization && !hasTimeControls;++ const baseVisualizationHeight = hasTimeControls+ ? `calc(${MCP_CONTENT_HEIGHT} - 8.5rem)`+ : `calc(${MCP_CONTENT_HEIGHT} - 8.5rem + ${QUERY_BAR_RESERVED_HEIGHT})`;++ const tableVisualizationHeight = `calc(${baseVisualizationHeight} + ${RECLAIMED_CONTENT_BOTTOM_PADDING} + ${safeAreaPaddingTop}px)`;++ const resolvedVisualizationHeight = shouldUseFullHeightTable+ ? tableVisualizationHeight+ : baseVisualizationHeight;++ // We cannot reduce top padding when chart type selector is shown,+ // as switching between them will cause layout shift due to height change.+ const shouldReduceTopPadding =+ shouldUseFullHeightTable && !hasChartTypeSelector;++ const contentStyle: CSSProperties = {+ boxSizing: "border-box",+ paddingTop: shouldReduceTopPadding+ ? "calc(var(--mantine-spacing-lg) + 0px)"+ : `calc(var(--mantine-spacing-lg) + ${safeAreaPaddingTop}px)`,+ };++ return (+ <Flex+ direction="column"+ justify="space-between"+ h={MCP_CONTENT_HEIGHT}+ gap="sm"+ pb={shouldUseFullHeightTable ? undefined : "lg"}+ style={contentStyle}+ >+ <Flex+ px="lg"+ align="center"+ justify="space-between"+ gap="sm"+ flex="0 0 auto"+ >+ <Box flex={1} miw={0}>+ <McpQuestionTitle />+ </Box>++ <Flex align="center" flex="0 0 auto">+ {hasChartTypeSelector && (+ <ChartTypePicker+ chartTypes={chartTypes}+ value={currentChartType}+ onChange={onChartTypeChange}+ />+ )}+ </Flex>+ </Flex>++ <Flex px="xs" flex={1} style={{ overflow: "hidden" }}>+ <SdkQuestion.QuestionVisualization+ height={resolvedVisualizationHeight}+ />+ </Flex>++ {hasTimeControls && (+ <Flex px="lg" justify="center">+ <Flex+ h={32}+ align="stretch"+ bd="1px solid var(--mb-color-border)"+ bdrs="md"+ style={{ overflow: "hidden" }}+ data-testid="query-explorer-bar"+ >+ {timeRange && <TimeRangeControl timeRange={timeRange} />}++ {timeRange && timeGranularity && <Divider orientation="vertical" />}++ {timeGranularity && (+ <TimeGranularityControl timeGranularity={timeGranularity} />+ )}+ </Flex>+ </Flex>+ )}+ </Flex>+ );+}diff --git a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsxindex b80ee5c2ab5..ba6670cb340 100644--- a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx+++ b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx@@ -7,18 +7,36 @@ import { getSdkStore } from "embedding-sdk-bundle/store";import { Flex } from "metabase/ui";import type { ResolvedColorScheme } from "metabase/utils/color-scheme";-import { McpFeedbackButtons } from "./McpFeedbackButtons";-import { McpQueryBar } from "./McpQueryBar";-import { McpQuestionTitle } from "./McpQuestionTitle";+import { McpCardFooter } from "./McpCardFooter";+import { McpFeedbackArea } from "./McpFeedbackArea";+import { MCP_CONTENT_HEIGHT, McpQuestionView } from "./McpQuestionView";import { getMcpDeserializedCard } from "./McpUiAppRoute.utils";import { useHandleMcpDrillThrough } from "./hooks/useHandleMcpDrillThrough";-import { useMcpApp } from "./hooks/useMcpApp";+import { type McpAppState, useMcpApp } from "./hooks/useMcpApp";+import { useMcpFeedback } from "./hooks/useMcpFeedback";import { useMcpUserAndSettingsFetch } from "./hooks/useMcpUserAndSettingsFetch";import { buildMcpAppsTheme } from "./utils/buildMcpAppsTheme";const store = getSdkStore();const DEFAULT_INSETS = { top: 0, right: 0, bottom: 0, left: 0 };+const FOOTER_HEIGHT = "50px";+const FOOTER_HORIZONTAL_PADDING = 16;++interface McpUiAppRouteContentProps {+ app: McpAppState["app"];+ hostContext: McpAppState["hostContext"];+ instanceUrl: string;+ prompt: McpAppState["prompt"];+ query: McpAppState["query"];+ sessionToken: string;+}++interface McpMetabaseConfig {+ instanceUrl: string;+ sessionToken: string;+ mcpSessionId: string;+}// CSS for .mcp-loading and .mcp-spinner is defined globally in embed-mcp.html.const SimpleLoader = () => (@@ -28,19 +46,10 @@ const SimpleLoader = () => ();export function McpUiAppRoute() {- const { query, prompt, hostContext, app } = useMcpApp();-- const handleDrillThrough = useHandleMcpDrillThrough(app);+ const { app, hostContext, prompt, query } = useMcpApp();- const {- instanceUrl = "",- sessionToken = "",- mcpSessionId = "",- } = (window.metabaseConfig as {- instanceUrl: string;- sessionToken: string;- mcpSessionId: string;- }) ?? {};+ const { instanceUrl = "", sessionToken = "" } =+ (window.metabaseConfig as McpMetabaseConfig) ?? {};const scheme: ResolvedColorScheme =hostContext?.theme === "dark" ? "dark" : "light";@@ -50,6 +59,43 @@ export function McpUiAppRoute() {[hostContext?.styles?.variables],);+ const theme = useMemo(+ () => buildMcpAppsTheme(hostCssVariables, scheme),+ [hostCssVariables, scheme],+ );++ return (+ <ComponentProvider+ authConfig={{ metabaseInstanceUrl: instanceUrl }}+ theme={theme}+ reduxStore={store}+ loaderComponent={SimpleLoader}+ >+ <McpUiAppRouteContent+ app={app}+ hostContext={hostContext}+ instanceUrl={instanceUrl}+ prompt={prompt}+ query={query}+ sessionToken={sessionToken}+ />+ </ComponentProvider>+ );+}++function McpUiAppRouteContent({+ app,+ hostContext,+ instanceUrl,+ prompt,+ query,+ sessionToken,+}: McpUiAppRouteContentProps) {+ const handleDrillThrough = useHandleMcpDrillThrough(app);++ const { mcpSessionId = "" } =+ (window.metabaseConfig as McpMetabaseConfig) ?? {};+const safeAreaInsets = hostContext?.safeAreaInsets ?? DEFAULT_INSETS;const deserializedCard = useMemo(() => {@@ -60,11 +106,6 @@ export function McpUiAppRoute() {return getMcpDeserializedCard(query);}, [query]);- const theme = useMemo(- () => buildMcpAppsTheme(hostCssVariables, scheme),- [hostCssVariables, scheme],- );-const { isSettingsReady, userAndSettingsFetchError } =useMcpUserAndSettingsFetch({instanceUrl,@@ -87,26 +128,75 @@ export function McpUiAppRoute() {}}, [isReady, userAndSettingsFetchError]);- const height = "500px";- const visualizationHeight = `calc(${height} - 8.5rem)`;- const safeAreaMargins = `${Math.max(safeAreaInsets.top, 0)}px ${Math.max(safeAreaInsets.right, 0)}px ${Math.max(safeAreaInsets.bottom, 0)}px ${Math.max(safeAreaInsets.left, 0)}px`;+ const height = `calc(${MCP_CONTENT_HEIGHT} + ${FOOTER_HEIGHT})`;- const containerStyle: CSSProperties = {- height,- margin: safeAreaMargins,- background: theme.colors?.background,+ const safeAreaPadding = {+ top: Math.max(safeAreaInsets.top, 0),+ right: Math.max(safeAreaInsets.right, 0),+ bottom: Math.max(safeAreaInsets.bottom, 0),+ left: Math.max(safeAreaInsets.left, 0),};- const renderContent = () => {- if (userAndSettingsFetchError) {- return <SdkError message={userAndSettingsFetchError} />;- }+ const containerStyle: CSSProperties = { height };+ const feedbackContainerStyle: CSSProperties = { boxSizing: "border-box" };- if (!isReady) {- return null;+ const footerStyle: CSSProperties = {+ boxSizing: "border-box",+ borderTop: "1px solid var(--mb-color-border)",+ paddingRight: Math.max(safeAreaPadding.right, FOOTER_HORIZONTAL_PADDING),+ paddingTop: safeAreaPadding.bottom,+ paddingBottom: safeAreaPadding.bottom,+ paddingLeft: Math.max(safeAreaPadding.left, FOOTER_HORIZONTAL_PADDING),+ };++ const {+ isSubmittingFeedback,+ selectedFeedback,+ submittedFeedback,+ setSelectedFeedback,+ handleFeedbackSubmit,+ } = useMcpFeedback({+ instanceUrl,+ mcpSessionId,+ prompt,+ query,+ sessionToken,+ });++ const renderSdkQuestionContent = () => {+ if (selectedFeedback !== null) {+ return (+ // Keep the feedback overlay inside SdkQuestion's container because+ // it relies on the style from PublicComponentStyleWrapper+ <Flex h={height} w="100%" style={feedbackContainerStyle}>+ <McpFeedbackArea+ feedback={selectedFeedback}+ isSubmitting={isSubmittingFeedback}+ onCancel={() => setSelectedFeedback(null)}+ onSubmit={handleFeedbackSubmit}+ />+ </Flex>+ );}return (+ <>+ <McpQuestionView safeAreaPaddingTop={safeAreaPadding.top} />++ <McpCardFooter+ app={app}+ footerStyle={footerStyle}+ instanceUrl={instanceUrl}+ isSubmittingFeedback={isSubmittingFeedback}+ onSelectFeedback={setSelectedFeedback}+ submittedFeedback={submittedFeedback}+ />+ </>+ );+ };++ const renderQuestionCardView = () =>+ deserializedCard && (<SdkQuestiondeserializedCard={deserializedCard}isSaveEnabled={false}@@ -115,54 +205,21 @@ export function McpUiAppRoute() {withChartTypeSelector={false}onDrillThrough={handleDrillThrough}>- <Flex- direction="column"- justify="space-between"- h="100%"- py="lg"- gap="sm"- >- <Flex- px="lg"- align="center"- justify="space-between"- style={{ flexShrink: 0 }}- >- <div style={{ flex: 1, minWidth: 0 }}>- <McpQuestionTitle />- </div>-- <Flex align="center" gap="xs" style={{ flexShrink: 0 }}>- <McpFeedbackButtons- instanceUrl={instanceUrl}- sessionToken={sessionToken}- mcpSessionId={mcpSessionId}- prompt={prompt}- query={query}- />- </Flex>- </Flex>-- <Flex px="xs" flex={1} style={{ overflow: "hidden" }}>- <SdkQuestion.QuestionVisualization height={visualizationHeight} />- </Flex>-- <Flex px="lg">- <McpQueryBar app={app} instanceUrl={instanceUrl} />- </Flex>- </Flex>+ {renderSdkQuestionContent()}</SdkQuestion>);++ const renderContentView = () => {+ if (userAndSettingsFetchError) {+ return <SdkError message={userAndSettingsFetchError} />;+ }++ if (!isReady) {+ return null;+ }++ return renderQuestionCardView();};- return (- <ComponentProvider- authConfig={{ metabaseInstanceUrl: instanceUrl }}- theme={theme}- reduxStore={store}- loaderComponent={SimpleLoader}- >- <div style={containerStyle}>{renderContent()}</div>- </ComponentProvider>- );+ return <div style={containerStyle}>{renderContentView()}</div>;}diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.stories.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.stories.tsxdeleted file mode 100644index 0d0d266ba2e..00000000000--- a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.stories.tsx+++ /dev/null@@ -1,91 +0,0 @@-import type { Meta, StoryFn } from "@storybook/react";--import {- QueryExplorerBar,- type QueryExplorerBarChartType,- type QueryExplorerBarProps,-} from "./QueryExplorerBar";--const CHART_TYPES: QueryExplorerBarChartType[] = [- { type: "line", icon: "line" },- { type: "area", icon: "area" },- { type: "bar", icon: "bar" },-];--export default {- title: "Embedding/MCP/QueryExplorerBar",- component: QueryExplorerBar,- argTypes: {- currentChartType: {- control: "select",- options: ["table", "line", "area", "bar"],- },- },-} satisfies Meta<typeof QueryExplorerBar>;--const Template: StoryFn<QueryExplorerBarProps> = (args) => (- <div- style={{- display: "flex",- flexDirection: "column",- background: "var(--mb-color-background-primary)",- }}- >- <div- style={{- height: "300px",- display: "flex",- alignItems: "center",- justifyContent: "center",- marginBottom: "24px",- }}- >- placeholder for where the chart would be- </div>-- <div- style={{- padding: "12px",- borderRadius: "8px",- display: "flex",- alignItems: "center",- justifyContent: "center",- }}- >- <QueryExplorerBar {...args} />- </div>- </div>-);--export const Default = {- render: Template,- args: {- chartTypes: CHART_TYPES,- currentChartType: "bar",- onChartTypeChange: () => {},- timeRange: {- label: "All time",- value: undefined,- availableUnits: [],- hasActiveFilter: false,- onChange: () => {},- onClear: () => {},- },- timeGranularity: {- label: "by month",- currentUnit: "month",- availableItems: [],- onChange: () => {},- },- onExplore: () => {},- },-};--export const WithTable = {- render: Template,- args: {- ...Default.args,- chartTypes: [{ type: "table", icon: "table2" }, ...CHART_TYPES],- currentChartType: "table",- },-};diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.tsxdeleted file mode 100644index 29e1b62f039..00000000000--- a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.tsx+++ /dev/null@@ -1,83 +0,0 @@-import { t } from "ttag";--import { Button, Divider, Flex, Icon } from "metabase/ui";--import { ChartTypePicker } from "./ChartTypePicker";-import { TimeGranularityControl } from "./TimeGranularityControl";-import { TimeRangeControl } from "./TimeRangeControl";-import type { QueryExplorerBarProps } from "./types";--export type {- QueryExplorerBarChartType,- QueryExplorerBarProps,- TimeGranularityConfig,- TimeGranularityItem,- TimeRangeConfig,-} from "./types";--export function QueryExplorerBar({- chartTypes,- currentChartType,- onChartTypeChange,- timeRange,- timeGranularity,- onExplore,-}: QueryExplorerBarProps) {- const hasCenterControls = timeRange || timeGranularity;- const hasChartTypes = chartTypes.length > 0;-- return (- <Flex- w="100%"- direction={{ base: "column", xs: "row" }}- align={{ base: "flex-start", xs: "center" }}- justify={{ base: "flex-start", xs: "space-between" }}- gap={{ base: "sm", xs: "xs" }}- data-testid="query-explorer-bar"- >- {hasChartTypes && (- <Flex align="center" gap="xs">- <ChartTypePicker- chartTypes={chartTypes}- value={currentChartType}- onChange={onChartTypeChange}- />- </Flex>- )}-- {hasCenterControls && (- <Flex- h={32}- align="stretch"- bd="1px solid var(--mb-color-border)"- bdrs="md"- style={{ overflow: "hidden" }}- >- {timeRange && <TimeRangeControl timeRange={timeRange} />}-- {timeRange && timeGranularity && <Divider orientation="vertical" />}-- {timeGranularity && (- <TimeGranularityControl timeGranularity={timeGranularity} />- )}- </Flex>- )}-- {onExplore && (- <Flex align="center">- <Button- variant="default"- size="xs"- h={32}- px="10px"- leftSection={<Icon name="click" size={12} />}- onClick={onExplore}- bg="transparent"- >- {t`Explore`}- </Button>- </Flex>- )}- </Flex>- );-}diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.unit.spec.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.unit.spec.tsxdeleted file mode 100644index 3111b7ef4b5..00000000000--- a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.unit.spec.tsx+++ /dev/null@@ -1,200 +0,0 @@-import { screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";--import { renderWithProviders } from "__support__/ui";-import type * as Lib from "metabase-lib";--import { QueryExplorerBar } from "./QueryExplorerBar";--const CHART_TYPES = [- { type: "line", icon: "line" as const },- { type: "area", icon: "area" as const },- { type: "bar", icon: "bar" as const },-];--describe("QueryExplorerBar", () => {- it("shows chart type buttons", () => {- renderWithProviders(- <QueryExplorerBar- chartTypes={CHART_TYPES}- currentChartType="line"- onChartTypeChange={() => {}}- />,- );-- expect(screen.getAllByRole("button")).toHaveLength(3);- expect(screen.getByRole("button", { name: "line" })).toBeInTheDocument();- expect(screen.getByRole("button", { name: "area" })).toBeInTheDocument();- expect(screen.getByRole("button", { name: "bar" })).toBeInTheDocument();- });-- it("calls onChartTypeChange when chart type button is clicked", async () => {- const user = userEvent.setup();- const onChartTypeChange = jest.fn();-- renderWithProviders(- <QueryExplorerBar- chartTypes={CHART_TYPES}- currentChartType="line"- onChartTypeChange={onChartTypeChange}- />,- );-- await user.click(screen.getByRole("button", { name: "bar" }));-- expect(onChartTypeChange).toHaveBeenCalledWith("bar");- expect(onChartTypeChange).toHaveBeenCalledTimes(1);- });-- it("opens the date picker when the time range button is clicked", async () => {- const user = userEvent.setup();-- renderWithProviders(- <QueryExplorerBar- chartTypes={CHART_TYPES}- currentChartType="bar"- onChartTypeChange={() => {}}- timeRange={{- label: "Last 30 days",- value: undefined,- availableUnits: [],- hasActiveFilter: false,- onChange: () => {},- onClear: () => {},- }}- />,- );-- expect(- screen.getByRole("button", { name: "Last 30 days" }),- ).toBeInTheDocument();-- await user.click(screen.getByRole("button", { name: "Last 30 days" }));-- expect(screen.getByTestId("date-picker-type-specific")).toBeInTheDocument();- });-- it("opens granularity dropdown and calls onChange when an item is selected", async () => {- const user = userEvent.setup();- const onChange = jest.fn();- const mockBucket = {} as Lib.Bucket;-- renderWithProviders(- <QueryExplorerBar- chartTypes={CHART_TYPES}- currentChartType="bar"- onChartTypeChange={() => {}}- timeGranularity={{- label: "by month",- currentUnit: "month",- availableItems: [- { bucket: mockBucket, unit: "month", label: "Month" },- { bucket: mockBucket, unit: "year", label: "Year" },- ],- onChange,- }}- />,- );-- expect(- screen.getByRole("button", { name: "by month" }),- ).toBeInTheDocument();-- await user.click(screen.getByRole("button", { name: "by month" }));-- expect(screen.getByRole("option", { name: "Month" })).toBeInTheDocument();- expect(screen.getByRole("option", { name: "Year" })).toBeInTheDocument();-- await user.click(screen.getByRole("option", { name: "Year" }));-- expect(onChange).toHaveBeenCalledWith(mockBucket);- expect(onChange).toHaveBeenCalledTimes(1);- });-- it("renders the table chart type button when provided", () => {- renderWithProviders(- <QueryExplorerBar- chartTypes={[- ...CHART_TYPES,- { type: "table", icon: "table2" as const },- ]}- currentChartType="table"- onChartTypeChange={() => {}}- />,- );-- expect(screen.getByRole("button", { name: "table" })).toBeInTheDocument();- });-- it("calls onExplore when Explore button is clicked", async () => {- const user = userEvent.setup();- const onExplore = jest.fn();-- renderWithProviders(- <QueryExplorerBar- chartTypes={CHART_TYPES}- currentChartType="line"- onChartTypeChange={jest.fn()}- onExplore={onExplore}- />,- );-- expect(- screen.getByRole("button", { name: /explore/i }),- ).toBeInTheDocument();-- await user.click(screen.getByRole("button", { name: /explore/i }));-- expect(onExplore).toHaveBeenCalledTimes(1);- });-- it("does not show Explore button when onExplore is not provided", () => {- renderWithProviders(- <QueryExplorerBar- chartTypes={CHART_TYPES}- currentChartType="line"- onChartTypeChange={jest.fn()}- />,- );-- expect(- screen.queryByRole("button", { name: /explore/i }),- ).not.toBeInTheDocument();- });-- it("renders remaining controls when chart type controls are empty", () => {- renderWithProviders(- <QueryExplorerBar- chartTypes={[]}- currentChartType=""- onChartTypeChange={jest.fn()}- timeRange={{- label: "2024 only",- value: undefined,- availableUnits: [],- hasActiveFilter: true,- onChange: jest.fn(),- onClear: jest.fn(),- }}- onExplore={jest.fn()}- />,- );-- expect(screen.getByTestId("query-explorer-bar")).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "2024 only" }),- ).toBeInTheDocument();- expect(- screen.getByRole("button", { name: /explore/i }),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "line" }),- ).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "bar" }),- ).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "area" }),- ).not.toBeInTheDocument();- });-});diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/index.ts b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/index.tsdeleted file mode 100644index 00467a0454b..00000000000--- a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/index.ts+++ /dev/null@@ -1,8 +0,0 @@-export { QueryExplorerBar } from "./QueryExplorerBar";-export type {- QueryExplorerBarProps,- QueryExplorerBarChartType,- TimeRangeConfig,- TimeGranularityConfig,- TimeGranularityItem,-} from "./QueryExplorerBar";diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/types.ts b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/types.tsdeleted file mode 100644index 931da8244f1..00000000000--- a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/types.ts+++ /dev/null@@ -1,42 +0,0 @@-import type {- DatePickerUnit,- DatePickerValue,-} from "metabase/querying/common/types";-import type * as Lib from "metabase-lib";-import type { IconName, TemporalUnit } from "metabase-types/api";--export type QueryExplorerBarChartType = {- type: string;- icon: IconName;-};--export type TimeRangeConfig = {- label: string;- value: DatePickerValue | undefined;- availableUnits: DatePickerUnit[];- hasActiveFilter: boolean;- onChange: (value: DatePickerValue) => void;- onClear: () => void;-};--export type TimeGranularityItem = {- bucket: Lib.Bucket;- unit: TemporalUnit;- label: string;-};--export type TimeGranularityConfig = {- label: string;- currentUnit: TemporalUnit | undefined;- availableItems: TimeGranularityItem[];- onChange: (bucket: Lib.Bucket | null) => void;-};--export type QueryExplorerBarProps = {- chartTypes: QueryExplorerBarChartType[];- currentChartType: string;- onChartTypeChange: (type: string) => void;- timeRange?: TimeRangeConfig;- timeGranularity?: TimeGranularityConfig;- onExplore?: () => void;-};diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.module.css b/frontend/src/metabase/embedding/mcp/TimeControlBar/TimeControlPopover.module.csssimilarity index 100%rename from frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.module.cssrename to frontend/src/metabase/embedding/mcp/TimeControlBar/TimeControlPopover.module.cssdiff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.tsx b/frontend/src/metabase/embedding/mcp/TimeControlBar/TimeControlPopover.tsxsimilarity index 100%rename from frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.tsxrename to frontend/src/metabase/embedding/mcp/TimeControlBar/TimeControlPopover.tsxdiff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeGranularityControl.tsx b/frontend/src/metabase/embedding/mcp/TimeControlBar/TimeGranularityControl.tsxsimilarity index 100%rename from frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeGranularityControl.tsxrename to frontend/src/metabase/embedding/mcp/TimeControlBar/TimeGranularityControl.tsxdiff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeRangeControl.tsx b/frontend/src/metabase/embedding/mcp/TimeControlBar/TimeRangeControl.tsxsimilarity index 100%rename from frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeRangeControl.tsxrename to frontend/src/metabase/embedding/mcp/TimeControlBar/TimeRangeControl.tsxdiff --git a/frontend/src/metabase/embedding/mcp/TimeControlBar/types.ts b/frontend/src/metabase/embedding/mcp/TimeControlBar/types.tsnew file mode 100644index 00000000000..5153d545cc3--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/TimeControlBar/types.ts@@ -0,0 +1,24 @@+import type {+ DatePickerUnit,+ DatePickerValue,+} from "metabase/querying/common/types";+import type * as Lib from "metabase-lib";+import type { TemporalUnit } from "metabase-types/api";++import type { TemporalGranularityItem } from "../hooks/useTemporalGranularity";++export interface TimeRangeConfig {+ label: string;+ value: DatePickerValue | undefined;+ availableUnits: DatePickerUnit[];+ hasActiveFilter: boolean;+ onChange: (value: DatePickerValue) => void;+ onClear: () => void;+}++export interface TimeGranularityConfig {+ label: string;+ currentUnit: TemporalUnit | undefined;+ availableItems: TemporalGranularityItem[];+ onChange: (bucket: Lib.Bucket | null) => void;+}diff --git a/frontend/src/metabase/embedding/mcp/hooks/useChartTypes.ts b/frontend/src/metabase/embedding/mcp/hooks/useChartTypes.tsindex 0553803de45..1f46d065091 100644--- a/frontend/src/metabase/embedding/mcp/hooks/useChartTypes.ts+++ b/frontend/src/metabase/embedding/mcp/hooks/useChartTypes.ts@@ -1,41 +1,40 @@-import { useMemo } from "react";+import { useMemo, useRef } from "react";import { getSensibleVisualizations } from "metabase/visualizations/lib/sensibility";import type Question from "metabase-lib/v1/Question";-import type { Dataset } from "metabase-types/api";+import type { CardDisplayType, Dataset } from "metabase-types/api";-const CHART_TYPES = [- { type: "line" as const, icon: "line" as const },- { type: "bar" as const, icon: "bar" as const },- { type: "area" as const, icon: "area" as const },-];--const TABLE_CHART_TYPE = { type: "table" as const, icon: "table2" as const };--export type McpChartType = "line" | "bar" | "area" | "table";--const isMcpChartType = (type: string): type is McpChartType =>- [...CHART_TYPES, TABLE_CHART_TYPE].some(- (chartType) => chartType.type === type,- );--type UpdateQuestion = (question: Question, opts: { run: boolean }) => void;--type ChartTypeEntry = (typeof CHART_TYPES)[number] | typeof TABLE_CHART_TYPE;+import {+ type McpChartTypeEntry,+ getMcpChartTypes,+} from "../utils/getMcpChartTypes";interface UseChartTypesResult {- sensibleChartTypes: ChartTypeEntry[];+ sensibleChartTypes: McpChartTypeEntry[];hasOnlyTable: boolean;- selectedChartType: McpChartType | null;- handleDisplayChange: (type: string) => void;+ selectedChartType: CardDisplayType | null;+ handleDisplayChange: (type: CardDisplayType) => void;}export function useChartTypes(question: Question | undefined,queryResults: Dataset[] | null | undefined,- updateQuestion: UpdateQuestion,+ updateQuestion: (question: Question, opts: { run: boolean }) => void,): UseChartTypesResult {const queryResult = queryResults?.[0] ?? null;+ const currentDisplay = question?.display() ?? null;++ const defaultDisplayRef = useRef<{+ queryResult: Dataset | null;+ display: CardDisplayType | null;+ } | null>(null);++ if (defaultDisplayRef.current?.queryResult !== queryResult) {+ defaultDisplayRef.current = {+ queryResult,+ display: currentDisplay,+ };+ }const { sensibleVisualizations } = useMemo(() => getSensibleVisualizations({ result: queryResult }),@@ -43,42 +42,22 @@ export function useChartTypes();const rowCount = queryResult?.data?.rows?.length ?? 0;- const tableVisible = rowCount >= 2;-- const sensibleChartTypes = [- ...CHART_TYPES.filter(({ type }) => {- if (!sensibleVisualizations.includes(type)) {- return false;- }-- // Hide area when table is shown as they occupy the same slot.- if (type === "area" && tableVisible) {- return false;- }- return true;- }),-- ...(tableVisible ? [TABLE_CHART_TYPE] : []),- ];+ const sensibleChartTypes = getMcpChartTypes({+ defaultDisplay: defaultDisplayRef.current?.display ?? null,+ sensibleVisualizations: sensibleVisualizations as CardDisplayType[],+ canShowTable: rowCount >= 2,+ });const hasOnlyTable =sensibleChartTypes.length === 1 && sensibleChartTypes[0].type === "table";- const rawDisplay = question?.display() ?? "";-- const selectedChartType: McpChartType | null = isMcpChartType(rawDisplay)- ? rawDisplay- : null;-- const handleDisplayChange = (type: string) => {+ const handleDisplayChange = (type: CardDisplayType) => {if (!question) {return;}- const nextQuestion = question- .setDisplay(type as McpChartType)- .lockDisplay();+ const nextQuestion = question.setDisplay(type).lockDisplay();updateQuestion(nextQuestion, { run: false });};@@ -86,7 +65,7 @@ export function useChartTypes(return {sensibleChartTypes,hasOnlyTable,- selectedChartType,+ selectedChartType: currentDisplay,handleDisplayChange,};}diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsxindex ed55340c4a7..f1eb27d2376 100644--- a/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx@@ -8,7 +8,7 @@ import {} from "@modelcontextprotocol/ext-apps/react";import { useEffect, useState } from "react";-interface McpAppState {+export interface McpAppState {query: string | null;/**diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.tsnew file mode 100644index 00000000000..dc63ad07b64--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.ts@@ -0,0 +1,110 @@+import { useEffect, useState } from "react";+import { useLatest } from "react-use";+import { t } from "ttag";++import { useToast } from "metabase/common/hooks";+import type { McpAppsFeedback } from "metabase-types/api";++import type {+ McpFeedbackAreaValues,+ McpFeedbackChoice,+} from "../McpFeedbackArea";+import { submitMcpFeedback } from "../api";++interface UseMcpFeedbackProps {+ instanceUrl: string;++ /** ID for the current MCP session */+ mcpSessionId: string;++ /** User prompt captured from construct_query */+ prompt: string | null;++ /** Ad-hoc query that is being shown, captured from construct_query */+ query: string | null;++ /** Metabase session tokens for authenticating feedback requests */+ sessionToken: string;+}++export function useMcpFeedback({+ instanceUrl,+ mcpSessionId,+ prompt,+ query,+ sessionToken,+}: UseMcpFeedbackProps) {+ const [selectedFeedback, setSelectedFeedback] =+ useState<McpFeedbackChoice | null>(null);++ const [submittedFeedback, setSubmittedFeedback] =+ useState<McpFeedbackChoice | null>(null);++ const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false);++ const [sendToast] = useToast();++ const feedbackContextRef = useLatest({ prompt, query });++ useEffect(() => {+ setSubmittedFeedback(null);+ setSelectedFeedback(null);+ }, [prompt, query]);++ const handleFeedbackSubmit = async (values: McpFeedbackAreaValues) => {+ if (selectedFeedback == null) {+ return;+ }++ const submittedContext = feedbackContextRef.current;+ const positive = selectedFeedback === "positive";++ const payload: McpAppsFeedback = {+ feedback: {+ positive,+ message_id: crypto.randomUUID(),+ issue_type: values.issue_type || undefined,+ freeform_feedback: values.freeform_feedback || undefined,+ },+ conversation_data: { source: "mcp", ...submittedContext },+ };++ try {+ setIsSubmittingFeedback(true);++ await submitMcpFeedback({+ instanceUrl,+ sessionToken,+ mcpSessionId,+ payload,+ });++ if (+ submittedContext.prompt === feedbackContextRef.current.prompt &&+ submittedContext.query === feedbackContextRef.current.query+ ) {+ sendToast({ icon: "check", message: t`Feedback submitted` });++ setSubmittedFeedback(selectedFeedback);+ setSelectedFeedback(null);+ }+ } catch {+ if (+ submittedContext.prompt === feedbackContextRef.current.prompt &&+ submittedContext.query === feedbackContextRef.current.query+ ) {+ sendToast({ icon: "warning", message: t`Failed to submit feedback` });+ }+ } finally {+ setIsSubmittingFeedback(false);+ }+ };++ return {+ isSubmittingFeedback,+ selectedFeedback,+ submittedFeedback,+ setSelectedFeedback,+ handleFeedbackSubmit,+ };+}diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.unit.spec.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.unit.spec.tsnew file mode 100644index 00000000000..673768279a2--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpFeedback.unit.spec.ts@@ -0,0 +1,70 @@+import { act } from "@testing-library/react";+import fetchMock from "fetch-mock";++import { renderHookWithProviders, waitFor } from "__support__/ui";++import { useMcpFeedback } from "./useMcpFeedback";++describe("useMcpFeedback", () => {+ const randomUuidSpy = jest.spyOn(crypto, "randomUUID");+ const feedbackMessageId = "11111111-1111-1111-1111-111111111111";++ beforeEach(() => {+ randomUuidSpy.mockReturnValue(feedbackMessageId);+ fetchMock.post("path:/api/embed-mcp/feedback", 200);+ });++ afterEach(() => {+ randomUuidSpy.mockReset();+ });++ it("submits the MCP feedback payload", async () => {+ const { result } = renderHookWithProviders(+ () =>+ useMcpFeedback({+ instanceUrl: "https://metabase.example",+ mcpSessionId: "mcp-session-id",+ prompt: "visualize customers",+ query: "encoded-query",+ sessionToken: "session-token",+ }),+ {},+ );++ act(() => {+ result.current.setSelectedFeedback("negative");+ });++ await act(async () => {+ await result.current.handleFeedbackSubmit({+ issue_type: "wrong-visualization",+ freeform_feedback: "Needs a different chart",+ });+ });++ await waitFor(() => {+ expect(fetchMock.callHistory.called("path:/api/embed-mcp/feedback")).toBe(+ true,+ );+ });++ const lastCall = fetchMock.callHistory.lastCall(+ "path:/api/embed-mcp/feedback",+ { method: "POST" },+ );++ expect(JSON.parse(lastCall?.options?.body as string)).toEqual({+ feedback: {+ positive: false,+ message_id: feedbackMessageId,+ issue_type: "wrong-visualization",+ freeform_feedback: "Needs a different chart",+ },+ conversation_data: {+ source: "mcp",+ prompt: "visualize customers",+ query: "encoded-query",+ },+ });+ });+});diff --git a/frontend/src/metabase/embedding/mcp/McpQueryBar.tsx b/frontend/src/metabase/embedding/mcp/hooks/useMcpQueryControls.tssimilarity index 52%rename from frontend/src/metabase/embedding/mcp/McpQueryBar.tsxrename to frontend/src/metabase/embedding/mcp/hooks/useMcpQueryControls.tsindex 53f15f88728..fa2506d7136 100644--- a/frontend/src/metabase/embedding/mcp/McpQueryBar.tsx+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpQueryControls.ts@@ -1,19 +1,10 @@-import type { App } from "@modelcontextprotocol/ext-apps/react";-import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";-import * as Urls from "metabase/urls";--import { QueryExplorerBar } from "./QueryExplorerBar";-import { useChartTypes } from "./hooks/useChartTypes";-import { useDateFilter } from "./hooks/useDateFilter";-import { useTemporalGranularity } from "./hooks/useTemporalGranularity";-interface McpQueryBarProps {- app: App | null;- instanceUrl: string;-}+import { useChartTypes } from "./useChartTypes";+import { useDateFilter } from "./useDateFilter";+import { useTemporalGranularity } from "./useTemporalGranularity";-export function McpQueryBar({ app, instanceUrl }: McpQueryBarProps) {+export function useMcpQueryControls() {const { question, updateQuestion, queryResults } = useSdkQuestionContext();const {@@ -41,10 +32,6 @@ export function McpQueryBar({ app, instanceUrl }: McpQueryBarProps) {handleDateFilterClear,} = useDateFilter(question, updateQuestion, rawTemporalColumn);- if (!question || !queryResults || hasOnlyTable) {- return null;- }-const timeRange =rawTemporalColumn !== null? {@@ -67,31 +54,21 @@ export function McpQueryBar({ app, instanceUrl }: McpQueryBarProps) {}: undefined;- const hasControls =- sensibleChartTypes.length > 0 || timeRange || timeGranularity || app;-- if (!hasControls) {- return null;- }-- async function handleExploreClicked() {- if (!instanceUrl || !question || !app) {- return;- }+ const hasQueryResults = !!question && !!queryResults;+ const canShowChartControls = hasQueryResults && !hasOnlyTable;- const url = instanceUrl + Urls.serializedQuestion(question.card());+ const hasChartTypeSelector =+ canShowChartControls && sensibleChartTypes.length > 1;- await app.openLink({ url });- }+ const hasTimeControls = hasQueryResults && !!(timeRange || timeGranularity);- return (- <QueryExplorerBar- chartTypes={sensibleChartTypes}- currentChartType={selectedChartType ?? ""}- onChartTypeChange={handleDisplayChange}- timeRange={timeRange}- timeGranularity={timeGranularity}- onExplore={handleExploreClicked}- />- );+ return {+ chartTypes: sensibleChartTypes,+ currentChartType: selectedChartType,+ hasChartTypeSelector,+ hasTimeControls,+ onChartTypeChange: handleDisplayChange,+ timeGranularity,+ timeRange,+ };}diff --git a/frontend/src/metabase/embedding/mcp/utils/buildMcpAppsTheme.ts b/frontend/src/metabase/embedding/mcp/utils/buildMcpAppsTheme.tsindex ddf3cead57f..3ff8143dc3b 100644--- a/frontend/src/metabase/embedding/mcp/utils/buildMcpAppsTheme.ts+++ b/frontend/src/metabase/embedding/mcp/utils/buildMcpAppsTheme.ts@@ -20,7 +20,6 @@ const MCP_HOST_VAR_TO_SDK_COLOR: Record<"--color-text-primary": "text-primary","--color-text-secondary": "text-secondary","--color-text-tertiary": "text-tertiary",- "--color-border-secondary": "border",};export function buildMcpAppsTheme(diff --git a/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.ts b/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.tsnew file mode 100644index 00000000000..81617e5ab4f--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.ts@@ -0,0 +1,85 @@+import visualizations from "metabase/visualizations";+import type { CardDisplayType, IconName } from "metabase-types/api";++// Default visualization can be any sensible visualization, so the+// chart type picker needs to be able to show any icon.+const MCP_CHART_TYPE_ICONS: Record<CardDisplayType, IconName> = {+ area: "area",+ bar: "bar",+ boxplot: "boxplot",+ combo: "lineandbar",+ funnel: "funnel",+ gauge: "gauge",+ line: "line",+ map: "pinmap",+ object: "document",+ pie: "pie",+ pivot: "pivot_table",+ progress: "progress",+ row: "horizontal_bar",+ sankey: "sankey",+ scalar: "number",+ scatter: "bubble",+ smartscalar: "smartscalar",+ table: "table2",+ waterfall: "waterfall",+ list: "table2",+};++// Chart types that can be the alternative.+const MCP_ALTERNATIVE_CHART_TYPES: CardDisplayType[] = ["bar", "line"];++export type McpChartTypeEntry = {+ type: CardDisplayType;+ icon: IconName;+};++interface GetMcpChartTypesProps {+ defaultDisplay: CardDisplayType | null;+ sensibleVisualizations: CardDisplayType[];+ canShowTable: boolean;+}++function getChartTypeIcon(type: CardDisplayType) {+ const visualization = visualizations.get(type);++ return visualization?.iconName ?? MCP_CHART_TYPE_ICONS[type] ?? null;+}++export function getMcpChartTypes({+ defaultDisplay,+ sensibleVisualizations,+ canShowTable,+}: GetMcpChartTypesProps): McpChartTypeEntry[] {+ const candidates = MCP_ALTERNATIVE_CHART_TYPES.filter(+ (type) => type !== defaultDisplay,+ );++ const chartTypes: Array<CardDisplayType | null> = [+ // Slot 1: the original visualization+ // Lets them go back the original viz even if it's not bar/line/area.+ defaultDisplay,++ // Slot 2: sensible visualization that isn't already the default+ candidates.find((type) => sensibleVisualizations.includes(type)) ?? null,++ // Slot 3: show table if we can, otherwise show area as the fallback+ canShowTable ? "table" : "area",+ ];++ return Array.from(new Set(chartTypes))+ .map((type) => {+ if (!type) {+ return null;+ }++ const icon = getChartTypeIcon(type);++ if (!icon) {+ return null;+ }++ return { type, icon };+ })+ .filter((entry): entry is McpChartTypeEntry => entry != null);+}diff --git a/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.unit.spec.ts b/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.unit.spec.tsnew file mode 100644index 00000000000..b1b4a0f454e--- /dev/null+++ b/frontend/src/metabase/embedding/mcp/utils/getMcpChartTypes.unit.spec.ts@@ -0,0 +1,57 @@+import type { CardDisplayType } from "metabase-types/api";++import { getMcpChartTypes } from "./getMcpChartTypes";++const getChartTypes = ({+ defaultDisplay,+ sensibleVisualizations = [],+ canShowTable = true,+}: {+ defaultDisplay: CardDisplayType;+ sensibleVisualizations?: CardDisplayType[];+ canShowTable?: boolean;+}) =>+ getMcpChartTypes({+ defaultDisplay,+ sensibleVisualizations,+ canShowTable,+ }).map(({ type }) => type);++describe("getMcpChartTypes", () => {+ // Based on the design feedback: if the sensible visualization+ // renders a pie chart by default but it's not the standard MCP viz type,+ // we should still show it so they can switch back.+ it("keeps the default visualization in selector even when it is not a MCP viz type", () => {+ expect(+ getChartTypes({+ defaultDisplay: "pie",+ sensibleVisualizations: ["pie", "bar", "line"],+ }),+ ).toEqual(["pie", "bar", "table"]);+ });++ it("does not add a chart type that is not sensible", () => {+ expect(+ getChartTypes({+ defaultDisplay: "scalar",+ sensibleVisualizations: ["scalar"],+ }),+ ).toEqual(["scalar", "table"]);+ });++ it("does not add a fallback chart when the visualization is already a bar chart", () => {+ expect(+ getChartTypes({ defaultDisplay: "bar", sensibleVisualizations: ["bar"] }),+ ).toEqual(["bar", "table"]);+ });++ it("shows area instead of table when table is not visible", () => {+ expect(+ getChartTypes({+ defaultDisplay: "pie",+ sensibleVisualizations: ["pie", "bar", "line"],+ canShowTable: false,+ }),+ ).toEqual(["pie", "bar", "area"]);+ });+});diff --git a/resources/frontend_client/mcp_apps_template.html b/resources/frontend_client/mcp_apps_template.htmlindex 0c923644fc0..3f462b67af5 100644--- a/resources/frontend_client/mcp_apps_template.html+++ b/resources/frontend_client/mcp_apps_template.html@@ -14,7 +14,7 @@body {margin: 0;- height: 500px;+ height: 550px;}body {diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.cljindex 512a1e4e86e..d34da839b19 100644--- a/src/metabase/mcp/resources.clj+++ b/src/metabase/mcp/resources.clj@@ -80,11 +80,13 @@:uri->resource (sorted-map):tools (sorted-map)}))-(defn- ui-csp-meta []+(defn- ui-meta [resource](let [url (system/site-url)]- {:ui {:csp {:connectDomains [url]- :resourceDomains [url]- :frameDomains [url]}}}))+ {:ui (cond-> {:csp {:connectDomains [url]+ :resourceDomains [url]+ :frameDomains [url]}}+ (contains? resource :prefersBorder)+ (assoc :prefersBorder (:prefersBorder resource)))}))(mu/defn register-resource!"Register an MCP resource. Overwrites any existing entry with the same `:uri`."@@ -106,7 +108,8 @@resource :- [:map[:name :string][:description :string]- [:render-fn fn?]]]+ [:render-fn fn?]+ [:prefersBorder {:optional true} :boolean]]](let [resource (-> (assoc resource :uri uri :scope scope :ui? true)(update :mimeType #(or % "text/html;profile=mcp-app")))](swap! registry #(-> %@@ -145,7 +148,7 @@(comp (filter #(mcp.scope/public-or-matches? token-scopes (:scope %)))(map (fn [resource](cond-> (select-keys resource [:uri :name :description :mimeType])- (:ui? resource) (assoc :_meta (ui-csp-meta))))))+ (:ui? resource) (assoc :_meta (ui-meta resource))))))(vals (:uri->resource @registry)))})(defn check-resource-access@@ -169,7 +172,7 @@{:status :ok:contents [(cond-> (select-keys resource [:uri :mimeType])true (assoc :text (render-fn opts))- ui? (assoc :_meta (ui-csp-meta)))]}+ ui? (assoc :_meta (ui-meta resource)))]}{:status :scope-denied}){:status :not-found}))@@ -206,6 +209,7 @@"agent:visualize"{:name "Visualize Query":description "Interactive Metabase SDK visualization for a query"+ :prefersBorder true:render-fn (fn [opts](let [site-url (system/site-url)session-key (:session-key opts)diff --git a/test/metabase/mcp/resources_test.clj b/test/metabase/mcp/resources_test.cljindex 769b3379a83..d68f7273cdc 100644--- a/test/metabase/mcp/resources_test.clj+++ b/test/metabase/mcp/resources_test.clj@@ -76,3 +76,14 @@:name "Construct Query Reference"}(some #(when (= "metabase://docs/construct-query.md" (:uri %)) %)(:resources (mcp.resources/list-resources #{})))))))++(deftest builtin-ui-resource-prefers-border-test+ (testing "the visualize query UI resource explicitly asks the host to provide a border"+ (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:visualize"}+ {}))))))