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
Add MCP apps CORS settings page and settings (#71763)
Phoomparin Mano71b8317b6548
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 4248ee27f28..67a0d60f442 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1139,13 +1139,16 @@mcp{:team "Metabot"- :api #{metabase.mcp.api}+ :api #{metabase.mcp.api+ metabase.mcp.core+ metabase.mcp.init}:uses #{agent-apiapiconfigoauth-serverrequestserver+ settingssystemutil}}@@ -1885,6 +1888,7 @@embeddinginitialization-statuslib-be+ mcpoauth-serverpremium-featuresquery-processordiff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex 373d6290a57..d2c9e4ca959 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -409,5 +409,7 @@ export const createMockSettings = ("sdk-iframe-embed-setup-settings": null,"use-tenants": false,"encryption-enabled": false,+ "mcp-apps-cors-enabled-clients": [],+ "mcp-apps-cors-custom-origins": "",...opts,});diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 9e1457224bb..c4bb50296c1 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -773,6 +773,8 @@ export interface EnterpriseSettings extends Settings {"slack-connect-enabled"?: boolean | null;"slack-connect-client-id"?: string | null;"slack-connect-client-secret"?: string | null;+ "mcp-apps-cors-enabled-clients": string[] | null;+ "mcp-apps-cors-custom-origins": string | null;/*** @deprecated*/diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.tsxnew file mode 100644index 00000000000..5cde1fc5d71--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.tsx@@ -0,0 +1,123 @@+import { useCallback, useState } from "react";+import { t } from "ttag";++import { SettingsSection } from "metabase/admin/components/SettingsSection";+import { SettingHeader } from "metabase/admin/settings/components/SettingHeader";+import { useAdminSetting } from "metabase/api/utils";+import { Box, Stack, Switch, Text, TextInput } from "metabase/ui";++const getMcpClients = () =>+ [+ {+ key: "claude",+ label: t`Claude`,+ },+ {+ key: "cursor-vscode",+ label: t`Cursor and VS Code`,+ },+ {+ key: "chatgpt",+ label: t`ChatGPT`,+ },+ ] as const;++export const McpAppsSettings = () => (+ <SettingsSection+ title={t`MCP apps`}+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- admin UI+ description={t`Allow MCP clients to connect to your Metabase instance by enabling CORS for their sandbox domains.`}+ >+ <CommonMcpClientsSection />++ <CustomMcpOriginsSection />+ </SettingsSection>+);++function CommonMcpClientsSection() {+ const mcpClients = getMcpClients();++ const { value: savedValue, updateSetting } = useAdminSetting(+ "mcp-apps-cors-enabled-clients",+ );++ const [enabledClients, setEnabledClients] = useState<string[]>(+ savedValue ?? [],+ );++ const handleToggle = useCallback(+ (clientKey: string, checked: boolean) => {+ const updated = checked+ ? [...enabledClients, clientKey]+ : enabledClients.filter((k) => k !== clientKey);++ setEnabledClients(updated);++ updateSetting({+ key: "mcp-apps-cors-enabled-clients",+ value: updated,+ });+ },+ [enabledClients, updateSetting],+ );++ return (+ <Box>+ <SettingHeader+ id="common-mcp-clients"+ title={t`Supported MCP clients`}+ description={t`Select which MCP clients you want to allow. Their sandbox domains will be automatically added to the CORS allowlist.`}+ />+ <Stack gap="md" mt="md">+ {mcpClients.map(({ key, label }) => (+ <Switch+ key={key}+ data-testid={`mcp-client-${key}`}+ checked={enabledClients.includes(key)}+ onChange={(e) => handleToggle(key, e.target.checked)}+ label={label}+ size="sm"+ w="auto"+ />+ ))}+ </Stack>+ </Box>+ );+}++function CustomMcpOriginsSection() {+ const { value: savedValue, updateSetting } = useAdminSetting(+ "mcp-apps-cors-custom-origins",+ );++ const [localValue, setLocalValue] = useState(savedValue ?? "");++ const handleBlur = useCallback(() => {+ if (localValue !== savedValue) {+ updateSetting({+ key: "mcp-apps-cors-custom-origins",+ value: localValue,+ });+ }+ }, [localValue, savedValue, updateSetting]);++ return (+ <Box>+ <SettingHeader+ id="custom-mcp-origins"+ title={t`Custom MCP client domains`}+ description={t`For self-hosted MCP clients. Separate values with a space.`}+ />+ <TextInput+ mt="md"+ value={localValue}+ onChange={(e) => setLocalValue(e.target.value)}+ onBlur={handleBlur}+ placeholder="https://*.example.com"+ />+ <Text c="text-tertiary" fz="sm" mt="xs">+ {t`Changes will take effect within one minute.`}+ </Text>+ </Box>+ );+}diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.unit.spec.tsxnew file mode 100644index 00000000000..85dbce87daa--- /dev/null+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/McpAppsSettings.unit.spec.tsx@@ -0,0 +1,81 @@+import userEvent from "@testing-library/user-event";++import {+ findRequests,+ setupPropertiesEndpoints,+ setupSettingsEndpoints,+ setupUpdateSettingEndpoint,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import { createMockSettings } from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import { McpAppsSettings } from "./McpAppsSettings";++const setup = async ({+ commonOrigins = [],+ customOrigins = "",+}: {+ commonOrigins?: string[];+ customOrigins?: string;+} = {}) => {+ const settings = createMockSettings({+ "mcp-apps-cors-enabled-clients": commonOrigins,+ "mcp-apps-cors-custom-origins": customOrigins,+ });++ setupPropertiesEndpoints(settings);+ setupSettingsEndpoints([]);+ setupUpdateSettingEndpoint();++ renderWithProviders(<McpAppsSettings />, {+ storeInitialState: createMockState({+ settings: mockSettings(settings),+ }),+ });++ await screen.findByText("Supported MCP clients");+};++describe("McpAppsSettings", () => {+ it("should show all MCP client toggles", async () => {+ await setup();++ expect(await screen.findByText("Claude")).toBeInTheDocument();+ expect(await screen.findByText("Cursor and VS Code")).toBeInTheDocument();+ expect(await screen.findByText("ChatGPT")).toBeInTheDocument();+ });++ it("can toggle all MCP clients on", async () => {+ await setup();++ await userEvent.click(await screen.findByLabelText("Claude"));+ await userEvent.click(await screen.findByLabelText("Cursor and VS Code"));+ await userEvent.click(await screen.findByLabelText("ChatGPT"));++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(3);++ expect(puts[0].body).toEqual({ value: ["claude"] });+ expect(puts[1].body).toEqual({ value: ["claude", "cursor-vscode"] });+ expect(puts[2].body).toEqual({+ value: ["claude", "cursor-vscode", "chatgpt"],+ });+ });++ it("can update custom origins on blur", async () => {+ await setup();++ const input = await screen.findByPlaceholderText("https://*.example.com");+ await userEvent.type(input, "https://my-app.example.com");+ await userEvent.tab();++ const puts = await findRequests("PUT");+ expect(puts).toHaveLength(1);++ const [{ url, body }] = puts;+ expect(url).toContain("/setting/mcp-apps-cors-custom-origins");+ expect(body).toEqual({ value: "https://my-app.example.com" });+ });+});diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotAdminPage.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotAdminPage.tsxindex 281416c2fb4..f2135545c66 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotAdminPage.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotAdminPage.tsx@@ -1,5 +1,6 @@import { IndexRoute, Route } from "react-router";+import { McpAppsSettings } from "./McpAppsSettings";import { MetabotAdminLayout } from "./MetabotAdminLayout";import { MetabotConfig } from "./MetabotConfig";import { MetabotSetup } from "./MetabotSetup";@@ -9,6 +10,7 @@ export function getAdminRoutes() {<Route key="layout" component={MetabotAdminLayout}><IndexRoute key="index" component={MetabotConfig} /><Route key="setup" path="setup" component={MetabotSetup} />+ <Route key="mcp" path="mcp" component={McpAppsSettings} />,<Route key="metabot" path=":metabotId" component={MetabotConfig} /></Route>,];diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsxindex f404f48b119..f33908fc80e 100644--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx@@ -41,6 +41,11 @@ export function MetabotNavPane() {)}</>)}+ <AdminNavItem+ icon="bolt"+ label={t`MCP apps`}+ path="/admin/metabot/mcp"+ /></AdminNavWrapper></Flex>);diff --git a/mage/src/mage/modules.clj b/mage/src/mage/modules.cljindex 6d514722a47..2e2e1302480 100644--- a/mage/src/mage/modules.clj+++ b/mage/src/mage/modules.clj@@ -117,8 +117,10 @@internal-statsllmlogin-history+ mcpmetabotnotification+ oauth-serverpermissionspremium-featurespublic-sharingdiff --git a/src/metabase/core/init.clj b/src/metabase/core/init.cljindex c7bfdecf7e2..9dd7a5a7ff4 100644--- a/src/metabase/core/init.clj+++ b/src/metabase/core/init.clj@@ -37,6 +37,7 @@[metabase.llm.init][metabase.logger.init][metabase.login-history.init]+ [metabase.mcp.init][metabase.metabot.init][metabase.model-persistence.init][metabase.models.init]diff --git a/src/metabase/mcp/core.clj b/src/metabase/mcp/core.cljnew file mode 100644index 00000000000..a2a1642de32--- /dev/null+++ b/src/metabase/mcp/core.clj@@ -0,0 +1,25 @@+(ns metabase.mcp.core+ "Public API for the MCP module. External consumers should use this namespace+ rather than reaching into internal namespaces like [[metabase.mcp.settings]]."+ (:require+ [clojure.string :as str]+ [metabase.mcp.settings :as mcp.settings]))++(defn cors-origins+ "Returns space-separated CORS origins from both common and custom MCP client settings."+ []+ (mcp.settings/mcp-apps-cors-origins))++(defn vscode-webview-enabled?+ "Returns true if vscode/cursor is enabled in common MCP apps."+ []+ (some #{"cursor-vscode"} (mcp.settings/mcp-apps-cors-enabled-clients)))++(defn sandbox-origin?+ "Returns true if the origin matches an enabled MCP client's non-standard sandbox pattern.+ Currently handles vscode-webview:// origins used by VS Code and Cursor."+ [raw-origin]+ (when raw-origin+ (condp #(str/starts-with? %2 %1) raw-origin+ "vscode-webview://" (vscode-webview-enabled?)+ false)))diff --git a/src/metabase/mcp/init.clj b/src/metabase/mcp/init.cljnew file mode 100644index 00000000000..42661aaa175--- /dev/null+++ b/src/metabase/mcp/init.clj@@ -0,0 +1,3 @@+(ns metabase.mcp.init+ (:require+ [metabase.mcp.settings]))diff --git a/src/metabase/mcp/settings.clj b/src/metabase/mcp/settings.cljnew file mode 100644index 00000000000..d134f7e2400--- /dev/null+++ b/src/metabase/mcp/settings.clj@@ -0,0 +1,49 @@+(ns metabase.mcp.settings+ "Settings for MCP Apps CORS origins."+ (:require+ [clojure.string :as str]+ [metabase.settings.core :refer [defsetting]]+ [metabase.util.i18n :refer [deferred-tru]]))++;;; ------------------------------------------------ Client → Domain Mapping --------------------------------++(def ^:private mcp-client-apps-sandbox-domains+ "Maps MCP client keys to MCP Apps sandbox domains.+ vscode-webview:// origins need special handling (prefix match, not wildcard domain)."+ {"claude" ["https://*.claudemcpcontent.com"]+ "chatgpt" ["https://*.web-sandbox.oaiusercontent.com"]++ ;; vscode-webview:// handled by mcp-sandbox-origin? in security middleware+ "cursor-vscode" []})++;;; ------------------------------------------------ Settings ------------------------------------------------++(defsetting mcp-apps-cors-enabled-clients+ (deferred-tru "Popular MCP clients enabled for CORS, stored as CSV client keys (e.g. claude, vscode).")+ :type :csv+ :default []+ :visibility :admin+ :export? false+ :encryption :no+ :audit :getter)++(defsetting mcp-apps-cors-custom-origins+ (deferred-tru "Custom CORS origins for self-hosted MCP clients, space-separated.")+ :type :string+ :default ""+ :visibility :admin+ :export? false+ :encryption :no+ :audit :getter)++;;; ------------------------------------------------ Helpers ------------------------------------------------++(defn mcp-apps-cors-origins+ "Returns space-separated CORS origins from both common and custom MCP client settings."+ []+ (let [common-domains (mapcat mcp-client-apps-sandbox-domains (mcp-apps-cors-enabled-clients))+ custom-domains (str/split (mcp-apps-cors-custom-origins) #"\s+")]+ (->> (concat common-domains custom-domains)+ (map str/trim)+ (keep not-empty)+ (str/join " "))))diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.cljindex aba4e9e5540..632a568636e 100644--- a/src/metabase/server/middleware/security.clj+++ b/src/metabase/server/middleware/security.clj@@ -8,6 +8,7 @@[metabase.analytics.core :as analytics][metabase.config.core :as config][metabase.embedding.settings :as embedding.settings]+ [metabase.mcp.core :as mcp][metabase.request.core :as request][metabase.server.settings :as server.settings]@@ -251,20 +252,24 @@(when (and (seq raw-origin) (seq approved-origins-raw))(let [approved-list (parse-approved-origins approved-origins-raw)origin (parse-url raw-origin)]- (some (fn [approved-origin]- (and- (approved-domain? (:domain origin) (:domain approved-origin))- (approved-protocol? (:protocol origin) (:protocol approved-origin))- (approved-port? (:port origin) (:port approved-origin))))- approved-list))))))+ (when origin+ (some (fn [approved-origin]+ (and+ (approved-domain? (:domain origin) (:domain approved-origin))+ (approved-protocol? (:protocol origin) (:protocol approved-origin))+ (approved-port? (:port origin) (:port approved-origin))))+ approved-list)))))))(defn access-control-headers- "Returns headers for CORS requests"+ "Returns headers for CORS requests. Merges embedding SDK origins and MCP app origins."[origin approved-origins]- (let [localhost-allowed? (and (localhost-origin? origin) (not (server.settings/disable-cors-on-localhost)))]- (when (or (seq approved-origins) localhost-allowed?)+ (let [mcp-origins (mcp/cors-origins)+ all-origins (str/trim (str approved-origins " " mcp-origins))+ localhost-allowed? (and (localhost-origin? origin) (not (server.settings/disable-cors-on-localhost)))+ mcp-sandbox? (mcp/sandbox-origin? origin)]+ (when (or (seq all-origins) localhost-allowed? mcp-sandbox?)(merge- (when (approved-origin? origin approved-origins)+ (when (or (approved-origin? origin all-origins) mcp-sandbox?){"Access-Control-Allow-Origin" origin"Vary" "Origin"}){"Access-Control-Allow-Headers" "*"diff --git a/test/metabase/server/middleware/security_mcp_test.clj b/test/metabase/server/middleware/security_mcp_test.cljnew file mode 100644index 00000000000..ea6f9ffd70d--- /dev/null+++ b/test/metabase/server/middleware/security_mcp_test.clj@@ -0,0 +1,92 @@+(ns metabase.server.middleware.security-mcp-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.mcp.settings :as mcp.settings]+ [metabase.server.middleware.security :as mw.security]+ [metabase.test :as mt]))++(defn- get-cors-origin-header+ "Returns the Access-Control-Allow-Origin header value for a given request origin."+ [request-origin]+ (let [wrapped-handler (mw.security/add-security-headers+ (fn [_request respond _raise]+ (respond {:status 200 :headers {} :body "ok"})))+ response (wrapped-handler {:headers {"origin" request-origin}+ :uri "/api/dashboard/1"}+ identity identity)]+ (get-in response [:headers "Access-Control-Allow-Origin"])))++(defn- assert-cors-allowed!+ "Asserts that the given origin is allowed (header echoes the origin back)."+ [origin]+ (is (= origin (get-cors-origin-header origin))))++(defn- assert-cors-blocked!+ "Asserts that the given origin is blocked (no Access-Control-Allow-Origin header)."+ [origin]+ (is (nil? (get-cors-origin-header origin))))++(deftest test-mcp-common-cors-origins+ (testing "Claude sandbox origins should be allowed when claude is enabled"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["claude"]]+ (assert-cors-allowed! "https://abc.claudemcpcontent.com")))++ (testing "ChatGPT sandbox origins should be allowed when chatgpt is enabled"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["chatgpt"]]+ (assert-cors-allowed! "https://abc.web-sandbox.oaiusercontent.com")))++ (testing "Claude sandbox origins should NOT be allowed when only chatgpt is enabled"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["chatgpt"]]+ (assert-cors-blocked! "https://abc.claudemcpcontent.com")))++ (testing "Multiple MCP clients can be enabled simultaneously"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["claude" "chatgpt"]]+ (assert-cors-allowed! "https://abc.claudemcpcontent.com")+ (assert-cors-allowed! "https://xyz.web-sandbox.oaiusercontent.com"))))++(deftest test-mcp-vscode-webview-origin+ (testing "vscode-webview:// origins should be allowed when vscode is enabled"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["cursor-vscode"]]+ (assert-cors-allowed! "vscode-webview://abc123")))++ (testing "vscode-webview:// origins should NOT be allowed when vscode is not enabled"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["claude"]]+ (assert-cors-blocked! "vscode-webview://abc123"))))++(deftest test-mcp-custom-cors-origins+ (testing "Custom MCP origins should be allowed"+ (mt/with-temporary-setting-values [mcp-apps-cors-custom-origins "https://my-librechat.example.com"]+ (assert-cors-allowed! "https://my-librechat.example.com")))++ (testing "Custom MCP origins should work alongside common MCP origins"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["claude"]+ mcp-apps-cors-custom-origins "https://my-librechat.example.com"]+ (assert-cors-allowed! "https://abc.claudemcpcontent.com")+ (assert-cors-allowed! "https://my-librechat.example.com"))))++(deftest test-mcp-cors-merged-with-embedding+ (testing "MCP origins and embedding origins should both work"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["claude"]+ embedding-app-origins-sdk "https://my-app.example.com"]+ (assert-cors-allowed! "https://my-app.example.com")+ (assert-cors-allowed! "https://abc.claudemcpcontent.com"))))++(deftest test-mcp-settings-helper+ (testing "mcp-apps-cors-origins returns space-separated origins for enabled clients"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["claude" "chatgpt"]]+ (let [origins (mcp.settings/mcp-apps-cors-origins)]+ (is (str/includes? origins "*.claudemcpcontent.com"))+ (is (str/includes? origins "*.web-sandbox.oaiusercontent.com")))))++ (testing "mcp-apps-cors-origins includes custom origins"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients ["claude"]+ mcp-apps-cors-custom-origins "https://custom.example.com"]+ (let [origins (mcp.settings/mcp-apps-cors-origins)]+ (is (str/includes? origins "*.claudemcpcontent.com"))+ (is (str/includes? origins "https://custom.example.com")))))++ (testing "mcp-apps-cors-origins returns empty string when nothing is configured"+ (mt/with-temporary-setting-values [mcp-apps-cors-enabled-clients []+ mcp-apps-cors-custom-origins ""]+ (is (= "" (mcp.settings/mcp-apps-cors-origins))))))