Skip to content

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

Add MCP Apps with React SDK (#71001)

Phoomparin Manob3869c0b8925
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 2468cc8e456..4b929bb0bf1 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1180,16 +1180,18 @@
mcp
{:team "Metabot"
:api #{metabase.mcp.api
+ metabase.mcp.callback-api
metabase.mcp.core
metabase.mcp.init}
:uses #{agent-api
api
- api-scope
+ app-db
config
llm
oauth-server
request
server
+ session
settings
system
util}}
@@ -1255,6 +1257,7 @@
settings
slackbot
sql-tools
+ store-api
sync
system
task
@@ -1419,6 +1422,7 @@
metabase.oauth-server.init}
:uses #{api
appearance
+ mcp
models
request
settings
diff --git a/.gitignore b/.gitignore
index d2f2e7de9bb..996006a03bc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -78,6 +78,7 @@ cypress.env.json
/resources/frontend_client/tmp-*/
/resources/frontend_client/embed.html
/resources/frontend_client/embed-sdk.html
+/resources/frontend_client/embed-mcp.html
/resources/frontend_client/index.html
/resources/frontend_client/public.html
/resources/embedding-sdk
diff --git a/bin/find-never-defined-css-variables/find-never-defined-css-variables.ts b/bin/find-never-defined-css-variables/find-never-defined-css-variables.ts
index fc5cc1df092..32bc3c3bae8 100644
--- a/bin/find-never-defined-css-variables/find-never-defined-css-variables.ts
+++ b/bin/find-never-defined-css-variables/find-never-defined-css-variables.ts
@@ -45,9 +45,9 @@ interface UsageMap {
}
const findFiles = (): string[] => {
- return glob.sync(
- "{frontend,enterprise/frontend}/**/*.{css,module.css,js,jsx,ts,tsx}",
- );
+ return glob
+ .sync("{frontend,enterprise/frontend}/**/*.{css,module.css,js,jsx,ts,tsx}")
+ .filter(f => !/\.(unit\.spec|spec|test)\.(js|jsx|ts|tsx)$/.test(f));
};
const extractVariableDefinitions = (filePath: string): Set<string> => {
diff --git a/bun.lock b/bun.lock
index ac377fd7ff7..626ae31b8b4 100644
--- a/bun.lock
+++ b/bun.lock
@@ -38,6 +38,7 @@
"@mantine/core": "8.3.18",
"@mantine/dates": "8.3.18",
"@mantine/hooks": "8.3.18",
+ "@modelcontextprotocol/ext-apps": "^1.3.2",
"@popperjs/core": "^2.11.8",
"@react-oauth/google": "^0.11.1",
"@reduxjs/toolkit": "^2.5.0",
@@ -994,6 +995,8 @@
"@hey-api/openapi-ts": ["@hey-api/[email protected]", "", { "dependencies": { "@hey-api/codegen-core": "^0.3.3", "@hey-api/json-schema-ref-parser": "1.2.1", "ansi-colors": "4.1.3", "c12": "3.3.1", "color-support": "1.1.3", "commander": "14.0.1", "open": "10.2.0", "semver": "7.7.2" }, "bin": { "openapi-ts": "bin/run.js" } }, "sha512-IFjwE11VPebjbCJqtTnszx22IWeabWWIOAkKKsn6AlV4i2voiUUolB/a/vSnvbwdoolnzB+jOhkYyww2odoJaQ=="],
+ "@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g=="],
+
"@humanfs/core": ["@humanfs/[email protected]", "", {}, "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA=="],
"@humanfs/node": ["@humanfs/[email protected]", "", { "dependencies": { "@humanfs/core": "^0.19.1", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ=="],
@@ -1182,6 +1185,10 @@
"@microsoft/tsdoc-config": ["@microsoft/[email protected]", "", { "dependencies": { "@microsoft/tsdoc": "0.15.1", "ajv": "~8.12.0", "jju": "~1.4.0", "resolve": "~1.22.2" } }, "sha512-UtjIFe0C6oYgTnad4q1QP4qXwLhe6tIpNTRStJ2RZEPIkqQPREAwE5spzVxsdn9UaEMUqhh0AqSx3X4nWAKXWw=="],
+ "@modelcontextprotocol/ext-apps": ["@modelcontextprotocol/[email protected]", "", { "peerDependencies": { "@modelcontextprotocol/sdk": "^1.24.0", "react": "^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-DGG1FxN3s8g4KV+BF64dxph8j2mtxgU56Lu/WgBjylomqRIPshW0ut47OtBN4+V8r+Qp8kKUvCOBBzPY9+GurA=="],
+
+ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-gmloF+i+flI8ouQK7MWW4mOwuMh4RePBuPFAEPC6+pdqyWOUMDOixb6qZ69owLJpz6XmyllCouc4t8YWO+E2Nw=="],
+
"@module-federation/error-codes": ["@module-federation/[email protected]", "", {}, "sha512-Woonm8ehyVIUPXChmbu80Zj6uJkC0dD9SJUZ/wOPtO8iiz/m+dkrOugAuKgoiR6qH4F+yorWila954tBz4uKsQ=="],
"@module-federation/runtime": ["@module-federation/[email protected]", "", { "dependencies": { "@module-federation/error-codes": "0.18.0", "@module-federation/runtime-core": "0.18.0", "@module-federation/sdk": "0.18.0" } }, "sha512-+C4YtoSztM7nHwNyZl6dQKGUVJdsPrUdaf3HIKReg/GQbrt9uvOlUWo2NXMZ8vDAnf/QRrpSYAwXHmWDn9Obaw=="],
@@ -2576,6 +2583,8 @@
"core-util-is": ["[email protected]", "", {}, "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="],
+ "cors": ["[email protected]", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
+
"corser": ["[email protected]", "", {}, "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ=="],
"cosmiconfig": ["[email protected]", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" } }, "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg=="],
@@ -3036,6 +3045,10 @@
"events": ["[email protected]", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],
+ "eventsource": ["[email protected]", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
+
+ "eventsource-parser": ["[email protected]", "", {}, "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg=="],
+
"evp_bytestokey": ["[email protected]", "", { "dependencies": { "md5.js": "^1.3.4", "safe-buffer": "^5.1.1" } }, "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA=="],
"execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.0", "onetime": "^5.1.0", "signal-exit": "^3.0.2", "strip-final-newline": "^2.0.0" } }, "sha512-j5W0//W7f8UxAn8hXVnwG8tLwdiUy4FJLcSupCg6maBYZDpyBvTApK7KyuI4bKj8KOh1r2YH+6ucuYtJv1bTZA=="],
@@ -3050,6 +3063,8 @@
"express": ["[email protected]", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "1.20.3", "content-disposition": "0.5.4", "content-type": "~1.0.4", "cookie": "0.7.1", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "1.3.1", "fresh": "0.5.2", "http-errors": "2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "0.1.12", "proxy-addr": "~2.0.7", "qs": "6.13.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "0.19.0", "serve-static": "1.16.2", "setprototypeof": "1.2.0", "statuses": "2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA=="],
+ "express-rate-limit": ["[email protected]", "", { "dependencies": { "ip-address": "10.1.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw=="],
+
"exsolve": ["[email protected]", "", {}, "sha512-VO5fQUzZtI6C+vx4w/4BWJpg3s/5l+6pRQEHzFRM8WFi4XffSP1Z+4qi7GbjWbvRQEbdIco5mIMq+zX4rPuLrw=="],
"extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
@@ -3316,6 +3331,8 @@
"homedir-polyfill": ["[email protected]", "", { "dependencies": { "parse-passwd": "^1.0.0" } }, "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA=="],
+ "hono": ["[email protected]", "", {}, "sha512-wy3T8Zm2bsEvxKZM5w21VdHDDcwVS1yUFFY6i8UobSsKfFceT7TOwhbhfKsDyx7tYQlmRM5FLpIuYvNFyjctiA=="],
+
"hookified": ["[email protected]", "", {}, "sha512-xnKGl+iMIlhrZmGHB729MqlmPoWBznctSQTYCpFKqNsCgimJQmithcW0xSQMMFzYnV2iKUh25alswn6epgxS0Q=="],
"hosted-git-info": ["[email protected]", "", {}, "sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg=="],
@@ -3438,6 +3455,8 @@
"iobuffer": ["[email protected]", "", {}, "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA=="],
+ "ip-address": ["[email protected]", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
+
"ipaddr.js": ["[email protected]", "", {}, "sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA=="],
"is-absolute-url": ["[email protected]", "", {}, "sha512-/51/TKE88Lmm7Gc4/8btclNXWS+g50wXhYJq8HWIBAGUBnoAdRu1aXeh364t/O7wXDAcTJDP8PNuNKWUDWie+A=="],
@@ -3524,6 +3543,8 @@
"is-potential-custom-element-name": ["[email protected]", "", {}, "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ=="],
+ "is-promise": ["[email protected]", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
+
"is-property": ["[email protected]", "", {}, "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g=="],
"is-regex": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g=="],
@@ -3682,6 +3703,8 @@
"json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
+ "json-schema-typed": ["[email protected]", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
+
"json-stable-stringify": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.4", "isarray": "^2.0.5", "jsonify": "^0.0.1", "object-keys": "^1.1.1" } }, "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg=="],
"json-stable-stringify-without-jsonify": ["[email protected]", "", {}, "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE="],
@@ -4290,6 +4313,8 @@
"pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^6.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-o8mkY4E/+LNUf6LzX96ht6k6CEDi65k9G2rjMtBe9Oo+VPKSvl+0GKHuH/AlG+GA5LPG/i5hrekkxUc3s2HU+Q=="],
+ "pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
+
"pkg-dir": ["[email protected]", "", { "dependencies": { "find-up": "^4.0.0" } }, "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ=="],
"pkg-types": ["[email protected]", "", { "dependencies": { "confbox": "^0.2.2", "exsolve": "^1.0.7", "pathe": "^2.0.3" } }, "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig=="],
@@ -4744,6 +4769,8 @@
"rope-sequence": ["[email protected]", "", {}, "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ=="],
+ "router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
+
"rrweb-cssom": ["[email protected]", "", {}, "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw=="],
"rtl-css-js": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.1.2" } }, "sha512-lRQgou1mu19e+Ya0LsTvKrVJ5TYUbqCVPAiImX3UfLTenarvPUl1QFdvu5Z3PYmHT9RCcwIfbjRQBntExyj3Zg=="],
@@ -5452,6 +5479,10 @@
"yup": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.15.4", "@types/lodash": "^4.14.175", "lodash": "^4.17.21", "lodash-es": "^4.17.21", "nanoclone": "^0.2.1", "property-expr": "^2.0.4", "toposort": "^2.0.2" } }, "sha512-Z2Fe1bn+eLstG8DRR6FTavGD+MeAwyfmouhHsIUgaADz8jvFKbO/fXc2trJKZg+5EBjh4gGm3iU/t3onKlXHIg=="],
+ "zod": ["[email protected]", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
+
+ "zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
+
"zrender": ["[email protected]", "", { "dependencies": { "tslib": "2.3.0" } }, "sha512-41dFXEEXuJpNecuUQq6JlbybmnHaqqpGlbH1yxnA5V9MMP4SbohSVZsJIwz+zdjQXSSlR1Vc34EgH1zxyTDvhg=="],
"zustand": ["[email protected]", "", { "dependencies": { "use-sync-external-store": "^1.2.2" } }, "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw=="],
@@ -5648,6 +5679,10 @@
"@microsoft/tsdoc-config/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2", "uri-js": "^4.2.2" } }, "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA=="],
+ "@modelcontextprotocol/sdk/express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
+
+ "@modelcontextprotocol/sdk/jose": ["[email protected]", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="],
+
"@nicolo-ribaudo/eslint-scope-5-internals/eslint-scope": ["[email protected]", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw=="],
"@pmmmwh/react-refresh-webpack-plugin/source-map": ["[email protected]", "", {}, "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ=="],
@@ -6266,6 +6301,8 @@
"get-intrinsic/es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
+ "gettext-parser/readable-stream": ["[email protected]", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-Lk/fICSyIhodxy1IDK2HazkeGjSmezAWX2egdtJnYhtzKEsBPJowlI6F6LPb5tqIQILrMbx22S5o3GuJavPusA=="],
+
"gettext-parser/safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"giget/consola": ["[email protected]", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="],
@@ -6468,6 +6505,8 @@
"json-schema-to-ts/@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
+ "json-stable-stringify/call-bind": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "set-function-length": "^1.2.1" } }, "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w=="],
+
"jsonwebtoken/semver": ["[email protected]", "", { "dependencies": { "lru-cache": "^6.0.0" }, "bin": { "semver": "bin/semver.js" } }, "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA=="],
"jspdf/@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA=="],
@@ -6480,6 +6519,8 @@
"kbar/fuse.js": ["[email protected]", "", {}, "sha512-cJaJkxCCxC8qIIcPBF9yGxY0W/tVZS3uEISDxhYIdtk8OL93pe+6Zj7LjCqVV4dzbqcriOZ+kQ/NE4RXZHsIGA=="],
+ "klaw-sync/graceful-fs": ["[email protected]", "", {}, "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw=="],
+
"knex/colorette": ["[email protected]", "", {}, "sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ=="],
"knex/commander": ["[email protected]", "", {}, "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ=="],
@@ -6722,6 +6763,8 @@
"raw-body/bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
+ "raw-body/http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
+
"raw-body/iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3" } }, "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA=="],
"react-devtools-core/ws": ["[email protected]", "", {}, "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ=="],
@@ -6812,6 +6855,8 @@
"rollup-plugin-inject/magic-string": ["[email protected]", "", { "dependencies": { "sourcemap-codec": "^1.4.8" } }, "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ=="],
+ "router/path-to-regexp": ["[email protected]", "", {}, "sha512-PuseHIvAnz3bjrM2rGJtSgo1zjgxapTLZ7x2pjhzWwlp4SJQgK3f3iZIQwkpEnBaKz6seKBADpM4B4ySkuYypg=="],
+
"rxjs/tslib": ["[email protected]", "", {}, "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q=="],
"sass/chokidar": ["[email protected]", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="],
@@ -7212,6 +7257,28 @@
"@microsoft/tsdoc-config/ajv/uri-js": ["[email protected]", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-B0yRTzYdUCCn9n+F4+Gh4yIDtMQcaJsmYBDsTSG8g/OejKBodLQ2IHfN3bM7jUsRXndopT7OIXWdYqc1fjmV6g=="],
+ "@modelcontextprotocol/sdk/express/accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
+
+ "@modelcontextprotocol/sdk/express/body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
+
+ "@modelcontextprotocol/sdk/express/content-disposition": ["[email protected]", "", {}, "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q=="],
+
+ "@modelcontextprotocol/sdk/express/cookie-signature": ["[email protected]", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
+
+ "@modelcontextprotocol/sdk/express/finalhandler": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
+
+ "@modelcontextprotocol/sdk/express/fresh": ["[email protected]", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
+
+ "@modelcontextprotocol/sdk/express/merge-descriptors": ["[email protected]", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
+
+ "@modelcontextprotocol/sdk/express/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
+
+ "@modelcontextprotocol/sdk/express/send": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
+
+ "@modelcontextprotocol/sdk/express/serve-static": ["[email protected]", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
+
+ "@modelcontextprotocol/sdk/express/type-is": ["[email protected]", "", { "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw=="],
+
"@nicolo-ribaudo/eslint-scope-5-internals/eslint-scope/estraverse": ["[email protected]", "", {}, "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw=="],
"@redocly/cli/glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^5.0.2" } }, "sha512-ugkC31VaVg9cF0DFVoADH12k6061zNZkZON+aX8AWsR9GhPcErkcMBceb6znR8wLERM2AkkOxy2nWRLpT9Jq5w=="],
@@ -7396,6 +7463,8 @@
"babel-plugin-ttag/babel-plugin-macros/cosmiconfig": ["[email protected]", "", { "dependencies": { "@types/parse-json": "^4.0.0", "import-fresh": "^3.1.0", "parse-json": "^5.0.0", "path-type": "^4.0.0", "yaml": "^1.7.2" } }, "sha512-xb3ZL6+L8b9JLLCx3ZdoZy4+2ECphCMo2PwqgP1tlfVq6M6YReyzBJtvWWtbDSpNr9hn96pkCiZqUcFEc+54Qg=="],
+ "babel-plugin-ttag/babel-plugin-macros/resolve": ["[email protected]", "", { "dependencies": { "path-parse": "^1.0.6" } }, "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w=="],
+
"better-opn/open/define-lazy-prop": ["[email protected]", "", {}, "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="],
"better-opn/open/is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="],
@@ -7768,6 +7837,10 @@
"jsdom/whatwg-url/tr46": ["[email protected]", "", { "dependencies": { "punycode": "^2.3.1" } }, "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw=="],
+ "json-stable-stringify/call-bind/get-intrinsic": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2", "has-proto": "^1.0.1", "has-symbols": "^1.0.3", "hasown": "^2.0.0" } }, "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ=="],
+
+ "json-stable-stringify/call-bind/set-function-length": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.1.2", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.3", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.1" } }, "sha512-j4t6ccc+VsKwYHso+kElc5neZpjtq9EnRICFZtWyBsLojhmeF/ZBd/elqm22WJh/BziDe/SBiOeAt0m2mfLD0g=="],
+
"jsonwebtoken/semver/lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="],
"jsx-ast-utils/array-includes/call-bind": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.1", "get-intrinsic": "^1.0.2" } }, "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA=="],
@@ -7960,6 +8033,8 @@
"public-encrypt/parse-asn1/asn1.js": ["[email protected]", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0", "safer-buffer": "^2.1.0" } }, "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA=="],
+ "raw-body/http-errors/statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
+
"react-dnd-html5-backend/dnd-core/redux": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.9.2" } }, "sha512-oSBmcKKIuIR4ME29/AeNUnl5L+hvBq7OaJWzaptTQJAntaPvxIJqfnjbaEiCzzaIz+XmVILfqAM3Ob0aXLPfjA=="],
"react-dnd/dnd-core/redux": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.9.2" } }, "sha512-oSBmcKKIuIR4ME29/AeNUnl5L+hvBq7OaJWzaptTQJAntaPvxIJqfnjbaEiCzzaIz+XmVILfqAM3Ob0aXLPfjA=="],
@@ -8240,6 +8315,24 @@
"@microsoft/tsdoc-config/ajv/uri-js/punycode": ["[email protected]", "", {}, "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A=="],
+ "@modelcontextprotocol/sdk/express/accepts/negotiator": ["[email protected]", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
+
+ "@modelcontextprotocol/sdk/express/body-parser/bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
+
+ "@modelcontextprotocol/sdk/express/body-parser/http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
+
+ "@modelcontextprotocol/sdk/express/body-parser/iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
+
+ "@modelcontextprotocol/sdk/express/finalhandler/statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
+
+ "@modelcontextprotocol/sdk/express/mime-types/mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
+
+ "@modelcontextprotocol/sdk/express/send/http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
+
+ "@modelcontextprotocol/sdk/express/send/statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
+
+ "@modelcontextprotocol/sdk/express/type-is/media-typer": ["[email protected]", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
+
"@redocly/cli/glob/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw=="],
"@rushstack/node-core-library/semver/lru-cache/yallist": ["[email protected]", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
@@ -8298,6 +8391,8 @@
"babel-plugin-macros/cosmiconfig/import-fresh/resolve-from": ["[email protected]", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
+ "babel-plugin-ttag/babel-plugin-macros/cosmiconfig/import-fresh": ["[email protected]", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ=="],
+
"babel-plugin-ttag/babel-plugin-macros/cosmiconfig/parse-json": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="],
"babel-plugin-ttag/babel-plugin-macros/cosmiconfig/yaml": ["[email protected]", "", {}, "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA=="],
@@ -8472,6 +8567,14 @@
"jest-runtime/glob/path-scurry/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
+ "json-stable-stringify/call-bind/get-intrinsic/has-proto": ["[email protected]", "", {}, "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg=="],
+
+ "json-stable-stringify/call-bind/get-intrinsic/has-symbols": ["[email protected]", "", {}, "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A=="],
+
+ "json-stable-stringify/call-bind/get-intrinsic/hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-1/th4MHjnwncwXsIW6QMzlvYL9kG5e/CpVvLRZe4XPa8TOUNbCELqmvhDmnkNsAjwaG4+I8gJJL0JBvTTLO9qA=="],
+
+ "json-stable-stringify/call-bind/set-function-length/gopd": ["[email protected]", "", { "dependencies": { "get-intrinsic": "^1.1.3" } }, "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA=="],
+
"jsonwebtoken/semver/lru-cache/yallist": ["[email protected]", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
"jsx-ast-utils/array-includes/es-abstract/array-buffer-byte-length": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.5", "is-array-buffer": "^3.0.4" } }, "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg=="],
@@ -8798,6 +8901,8 @@
"@jest/reporters/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+ "@modelcontextprotocol/sdk/express/body-parser/http-errors/statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
+
"@redocly/cli/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", { "dependencies": { "jackspeak": "^4.2.3" } }, "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg=="],
"@storybook/addon-webpack5-compiler-babel/babel-loader/find-cache-dir/pkg-dir/find-up": ["[email protected]", "", { "dependencies": { "locate-path": "^7.1.0", "path-exists": "^5.0.0" } }, "sha512-v2ZsoEuVHYy8ZIlYqwPe/39Cy+cFDzp4dXPaxNvkEuouymu+2Jbz0PxpKarJHYJTmv2HWT3O382qY8l4jMWthw=="],
@@ -8816,6 +8921,8 @@
"babel-loader/schema-utils/ajv/uri-js/punycode": ["[email protected]", "", {}, "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A=="],
+ "babel-plugin-ttag/babel-plugin-macros/cosmiconfig/import-fresh/resolve-from": ["[email protected]", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
+
"chokidar-cli/yargs/cliui/wrap-ansi/ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^1.9.0" } }, "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA=="],
"chokidar-cli/yargs/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="],
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index d7f5d969e0e..b3fc907415f 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -87,6 +87,7 @@
"HTTPAction"
"ImplicitAction"
"LoginHistory"
+ "McpQueryHandle"
"MetabotConversation"
"MetabotFeedback"
"MetabotGroupLimit"
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
index 368021ac8f0..b9daf746f73 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
@@ -60,6 +60,7 @@
:model/CollectionPermissionGraphRevision
:model/DashboardCardSeries
:model/LoginHistory
+ :model/McpQueryHandle
:model/FieldValues
:model/MetabotConversation
:model/MetabotFeedback
diff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
index 524cb472032..64b7df5c840 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
@@ -33,6 +33,7 @@ import { requestSessionTokenFromEmbedJs } from "metabase/embedding/embedding-ifr
import {
EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG,
isEmbeddingEajs,
+ isEmbeddingMcpApp,
} from "metabase/embedding-sdk/config";
import { samlTokenStorage } from "metabase/embedding-sdk/lib/saml-token-storage";
import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types/refresh-token";
@@ -54,6 +55,11 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
authConfig: MetabaseAuthConfig & { isLocalHost?: boolean },
{ dispatch }: { dispatch: SdkDispatch },
) => {
+ // MCP Apps inject a session token directly and manage user/settings themselves.
+ if (isEmbeddingMcpApp()) {
+ return;
+ }
+
const { metabaseInstanceUrl, apiKey, isLocalHost } = authConfig;
// remove any stale tokens that might be there from a previous session
diff --git a/eslint.config.mjs b/eslint.config.mjs
index a4bedf33bc8..0fd687524ad 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -584,7 +584,16 @@ const configs = [
},
},
{
- files: ["frontend/src/metabase/redux/hooks.ts"],
+ // MCP UI app is a standalone SDK consumer — allow embedding-sdk-package imports
+ // and raw hex color literals (used for MCP host theme fallback values).
+ files: ["frontend/src/metabase/embedding/mcp/**/*"],
+ rules: {
+ "no-restricted-imports": "off",
+ "metabase/no-color-literals": "off",
+ },
+ },
+ {
+ files: ["frontend/src/metabase/utils/redux/hooks.ts"],
rules: {
"no-restricted-imports": "off",
},
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
index 7cee268d1f8..de09ec5e3c0 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
@@ -26,6 +26,7 @@ import {
getPlugins,
getSessionTokenState,
} from "embedding-sdk-bundle/store/selectors";
+import type { NavigateToNewCardParams } from "embedding-sdk-bundle/types";
import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";
import { EmbeddingEntityContextProvider } from "metabase/embedding/context";
import { transformSdkQuestion } from "metabase/embedding-sdk/lib/transform-question";
@@ -83,6 +84,7 @@ export const SdkQuestionProvider = ({
backToDashboard,
getClickActionMode: userGetClickActionMode,
navigateToNewCard: userNavigateToNewCard,
+ onDrillThrough,
onVisualizationChange,
}: SdkQuestionProviderProps) => {
const isGuestEmbed = useSdkSelector(getIsGuestEmbed);
@@ -227,11 +229,31 @@ export const SdkQuestionProvider = ({
const mode = (question && getClickActionMode({ question })) ?? null;
+ // Wrap navigateToNewCard to intercept navigation to new card
+ const navigateToNewCardWithDrillThrough = useCallback(
+ async (params: NavigateToNewCardParams) => {
+ if (onDrillThrough) {
+ await onDrillThrough(
+ {
+ drillName: params.drillName,
+ nextCard: params.nextCard,
+ },
+ async () => {
+ await navigateToNewCard?.(params);
+ },
+ );
+ } else {
+ await navigateToNewCard?.(params);
+ }
+ },
+ [navigateToNewCard, onDrillThrough],
+ );
+
// Wrap navigateToNewCard to push the virtual entry for the internal navigation system
const navigateToNewCardWithSdkInternalNavigation = useCallback(
- async (params: Parameters<NonNullable<typeof navigateToNewCard>>[0]) => {
+ async (params: NavigateToNewCardParams) => {
// This actually changes what gets rendered
- await navigateToNewCard?.(params);
+ await navigateToNewCardWithDrillThrough(params);
// Push virtual entry if last entry is NOT already a question drill
const currentEntry = navigation?.stack.at(-1);
@@ -244,7 +266,12 @@ export const SdkQuestionProvider = ({
});
}
},
- [navigateToNewCard, navigation, question, loadAndQueryQuestion],
+ [
+ navigateToNewCardWithDrillThrough,
+ navigation,
+ question,
+ loadAndQueryQuestion,
+ ],
);
const query = question?.query();
@@ -278,7 +305,7 @@ export const SdkQuestionProvider = ({
updateParameterValues,
navigateToNewCard:
userNavigateToNewCard !== undefined
- ? navigateToNewCard
+ ? navigateToNewCardWithDrillThrough
: navigateToNewCardWithSdkInternalNavigation,
plugins,
question,
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
index 848fb1c8239..7fc7e198e13 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
@@ -21,7 +21,7 @@ import type {
QueryClickActionsMode,
} from "metabase/visualizations/types";
import type Question from "metabase-lib/v1/Question";
-import type { CardDisplayType, DashboardId } from "metabase-types/api";
+import type { Card, CardDisplayType, DashboardId } from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";
type SdkQuestionConfig = {
@@ -169,6 +169,21 @@ export type SdkQuestionProviderProps = PropsWithChildren<
* @internal
*/
navigateToNewCard?: Nullable<LoadQuestionHookResult["navigateToNewCard"]>;
+
+ /**
+ * Called when a drill-through action is about to navigate to a new card.
+ * Receives the navigation params and a `defaultNavigate` callback.
+ * Call `defaultNavigate()` to allow normal navigation, or omit it to intercept.
+ *
+ * @internal
+ */
+ onDrillThrough?: (
+ params: {
+ drillName: string | undefined;
+ nextCard: Card;
+ },
+ defaultNavigate: () => Promise<void>,
+ ) => Promise<void>;
}
>;
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
index 90077756705..659d3e6e670 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
@@ -66,6 +66,11 @@ export interface SdkQuestionDefaultViewProps extends FlexibleSizeProps {
* Determines whether the chart type selector and corresponding settings button are shown. Only relevant when using the default layout.
*/
withChartTypeSelector?: boolean;
+
+ /**
+ * Determines whether the editor button is shown. Only relevant when using the default layout.
+ */
+ withEditorButton?: boolean;
}
export const SdkQuestionDefaultView = ({
@@ -75,6 +80,7 @@ export const SdkQuestionDefaultView = ({
style,
title,
withChartTypeSelector,
+ withEditorButton = true,
}: SdkQuestionDefaultViewProps): ReactElement => {
const { isLocaleLoading } = useLocale();
const {
@@ -254,7 +260,9 @@ export const SdkQuestionDefaultView = ({
<QuestionAlertsButton />
</>
)}
- <EditorButton isOpen={isEditorOpen} onClick={toggleEditor} />
+ {withEditorButton && (
+ <EditorButton isOpen={isEditorOpen} onClick={toggleEditor} />
+ )}
</RenderIfHasContent>
</RenderIfHasContent>
)}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
index 7bebe79b097..26f81f5c957 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
@@ -50,8 +50,10 @@ const propsSchema: Yup.SchemaOf<InteractiveQuestionInternalProps> = Yup.object({
title: Yup.mixed().optional(),
width: Yup.mixed().optional(),
withChartTypeSelector: Yup.mixed().optional(),
+ withEditorButton: Yup.mixed().optional(),
withDownloads: Yup.mixed().optional(),
withAlerts: Yup.mixed().optional(),
+ onDrillThrough: Yup.mixed().optional(),
onVisualizationChange: Yup.mixed().optional(),
}).noUnknown();
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion-drills.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion-drills.unit.spec.tsx
new file mode 100644
index 00000000000..cd1c24521cb
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion-drills.unit.spec.tsx
@@ -0,0 +1,134 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupCardEndpoints,
+ setupCardQueryEndpoints,
+ setupCardQueryMetadataEndpoint,
+ setupDatabaseEndpoints,
+ setupTableEndpoints,
+} from "__support__/server-mocks";
+import { act, screen, waitFor, waitForLoaderToBeRemoved } from "__support__/ui";
+import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";
+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 type { NavigateToNewCardParams } from "embedding-sdk-bundle/types";
+import type { CardId } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockColumn,
+ createMockDatabase,
+ createMockDataset,
+ createMockDatasetData,
+ createMockTable,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { SdkQuestion, type SdkQuestionProps } from "./SdkQuestion";
+
+const TEST_USER = createMockUser();
+const TEST_DB_ID = 1;
+const TEST_DB = createMockDatabase({ id: TEST_DB_ID });
+
+const TEST_TABLE_ID = 1;
+const TEST_TABLE = createMockTable({ id: TEST_TABLE_ID, db_id: TEST_DB_ID });
+
+const TEST_COLUMN = createMockColumn({
+ display_name: "Test Column",
+ name: "Test Column",
+});
+
+const TEST_DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [TEST_COLUMN],
+ rows: [["Test Row"]],
+ }),
+});
+
+const TEST_CARD_ID: CardId = 1 as const;
+const TEST_CARD = createMockCard({ id: TEST_CARD_ID, name: "My Question" });
+
+// A card with a different object reference than TEST_CARD, used as nextCard
+// so runQuestionOnNavigateSdk doesn't bail out early on reference equality.
+const NEXT_CARD = { ...TEST_CARD };
+
+const DrillTrigger = ({ params }: { params: NavigateToNewCardParams }) => {
+ const { navigateToNewCard } = useSdkQuestionContext();
+
+ return (
+ <button onClick={() => navigateToNewCard?.(params)}>Trigger Drill</button>
+ );
+};
+
+const setup = async ({
+ onDrillThrough,
+}: {
+ onDrillThrough?: SdkQuestionProps["onDrillThrough"];
+}) => {
+ const { state } = setupSdkState({ currentUser: TEST_USER });
+
+ setupDatabaseEndpoints(TEST_DB);
+ setupTableEndpoints(TEST_TABLE);
+ setupCardEndpoints(TEST_CARD);
+ setupCardQueryEndpoints(TEST_CARD, TEST_DATASET);
+
+ setupCardQueryMetadataEndpoint(
+ TEST_CARD,
+ createMockCardQueryMetadata({ databases: [TEST_DB] }),
+ );
+
+ const drillParams: NavigateToNewCardParams = {
+ nextCard: NEXT_CARD,
+ previousCard: TEST_CARD,
+ objectId: 1,
+ drillName: "drill-thru/pk",
+ };
+
+ renderWithSDKProviders(
+ <SdkQuestion questionId={TEST_CARD_ID} onDrillThrough={onDrillThrough}>
+ <DrillTrigger params={drillParams} />
+ </SdkQuestion>,
+ {
+ componentProviderProps: { authConfig: createMockSdkConfig() },
+ storeInitialState: state,
+ },
+ );
+
+ await waitForLoaderToBeRemoved();
+};
+
+describe("SdkQuestion onDrillThrough", () => {
+ it("triggers navigation when defaultNavigate is called", async () => {
+ const queryPath = `path:/api/card/${TEST_CARD.id}/query`;
+
+ let defaultNavigate: (() => Promise<void>) | undefined;
+
+ const onDrillThrough = jest.fn(async (_, _defaultNavigate) => {
+ defaultNavigate = _defaultNavigate;
+ });
+
+ await setup({ onDrillThrough });
+
+ await userEvent.click(screen.getByText("Trigger Drill"));
+
+ // Should be called with drill names and next card
+ expect(onDrillThrough).toHaveBeenCalledWith(
+ { drillName: "drill-thru/pk", nextCard: NEXT_CARD },
+ expect.any(Function),
+ );
+
+ // One card query: defaultNavigate hasn't been called yet
+ expect(fetchMock.callHistory.calls(queryPath)).toHaveLength(1);
+
+ await act(async () => {
+ await defaultNavigate?.();
+ });
+
+ // Two card query: defaultNavigate is called
+ await waitFor(() => {
+ expect(fetchMock.callHistory.calls(queryPath)).toHaveLength(2);
+ });
+ });
+});
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
index c073f61d4c7..36da1d28a0d 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
@@ -145,6 +145,7 @@ export const _SdkQuestion = ({
backToDashboard,
getClickActionMode,
navigateToNewCard,
+ onDrillThrough,
height,
width,
@@ -152,6 +153,7 @@ export const _SdkQuestion = ({
style,
title,
withChartTypeSelector = true,
+ withEditorButton = true,
onVisualizationChange,
}: SdkQuestionProps): JSX.Element | null => {
const drillThroughQuestionProps: DrillThroughQuestionProps = {
@@ -161,6 +163,7 @@ export const _SdkQuestion = ({
style,
title,
withChartTypeSelector,
+ withEditorButton,
isSaveEnabled,
targetCollection,
entityTypes,
@@ -203,6 +206,7 @@ export const _SdkQuestion = ({
backToDashboard={backToDashboard}
getClickActionMode={getClickActionMode}
navigateToNewCard={navigateToNewCard}
+ onDrillThrough={onDrillThrough}
onVisualizationChange={onVisualizationChange}
>
{children ?? (
@@ -213,6 +217,7 @@ export const _SdkQuestion = ({
style={style}
title={title}
withChartTypeSelector={withChartTypeSelector}
+ withEditorButton={withEditorButton}
/>
)}
</SdkQuestionProvider>
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props.ts
index dfc6ef3c4d9..c075113efac 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-normalize-component-provider-props.ts
@@ -3,6 +3,7 @@ import _ from "underscore";
import type { ComponentProviderInternalProps } from "embedding-sdk-bundle/components/public/ComponentProvider";
import { useSdkSelector } from "embedding-sdk-bundle/store";
import { getHasTokenFeature } from "embedding-sdk-bundle/store/selectors";
+import { isEmbeddingMcpApp } from "metabase/embedding-sdk/config";
export const useNormalizeComponentProviderProps = (
props: ComponentProviderInternalProps,
@@ -10,7 +11,8 @@ export const useNormalizeComponentProviderProps = (
const hasTokenFeature = useSdkSelector(getHasTokenFeature);
const normalizedProps = { ...props };
- if (!hasTokenFeature) {
+ // MCP Apps in OSS must apply the theme variables from MCP hosts.
+ if (!hasTokenFeature && !isEmbeddingMcpApp()) {
// We prevent defining a locale
delete normalizedProps.locale;
diff --git a/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts b/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts
index 7e6b12412d1..fe549ae0c4c 100644
--- a/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts
@@ -5,7 +5,10 @@ import type {
SdkUsageProblem,
SdkUsageProblemKey,
} from "embedding-sdk-bundle/types/usage-problem";
-import { isEmbeddingEajs } from "metabase/embedding-sdk/config";
+import {
+ EMBEDDING_SDK_CONFIG,
+ isEmbeddingEajs,
+} from "metabase/embedding-sdk/config";
import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types/refresh-token";
import { getIsLocalhost } from "./get-is-localhost";
@@ -17,6 +20,7 @@ interface SdkProblemOptions {
hasTokenFeature: boolean;
isDevelopmentMode?: boolean;
session: MetabaseEmbeddingSessionToken | null;
+
/**
* Indicates whether the current environment is localhost.
* If not provided, it will be determined automatically based on window.location.
@@ -75,7 +79,9 @@ export function getSdkUsageProblem(
session,
isLocalHost,
} = options;
+
const { apiKey } = authConfig;
+ const { isMcpApp } = EMBEDDING_SDK_CONFIG;
const isSSO = !apiKey;
const isApiKey = !!apiKey;
@@ -109,7 +115,10 @@ export function getSdkUsageProblem(
isLocalhost,
isEnabled,
session,
+ isMcpApp,
})
+ // MCP Apps uses temporary sessions created by MCP backend.
+ .with({ isMcpApp: true }, () => null)
.with({ isSSO: true, hasTokenFeature: false, isLocalhost: true }, () =>
toError("SSO_WITHOUT_LICENSE"),
)
diff --git a/frontend/src/embedding-sdk-bundle/types/question.ts b/frontend/src/embedding-sdk-bundle/types/question.ts
index 5f4b9e52213..13fda79fe48 100644
--- a/frontend/src/embedding-sdk-bundle/types/question.ts
+++ b/frontend/src/embedding-sdk-bundle/types/question.ts
@@ -118,6 +118,7 @@ export interface NavigateToNewCardParams {
previousCard: Card;
objectId: ObjectId;
cancelDeferred?: Deferred;
+ drillName?: string;
}
export interface QuestionStateParams {
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index 7d44d668226..4a2d3a9c200 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -274,6 +274,45 @@ export type MetabotSourceFeedback = {
positive: boolean;
};
+/**
+ * Feedback payload for MCP Apps visualization results.
+ *
+ * Sends the prompt and query context needed for Harbormaster
+ * to understand the generated visualization.
+ */
+export type McpAppsFeedback = {
+ /** User's rating and optional comments about the generated visualization. */
+ feedback: {
+ positive: boolean;
+
+ /** Client-generated id for feedback submission. */
+ message_id: string;
+
+ /** Optional category for negative feedback. */
+ issue_type?: string;
+
+ /** Optional free-form user feedback text. */
+ freeform_feedback?: string;
+ };
+
+ /** MCP-specific context that Harbormaster needs to evaluate the result. */
+ conversation_data: {
+ /** Identifies this submission as coming from the MCP Apps flow. */
+ source: "mcp";
+
+ /** User prompt that produced the visualization, when available. */
+ prompt: string | null;
+
+ /** Query text or structured query snapshot for the result, when available. */
+ query: string | null;
+ };
+};
+
+export type SubmitMcpAppsFeedbackRequest = {
+ mcpSessionId: string;
+ payload: McpAppsFeedback;
+};
+
/* Metabot v3 - Entity Types */
export type MetabotId = number;
diff --git a/frontend/src/metabase/app-embed-mcp.tsx b/frontend/src/metabase/app-embed-mcp.tsx
new file mode 100644
index 00000000000..c5f725722c7
--- /dev/null
+++ b/frontend/src/metabase/app-embed-mcp.tsx
@@ -0,0 +1,45 @@
+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 api from "metabase/api/legacy-client";
+import { McpUiAppRoute } from "metabase/embedding/mcp/McpUiAppRoute";
+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
+
+// Load EE plugins (whitelabeling, etc.) - no-op in OSS
+import "sdk-iframe-embedding-ee-plugins";
+
+EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;
+EMBEDDING_SDK_CONFIG.isMcpApp = true;
+EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader = "mcp-apps";
+EMBEDDING_SDK_CONFIG.tokenFeatureKey = "embedding_simple";
+
+// Set session token immediately so all SDK API calls include X-Metabase-Session.
+// @ts-expect-error -- this is ONLY set in the MCP Apps route
+const { instanceUrl = "", sessionToken = "" } = window.metabaseConfig ?? {};
+
+if (instanceUrl) {
+ api.basename = instanceUrl;
+}
+
+if (sessionToken) {
+ api.sessionToken = sessionToken;
+}
+
+function init() {
+ const rootElement = document.getElementById("root");
+
+ if (!rootElement) {
+ console.error("no #root element found on mcp embed route");
+ return;
+ }
+
+ createRoot(rootElement).render(<McpUiAppRoute />);
+}
+
+if (document.readyState !== "loading") {
+ init();
+} else {
+ document.addEventListener("DOMContentLoaded", init);
+}
diff --git a/frontend/src/metabase/embedding-sdk/config.ts b/frontend/src/metabase/embedding-sdk/config.ts
index cef9f4b51fb..a49ad5c912a 100644
--- a/frontend/src/metabase/embedding-sdk/config.ts
+++ b/frontend/src/metabase/embedding-sdk/config.ts
@@ -4,7 +4,11 @@ export const EMBEDDING_SDK_PORTAL_ROOT_ELEMENT_ID = "metabase-sdk-portal-root";
type InternalSdkConfig = {
isEmbeddingSdk: boolean;
- metabaseClientRequestHeader: "embedding-sdk-react" | "embedding-simple";
+ isMcpApp: boolean;
+ metabaseClientRequestHeader:
+ | "embedding-sdk-react"
+ | "embedding-simple"
+ | "mcp-apps";
enableEmbeddingSettingKey: "enable-embedding-sdk" | "enable-embedding-simple";
tokenFeatureKey: "embedding_sdk" | "embedding_simple";
};
@@ -16,6 +20,11 @@ export const EMBEDDING_SDK_CONFIG: InternalSdkConfig = {
**/
isEmbeddingSdk: false,
+ /**
+ * Whether we are in the MCP Apps context.
+ **/
+ isMcpApp: false,
+
/**
* Which X-Metabase-Client header to use for requests to the Metabase instance?
*/
@@ -46,6 +55,11 @@ export const EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG = {
**/
export const isEmbeddingSdk = () => EMBEDDING_SDK_CONFIG.isEmbeddingSdk;
+/**
+ * Whether we are in the MCP Apps context.
+ */
+export const isEmbeddingMcpApp = () => EMBEDDING_SDK_CONFIG.isMcpApp;
+
/**
* Whether we are in the Embedded Analytics JS
*/
diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.tsx
new file mode 100644
index 00000000000..ca9695dad9e
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.tsx
@@ -0,0 +1,163 @@
+import { forwardRef, useEffect, useRef, useState } from "react";
+import { t } from "ttag";
+
+import { useToast } from "metabase/common/hooks";
+import type { IconName } from "metabase/ui";
+import { ActionIcon, Icon, Tooltip } from "metabase/ui";
+
+import {
+ McpFeedbackModal,
+ type McpFeedbackModalValues,
+} from "./McpFeedbackModal";
+import { submitMcpFeedback } from "./api";
+
+interface FeedbackButtonProps {
+ "data-testid": string;
+ disabled: boolean;
+ icon: IconName;
+ onClick: () => void;
+ hasBeenClicked: boolean;
+}
+
+interface McpFeedbackButtonsProps {
+ instanceUrl: string;
+ sessionToken: string;
+ mcpSessionId: string;
+ prompt: string | null;
+ query: string | null;
+}
+
+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,
+}: 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`}>
+ <FeedbackButton
+ data-testid="mcp-feedback-thumbs-up"
+ icon="thumbs_up"
+ hasBeenClicked={submittedFeedback === "positive"}
+ disabled={isSubmitting}
+ onClick={() => setSelectedFeedback("positive")}
+ />
+ </Tooltip>
+
+ <Tooltip label={t`Give negative feedback`}>
+ <FeedbackButton
+ data-testid="mcp-feedback-thumbs-down"
+ icon="thumbs_down"
+ hasBeenClicked={submittedFeedback === "negative"}
+ disabled={isSubmitting}
+ onClick={() => setSelectedFeedback("negative")}
+ />
+ </Tooltip>
+
+ {selectedFeedback != null && (
+ <McpFeedbackModal
+ isSubmitting={isSubmitting}
+ positive={selectedFeedback === "positive"}
+ onClose={() => setSelectedFeedback(null)}
+ onSubmit={(values) =>
+ handleFeedback({
+ positive: selectedFeedback === "positive",
+ ...values,
+ })
+ }
+ />
+ )}
+ </>
+ );
+}
+
+const FeedbackButton = forwardRef<HTMLButtonElement, FeedbackButtonProps>(
+ function FeedbackButton(
+ { "data-testid": dataTestId, disabled, icon, onClick, hasBeenClicked },
+ ref,
+ ) {
+ return (
+ <ActionIcon
+ data-testid={dataTestId}
+ onClick={onClick}
+ disabled={disabled}
+ h="sm"
+ ref={ref}
+ >
+ <Icon
+ name={icon}
+ size="1rem"
+ c={hasBeenClicked ? "brand" : "currentColor"}
+ />
+ </ActionIcon>
+ );
+ },
+);
diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.unit.spec.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.unit.spec.tsx
new file mode 100644
index 00000000000..5274f168509
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpFeedbackButtons.unit.spec.tsx
@@ -0,0 +1,176 @@
+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 { 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 () => {
+ const user = userEvent.setup();
+ const instanceUrl = "http://localhost:3000";
+
+ fetchMock.post("path:/api/embed-mcp/feedback", 204);
+
+ 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.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",
+ },
+ });
+ });
+
+ 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(
+ <McpFeedbackButtons
+ instanceUrl={instanceUrl}
+ sessionToken="metabase-session-token"
+ mcpSessionId="mcp-session-id"
+ prompt="show me products"
+ query="new-encoded-query"
+ />,
+ );
+
+ 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(),
+ );
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/McpFeedbackModal.tsx b/frontend/src/metabase/embedding/mcp/McpFeedbackModal.tsx
new file mode 100644
index 00000000000..60f4cb3752c
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpFeedbackModal.tsx
@@ -0,0 +1,104 @@
+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/McpQueryBar.tsx b/frontend/src/metabase/embedding/mcp/McpQueryBar.tsx
new file mode 100644
index 00000000000..53f15f88728
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpQueryBar.tsx
@@ -0,0 +1,97 @@
+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;
+}
+
+export function McpQueryBar({ app, instanceUrl }: McpQueryBarProps) {
+ const { question, updateQuestion, queryResults } = useSdkQuestionContext();
+
+ const {
+ sensibleChartTypes,
+ hasOnlyTable,
+ selectedChartType,
+ handleDisplayChange,
+ } = useChartTypes(question, queryResults, updateQuestion);
+
+ const {
+ temporalColumn,
+ rawTemporalColumn,
+ currentUnit,
+ availableItems,
+ bucketLabel,
+ handleBucketChange,
+ } = useTemporalGranularity(question, updateQuestion);
+
+ const {
+ dateFilterClause,
+ dateFilterValue,
+ dateFilterLabel,
+ datePickerUnits,
+ handleDateFilterChange,
+ handleDateFilterClear,
+ } = useDateFilter(question, updateQuestion, rawTemporalColumn);
+
+ if (!question || !queryResults || hasOnlyTable) {
+ return null;
+ }
+
+ const timeRange =
+ rawTemporalColumn !== null
+ ? {
+ label: dateFilterLabel,
+ value: dateFilterValue,
+ availableUnits: datePickerUnits,
+ hasActiveFilter: !!dateFilterClause,
+ onChange: handleDateFilterChange,
+ onClear: handleDateFilterClear,
+ }
+ : undefined;
+
+ const timeGranularity =
+ temporalColumn !== null && availableItems.length > 0
+ ? {
+ label: bucketLabel,
+ currentUnit,
+ availableItems,
+ onChange: handleBucketChange,
+ }
+ : undefined;
+
+ const hasControls =
+ sensibleChartTypes.length > 0 || timeRange || timeGranularity || app;
+
+ if (!hasControls) {
+ return null;
+ }
+
+ async function handleExploreClicked() {
+ if (!instanceUrl || !question || !app) {
+ return;
+ }
+
+ const url = instanceUrl + Urls.serializedQuestion(question.card());
+
+ await app.openLink({ url });
+ }
+
+ return (
+ <QueryExplorerBar
+ chartTypes={sensibleChartTypes}
+ currentChartType={selectedChartType ?? ""}
+ onChartTypeChange={handleDisplayChange}
+ timeRange={timeRange}
+ timeGranularity={timeGranularity}
+ onExplore={handleExploreClicked}
+ />
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/McpQueryBar.unit.spec.tsx b/frontend/src/metabase/embedding/mcp/McpQueryBar.unit.spec.tsx
new file mode 100644
index 00000000000..0f83fedb0ab
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpQueryBar.unit.spec.tsx
@@ -0,0 +1,119 @@
+import {
+ setupAlertsEndpoints,
+ setupCardEndpoints,
+ setupCardQueryEndpoints,
+ setupCardQueryMetadataEndpoint,
+ setupDatabaseEndpoints,
+} from "__support__/server-mocks";
+import { screen } 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 {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockDataset,
+ createMockDatasetData,
+ createMockNumericColumn,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import {
+ ORDERS,
+ ORDERS_ID,
+ SAMPLE_DB_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
+
+import { McpQueryBar } from "./McpQueryBar";
+
+const TEST_USER = createMockUser();
+const TEST_DATABASE = createSampleDatabase();
+const TEST_CARD = createMockCard({
+ display: "line",
+ dataset_query: {
+ type: "query",
+ database: SAMPLE_DB_ID,
+ query: {
+ "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({
+ data: createMockDatasetData({
+ cols: [
+ createMockNumericColumn({
+ name: "count",
+ display_name: "Count",
+ source: "aggregation",
+ }),
+ ],
+ rows: [[26000]],
+ }),
+});
+
+function setup() {
+ const { state } = setupSdkState({ currentUser: TEST_USER });
+ const app = { openLink: jest.fn() };
+
+ setupCardEndpoints(TEST_CARD);
+ setupCardQueryMetadataEndpoint(
+ TEST_CARD,
+ createMockCardQueryMetadata({ databases: [TEST_DATABASE] }),
+ );
+ setupDatabaseEndpoints(TEST_DATABASE);
+
+ setupAlertsEndpoints(TEST_CARD, []);
+ setupCardQueryEndpoints(TEST_CARD, ONE_POINT_RESULT);
+
+ renderWithSDKProviders(
+ <SdkQuestion
+ questionId={TEST_CARD.id}
+ isSaveEnabled={false}
+ withEditorButton={false}
+ withChartTypeSelector={false}
+ >
+ <McpQueryBar app={app as any} instanceUrl="https://metabase.example" />
+ </SdkQuestion>,
+ {
+ componentProviderProps: {
+ authConfig: createMockSdkConfig(),
+ },
+ storeInitialState: state,
+ },
+ );
+
+ return { app };
+}
+
+describe("McpQueryBar", () => {
+ it("renders remaining query controls when a one-point result has no MCP chart types", async () => {
+ setup();
+
+ 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();
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/McpQuestionTitle.tsx b/frontend/src/metabase/embedding/mcp/McpQuestionTitle.tsx
new file mode 100644
index 00000000000..1901eb12b3c
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpQuestionTitle.tsx
@@ -0,0 +1,52 @@
+import { useMemo } from "react";
+
+import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";
+import {
+ describeQueryStage,
+ getInfoStageIndex,
+} from "metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/utils";
+import { Text } from "metabase/ui";
+import * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
+
+/**
+ * Renders a minimal question title without temporal bucket suffixes.
+ * e.g. "Sum of Total by Created At" instead of "Sum of Total by Created At: Month".
+ *
+ * Mirrors the stage-selection logic from AdHocQuestionDescription: uses stage -2
+ * when the last stage is an empty filter stage (common in drill-through queries),
+ * otherwise stage -1.
+ *
+ * Returns null when no meaningful title can be derived.
+ */
+export function getMcpQuestionTitle(question: Question | undefined) {
+ if (!question) {
+ return null;
+ }
+
+ const query = question.query();
+ const stageIndex = getInfoStageIndex(query);
+
+ return (
+ describeQueryStage(query, stageIndex, { stripTemporalBucket: true }) ??
+ Lib.suggestedName(query)
+ );
+}
+
+export function McpQuestionTitle() {
+ const { question } = useSdkQuestionContext();
+
+ const title = useMemo(() => {
+ return getMcpQuestionTitle(question);
+ }, [question]);
+
+ if (!title) {
+ return null;
+ }
+
+ return (
+ <Text fw={700} fz="h3" px="md" py="sm" truncate>
+ {title}
+ </Text>
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/McpQuestionTitle.unit.spec.ts b/frontend/src/metabase/embedding/mcp/McpQuestionTitle.unit.spec.ts
new file mode 100644
index 00000000000..85fa0aeae0e
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpQuestionTitle.unit.spec.ts
@@ -0,0 +1,33 @@
+import * as Lib from "metabase-lib";
+import { SAMPLE_METADATA, SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
+import Question from "metabase-lib/v1/Question";
+import { ORDERS_ID } from "metabase-types/api/mocks/presets";
+
+import { getMcpQuestionTitle } from "./McpQuestionTitle";
+
+const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [
+ {
+ type: "column",
+ name: "CREATED_AT",
+ sourceName: "ORDERS",
+ unit: "month",
+ },
+ ],
+ },
+ ],
+});
+
+const question = Question.create({
+ metadata: SAMPLE_METADATA,
+}).setQuery(query);
+
+describe("getMcpQuestionTitle", () => {
+ it("uses a generated question description without temporal buckets", () => {
+ expect(getMcpQuestionTitle(question)).toBe("Count by Created At");
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx
new file mode 100644
index 00000000000..b80ee5c2ab5
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.tsx
@@ -0,0 +1,168 @@
+import { type CSSProperties, useEffect, useMemo } from "react";
+
+import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError";
+import { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";
+import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";
+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 { getMcpDeserializedCard } from "./McpUiAppRoute.utils";
+import { useHandleMcpDrillThrough } from "./hooks/useHandleMcpDrillThrough";
+import { useMcpApp } from "./hooks/useMcpApp";
+import { useMcpUserAndSettingsFetch } from "./hooks/useMcpUserAndSettingsFetch";
+import { buildMcpAppsTheme } from "./utils/buildMcpAppsTheme";
+
+const store = getSdkStore();
+
+const DEFAULT_INSETS = { top: 0, right: 0, bottom: 0, left: 0 };
+
+// CSS for .mcp-loading and .mcp-spinner is defined globally in embed-mcp.html.
+const SimpleLoader = () => (
+ <div className="mcp-loading">
+ <span className="mcp-spinner" />
+ </div>
+);
+
+export function McpUiAppRoute() {
+ const { query, prompt, hostContext, app } = useMcpApp();
+
+ const handleDrillThrough = useHandleMcpDrillThrough(app);
+
+ const {
+ instanceUrl = "",
+ sessionToken = "",
+ mcpSessionId = "",
+ } = (window.metabaseConfig as {
+ instanceUrl: string;
+ sessionToken: string;
+ mcpSessionId: string;
+ }) ?? {};
+
+ const scheme: ResolvedColorScheme =
+ hostContext?.theme === "dark" ? "dark" : "light";
+
+ const hostCssVariables: Record<string, string> = useMemo(
+ () => hostContext?.styles?.variables ?? {},
+ [hostContext?.styles?.variables],
+ );
+
+ const safeAreaInsets = hostContext?.safeAreaInsets ?? DEFAULT_INSETS;
+
+ const deserializedCard = useMemo(() => {
+ if (!query) {
+ return null;
+ }
+
+ return getMcpDeserializedCard(query);
+ }, [query]);
+
+ const theme = useMemo(
+ () => buildMcpAppsTheme(hostCssVariables, scheme),
+ [hostCssVariables, scheme],
+ );
+
+ const { isSettingsReady, userAndSettingsFetchError } =
+ useMcpUserAndSettingsFetch({
+ instanceUrl,
+ sessionToken,
+ store,
+ });
+
+ const isReady = !!(
+ instanceUrl &&
+ hostContext &&
+ isSettingsReady &&
+ 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) {
+ document.getElementById("mcp-loading")?.remove();
+ }
+ }, [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 containerStyle: CSSProperties = {
+ height,
+ margin: safeAreaMargins,
+ background: theme.colors?.background,
+ };
+
+ const renderContent = () => {
+ if (userAndSettingsFetchError) {
+ return <SdkError message={userAndSettingsFetchError} />;
+ }
+
+ if (!isReady) {
+ return null;
+ }
+
+ return (
+ <SdkQuestion
+ deserializedCard={deserializedCard}
+ isSaveEnabled={false}
+ // we should never show query builder in chat interfaces
+ withEditorButton={false}
+ 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>
+ </SdkQuestion>
+ );
+ };
+
+ return (
+ <ComponentProvider
+ authConfig={{ metabaseInstanceUrl: instanceUrl }}
+ theme={theme}
+ reduxStore={store}
+ loaderComponent={SimpleLoader}
+ >
+ <div style={containerStyle}>{renderContent()}</div>
+ </ComponentProvider>
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.utils.ts b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.utils.ts
new file mode 100644
index 00000000000..a7c2d4e18dc
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.utils.ts
@@ -0,0 +1,19 @@
+import { b64_to_utf8 } from "metabase/utils/encoding";
+import type { Card, VisualizationSettings } from "metabase-types/api";
+
+export const MCP_APP_VISUALIZATION_SETTINGS: VisualizationSettings = {
+ "graph.x_axis.labels_enabled": false,
+ "graph.y_axis.labels_enabled": false,
+};
+
+export function getMcpDeserializedCard(query: string): Card | null {
+ try {
+ return {
+ display: "table",
+ dataset_query: JSON.parse(b64_to_utf8(query)),
+ visualization_settings: MCP_APP_VISUALIZATION_SETTINGS,
+ } as Card;
+ } catch {
+ return null;
+ }
+}
diff --git a/frontend/src/metabase/embedding/mcp/McpUiAppRoute.utils.unit.spec.ts b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.utils.unit.spec.ts
new file mode 100644
index 00000000000..84fc94dc3b3
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/McpUiAppRoute.utils.unit.spec.ts
@@ -0,0 +1,25 @@
+import { utf8_to_b64 } from "metabase/utils/encoding";
+
+import { getMcpDeserializedCard } from "./McpUiAppRoute.utils";
+
+describe("getMcpDeserializedCard", () => {
+ it("hides axis labels for MCP App ad-hoc charts", () => {
+ const datasetQuery = { database: 1, type: "query", query: {} };
+ const query = utf8_to_b64(JSON.stringify(datasetQuery));
+
+ expect(getMcpDeserializedCard(query)).toEqual(
+ expect.objectContaining({
+ display: "table",
+ dataset_query: datasetQuery,
+ visualization_settings: {
+ "graph.x_axis.labels_enabled": false,
+ "graph.y_axis.labels_enabled": false,
+ },
+ }),
+ );
+ });
+
+ it("returns null for invalid query params", () => {
+ expect(getMcpDeserializedCard("not-json")).toBeNull();
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.module.css b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.module.css
new file mode 100644
index 00000000000..a1ac75000c6
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.module.css
@@ -0,0 +1,3 @@
+.selected {
+ box-shadow: 0 1px 2px var(--mb-color-shadow);
+}
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.tsx
new file mode 100644
index 00000000000..24a01095eca
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/ChartTypePicker.tsx
@@ -0,0 +1,47 @@
+import type { IconName } from "metabase/ui";
+import { ActionIcon, Flex, Icon } from "metabase/ui";
+
+import S from "./ChartTypePicker.module.css";
+
+type ChartTypeOption = {
+ type: string;
+ icon: IconName;
+};
+
+type ChartTypePickerProps = {
+ chartTypes: ChartTypeOption[];
+ value: string;
+ onChange: (type: string) => void;
+};
+
+export function ChartTypePicker({
+ chartTypes,
+ value,
+ onChange,
+}: ChartTypePickerProps) {
+ return (
+ <Flex
+ h={32}
+ align="center"
+ gap="xs"
+ bg="background-secondary"
+ px="xs"
+ bdrs="md"
+ >
+ {chartTypes.map(({ type, icon }) => (
+ <ActionIcon
+ w="2rem"
+ key={type}
+ size={24}
+ variant={value === type ? "filled" : "subtle"}
+ bg={value === type ? "background-primary" : undefined}
+ onClick={() => onChange(type)}
+ aria-label={type}
+ className={value === type ? S.selected : undefined}
+ >
+ <Icon name={icon} c={value === type ? "brand" : "text-primary"} />
+ </ActionIcon>
+ ))}
+ </Flex>
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.stories.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.stories.tsx
new file mode 100644
index 00000000000..0d0d266ba2e
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.stories.tsx
@@ -0,0 +1,91 @@
+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.tsx
new file mode 100644
index 00000000000..29e1b62f039
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.tsx
@@ -0,0 +1,83 @@
+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.tsx
new file mode 100644
index 00000000000..3111b7ef4b5
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/QueryExplorerBar.unit.spec.tsx
@@ -0,0 +1,200 @@
+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/TimeControlPopover.module.css b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.module.css
new file mode 100644
index 00000000000..de07e893573
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.module.css
@@ -0,0 +1,3 @@
+.popoverTargetButton:hover {
+ background-color: var(--mb-color-background-hover);
+}
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.tsx
new file mode 100644
index 00000000000..0f7764e950c
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeControlPopover.tsx
@@ -0,0 +1,37 @@
+import { useState } from "react";
+
+import { Button, Popover } from "metabase/ui";
+
+import S from "./TimeControlPopover.module.css";
+
+export function TimeControlPopover({
+ label,
+ children,
+}: {
+ label: string;
+ children: (closePopover: () => void) => React.ReactNode;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <Popover opened={isOpen} onChange={setIsOpen}>
+ <Popover.Target>
+ <Button
+ size="xs"
+ h={32}
+ fw="normal"
+ px="md"
+ variant="subtle"
+ color="text-primary"
+ lh="1"
+ classNames={{ root: S.popoverTargetButton }}
+ onClick={() => setIsOpen(!isOpen)}
+ >
+ {label}
+ </Button>
+ </Popover.Target>
+
+ <Popover.Dropdown>{children(() => setIsOpen(false))}</Popover.Dropdown>
+ </Popover>
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeGranularityControl.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeGranularityControl.tsx
new file mode 100644
index 00000000000..e6ab198a72c
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeGranularityControl.tsx
@@ -0,0 +1,45 @@
+import { t } from "ttag";
+
+import { Box, DefaultSelectItem } from "metabase/ui";
+
+import { TimeControlPopover } from "./TimeControlPopover";
+import type { TimeGranularityConfig } from "./types";
+
+export function TimeGranularityControl({
+ timeGranularity,
+}: {
+ timeGranularity: TimeGranularityConfig;
+}) {
+ return (
+ <TimeControlPopover label={timeGranularity.label}>
+ {(closePopover) => (
+ <Box p="sm" miw={180}>
+ <DefaultSelectItem
+ value="none"
+ label={t`All time`}
+ selected={!timeGranularity.currentUnit}
+ onClick={() => {
+ timeGranularity.onChange(null);
+ closePopover();
+ }}
+ role="option"
+ />
+
+ {timeGranularity.availableItems.map(({ bucket, unit, label }) => (
+ <DefaultSelectItem
+ key={unit}
+ value={unit}
+ label={label}
+ selected={timeGranularity.currentUnit === unit}
+ onClick={() => {
+ timeGranularity.onChange(bucket);
+ closePopover();
+ }}
+ role="option"
+ />
+ ))}
+ </Box>
+ )}
+ </TimeControlPopover>
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeRangeControl.tsx b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeRangeControl.tsx
new file mode 100644
index 00000000000..83989d8d715
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/TimeRangeControl.tsx
@@ -0,0 +1,52 @@
+import { t } from "ttag";
+
+import { DatePicker } from "metabase/querying/common/components/DatePicker";
+import { Button, Flex } from "metabase/ui";
+
+import { TimeControlPopover } from "./TimeControlPopover";
+import type { TimeRangeConfig } from "./types";
+
+export function TimeRangeControl({
+ timeRange,
+}: {
+ timeRange: TimeRangeConfig;
+}) {
+ return (
+ <TimeControlPopover label={timeRange.label}>
+ {(closePopover) => (
+ <DatePicker
+ value={timeRange.value}
+ availableUnits={timeRange.availableUnits}
+ onChange={(value) => {
+ timeRange.onChange(value);
+ closePopover();
+ }}
+ renderSubmitButton={({ value }) => (
+ <Flex justify="space-between" w="100%">
+ {timeRange.hasActiveFilter ? (
+ <Button
+ variant="subtle"
+ c="text-secondary"
+ onClick={() => {
+ timeRange.onClear();
+ closePopover();
+ }}
+ >
+ {t`All time`}
+ </Button>
+ ) : (
+ <div />
+ )}
+
+ <Button
+ type="submit"
+ variant="filled"
+ disabled={!value}
+ >{t`Apply`}</Button>
+ </Flex>
+ )}
+ />
+ )}
+ </TimeControlPopover>
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/QueryExplorerBar/index.ts b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/index.ts
new file mode 100644
index 00000000000..00467a0454b
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/index.ts
@@ -0,0 +1,8 @@
+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.ts
new file mode 100644
index 00000000000..40be91c7aaa
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/QueryExplorerBar/types.ts
@@ -0,0 +1,43 @@
+import type {
+ DatePickerUnit,
+ DatePickerValue,
+} from "metabase/querying/common/types";
+import type { IconName } from "metabase/ui";
+import type * as Lib from "metabase-lib";
+import type { 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/api.ts b/frontend/src/metabase/embedding/mcp/api.ts
new file mode 100644
index 00000000000..99dd4546774
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/api.ts
@@ -0,0 +1,76 @@
+/* eslint-disable metabase/no-literal-metabase-strings */
+
+import type { SubmitMcpAppsFeedbackRequest } from "metabase-types/api";
+
+type StoreDrillQueryRequest = {
+ instanceUrl: string;
+ sessionToken: string;
+ mcpSessionId: string;
+ encodedQuery: string;
+};
+
+type StoreDrillQueryResponse = {
+ handle: string;
+};
+
+type SubmitMcpFeedbackPayload = SubmitMcpAppsFeedbackRequest & {
+ instanceUrl: string;
+ sessionToken: string;
+};
+
+/**
+ * Stores the drill-through's query on the server and returns a handle UUID
+ * that the iframe threads into the agent message so `render_drill_through`
+ * can fetch the payload without the LLM ever seeing it.
+ *
+ * We cannot use RTK Query here as we are not in Metabase's React tree.
+ */
+export async function storeDrillQuery({
+ instanceUrl,
+ sessionToken,
+ mcpSessionId,
+ encodedQuery,
+}: StoreDrillQueryRequest): Promise<StoreDrillQueryResponse> {
+ const response = await fetch(`${instanceUrl}/api/embed-mcp/drills`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-Metabase-Client": "mcp-apps",
+ "X-Metabase-Session": sessionToken,
+ "Mcp-Session-Id": mcpSessionId,
+ },
+ body: JSON.stringify({ encodedQuery }),
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `storeDrillQuery failed: ${response.status} ${response.statusText}`,
+ );
+ }
+
+ return response.json();
+}
+
+export async function submitMcpFeedback({
+ instanceUrl,
+ sessionToken,
+ mcpSessionId,
+ payload,
+}: SubmitMcpFeedbackPayload): Promise<void> {
+ const response = await fetch(`${instanceUrl}/api/embed-mcp/feedback`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-Metabase-Client": "mcp-apps",
+ "X-Metabase-Session": sessionToken,
+ "Mcp-Session-Id": mcpSessionId,
+ },
+ body: JSON.stringify(payload),
+ });
+
+ if (!response.ok) {
+ throw new Error(
+ `submitMcpFeedback failed: ${response.status} ${response.statusText}`,
+ );
+ }
+}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/constants.ts b/frontend/src/metabase/embedding/mcp/hooks/constants.ts
new file mode 100644
index 00000000000..66b312e9bd9
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/constants.ts
@@ -0,0 +1 @@
+export const LAST_QUERY_STAGE_INDEX = -1;
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useChartTypes.ts b/frontend/src/metabase/embedding/mcp/hooks/useChartTypes.ts
new file mode 100644
index 00000000000..0553803de45
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useChartTypes.ts
@@ -0,0 +1,92 @@
+import { useMemo } from "react";
+
+import { getSensibleVisualizations } from "metabase/visualizations/lib/sensibility";
+import type Question from "metabase-lib/v1/Question";
+import type { 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;
+
+interface UseChartTypesResult {
+ sensibleChartTypes: ChartTypeEntry[];
+ hasOnlyTable: boolean;
+ selectedChartType: McpChartType | null;
+ handleDisplayChange: (type: string) => void;
+}
+
+export function useChartTypes(
+ question: Question | undefined,
+ queryResults: Dataset[] | null | undefined,
+ updateQuestion: UpdateQuestion,
+): UseChartTypesResult {
+ const queryResult = queryResults?.[0] ?? null;
+
+ const { sensibleVisualizations } = useMemo(
+ () => getSensibleVisualizations({ result: queryResult }),
+ [queryResult],
+ );
+
+ 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 hasOnlyTable =
+ sensibleChartTypes.length === 1 && sensibleChartTypes[0].type === "table";
+
+ const rawDisplay = question?.display() ?? "";
+
+ const selectedChartType: McpChartType | null = isMcpChartType(rawDisplay)
+ ? rawDisplay
+ : null;
+
+ const handleDisplayChange = (type: string) => {
+ if (!question) {
+ return;
+ }
+
+ const nextQuestion = question
+ .setDisplay(type as McpChartType)
+ .lockDisplay();
+
+ updateQuestion(nextQuestion, { run: false });
+ };
+
+ return {
+ sensibleChartTypes,
+ hasOnlyTable,
+ selectedChartType,
+ handleDisplayChange,
+ };
+}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useDateFilter.ts b/frontend/src/metabase/embedding/mcp/hooks/useDateFilter.ts
new file mode 100644
index 00000000000..889369cb588
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useDateFilter.ts
@@ -0,0 +1,103 @@
+import { t } from "ttag";
+
+import type { DatePickerValue } from "metabase/querying/common/types";
+import { getDateFilterDisplayName } from "metabase/querying/common/utils/dates";
+import {
+ getDateFilterClause,
+ getDatePickerUnits,
+ getDatePickerValue,
+} from "metabase/querying/filters/utils/dates";
+import * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
+
+import { LAST_QUERY_STAGE_INDEX } from "./constants";
+
+type UpdateQuestion = (question: Question, opts: { run: boolean }) => void;
+
+export interface UseDateFilterResult {
+ dateFilterClause: Lib.FilterClause | null;
+ dateFilterValue: DatePickerValue | undefined;
+ dateFilterLabel: string;
+ datePickerUnits: ReturnType<typeof getDatePickerUnits>;
+ handleDateFilterChange: (value: DatePickerValue) => void;
+ handleDateFilterClear: () => void;
+}
+
+export function useDateFilter(
+ question: Question | undefined,
+ updateQuestion: UpdateQuestion,
+ rawTemporalColumn: Lib.ColumnMetadata | null,
+): UseDateFilterResult {
+ const empty: UseDateFilterResult = {
+ dateFilterClause: null,
+ dateFilterValue: undefined,
+ dateFilterLabel: t`All time`,
+ datePickerUnits: [],
+
+ handleDateFilterChange: () => {},
+ handleDateFilterClear: () => {},
+ };
+
+ if (!question) {
+ return empty;
+ }
+
+ const query = question.query();
+ const stageIndex = LAST_QUERY_STAGE_INDEX;
+
+ const allFilters = Lib.filters(query, stageIndex);
+
+ let dateFilterClause: Lib.FilterClause | null = null;
+ let dateFilterValue: DatePickerValue | undefined = undefined;
+
+ for (const filter of allFilters) {
+ const nextDateFilterValue = getDatePickerValue(query, stageIndex, filter);
+
+ if (nextDateFilterValue != null) {
+ dateFilterClause = filter;
+ dateFilterValue = nextDateFilterValue;
+
+ break;
+ }
+ }
+
+ const dateFilterLabel = dateFilterValue
+ ? getDateFilterDisplayName(dateFilterValue)
+ : t`All time`;
+
+ const datePickerUnits = rawTemporalColumn
+ ? getDatePickerUnits(query, stageIndex, rawTemporalColumn)
+ : [];
+
+ const handleDateFilterChange = (value: DatePickerValue) => {
+ if (!rawTemporalColumn) {
+ return;
+ }
+
+ const newFilterClause = getDateFilterClause(rawTemporalColumn, value);
+ const newQuery = dateFilterClause
+ ? Lib.replaceClause(query, stageIndex, dateFilterClause, newFilterClause)
+ : Lib.filter(query, stageIndex, newFilterClause);
+
+ updateQuestion(question.setQuery(newQuery), { run: true });
+ };
+
+ const handleDateFilterClear = () => {
+ if (!dateFilterClause) {
+ return;
+ }
+
+ const newQuery = Lib.removeClause(query, stageIndex, dateFilterClause);
+ updateQuestion(question.setQuery(newQuery), { run: true });
+ };
+
+ return {
+ dateFilterClause,
+ dateFilterValue,
+ dateFilterLabel,
+ datePickerUnits,
+
+ handleDateFilterChange,
+ handleDateFilterClear,
+ };
+}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts
new file mode 100644
index 00000000000..9078ec9b995
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.ts
@@ -0,0 +1,111 @@
+import type { App } from "@modelcontextprotocol/ext-apps/react";
+import { useCallback } from "react";
+
+import * as Urls from "metabase/urls";
+import { utf8_to_b64 } from "metabase/utils/encoding";
+import type * as Lib from "metabase-lib";
+import type { Card } from "metabase-types/api";
+
+import { storeDrillQuery } from "../api";
+
+interface McpGlobalConfig {
+ instanceUrl?: string;
+ sessionToken?: string;
+ mcpSessionId?: string;
+}
+
+type DrillThruName<T extends Lib.DrillThruType = Lib.DrillThruType> =
+ T extends `drill-thru/${infer Name}` ? Name : never;
+
+// Drills that refine the current visualization without changing what it is.
+// The chart's conceptual title stays the same — zoom, granularity, ordering.
+// Match by prefix, e.g. "sort" matches both "sort.ascending" and "sort.descending".
+const STAY_DRILL_PREFIXES = [
+ "zoom",
+ "zoom-in.binning",
+ "zoom-in.timeseries",
+ "zoom-in.geographic",
+ "sort",
+] as const satisfies readonly DrillThruName[];
+
+const isStayDrill = (drillName: string | undefined) =>
+ drillName != null &&
+ STAY_DRILL_PREFIXES.some(
+ (prefix) => drillName === prefix || drillName.startsWith(`${prefix}.`),
+ );
+
+const isClaudeHost = (app: App) => {
+ const hostVersion = app.getHostVersion();
+
+ return hostVersion?.name.toLowerCase().includes("claude");
+};
+
+type DrillThroughHandler = (
+ params: { drillName?: string; nextCard: Card },
+ defaultNavigate: () => Promise<void>,
+) => Promise<void>;
+
+export function useHandleMcpDrillThrough(app: App | null): DrillThroughHandler {
+ return useCallback(
+ async ({ drillName, nextCard }, defaultNavigate) => {
+ if (isStayDrill(drillName) || !app) {
+ await defaultNavigate();
+ return;
+ }
+
+ const { instanceUrl, sessionToken, mcpSessionId } =
+ (window.metabaseConfig as McpGlobalConfig | undefined) ?? {};
+
+ if (isClaudeHost(app)) {
+ if (!instanceUrl) {
+ await defaultNavigate();
+ return;
+ }
+
+ await app.openLink({
+ url: instanceUrl + Urls.serializedQuestion(nextCard),
+ });
+
+ return;
+ }
+
+ if (!instanceUrl || !sessionToken || !mcpSessionId) {
+ await defaultNavigate();
+ return;
+ }
+
+ const encodedQuery = utf8_to_b64(JSON.stringify(nextCard.dataset_query));
+
+ let handle: string;
+ try {
+ // Store the card server-side in the MCP session. This is universal —
+ // works in all MCP clients (Claude Desktop, Cursor, VS Code).
+ // The handle UUID is threaded into the agent message so render_drill_through
+ // can fetch the payload without the LLM ever seeing it.
+ ({ handle } = await storeDrillQuery({
+ instanceUrl,
+ sessionToken,
+ mcpSessionId,
+ encodedQuery,
+ }));
+ } catch {
+ await defaultNavigate();
+ return;
+ }
+
+ // Uses the same term as the tool description ("show the result")
+ // so the LLM always calls render_drill_through, and includes the handle
+ // it must pass through.
+ await app.sendMessage({
+ role: "user",
+ content: [
+ {
+ type: "text",
+ text: `Show me the result. Use handle ${handle}.`,
+ },
+ ],
+ });
+ },
+ [app],
+ );
+}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts
new file mode 100644
index 00000000000..b975b09b6d7
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useHandleMcpDrillThrough.unit.spec.ts
@@ -0,0 +1,92 @@
+import { renderHook } from "@testing-library/react";
+import fetchMock from "fetch-mock";
+
+import * as Urls from "metabase/urls";
+import { createMockCard } from "metabase-types/api/mocks";
+
+import { useHandleMcpDrillThrough } from "./useHandleMcpDrillThrough";
+
+const NEXT_CARD = createMockCard({
+ dataset_query: {
+ type: "query",
+ database: 1,
+ query: { "source-table": 2 },
+ },
+});
+
+describe("useHandleMcpDrillThrough", () => {
+ beforeEach(() => {
+ (window as any).metabaseConfig = {
+ instanceUrl: "https://metabase.example",
+ sessionToken: "session-token",
+ mcpSessionId: "mcp-session-id",
+ };
+
+ fetchMock.post("path:/api/embed-mcp/drills", { handle: "drill-handle" });
+ });
+
+ afterEach(() => {
+ delete (window as any).metabaseConfig;
+ });
+
+ it("opens drill-through questions in Metabase for Claude", async () => {
+ const app = {
+ getHostVersion: () => ({ name: "Claude Desktop", version: "1.0.0" }),
+ openLink: jest.fn(),
+ sendMessage: jest.fn(),
+ };
+
+ const defaultNavigate = jest.fn();
+ const { result } = renderHook(() => useHandleMcpDrillThrough(app as any));
+
+ await result.current(
+ { drillName: "fk-details", nextCard: NEXT_CARD },
+ defaultNavigate,
+ );
+
+ expect(app.openLink).toHaveBeenCalledWith({
+ url: "https://metabase.example" + Urls.serializedQuestion(NEXT_CARD),
+ });
+
+ // It should not do the drill operations: no saving queries, no inline navigation
+ expect(
+ fetchMock.callHistory.calls("path:/api/embed-mcp/drills"),
+ ).toHaveLength(0);
+
+ expect(app.sendMessage).not.toHaveBeenCalled();
+ expect(defaultNavigate).not.toHaveBeenCalled();
+ });
+
+ it("stores drill queries and sends a render handle for non-Claude hosts", async () => {
+ const app = {
+ getHostVersion: () => ({ name: "Cursor", version: "1.0.0" }),
+ openLink: jest.fn(),
+ sendMessage: jest.fn(),
+ };
+
+ const defaultNavigate = jest.fn();
+ const { result } = renderHook(() => useHandleMcpDrillThrough(app as any));
+
+ await result.current(
+ { drillName: "fk-details", nextCard: NEXT_CARD },
+ defaultNavigate,
+ );
+
+ expect(
+ fetchMock.callHistory.calls("path:/api/embed-mcp/drills"),
+ ).toHaveLength(1);
+
+ expect(app.sendMessage).toHaveBeenCalledWith({
+ role: "user",
+ content: [
+ {
+ type: "text",
+ text: "Show me the result. Use handle drill-handle.",
+ },
+ ],
+ });
+
+ expect(app.openLink).not.toHaveBeenCalled();
+ expect(defaultNavigate).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx
new file mode 100644
index 00000000000..ed55340c4a7
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpApp.tsx
@@ -0,0 +1,102 @@
+import {
+ type App,
+ type McpUiHostContext,
+ applyDocumentTheme,
+ applyHostFonts,
+ applyHostStyleVariables,
+ useApp,
+} from "@modelcontextprotocol/ext-apps/react";
+import { useEffect, useState } from "react";
+
+interface McpAppState {
+ query: string | null;
+
+ /**
+ * Original user prompt that triggered this visualization, retrieved
+ * from `construct_query`, e.g. "visualize orders with Metabase".
+ */
+ prompt: string | null;
+
+ hostContext: McpUiHostContext | null;
+ app: App | null;
+}
+
+type VisualizeQueryToolInput = {
+ query?: string;
+};
+
+type VisualizeQueryToolResult = {
+ query?: string;
+ prompt?: string;
+};
+
+function applyHostContext(ctx: McpUiHostContext) {
+ if (ctx.theme) {
+ applyDocumentTheme(ctx.theme);
+ }
+
+ if (ctx.styles?.variables) {
+ applyHostStyleVariables(ctx.styles.variables);
+ }
+
+ if (ctx.styles?.css?.fonts) {
+ applyHostFonts(ctx.styles.css.fonts);
+ }
+}
+
+export function useMcpApp(): McpAppState {
+ const [query, setQuery] = useState<string | null>(null);
+ const [prompt, setPrompt] = useState<string | null>(null);
+ const [hostContext, setHostContext] = useState<McpUiHostContext | null>(null);
+
+ const { app } = useApp({
+ appInfo: { name: "metabase-visualize-query", version: "1.0.0" },
+ capabilities: {},
+ onAppCreated: (app) => {
+ app.onhostcontextchanged = (context) => {
+ if (context) {
+ applyHostContext(context);
+ setHostContext((prev) => ({ ...prev, ...context }));
+ }
+ };
+
+ app.ontoolinput = (params) => {
+ const { query } =
+ (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 } =
+ (params.structuredContent as VisualizeQueryToolResult | undefined) ??
+ {};
+
+ if (query) {
+ setQuery(query);
+ setPrompt(prompt ?? null);
+ }
+ };
+ },
+ });
+
+ // Read host context once connected and apply styles immediately
+ useEffect(() => {
+ if (app) {
+ const context = app.getHostContext();
+
+ if (context) {
+ applyHostContext(context);
+ setHostContext(context);
+ }
+ }
+ }, [app]);
+
+ return { query, prompt, hostContext, app };
+}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts
new file mode 100644
index 00000000000..a64f629e981
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useMcpUserAndSettingsFetch.ts
@@ -0,0 +1,86 @@
+import { useEffect, useState } from "react";
+
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import { refreshSiteSettings } from "metabase/redux/settings";
+import { userUpdated } from "metabase/redux/user";
+import { UserApi } from "metabase/services";
+
+import {
+ type McpAppsUserAndSettingsFetchErrorType,
+ getMcpAppsUserAndSettingsFetchErrorMessage,
+ getMcpAppsUserAndSettingsFetchErrorType,
+} from "../utils/getMcpAppsUserAndSettingsFetchError";
+
+interface UseMcpUserAndSettingsFetchOptions {
+ instanceUrl: string;
+ sessionToken: string;
+ store: SdkStore;
+}
+
+interface UseMcpUserAndSettingsFetchResult {
+ isSettingsReady: boolean;
+ userAndSettingsFetchError: string | null;
+}
+
+export function useMcpUserAndSettingsFetch({
+ instanceUrl,
+ sessionToken,
+ store,
+}: UseMcpUserAndSettingsFetchOptions): UseMcpUserAndSettingsFetchResult {
+ const [isSettingsReady, setIsSettingsReady] = useState(false);
+
+ const [fetchError, setFetchError] = useState<string | null>(null);
+
+ // The OSS no-op initAuth never loads user or settings. Do it ourselves so
+ // selectors like getTokenFeature has populated settings.
+ // We also no-op the EE auth flow (auth.ts) when in MCP Apps route.
+ useEffect(() => {
+ let isMounted = true;
+
+ const setErrorByType = (type: McpAppsUserAndSettingsFetchErrorType) =>
+ setFetchError(getMcpAppsUserAndSettingsFetchErrorMessage(type));
+
+ async function fetchUserAndSettings() {
+ try {
+ setIsSettingsReady(false);
+ setFetchError(null);
+
+ if (!sessionToken) {
+ setErrorByType("auth");
+ return;
+ }
+
+ if (!instanceUrl) {
+ setErrorByType("network");
+ return;
+ }
+
+ const [currentUser] = await Promise.all([
+ UserApi.current(),
+ store.dispatch(refreshSiteSettings()),
+ ]);
+
+ if (!isMounted) {
+ return;
+ }
+
+ store.dispatch(userUpdated(currentUser));
+ setIsSettingsReady(true);
+ } catch (error) {
+ console.error("Error initializing MCP app", error);
+
+ if (isMounted) {
+ setErrorByType(getMcpAppsUserAndSettingsFetchErrorType(error));
+ }
+ }
+ }
+
+ fetchUserAndSettings();
+
+ return () => {
+ isMounted = false;
+ };
+ }, [instanceUrl, sessionToken, store]);
+
+ return { isSettingsReady, userAndSettingsFetchError: fetchError };
+}
diff --git a/frontend/src/metabase/embedding/mcp/hooks/useTemporalGranularity.ts b/frontend/src/metabase/embedding/mcp/hooks/useTemporalGranularity.ts
new file mode 100644
index 00000000000..ec6e335ec71
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/hooks/useTemporalGranularity.ts
@@ -0,0 +1,119 @@
+import { t } from "ttag";
+
+import * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
+import type { TemporalUnit } from "metabase-types/api";
+
+import { LAST_QUERY_STAGE_INDEX } from "./constants";
+
+type UpdateQuestion = (question: Question, opts: { run: boolean }) => void;
+
+export interface TemporalGranularityItem {
+ bucket: Lib.Bucket;
+ unit: TemporalUnit;
+ label: string;
+}
+
+export interface UseTemporalGranularityResult {
+ temporalColumn: Lib.ColumnMetadata | null;
+ rawTemporalColumn: Lib.ColumnMetadata | null;
+ currentUnit: TemporalUnit | undefined;
+ availableItems: TemporalGranularityItem[];
+ bucketLabel: string;
+ handleBucketChange: (bucket: Lib.Bucket | null) => void;
+}
+
+/**
+ * Handlers for showing and updating time granularity controls
+ * via the query explorer bar.
+ */
+export function useTemporalGranularity(
+ question: Question | undefined,
+ updateQuestion: UpdateQuestion,
+): UseTemporalGranularityResult {
+ if (!question) {
+ return {
+ temporalColumn: null,
+ rawTemporalColumn: null,
+ currentUnit: undefined,
+ availableItems: [],
+ bucketLabel: t`All time`,
+ handleBucketChange: () => {},
+ };
+ }
+
+ const query = question.query();
+ const stageIndex = LAST_QUERY_STAGE_INDEX;
+
+ const breakoutClauses = Lib.breakouts(query, stageIndex);
+
+ let temporalClause: Lib.BreakoutClause | null = null;
+ let temporalColumn: Lib.ColumnMetadata | null = null;
+
+ for (const clause of breakoutClauses) {
+ const column = Lib.breakoutColumn(query, stageIndex, clause);
+
+ if (column && Lib.isTemporalBucketable(query, stageIndex, column)) {
+ temporalClause = clause;
+ temporalColumn = column;
+ break;
+ }
+ }
+
+ // Strip the temporal bucket from the column — date filters operate on the
+ // raw date column, not the bucketed version used in the breakout.
+ const rawTemporalColumn = temporalColumn
+ ? Lib.withTemporalBucket(temporalColumn, null)
+ : null;
+
+ const currentBucket = temporalColumn
+ ? Lib.temporalBucket(temporalColumn)
+ : null;
+
+ const currentUnit = currentBucket
+ ? (Lib.displayInfo(query, stageIndex, currentBucket)
+ .shortName as TemporalUnit)
+ : undefined;
+
+ const availableBuckets = temporalColumn
+ ? Lib.availableTemporalBuckets(query, stageIndex, temporalColumn)
+ : [];
+
+ const availableItems: TemporalGranularityItem[] = availableBuckets.map(
+ (bucket) => {
+ const info = Lib.displayInfo(query, stageIndex, bucket);
+ const unit = info.shortName as TemporalUnit;
+
+ return { bucket, unit, label: Lib.describeTemporalUnit(unit) };
+ },
+ );
+
+ const bucketLabel = currentUnit
+ ? t`by ${Lib.describeTemporalUnit(currentUnit).toLowerCase()}`
+ : t`All time`;
+
+ const handleBucketChange = (bucket: Lib.Bucket | null) => {
+ if (!temporalClause || !temporalColumn) {
+ return;
+ }
+
+ const newColumn = Lib.withTemporalBucket(temporalColumn, bucket);
+ const newQuery = Lib.replaceClause(
+ query,
+ stageIndex,
+ temporalClause,
+ newColumn,
+ );
+
+ updateQuestion(question.setQuery(newQuery), { run: true });
+ };
+
+ return {
+ temporalColumn,
+ rawTemporalColumn,
+ currentUnit,
+ availableItems,
+ bucketLabel,
+ handleBucketChange,
+ };
+}
diff --git a/frontend/src/metabase/embedding/mcp/utils/buildMcpAppsTheme.ts b/frontend/src/metabase/embedding/mcp/utils/buildMcpAppsTheme.ts
new file mode 100644
index 00000000000..ddf3cead57f
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/utils/buildMcpAppsTheme.ts
@@ -0,0 +1,42 @@
+import type {
+ MetabaseColor,
+ MetabaseTheme,
+} from "metabase/embedding-sdk/theme";
+import type { ResolvedColorScheme } from "metabase/utils/color-scheme";
+
+import { resolveConcreteColor } from "../utils/resolveConcreteColor";
+
+/**
+ * Map the MCP Apps' host-provided CSS variables to SDK color keys.
+ * This differs by MCP hosts e.g. Claude Desktop, Visual Studio Code.
+ */
+const MCP_HOST_VAR_TO_SDK_COLOR: Record<
+ string,
+ Exclude<MetabaseColor, "charts">
+> = {
+ "--color-background-primary": "background",
+ "--color-background-secondary": "background-secondary",
+ "--color-background-disabled": "background-disabled",
+ "--color-text-primary": "text-primary",
+ "--color-text-secondary": "text-secondary",
+ "--color-text-tertiary": "text-tertiary",
+ "--color-border-secondary": "border",
+};
+
+export function buildMcpAppsTheme(
+ hostCssVariables: Record<string, string>,
+ preset: ResolvedColorScheme,
+): MetabaseTheme {
+ const colors: MetabaseTheme["colors"] = {};
+
+ for (const [cssVarKey, sdkKey] of Object.entries(MCP_HOST_VAR_TO_SDK_COLOR)) {
+ if (hostCssVariables[cssVarKey]) {
+ colors[sdkKey] = resolveConcreteColor(
+ hostCssVariables[cssVarKey],
+ preset,
+ );
+ }
+ }
+
+ return { preset, colors };
+}
diff --git a/frontend/src/metabase/embedding/mcp/utils/getMcpAppsUserAndSettingsFetchError.ts b/frontend/src/metabase/embedding/mcp/utils/getMcpAppsUserAndSettingsFetchError.ts
new file mode 100644
index 00000000000..385935ef086
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/utils/getMcpAppsUserAndSettingsFetchError.ts
@@ -0,0 +1,36 @@
+/* eslint-disable metabase/no-literal-metabase-strings */
+
+import { match } from "ts-pattern";
+import { t } from "ttag";
+
+export type McpAppsUserAndSettingsFetchErrorType = "auth" | "network";
+
+export function getMcpAppsUserAndSettingsFetchErrorType(
+ error: unknown,
+): McpAppsUserAndSettingsFetchErrorType {
+ if (!error || typeof error !== "object") {
+ return "network";
+ }
+
+ if ("status" in error && error.status === 401) {
+ return "auth";
+ }
+
+ return "network";
+}
+
+export const getMcpAppsUserAndSettingsFetchErrorMessage = (
+ type: McpAppsUserAndSettingsFetchErrorType,
+): string =>
+ match(type)
+ .with(
+ "auth",
+ () =>
+ t`Authentication failed. Try signing out and signing back in, then ask your MCP client to show this again.`,
+ )
+ .with(
+ "network",
+ () =>
+ t`Could not connect to Metabase. Make sure this MCP client is enabled in AI settings and that Metabase is reachable.`,
+ )
+ .exhaustive();
diff --git a/frontend/src/metabase/embedding/mcp/utils/getMcpAppsUserAndSettingsFetchError.unit.spec.ts b/frontend/src/metabase/embedding/mcp/utils/getMcpAppsUserAndSettingsFetchError.unit.spec.ts
new file mode 100644
index 00000000000..c3ee9c68db5
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/utils/getMcpAppsUserAndSettingsFetchError.unit.spec.ts
@@ -0,0 +1,27 @@
+import { getMcpAppsUserAndSettingsFetchErrorType } from "./getMcpAppsUserAndSettingsFetchError";
+
+describe("getMcpAppsUserAndSettingsFetchErrorType", () => {
+ it("returns auth for unauthorized current user or settings API errors", () => {
+ expect(
+ getMcpAppsUserAndSettingsFetchErrorType({
+ status: 401,
+ data: "Unauthenticated",
+ }),
+ ).toBe("auth");
+ });
+
+ it("returns network for non-auth current user or settings API errors", () => {
+ expect(
+ getMcpAppsUserAndSettingsFetchErrorType({
+ status: 500,
+ data: "Internal server error",
+ }),
+ ).toBe("network");
+ });
+
+ it("returns network for unreadable CORS or network failures", () => {
+ expect(
+ getMcpAppsUserAndSettingsFetchErrorType(new TypeError("Failed to fetch")),
+ ).toBe("network");
+ });
+});
diff --git a/frontend/src/metabase/embedding/mcp/utils/resolveConcreteColor.tsx b/frontend/src/metabase/embedding/mcp/utils/resolveConcreteColor.tsx
new file mode 100644
index 00000000000..25b8e07e66d
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/utils/resolveConcreteColor.tsx
@@ -0,0 +1,37 @@
+import type { ResolvedColorScheme } from "metabase/utils/color-scheme";
+
+/**
+ * Resolve a CSS value that may contain var() or light-dark() into a concrete color.
+ *
+ * MCP hosts like Visual Studio Code send CSS variable references
+ * e.g. `light-dark(white, black)` as theming values.
+ *
+ * The SDK requires concrete color values, so we resolve them via the browser's
+ * computed style cascade. Setting `color-scheme` on the container ensures
+ * light-dark() resolves to the correct arm for the host's theme.
+ */
+export function resolveConcreteColor(
+ valueOrCssVariable: string,
+ scheme: ResolvedColorScheme,
+): string {
+ if (!valueOrCssVariable) {
+ return valueOrCssVariable;
+ }
+
+ if (
+ !valueOrCssVariable.startsWith("var(") &&
+ !valueOrCssVariable.startsWith("light-dark(")
+ ) {
+ return valueOrCssVariable;
+ }
+
+ const container = document.createElement("div");
+ container.style.colorScheme = scheme;
+ container.style.color = valueOrCssVariable;
+ document.body.appendChild(container);
+
+ const resolved = getComputedStyle(container).color;
+ document.body.removeChild(container);
+
+ return resolved || valueOrCssVariable;
+}
diff --git a/frontend/src/metabase/embedding/mcp/utils/resolveConcreteColor.unit.spec.ts b/frontend/src/metabase/embedding/mcp/utils/resolveConcreteColor.unit.spec.ts
new file mode 100644
index 00000000000..5705a5e35ad
--- /dev/null
+++ b/frontend/src/metabase/embedding/mcp/utils/resolveConcreteColor.unit.spec.ts
@@ -0,0 +1,57 @@
+import { resolveConcreteColor } from "./resolveConcreteColor";
+
+describe("resolveConcreteColor", () => {
+ it.each([
+ // plain values
+ { input: "#ff0000", scheme: "light", expected: "#ff0000" },
+ { input: "rgb(255, 0, 0)", scheme: "light", expected: "rgb(255, 0, 0)" },
+ { input: "", scheme: "light", expected: "" },
+ ] as const)(
+ "resolveConcreteColor($input, $scheme) → $expected",
+ ({ input, scheme, expected }) => {
+ expect(resolveConcreteColor(input, scheme)).toBe(expected);
+ },
+ );
+
+ describe("var() values", () => {
+ let appendSpy: jest.SpyInstance;
+ let removeSpy: jest.SpyInstance;
+ let getComputedStyleSpy: jest.SpyInstance;
+
+ beforeEach(() => {
+ appendSpy = jest
+ .spyOn(document.body, "appendChild")
+ .mockImplementation((el) => el as any);
+
+ removeSpy = jest
+ .spyOn(document.body, "removeChild")
+ .mockImplementation((el) => el as any);
+ });
+
+ afterEach(() => {
+ appendSpy.mockRestore();
+ removeSpy.mockRestore();
+ getComputedStyleSpy?.mockRestore();
+ });
+
+ it("resolves a var() reference via computed style", () => {
+ getComputedStyleSpy = jest
+ .spyOn(window, "getComputedStyle")
+ .mockReturnValue({ color: "rgb(30, 30, 30)" } as CSSStyleDeclaration);
+
+ expect(
+ resolveConcreteColor("var(--vscode-editor-background)", "light"),
+ ).toBe("rgb(30, 30, 30)");
+ });
+
+ it("falls back to original value when computed style returns empty", () => {
+ getComputedStyleSpy = jest
+ .spyOn(window, "getComputedStyle")
+ .mockReturnValue({ color: "" } as CSSStyleDeclaration);
+
+ expect(resolveConcreteColor("var(--unknown-variable)", "light")).toBe(
+ "var(--unknown-variable)",
+ );
+ });
+ });
+});
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricControls/ChartTypePicker/index.ts b/frontend/src/metabase/metrics-viewer/components/MetricControls/ChartTypePicker/index.ts
index b5e8208e8f2..6f5a9434e03 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricControls/ChartTypePicker/index.ts
+++ b/frontend/src/metabase/metrics-viewer/components/MetricControls/ChartTypePicker/index.ts
@@ -1 +1,2 @@
export { ChartTypePicker } from "./ChartTypePicker";
+export type { ChartTypeOption } from "../../../utils/tab-config";
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/AdHocQuestionDescription.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/AdHocQuestionDescription.tsx
index e34f9cd60d2..175a656a351 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/AdHocQuestionDescription.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/AdHocQuestionDescription.tsx
@@ -1,10 +1,11 @@
import { useMemo } from "react";
-import { msgid, ngettext, t } from "ttag";
import CS from "metabase/css/core/index.css";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
+import { describeQueryStage, getInfoStageIndex } from "./utils";
+
type AdHocQuestionDescriptionProps = {
onClick?: () => void;
} & GetAdhocQuestionDescriptionProps;
@@ -28,47 +29,8 @@ export const getAdHocQuestionDescription = ({
question,
}: GetAdhocQuestionDescriptionProps) => {
const query = question.query();
- const stageIndex = getInfoStageIndex(query);
- const aggregations = Lib.aggregations(query, stageIndex);
- const breakouts = Lib.breakouts(query, stageIndex);
- const aggregationDescription =
- aggregations.length === 0
- ? null
- : aggregations.length > 2
- ? ngettext(
- msgid`${aggregations.length} metric`,
- `${aggregations.length} metrics`,
- aggregations.length,
- )
- : aggregations
- .map(
- (aggregation) =>
- Lib.displayInfo(query, stageIndex, aggregation).longDisplayName,
- )
- .join(t` and `);
- const breakoutDescription =
- breakouts.length === 0
- ? null
- : breakouts.length > 2
- ? ngettext(
- msgid`${breakouts.length} breakout`,
- `${breakouts.length} breakouts`,
- breakouts.length,
- )
- : breakouts
- .map(
- (breakout) =>
- Lib.displayInfo(query, stageIndex, breakout).longDisplayName,
- )
- .join(t` and `);
- if (!aggregationDescription && !breakoutDescription) {
- return null;
- }
-
- return [aggregationDescription, breakoutDescription]
- .filter(Boolean)
- .join(t` by `);
+ return describeQueryStage(query, getInfoStageIndex(query));
};
export const AdHocQuestionDescription = ({
@@ -90,19 +52,4 @@ export const AdHocQuestionDescription = ({
);
};
-const getInfoStageIndex = (query: Lib.Query): number => {
- const hasExtraEmptyFilterStage =
- Lib.stageCount(query) > 1 && !Lib.hasClauses(query, -1);
-
- if (hasExtraEmptyFilterStage) {
- /**
- * If query is multi-stage and the last stage is empty (which means it's
- * an extra filtering stage - see Lib.ensureFilterStage), the last stage won't
- * provide any useful information to generate question description.
- * We have to use the previous, non-empty stage.
- */
- return -2;
- }
-
- return -1;
-};
+export { describeQueryStage, getInfoStageIndex };
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/AdHocQuestionDescription.unit.spec.ts b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/AdHocQuestionDescription.unit.spec.ts
new file mode 100644
index 00000000000..2b83ab26034
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/AdHocQuestionDescription.unit.spec.ts
@@ -0,0 +1,59 @@
+import * as Lib from "metabase-lib";
+import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
+import { ORDERS_ID, PRODUCTS_ID } from "metabase-types/api/mocks/presets";
+
+import { describeQueryStage } from "./utils";
+
+describe("describeQueryStage", () => {
+ it("can strip temporal bucket suffixes from breakout names", () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [
+ {
+ type: "column",
+ name: "CREATED_AT",
+ sourceName: "ORDERS",
+ unit: "month",
+ },
+ ],
+ },
+ ],
+ });
+
+ // Temporal buckets are included by default
+ expect(describeQueryStage(query, 0)).toBe("Count by Created At: Month");
+
+ // When stripTemporalBucket is true, the ": Month" suffix is then removed
+ expect(describeQueryStage(query, 0, { stripTemporalBucket: true })).toBe(
+ "Count by Created At",
+ );
+ });
+
+ it("preserves non-temporal breakout suffixes when stripping temporal buckets", () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: PRODUCTS_ID },
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [
+ {
+ type: "column",
+ name: "RATING",
+ sourceName: "PRODUCTS",
+ bins: 10,
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(describeQueryStage(query, 0)).toBe("Count by Rating: 10 bins");
+
+ expect(describeQueryStage(query, 0, { stripTemporalBucket: true })).toBe(
+ "Count by Rating: 10 bins",
+ );
+ });
+});
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/utils.ts b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/utils.ts
new file mode 100644
index 00000000000..0a3ff8a9108
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/AdHocQuestionDescription/utils.ts
@@ -0,0 +1,92 @@
+import { msgid, ngettext, t } from "ttag";
+
+import * as Lib from "metabase-lib";
+
+type DescribeQueryStageOptions = {
+ /**
+ * When true, strips temporal bucket suffixes from breakout names
+ * (e.g. "Created At" instead of "Created At: Month"). Useful when the
+ * granularity is shown separately via a UI control.
+ */
+ stripTemporalBucket?: boolean;
+};
+
+/**
+ * Formats a human-readable description of the aggregations and breakouts at a
+ * specific query stage. Used by both the query builder title and MCP app titles.
+ */
+export const describeQueryStage = (
+ query: Lib.Query,
+ stageIndex: number,
+ { stripTemporalBucket = false }: DescribeQueryStageOptions = {},
+): string | null => {
+ const aggregations = Lib.aggregations(query, stageIndex);
+ const breakouts = Lib.breakouts(query, stageIndex);
+
+ let aggregationDescription: string | null = null;
+
+ if (aggregations.length > 2) {
+ aggregationDescription = ngettext(
+ msgid`${aggregations.length} metric`,
+ `${aggregations.length} metrics`,
+ aggregations.length,
+ );
+ } else if (aggregations.length > 0) {
+ aggregationDescription = aggregations
+ .map(
+ (aggregation) =>
+ Lib.displayInfo(query, stageIndex, aggregation).longDisplayName,
+ )
+ .join(t` and `);
+ }
+
+ let breakoutDescription: string | null = null;
+ if (breakouts.length > 2) {
+ breakoutDescription = ngettext(
+ msgid`${breakouts.length} breakout`,
+ `${breakouts.length} breakouts`,
+ breakouts.length,
+ );
+ } else if (breakouts.length > 0) {
+ breakoutDescription = breakouts
+ .map((breakout) => {
+ if (stripTemporalBucket) {
+ const column = Lib.breakoutColumn(query, stageIndex, breakout);
+
+ if (column && Lib.isTemporalBucketable(query, stageIndex, column)) {
+ const unbucketed = Lib.withTemporalBucket(column, null);
+
+ return Lib.displayInfo(query, stageIndex, unbucketed).displayName;
+ }
+ }
+
+ return Lib.displayInfo(query, stageIndex, breakout).longDisplayName;
+ })
+ .join(t` and `);
+ }
+
+ if (!aggregationDescription && !breakoutDescription) {
+ return null;
+ }
+
+ return [aggregationDescription, breakoutDescription]
+ .filter(Boolean)
+ .join(t` by `);
+};
+
+export const getInfoStageIndex = (query: Lib.Query): number => {
+ const hasExtraEmptyFilterStage =
+ Lib.stageCount(query) > 1 && !Lib.hasClauses(query, -1);
+
+ if (hasExtraEmptyFilterStage) {
+ /**
+ * If query is multi-stage and the last stage is empty (which means it's
+ * an extra filtering stage - see Lib.ensureFilterStage), the last stage won't
+ * provide any useful information to generate question description.
+ * We have to use the previous, non-empty stage.
+ */
+ return -2;
+ }
+
+ return -1;
+};
diff --git a/frontend/src/metabase/visualizations/components/ClickActions/ClickActionsPopover.tsx b/frontend/src/metabase/visualizations/components/ClickActions/ClickActionsPopover.tsx
index 46b4149bc94..4a226791694 100644
--- a/frontend/src/metabase/visualizations/components/ClickActions/ClickActionsPopover.tsx
+++ b/frontend/src/metabase/visualizations/components/ClickActions/ClickActionsPopover.tsx
@@ -126,7 +126,9 @@ export class ClickActionsPopover extends Component<
onResize={() => {
this.instance?.popperInstance?.update();
}}
- onChangeCardAndRun={onChangeCardAndRun}
+ onChangeCardAndRun={(options) =>
+ onChangeCardAndRun({ drillName: popoverAction.name, ...options })
+ }
onClose={this.close}
series={series}
onUpdateVisualizationSettings={onUpdateVisualizationSettings}
diff --git a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
index a3cb0c0ced4..935f16c457d 100644
--- a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
+++ b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
@@ -116,6 +116,7 @@ type OnChangeCardAndRunOpts = {
nextCard: Card;
previousCard: Card;
objectId?: number;
+ drillName?: string;
};
type VisualizationOwnProps = {
@@ -603,7 +604,8 @@ class Visualization extends PureComponent<
handleOnChangeCardAndRun = ({
nextCard,
objectId,
- }: Pick<OnChangeCardAndRunOpts, "nextCard" | "objectId">) => {
+ drillName,
+ }: Pick<OnChangeCardAndRunOpts, "nextCard" | "objectId" | "drillName">) => {
const { dashcard, rawSeries, visualizerRawSeries, onChangeCardAndRun } =
this.props;
@@ -616,6 +618,7 @@ class Visualization extends PureComponent<
),
nextCard,
objectId,
+ drillName,
});
};
diff --git a/frontend/src/metabase/visualizations/lib/action.ts b/frontend/src/metabase/visualizations/lib/action.ts
index ff6c08d0f1b..1fe00af958d 100644
--- a/frontend/src/metabase/visualizations/lib/action.ts
+++ b/frontend/src/metabase/visualizations/lib/action.ts
@@ -71,6 +71,7 @@ export function performAction(
nextCard: question.card(),
...extra,
objectId,
+ drillName: action.name,
});
} else if (questionChangeBehavior === "updateQuestion") {
onUpdateQuestion?.(question);
diff --git a/frontend/src/metabase/visualizations/lib/action.unit.spec.ts b/frontend/src/metabase/visualizations/lib/action.unit.spec.ts
index ec86006e8d5..dcff29ac847 100644
--- a/frontend/src/metabase/visualizations/lib/action.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/lib/action.unit.spec.ts
@@ -254,6 +254,8 @@ describe("performAction", () => {
expect(extraProps.onChangeCardAndRun).toHaveBeenCalledTimes(1);
expect(extraProps.onChangeCardAndRun).toHaveBeenCalledWith({
nextCard: mockQuestion.card(),
+ objectId: undefined,
+ drillName: defaultQuestionAction.name,
});
expect(performAction(updateQuestionAction, extraProps)).toBe(true);
diff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.ts
index dbe8dc1d324..65c923e20e3 100644
--- a/frontend/src/metabase/visualizations/types/visualization.ts
+++ b/frontend/src/metabase/visualizations/types/visualization.ts
@@ -109,6 +109,7 @@ export type OnChangeCardAndRunOpts = {
nextCard: Card;
seriesIndex?: number;
objectId?: number;
+ drillName?: string;
};
export type OnChangeCardAndRun = (opts: OnChangeCardAndRunOpts) => void;
diff --git a/frontend/src/types/modelcontextprotocol.d.ts b/frontend/src/types/modelcontextprotocol.d.ts
new file mode 100644
index 00000000000..abfb7a049e9
--- /dev/null
+++ b/frontend/src/types/modelcontextprotocol.d.ts
@@ -0,0 +1,7 @@
+declare module "@modelcontextprotocol/ext-apps" {
+ export * from "@modelcontextprotocol/ext-apps/dist/src/app";
+}
+
+declare module "@modelcontextprotocol/ext-apps/react" {
+ export * from "@modelcontextprotocol/ext-apps/dist/src/react/index";
+}
diff --git a/package.json b/package.json
index 403ec938f54..d882b6be65b 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,7 @@
"@mantine/core": "8.3.18",
"@mantine/dates": "8.3.18",
"@mantine/hooks": "8.3.18",
+ "@modelcontextprotocol/ext-apps": "^1.3.2",
"@popperjs/core": "^2.11.8",
"@react-oauth/google": "^0.11.1",
"@reduxjs/toolkit": "^2.5.0",
diff --git a/resources/frontend_client/mcp_apps_template.html b/resources/frontend_client/mcp_apps_template.html
new file mode 100644
index 00000000000..0c923644fc0
--- /dev/null
+++ b/resources/frontend_client/mcp_apps_template.html
@@ -0,0 +1,93 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="robots" content="noindex" />
+
+ <title>Metabase</title>
+
+ <style>
+ :root {
+ /* Allow light-dark() to work */
+ color-scheme: light dark;
+ }
+
+ body {
+ margin: 0;
+ height: 500px;
+ }
+
+ body {
+ background: var(--color-background-primary);
+ color: var(--color-text-primary);
+ font-family: var(--font-sans);
+ }
+
+ /* Allow Cursor and VS Code to have proper colors & fonts */
+ body.vscode-light,
+ body.vscode-dark,
+ body.vscode-high-contrast {
+ color: var(--vscode-foreground);
+ background: var(--vscode-editor-background);
+ font-family: var(--vscode-font-family);
+ }
+
+ .mcp-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ }
+
+ @keyframes mcp-spinner-animation {
+ 0% {
+ transform: rotate(0deg);
+ }
+
+ 100% {
+ transform: rotate(360deg);
+ }
+ }
+
+ .mcp-spinner {
+ display: inline-block;
+ box-sizing: border-box;
+ width: 1.5rem;
+ height: 1.5rem;
+ }
+
+ .mcp-spinner::after {
+ content: "";
+ display: block;
+ box-sizing: border-box;
+ width: 1.5rem;
+ height: 1.5rem;
+ border-radius: 10000px;
+ border-width: calc(1.5rem / 8);
+ border-style: solid;
+ border-color: #509ee3 #509ee3 #509ee3 transparent;
+ animation: mcp-spinner-animation 1.2s linear infinite;
+ }
+ </style>
+ <script>
+ window.Metabase = window.Metabase || {};
+ window.Metabase.AssetErrorLoad = function (tag) {
+ console.error("Could not download asset " + tag.src);
+ };
+ </script>
+ </head>
+ <body>
+ <div id="root"></div>
+ <div id="mcp-loading" class="mcp-loading">
+ <span class="mcp-spinner"></span>
+ </div>
+
+ <script>
+ window.metabaseConfig = {
+ instanceUrl: {{{instanceUrl}}},
+ sessionToken: {{{sessionToken}}},
+ mcpSessionId: {{{mcpSessionId}}}
+ };
+ </script>
+ </body>
+</html>
diff --git a/resources/metabase/agent_api/construct_query.md b/resources/metabase/agent_api/construct_query.md
index e64824c574c..83e1c962bf3 100644
--- a/resources/metabase/agent_api/construct_query.md
+++ b/resources/metabase/agent_api/construct_query.md
@@ -6,15 +6,17 @@ Construct a Metabase MBQL query from a structured program. The body is the progr
{"source": {...}, "operations": [...]}
```
-Returns `{"query": "<base64>"}` — pass the string to `execute_query`.
+The `prompt` field is optional for Agent API callers. MCP clients should include it whenever they have the user's message; pass the original message as-is and do not summarize, rewrite, or infer a different prompt.
+
+In MCP, this returns `{"query_handle": "<uuid>"}` — pass the handle to `execute_query` or `visualize_query` as `query_handle`. The HTTP Agent API response contains `{"query": "<base64>"}` and echoes `prompt` only when supplied.
IMPORTANT: field IDs must come from entity-detail endpoints (`/v1/table/{id}`, `/v1/metric/{id}`). Do not invent IDs. The backend repairs minor mistakes (aliases, casing, over-wrapping) before validation, but the canonical names below always work.
## Workflow
1. Use `search` and the entity-detail tools (`get_table`, `get_metric`) to find the table/metric/model and its fields.
-2. Call `construct_query` with the program. You get back `{"query": "<base64>"}`.
-3. Pass that string to `execute_query`.
+2. Call `construct_query` with the program. Include the user's original `prompt` whenever available. In MCP, you get back `{"query_handle": "<uuid>"}`.
+3. Pass that handle to `execute_query` or `visualize_query` as `query_handle`.
Never embed IDs you did not read from a metadata endpoint — invented IDs will fail at execution.
diff --git a/resources/migrations/062/20260424_mcp_query_handle.yaml b/resources/migrations/062/20260424_mcp_query_handle.yaml
new file mode 100644
index 00000000000..ca564a49bb6
--- /dev/null
+++ b/resources/migrations/062/20260424_mcp_query_handle.yaml
@@ -0,0 +1,93 @@
+## Stores encoded query payloads handed off from the MCP iframe to MCP tool calls.
+## Used by both render_drill_through (drill-through payloads) and visualize_query
+## (construct_query results). Each row carries a fresh UUID handle that the iframe
+## passes through to the agent so the LLM never carries the encoded query.
+
+databaseChangeLog:
+ - logicalFilePath: migrations/062_update_migrations.yaml
+ - changeSet:
+ id: v62.2026-04-24T00:00:00
+ author: crisptrutski
+ comment: Create mcp_query_handle table for MCP query payloads
+ changes:
+ - createTable:
+ tableName: mcp_query_handle
+ remarks: Server-side store for encoded MBQL query payloads referenced by MCP tool calls
+ columns:
+ - column:
+ name: id
+ type: varchar(36)
+ remarks: Handle UUID; returned to the iframe and threaded through to the MCP tool call
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: mcp_session_id
+ type: varchar(36)
+ remarks: MCP session that owns this handle; used for explicit DELETE /api/mcp cleanup
+ constraints:
+ nullable: false
+ - column:
+ name: core_session_id
+ type: varchar(254)
+ remarks: core_session.id when one has been materialized; cascade-deletes with the session
+ - column:
+ name: encoded_query
+ type: ${text.type}
+ remarks: Base64-encoded MBQL query payload
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ remarks: When this handle was stored; useful for debugging and future TTL cleanup
+ constraints:
+ nullable: false
+ rollback:
+ - dropTable:
+ tableName: mcp_query_handle
+
+ - changeSet:
+ id: v62.2026-04-24T00:00:01
+ author: crisptrutski
+ comment: Index mcp_query_handle.mcp_session_id for delete-by-session cleanup
+ changes:
+ - createIndex:
+ tableName: mcp_query_handle
+ indexName: idx_mcp_query_handle_mcp_session_id
+ columns:
+ - column:
+ name: mcp_session_id
+ rollback:
+ - dropIndex:
+ tableName: mcp_query_handle
+ indexName: idx_mcp_query_handle_mcp_session_id
+
+ - changeSet:
+ id: v62.2026-04-24T00:00:02
+ author: crisptrutski
+ comment: Index mcp_query_handle.core_session_id for the FK
+ changes:
+ - createIndex:
+ tableName: mcp_query_handle
+ indexName: idx_mcp_query_handle_core_session_id
+ columns:
+ - column:
+ name: core_session_id
+ rollback:
+ - dropIndex:
+ tableName: mcp_query_handle
+ indexName: idx_mcp_query_handle_core_session_id
+
+ - changeSet:
+ id: v62.2026-04-24T00:00:03
+ author: crisptrutski
+ comment: FK from mcp_query_handle.core_session_id to core_session, cascade on delete
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: mcp_query_handle
+ baseColumnNames: core_session_id
+ referencedTableName: core_session
+ referencedColumnNames: id
+ constraintName: fk_mcp_query_handle_ref_core_session
+ onDelete: CASCADE
diff --git a/resources/migrations/062/20260428_mcp_ui_query_handle_prompt.yaml b/resources/migrations/062/20260428_mcp_ui_query_handle_prompt.yaml
new file mode 100644
index 00000000000..b72ff40ca42
--- /dev/null
+++ b/resources/migrations/062/20260428_mcp_ui_query_handle_prompt.yaml
@@ -0,0 +1,25 @@
+## Add prompt column to mcp_query_handle for construct_query handles.
+## Stores the user's original prompt (e.g. "visualize this orders") alongside
+## the query so visualize_query can surface it in the frontend.
+
+databaseChangeLog:
+ - logicalFilePath: migrations/062_update_migrations.yaml
+
+ - changeSet:
+ id: v62.2026-04-28T00:00:00
+ author: phoomparin
+ comment: Add prompt column to mcp_query_handle to store the user's original prompt
+ changes:
+ - addColumn:
+ tableName: mcp_query_handle
+ columns:
+ - column:
+ name: prompt
+ type: ${text.type}
+ remarks: The user's original prompt used to construct the query; nullable for drill-through handles
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: mcp_query_handle
+ columnName: prompt
diff --git a/rspack.main.config.js b/rspack.main.config.js
index d11212e6aaf..be989f51139 100644
--- a/rspack.main.config.js
+++ b/rspack.main.config.js
@@ -112,6 +112,7 @@ const config = {
"app-public": "./app-public.ts",
"app-embed": "./app-embed.ts",
"app-embed-sdk": "./app-embed-sdk.tsx",
+ "app-embed-mcp": "./app-embed-mcp.tsx",
"vendor-styles": "./css/vendor.css",
styles: "./css/index.module.css",
},
@@ -295,6 +296,18 @@ const config = {
chunks: ["vendor", "vendor-styles", "styles", "app-embed-sdk"],
template: __dirname + "/resources/frontend_client/index_template.html",
}),
+ new HtmlWebpackPlugin({
+ filename: "../../embed-mcp.html",
+ chunksSortMode: "manual",
+ chunks: ["vendor", "vendor-styles", "styles", "app-embed-mcp"],
+ template: __dirname + "/resources/frontend_client/mcp_apps_template.html",
+
+ // MCP apps are rendered inside a sandboxed srcdoc iframe (about:srcdoc),
+ // so asset URLs must point to the Metabase instance. We embed a Mustache
+ // variable in publicPath — HtmlWebpackPlugin emits it literally, then
+ // Stencil substitutes it at runtime with the real instance URL.
+ publicPath: "{{{instanceUrlRaw}}}/app/dist/",
+ }),
new rspack.BannerPlugin(getBannerOptions(LICENSE_TEXT)),
// https://github.com/orgs/remarkjs/discussions/903
new rspack.ProvidePlugin({
@@ -360,7 +373,10 @@ if (shouldEnableHotRefresh) {
config.plugins.unshift(
new ReactRefreshPlugin({
overlay: false,
- exclude: [SDK_DOCS_SNIPPETS_PATH],
+
+ // app-embed-mcp runs in an isolated iframe with CSP restrictions.
+ // Excluding it avoids injecting the React Refresh runtime which uses eval.
+ exclude: [SDK_DOCS_SNIPPETS_PATH, /app-embed-mcp/],
}),
);
}
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index c92df35844c..fc345f43420 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -3,6 +3,7 @@
Endpoints are versioned (e.g., /v1/search) and use standard HTTP semantics."
(:require
[clojure.string :as str]
+ [malli.util :as mut]
[metabase.agent-api.validation :as agent-api.validation]
[metabase.agent-lib.core :as agent-lib]
[metabase.api.common :as api]
@@ -14,7 +15,9 @@
[metabase.events.core :as events]
[metabase.lib.core :as lib]
[metabase.lib.schema.id :as lib.schema.id]
+ [metabase.metabot.config :as metabot.config]
[metabase.metabot.core :as metabot]
+ [metabase.metabot.feedback :as metabot.feedback]
[metabase.metabot.tools.construct :as metabot-construct]
[metabase.metabot.tools.entity-details :as entity-details]
[metabase.metabot.tools.field-stats :as field-stats]
@@ -63,6 +66,18 @@
(or structured-output
(api/check false [(or status-code 404) (or output "Not found.")])))
+(defn submit-mcp-visualization-feedback!
+ "Submit MCP Apps visualization feedback to Harbormaster.
+
+ MCP Apps do not create `metabot_message` rows, so this intentionally skips
+ local feedback persistence and forwards the MCP visualization context."
+ [body]
+ (let [metabot-id (api/check-500 (metabot.config/normalize-metabot-id metabot.config/embedded-metabot-id))
+ body (assoc body :metabot_id metabot-id)]
+ (metabot.config/check-metabot-enabled!)
+ (metabot.feedback/submit-to-harbormaster!
+ (metabot.feedback/mcp-harbormaster-payload body))))
+
;;; --------------------------------------------------- Schemas ------------------------------------------------------
;; Response schemas for the Agent API.
@@ -355,7 +370,7 @@
;;; ------------------------------------------------ Construct Query -------------------------------------------------
(mr/def ::program-request
- "Request body for /v2/construct-query and /v2/query.
+ "Request body for /v2/query.
An agent-lib structured program with `:source` and `:operations`. The top-level
`:source` must reference a database entity (`table`, `card`, `dataset`, or
`metric`); `context` and nested `program` sources are rejected at the HTTP
@@ -363,10 +378,32 @@
in-process evaluation context."
agent-lib/program-schema)
+(def ^:private construct-query-prompt-max-length
+ 10000)
+
+(def ^:private ConstructQueryPrompt
+ (mut/update-properties
+ [:and
+ ms/NonBlankString
+ [:string {:max construct-query-prompt-max-length}]]
+ merge
+ {:json-schema {:type "string"
+ :minLength 1
+ :maxLength construct-query-prompt-max-length
+ :description "The user's exact original message, when available. Pass it as-is without summarizing or rewriting."}}))
+
+(mr/def ::construct-query-request
+ "Request body for /v2/construct-query. Same as program-request, with an optional prompt
+ capturing the user's original intent when a caller has one."
+ (mut/merge agent-lib/program-schema
+ [:map
+ [:prompt {:optional true} ConstructQueryPrompt]]))
+
(mr/def ::construct-query-response
- "Response containing a base64-encoded MBQL query for use with /v1/execute."
+ "Response containing a base64-encoded MBQL query and, when supplied, the original prompt for use with /v1/execute."
[:map
- [:query ms/NonBlankString]])
+ [:query ms/NonBlankString]
+ [:prompt {:optional true} ConstructQueryPrompt]])
(def ^:private allowed-program-source-types
"Top-level program source types that the HTTP boundary accepts. `context` and
@@ -374,6 +411,132 @@
rejected here."
#{"table" "card" "dataset" "metric"})
+(def ^:private construct-query-tool-description
+ "User-facing description for the `construct_query` MCP tool. Tuned to give the
+ LLM enough structure to produce valid programs without reproducing the full
+ reference — covers the program shape, canonical operator names, reference forms,
+ and a few worked examples spanning the common patterns."
+ (str
+ "Construct a Metabase MBQL query from a structured program. The body structure is:\n"
+ "`{\"source\": {...}, \"operations\": [...]}`\n"
+ "For MCP calls, include `\"prompt\": \"<user's exact original message>\"` whenever you have the user's message; do not summarize or modify it.\n"
+ "Returns `{\"query_handle\": \"<uuid>\"}` — pass it as `query_handle` to `execute_query` or `visualize_query`.\n"
+ "For the full reference, read the `metabase://docs/construct-query.md` MCP resource.\n"
+ "\n"
+ "IMPORTANT: field IDs must come from entity-detail endpoints (`/v1/table/{id}`, `/v1/metric/{id}`). "
+ "Do not invent IDs. The backend repairs minor mistakes (aliases, casing, over-wrapping) before validation, "
+ "but the canonical names below always work.\n"
+ "\n"
+ "## Workflow\n"
+ "1. Use `search_entities` / entity-detail tools to find the table/metric/model and its fields.\n"
+ "2. Call `construct_query` with the program. Include the user's original `prompt` whenever available. You get back `{\"query_handle\": \"<uuid>\"}`.\n"
+ "3. Pass that handle to `execute_query` or `visualize_query` as `query_handle`.\n"
+ "Never embed IDs you did not read from a metadata endpoint — invented IDs will fail at execution.\n"
+ "\n"
+ "## Source\n"
+ "One of `{\"type\": T, \"id\": N}`:\n"
+ "- `table` — a database table\n"
+ "- `card` — a saved question\n"
+ "- `dataset` — a model (model card id)\n"
+ "- `metric` — a metric (supplies its own aggregation and time dimension; extra aggregates usually unnecessary)\n"
+ "\n"
+ "## Top-level operations (applied in order)\n"
+ "Each operation is `[\"op\", arg, ...]`:\n"
+ "- `[\"filter\", clause]` — add a filter\n"
+ "- `[\"aggregate\", agg-clause]` — add an aggregation\n"
+ "- `[\"breakout\", ref-or-bucketed]` — add a grouping dimension\n"
+ "- `[\"expression\", \"Name\", expr]` — define a named computed column (reference later with `expression-ref`)\n"
+ "- `[\"with-fields\", [refs...]]` — restrict returned columns\n"
+ "- `[\"order-by\", ref]` or `[\"order-by\", ref, \"asc\"|\"desc\"]` — sort\n"
+ "- `[\"limit\", N]` — cap rows\n"
+ "- `[\"join\", join-clause]` — join another entity\n"
+ "- `[\"append-stage\"]` — start a new query stage (needed to filter on aggregated values)\n"
+ "- `[\"with-page\", {\"page\": N, \"items\": M}]` — paginate\n"
+ "\n"
+ "## References (used as arguments inside operations)\n"
+ "- `[\"field\", N]` — database field by id. Do NOT put options in a third slot (no `[\"field\", id, {...}]`); wrap instead\n"
+ "- `[\"expression-ref\", \"Name\"]` — a named expression defined earlier\n"
+ "- `[\"aggregation-ref\", N]` — the Nth `aggregate` defined earlier (0-based). REQUIRED when sorting by an aggregated value\n"
+ "- `[\"measure\", N]` — a pre-defined measure on the source entity\n"
+ "- `[\"with-temporal-bucket\", ref, unit]` — temporal bucketing. `unit` is one of: `minute` `hour` `day` `week` `month` `quarter` `year`. Also `day-of-week`, `hour-of-day`, etc. (extraction aliases)\n"
+ "- `[\"with-binning\", ref, {\"strategy\": \"num-bins\"|\"bin-width\"|\"default\", ...}]` — numeric binning. E.g. `{\"strategy\": \"num-bins\", \"num-bins\": 10}`\n"
+ "\n"
+ "## Filter operators\n"
+ "`=`, `!=`, `<`, `<=`, `>`, `>=`, `between`, `in`, `not-in`, `is-null`, `not-null`, `is-empty`, `not-empty`, "
+ "`contains`, `does-not-contain`, `starts-with`, `ends-with`, `time-interval`, `and`, `or`, `not`, `segment`.\n"
+ "Examples: `[\"=\", [\"field\", 101], \"active\"]`, `[\"between\", [\"field\", 305], \"2024-01-01\", \"2024-12-31\"]`, "
+ "`[\"in\", [\"field\", 302], [10, 20, 30]]`, `[\"time-interval\", [\"field\", 305], -7, \"day\"]`.\n"
+ "\n"
+ "## Aggregation operators\n"
+ "`count`, `sum`, `avg`, `min`, `max`, `distinct`, `median`, `stddev`, `var`, `percentile`, "
+ "`count-where`, `sum-where`, `distinct-where`, `share`, `cum-count`, `cum-sum`. "
+ "Examples: `[\"count\"]`, `[\"sum\", [\"field\", 302]]`, `[\"count-where\", [\"=\", [\"field\", 101], \"completed\"]]`.\n"
+ "\n"
+ "## Temporal helpers (for use in `expression` or as grouping)\n"
+ "`get-year`, `get-quarter`, `get-month`, `get-week`, `get-day`, `get-day-of-week`, `get-hour`, `get-minute`, "
+ "`datetime-add`, `datetime-diff`, `datetime-subtract`, `now`, `today`, `relative-datetime`, `absolute-datetime`, "
+ "`with-temporal-bucket`, `convert-timezone`.\n"
+ "\n"
+ "## Examples\n"
+ "Top 5 customers by revenue:\n"
+ "```\n"
+ "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
+ " \"operations\": [[\"aggregate\", [\"sum\", [\"field\", 302]]],\n"
+ " [\"breakout\", [\"field\", 101]],\n"
+ " [\"order-by\", [\"aggregation-ref\", 0], \"desc\"],\n"
+ " [\"limit\", 5]]}\n"
+ "```\n"
+ "Monthly revenue from a metric (metric supplies the aggregation):\n"
+ "```\n"
+ "{\"source\": {\"type\": \"metric\", \"id\": 10},\n"
+ " \"operations\": [[\"breakout\", [\"with-temporal-bucket\", [\"field\", 305], \"month\"]],\n"
+ " [\"order-by\", [\"with-temporal-bucket\", [\"field\", 305], \"month\"], \"asc\"]]}\n"
+ "```\n"
+ "Filter on an aggregated value (requires `append-stage`):\n"
+ "```\n"
+ "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
+ " \"operations\": [[\"aggregate\", [\"sum\", [\"field\", 302]]],\n"
+ " [\"breakout\", [\"field\", 101]],\n"
+ " [\"append-stage\"],\n"
+ " [\"filter\", [\">\", [\"aggregation-ref\", 0], 1000]]]}\n"
+ "```\n"
+ "Named expression referenced later:\n"
+ "```\n"
+ "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
+ " \"operations\": [[\"expression\", \"Discount\", [\"-\", [\"field\", 302], [\"field\", 303]]],\n"
+ " [\"aggregate\", [\"sum\", [\"expression-ref\", \"Discount\"]]]]}\n"
+ "```\n"
+ "Previous-period comparison with `offset` (stay in the SAME stage — do NOT add `append-stage`):\n"
+ "```\n"
+ "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
+ " \"operations\": [[\"aggregate\", [\"sum\", [\"field\", 302]]],\n"
+ " [\"aggregate\", [\"offset\", [\"sum\", [\"field\", 302]], -1]],\n"
+ " [\"breakout\", [\"with-temporal-bucket\", [\"field\", 305], \"month\"]]]}\n"
+ "```\n"
+ "\n"
+ "## Rules & common pitfalls\n"
+ "Stage boundaries (most common source of errors):\n"
+ "- Filtering on an aggregated value REQUIRES `append-stage` between the aggregate/breakout and the filter "
+ "(see the \"filter on aggregated value\" example). Without it, `aggregation-ref` resolution fails in the same stage.\n"
+ "- Defining an `expression` that uses `aggregation-ref` also REQUIRES `append-stage` first.\n"
+ "- EXCEPTION: `offset` (previous-period comparison) stays in the same stage as its base aggregation and breakout — do NOT add `append-stage` for it.\n"
+ "\n"
+ "Refs & shapes:\n"
+ "- Aggregation helpers take field refs, not bare IDs: `[\"sum\", [\"field\", 201]]`, never `[\"sum\", 201]`.\n"
+ "- To sort by an aggregated value, use `[\"aggregation-ref\", N]` — not the original expression.\n"
+ "- Do NOT put options in a third slot of `field` (no `[\"field\", id, {...}]`). Wrap instead: `[\"with-temporal-bucket\", [\"field\", id], \"month\"]` or `[\"with-binning\", [\"field\", id], {...}]`.\n"
+ "- `case` takes `[[condition, value], ...]` branches and an optional bare fallback as the THIRD arg — do not wrap it as `{\"default\": ...}`. Omit the third arg when there is no fallback.\n"
+ "- JSON objects appear only where a helper explicitly calls for one (e.g. `with-page`, `with-binning`). Everywhere else, use operator tuples.\n"
+ "\n"
+ "Joins & related tables:\n"
+ "- If the source table's detail response already surfaces a related table's fields, use those field refs directly — no explicit join needed.\n"
+ "- Reach for `join` + `with-join-conditions` only for custom aliases, self-joins, explicit joined-field selection, or when direct related-field refs are unavailable.\n"
+ "- If an explicit join returns a permission error, the underlying table is not accessible — surface the error, do not retry with implicit refs.\n"
+ "\n"
+ "Metrics & dates:\n"
+ "- A `metric` source already provides its own aggregation and time dimension. Add only the additional breakouts/filters you need.\n"
+ "- When the user asks for an exact year (e.g. 2024), use `[\"=\", [\"field\", year_field], 2024]` or a `between` with explicit dates — not relative filters like `time-interval`.\n"))
+
(defn- evaluate-program-to-live-query
"Resolve a program's source entity, evaluate the program via agent-lib, and return
the live lib query (with lib metadata attached)."
@@ -396,22 +559,21 @@
"Construct an MBQL query from a structured agent-lib program.
The body is the program itself: a JSON object with `source` (identifying the
- table/card/dataset/metric to query) and `operations` (an array of operator
- tuples). Returns a base64-encoded MBQL query that can be executed via
- /v1/execute. See the agent_api reference for the full program syntax."
+ table/card/dataset/metric to query), `operations` (an array of operator
+ tuples), and `prompt` (the user's original request). Returns a base64-encoded
+ MBQL query that can be executed via /v1/execute. See the agent_api reference
+ for the full program syntax."
{:scope metabot/agent-query-construct
:tool {:name "construct_query"
- :description (str "Construct a Metabase query from a structured program with `source` and "
- "`operations`. Returns an opaque query string for execute_query. "
- "See the `metabase://docs/construct-query.md` resource for the full "
- "program syntax (sources, operations, operator forms, worked examples, "
- "and pitfalls).")
+ :description construct-query-tool-description
:annotations {:read-only? true :idempotent? true}}}
[_route-params
_query-params
- program :- ::program-request]
- (let [query (evaluate-program-for-execution program)]
- {:query (-> query json/encode u/encode-base64)}))
+ {:keys [prompt] :as request} :- ::construct-query-request]
+ (let [program (dissoc request :prompt)
+ query (evaluate-program-for-execution program)]
+ (cond-> {:query (-> query json/encode u/encode-base64)}
+ prompt (assoc :prompt prompt))))
;;; ------------------------------------------------- Combined Query -------------------------------------------------
@@ -595,7 +757,11 @@
Standard userspace query limits are enforced (2000 rows for simple queries, 10000 for aggregated)."
{:scope metabot/agent-query-execute
:tool {:name "execute_query"
- :description "Execute a previously constructed query and return the results with column metadata, row count, and execution time."
+ :description (str "Execute a previously constructed query and return raw results with column metadata, "
+ "row count, and execution time. Use this when the user explicitly asks for raw data, "
+ "rows, columns, counts, metadata, or programmatic query results. If the user asks to "
+ "show, display, visualize, plot, chart, or present the result, use visualize_query "
+ "instead.")
:annotations {:read-only? true :idempotent? true}}}
[_route-params
_query-params
diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.clj
index 8a4e86f699a..28c8d2b85f5 100644
--- a/src/metabase/api_routes/routes.clj
+++ b/src/metabase/api_routes/routes.clj
@@ -33,6 +33,7 @@
[metabase.logger.api]
[metabase.login-history.api]
[metabase.mcp.api]
+ [metabase.mcp.callback-api]
[metabase.measures.api]
[metabase.metabot.api]
[metabase.metabot.api.entity-analysis]
@@ -94,6 +95,7 @@
metabase.logger.api/keep-me
metabase.login-history.api/keep-me
metabase.mcp.api/keep-me
+ metabase.mcp.callback-api/keep-me
metabase.measures.api/keep-me
metabase.metrics.api/keep-me
metabase.model-persistence.api/keep-me
@@ -179,6 +181,7 @@
"/eid-translation" (+auth 'metabase.eid-translation.api)
"/email" metabase.channel.api/email-routes
"/embed" (+message-only-exceptions metabase.embedding-rest.api/embedding-routes)
+ "/embed-mcp" (+auth metabase.mcp.callback-api/routes)
"/embed-theme" (+auth metabase.embedding-rest.api/theme-routes)
"/field" (+auth metabase.warehouse-schema-rest.api/field-routes)
"/frontend-errors" metabase.frontend-errors.api/routes
diff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.md
index 416a4ccc239..1b282369073 100644
--- a/src/metabase/mcp/README.md
+++ b/src/metabase/mcp/README.md
@@ -49,14 +49,14 @@ Browser-based sessions (cookie auth) are also supported and receive unrestricted
Access tokens are scoped to limit what tools a client can use:
-| Scope | Grants access to |
-|--------------------------|-----------------------------------------------|
-| `agent:table:read` | `get_table`, `get_table_field_values` |
-| `agent:metric:read` | `get_metric`, `get_metric_field_values` |
-| `agent:search` | `search` |
-| `agent:query:construct` | `construct_query` |
-| `agent:query` | `query` |
-| `agent:query:execute` | `execute_query` |
+| Scope | Grants access to |
+| ----------------------- | --------------------------------------- |
+| `agent:table:read` | `get_table`, `get_table_field_values` |
+| `agent:metric:read` | `get_metric`, `get_metric_field_values` |
+| `agent:search` | `search` |
+| `agent:query:construct` | `construct_query` |
+| `agent:query` | `query` |
+| `agent:query:execute` | `execute_query` |
Wildcard patterns (e.g. `agent:*`) match any scope with that prefix.
@@ -72,16 +72,16 @@ By default our consent screen grants access to all scopes without the opportunit
The MCP server exposes these tools, dynamically generated from the Agent API endpoint metadata:
-| Tool | Description |
-|------|-------------|
-| `search` | Search for tables and metrics using keyword or natural language search. |
-| `get_table` | Get details about a table including its fields, related tables, and metrics. |
-| `get_table_field_values` | Get sample values and statistics for a field in a table. |
-| `get_metric` | Get details about a metric including its queryable dimensions. |
-| `get_metric_field_values` | Get sample values and statistics for a field in a metric. |
-| `construct_query` | Construct a query against a table or metric. Returns an opaque query string for use with `execute_query`. |
-| `execute_query` | Execute a previously constructed query and return results with column metadata. |
-| `query` | Query a table or metric directly. Supports pagination via continuation tokens. |
+| Tool | Description |
+| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `search` | Search for tables and metrics using keyword or natural language search. |
+| `get_table` | Get details about a table including its fields, related tables, and metrics. |
+| `get_table_field_values` | Get sample values and statistics for a field in a table. |
+| `get_metric` | Get details about a metric including its queryable dimensions. |
+| `get_metric_field_values` | Get sample values and statistics for a field in a metric. |
+| `construct_query` | Construct a query against a table or metric. Accepts the user's original `prompt` when available. Returns an opaque `query_handle` for use with `execute_query` or `visualize_query`. |
+| `execute_query` | Execute a previously constructed query and return results with column metadata. |
+| `query` | Query a table or metric directly. Supports pagination via continuation tokens. |
Query results are limited to 200 rows per request. When more rows are available, the response includes a
`continuation_token` that can be passed back to fetch the next page.
@@ -91,21 +91,21 @@ Query results are limited to 200 rows per request. When more rows are available,
The server exposes MCP [resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources) so
clients can fetch supplementary content by URI without inflating tool descriptions.
-| Resource URI | Description |
-|---|---|
+| Resource URI | Description |
+| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| `metabase://docs/construct-query.md` | Program syntax for `construct_query` and `query` — sources, operations, operator forms, worked examples, pitfalls. |
## Supported JSON-RPC methods
-| Method | Description |
-|--------|-------------|
-| `initialize` | Initialize the MCP connection. Returns server capabilities and a session ID. |
-| `notifications/initialized` | Client notification that initialization is complete. |
-| `tools/list` | List available tools (filtered by the token's scopes). |
-| `tools/call` | Call a tool with arguments. |
-| `resources/list` | List available resources (filtered by the token's scopes). |
-| `resources/read` | Read a resource by URI. Requires an initialized session. |
-| `ping` | Keepalive ping. |
+| Method | Description |
+| --------------------------- | ---------------------------------------------------------------------------- |
+| `initialize` | Initialize the MCP connection. Returns server capabilities and a session ID. |
+| `notifications/initialized` | Client notification that initialization is complete. |
+| `tools/list` | List available tools (filtered by the token's scopes). |
+| `tools/call` | Call a tool with arguments. |
+| `resources/list` | List available resources (filtered by the token's scopes). |
+| `resources/read` | Read a resource by URI. Requires an initialized session. |
+| `ping` | Keepalive ping. |
Requests can be sent individually or as a JSON-RPC batch. The server responds with JSON or SSE depending on the
`Accept` header.
diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.clj
index a796b322626..ddb71d6c12f 100644
--- a/src/metabase/mcp/api.clj
+++ b/src/metabase/mcp/api.clj
@@ -10,6 +10,7 @@
[metabase.api.macros.scope :as scope]
[metabase.api.open-api :as open-api]
[metabase.mcp.resources :as mcp.resources]
+ [metabase.mcp.session :as mcp.session]
[metabase.mcp.tools :as mcp.tools]
[metabase.mcp.validation :as mcp.validation]
[metabase.oauth-server.core :as oauth-server]
@@ -23,21 +24,10 @@
(:import
(java.io BufferedWriter OutputStreamWriter)
(java.net URI)
- (java.nio.charset StandardCharsets)
- (java.util UUID)))
+ (java.nio.charset StandardCharsets)))
(set! *warn-on-reflection* true)
-;;; --------------------------------------------------- Sessions ----------------------------------------------------
-
-(defn- create-session!
- "Generate an MCP session ID for protocol compatibility.
- The server currently treats MCP sessions as degenerate: callers must still
- send a session ID after `initialize`, but the ID is not otherwise required
- for auth, initialization state, or server-side validation."
- [_user-id]
- (str (UUID/randomUUID)))
-
;;; -------------------------------------------------- Auth --------------------------------------------------------
(defn- validate-bearer-token
@@ -81,48 +71,47 @@
(defn- handle-tools-list [id _params token-scopes]
(jsonrpc-response id {:tools (mcp.tools/list-tools token-scopes)}))
-(defn- handle-tools-call [id params token-scopes]
+(defn- handle-tools-call [id params session-id token-scopes]
(let [tool-name (:name params)
arguments (or (:arguments params) {})]
- (jsonrpc-response id (mcp.tools/call-tool token-scopes tool-name arguments))))
+ (jsonrpc-response id (mcp.tools/call-tool token-scopes session-id tool-name arguments))))
(defn- handle-resources-list [id _params token-scopes]
(jsonrpc-response id (mcp.resources/list-resources token-scopes)))
-(defn- handle-resources-read [id params token-scopes]
+(defn- handle-resources-read [id params session-id token-scopes]
(let [uri (:uri params)]
(if (or (not (string? uri)) (str/blank? uri))
(jsonrpc-error id -32602 "Missing required parameter: uri")
- (let [{:keys [status contents]} (mcp.resources/read-resource uri token-scopes {})]
- ;; :not-found and :scope-denied collapse to the same generic error so we
- ;; don't leak resource existence to callers without scope.
- (case status
+ (let [user-id api/*current-user-id*
+ session-key (when user-id (mcp.session/get-or-create-session-key! session-id user-id))
+ options {:session-key session-key
+ :session-id session-id}
+ result (mcp.resources/read-resource uri token-scopes options)]
+ (case (:status result)
(:not-found :scope-denied) (jsonrpc-error id -32602 "Resource not found")
- :ok (jsonrpc-response id {:contents contents}))))))
+ :ok (jsonrpc-response id {:contents (:contents result)}))))))
(defn- handle-ping [id _params]
(jsonrpc-response id {}))
(defn- dispatch-request
"Dispatch a single JSON-RPC request. Returns a response map or nil for notifications."
- [msg _session-id token-scopes]
- (let [id (:id msg)
- method (:method msg)
- params (:params msg)]
- (try
- (case method
- "notifications/initialized" nil
- "tools/list" (handle-tools-list id params token-scopes)
- "tools/call" (handle-tools-call id params token-scopes)
- "resources/list" (handle-resources-list id params 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))
- nil))
- (catch Throwable e
- (log/error e "Error dispatching JSON-RPC method" method)
- (jsonrpc-error id -32603 (or (ex-message e) "Internal error"))))))
+ [{:keys [id method params] :as _msg} session-id token-scopes]
+ (try
+ (case method
+ "notifications/initialized" nil
+ "tools/list" (handle-tools-list id params token-scopes)
+ "tools/call" (handle-tools-call id params session-id token-scopes)
+ "resources/list" (handle-resources-list id params token-scopes)
+ "resources/read" (handle-resources-read id params session-id token-scopes)
+ "ping" (handle-ping id params)
+ (if id
+ (jsonrpc-error id -32601 (str "Method not found: " method))
+ nil))
+ (catch Throwable e
+ (log/error e "Error dispatching JSON-RPC method" method)
+ (jsonrpc-error id -32603 (or (ex-message e) "Internal error")))))
;;; ----------------------------------------------------- SSE ------------------------------------------------------
@@ -135,7 +124,8 @@
(defn- sse-body
"Format a sequence of JSON-RPC messages as SSE event text."
[messages]
- (str/join (map #(str "event: message\ndata: " (json/encode %) "\n\n") messages)))
+ (str/join (for [message messages]
+ (str "event: message\ndata: " (json/encode message) "\n\n"))))
;;; -------------------------------------------------- Responses ---------------------------------------------------
@@ -174,22 +164,31 @@
(catch Exception _ false))
(json-response 403 (jsonrpc-error nil -32600 "Origin not allowed"))))))
-(defn- session-error-response
- "Return an HTTP error response when the MCP session header is missing, or nil if present.
- The session ID is compatibility-only and is not validated server-side."
- [session-id]
- (when (str/blank? session-id)
- (json-response 400 (jsonrpc-error nil -32600 "Missing Mcp-Session-Id header"))))
+(defn- require-valid-session
+ "Validate the Mcp-Session-Id header value. Checks UUID format and, when a
+ `core_session` has been materialized, verifies it belongs to `user-id`."
+ [user-id session-id]
+ (cond
+ (str/blank? session-id)
+ {:error (json-response 400 (jsonrpc-error nil -32600 "Missing Mcp-Session-Id header"))}
+
+ (not (mcp.session/valid-id? session-id))
+ {:error (json-response 404 (jsonrpc-error nil -32600 "Invalid or expired session"))}
+
+ (not (mcp.session/owned-by-user? session-id user-id))
+ {:error (json-response 404 (jsonrpc-error nil -32600 "Invalid or expired session"))}
+
+ :else
+ {:session-id session-id}))
;;; -------------------------------------------------- Handlers ---------------------------------------------------
(defn- handle-post
"Handle a POST request containing one or more JSON-RPC messages."
[user-id request]
- (let [body (:body request)
- session-id (get-in request [:headers "mcp-session-id"])
- batch? (sequential? body)
- session-err (delay (session-error-response session-id))]
+ (let [body (:body request)
+ session-id (get-in request [:headers "mcp-session-id"])
+ batch? (sequential? body)]
(cond
(nil? body)
(json-response 400 (jsonrpc-error nil -32700 "Parse error: empty body"))
@@ -207,40 +206,40 @@
;; Initialize: create session and return response with session header
(and (not batch?) (= "initialize" (:method body)))
- (let [session-id (create-session! user-id)
+ (let [session-id (mcp.session/create! user-id)
init-response (handle-initialize (:id body) (:params body))]
(if (accepts-sse? request)
(sse-response [init-response] {"Mcp-Session-Id" session-id})
(json-response 200 init-response {"Mcp-Session-Id" session-id})))
- ;; All other requests require a valid session (400 for missing header, 404 for invalid)
- (some? @session-err) @session-err
-
+ ;; All other requests require a valid session
:else
- (let [messages (if batch? body [body])
- results (mapv #(dispatch-request % session-id (:token-scopes request)) messages)
- responses (filterv some? results)]
- (cond
- (empty? responses)
- {:status 202 :headers {} :body ""}
+ (let [{:keys [error]} (require-valid-session user-id session-id)]
+ (if error
+ error
+ (let [messages (if batch? body [body])
+ responses (into [] (keep #(dispatch-request % session-id (:token-scopes request))) messages)]
+ (cond
+ (empty? responses)
+ {:status 202 :headers {} :body ""}
- (accepts-sse? request)
- (sse-response responses)
+ (accepts-sse? request)
+ (sse-response responses)
- (and (not batch?) (= 1 (count responses)))
- (json-response 200 (first responses))
+ (and (not batch?) (= 1 (count responses)))
+ (json-response 200 (first responses))
- :else
- (json-response 200 responses))))))
+ :else
+ (json-response 200 responses))))))))
(defn- handle-get
"Handle a GET request for SSE stream (keepalive for server-initiated notifications)."
- [_user-id request respond raise]
+ [user-id request respond raise]
(let [session-id (get-in request [:headers "mcp-session-id"])
- session-err (session-error-response session-id)]
+ {:keys [error]} (require-valid-session user-id session-id)]
(cond
- (some? session-err)
- (respond session-err)
+ (some? error)
+ (respond error)
:else
(let [resp (streaming-response/streaming-response
@@ -259,11 +258,12 @@
(defn- handle-delete
"Handle a DELETE request to tear down a session."
- [_user-id request]
- (let [session-id (get-in request [:headers "mcp-session-id"])
- session-err (session-error-response session-id)]
- (or session-err
- {:status 200 :headers {"Content-Type" "application/json"} :body ""})))
+ [user-id request]
+ (let [session-id-header (get-in request [:headers "mcp-session-id"])
+ {:keys [session-id error]} (require-valid-session user-id session-id-header)]
+ (or error
+ (do (mcp.session/delete! session-id user-id)
+ {:status 200 :headers {"Content-Type" "application/json"} :body ""}))))
;;; -------------------------------------------------- Throttling --------------------------------------------------
@@ -303,19 +303,26 @@
Uses JSON-RPC 2.0 over HTTP rather than REST, so the OpenAPI spec is empty."
(open-api/handler-with-open-api-spec
(fn [request respond raise]
- (let [origin-error (validate-origin request)
- bearer-token (oauth-server/extract-bearer-token request)
- session-auth api/*current-user-id*]
+ (let [origin-error (validate-origin request)
+ bearer-token (oauth-server/extract-bearer-token request)
+ session-auth api/*current-user-id*]
(letfn [(dispatch [user-id token-scopes]
(request/with-current-user user-id
(if-let [throttle-err (check-throttle user-id)]
(respond throttle-err)
(try
(let [request (assoc request :token-scopes token-scopes)]
- (case (:request-method request)
- :post (respond (handle-post user-id request))
- :get (handle-get user-id request respond raise)
- :delete (respond (handle-delete user-id request))
+ (cond
+ (= :post (:request-method request))
+ (respond (handle-post user-id request))
+
+ (= :get (:request-method request))
+ (handle-get user-id request respond raise)
+
+ (= :delete (:request-method request))
+ (respond (handle-delete user-id request))
+
+ :else
(respond (json-response 405 (jsonrpc-error nil -32600 "Method not allowed")))))
(catch Throwable e
(raise e))))))]
diff --git a/src/metabase/mcp/callback_api.clj b/src/metabase/mcp/callback_api.clj
new file mode 100644
index 00000000000..ee5655fd876
--- /dev/null
+++ b/src/metabase/mcp/callback_api.clj
@@ -0,0 +1,96 @@
+(ns metabase.mcp.callback-api
+ "Iframe-callback endpoints for the embedded MCP UI. The MCP iframe POSTs here to
+ stash query payloads server-side so the agent never has to carry them in the
+ model context — it just receives a handle UUID it can pass to the corresponding
+ MCP tool. Mounted as a sibling of `/api/mcp` so the JSON-RPC handler doesn't
+ have to special-case non-protocol routes."
+ (:require
+ [clojure.string :as str]
+ [metabase.agent-api.api :as agent-api]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.mcp.session :as mcp.session]
+ [metabase.mcp.validation :as mcp.validation]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.log :as log]
+ [metabase.util.malli.schema :as ms]))
+
+(defn- mcp-session-id-from-headers
+ [request]
+ (get-in request [:headers "mcp-session-id"]))
+
+(defn- check-session-header!
+ "Validate the `Mcp-Session-Id` header against `user-id`. Throws an api/check
+ exception on failure so defendpoint surfaces the right status code."
+ [session-id user-id]
+ (api/check (not (str/blank? session-id))
+ [400 (tru "Missing Mcp-Session-Id header")])
+ (api/check (mcp.session/valid-id? session-id)
+ [404 (tru "Invalid or expired session")])
+ (api/check (mcp.session/owned-by-user? session-id user-id)
+ [404 (tru "Invalid or expired session")]))
+
+(def ^:private feedback-text-max-length
+ 10000)
+
+(def ^:private OptionalFeedbackText
+ [:maybe [:string {:max feedback-text-max-length}]])
+
+(defn- rethrow-api-check-exception
+ [e]
+ (when (:status-code (ex-data e))
+ (throw e)))
+
+(defn- submit-mcp-feedback!
+ [body]
+ (let [submitted? (try
+ (agent-api/submit-mcp-visualization-feedback! body)
+ (catch clojure.lang.ExceptionInfo e
+ (rethrow-api-check-exception e)
+ (log/error e "Failed to submit MCP feedback to Harbormaster")
+ (api/check false [502 (tru "Could not submit feedback.")]))
+ (catch Exception e
+ (log/error e "Failed to submit MCP feedback to Harbormaster")
+ (api/check false [502 (tru "Could not submit feedback.")])))]
+ (api/check-400 submitted?
+ (tru "Cannot submit feedback. The license token and/or Store API URL are missing!"))))
+
+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
+(api.macros/defendpoint :post "/drills"
+ "Stash a base64-encoded MBQL query for the iframe's pending drill-through and
+ return a handle UUID the iframe will thread into the agent message so the
+ `render_drill_through` tool can fetch it."
+ [_route-params
+ _query-params
+ {:keys [encodedQuery]} :- [:map [:encodedQuery ms/NonBlankString]]
+ request]
+ (let [session-id (mcp-session-id-from-headers request)]
+ (check-session-header! session-id api/*current-user-id*)
+ {:handle (mcp.session/store-handle! session-id api/*current-user-id* encodedQuery)}))
+
+(api.macros/defendpoint :post "/feedback" :- [:map
+ [:status [:= 204]]
+ [:body :nil]]
+ "Proxy MCP Apps visualization feedback to Harbormaster."
+ [_route-params
+ _query-params
+ body :- [:map
+ [:feedback [:map
+ [:message_id ms/NonBlankString]
+ [:positive :boolean]
+ [:issue_type {:optional true} [:maybe :string]]
+ [:freeform_feedback {:optional true} OptionalFeedbackText]]]
+ [:conversation_data [:map
+ [:source [:= "mcp"]]
+ [:prompt {:optional true} OptionalFeedbackText]
+ [:query {:optional true} OptionalFeedbackText]]]]
+ request]
+ (let [session-id (mcp-session-id-from-headers request)
+ _ (check-session-header! session-id api/*current-user-id*)]
+ (submit-mcp-feedback! body))
+ api/generic-204-no-content)
+
+(def ^{:arglists '([request respond raise])} routes
+ "Iframe-callback routes mounted at `/api/embed-mcp`. MCP-feature gated; auth is
+ handled by the upstream `+auth` middleware in api-routes."
+ (mcp.validation/+mcp-enabled (api.macros/ns-handler *ns*)))
diff --git a/src/metabase/mcp/core.clj b/src/metabase/mcp/core.clj
index a2a1642de32..8294a190b81 100644
--- a/src/metabase/mcp/core.clj
+++ b/src/metabase/mcp/core.clj
@@ -3,8 +3,12 @@
rather than reaching into internal namespaces like [[metabase.mcp.settings]]."
(:require
[clojure.string :as str]
+ [metabase.api.macros :as api.macros]
+ [metabase.mcp.resources :as mcp.resources]
[metabase.mcp.settings :as mcp.settings]))
+(set! *warn-on-reflection* true)
+
(defn cors-origins
"Returns space-separated CORS origins from both common and custom MCP client settings."
[]
@@ -23,3 +27,12 @@
(condp #(str/starts-with? %2 %1) raw-origin
"vscode-webview://" (vscode-webview-enabled?)
false)))
+
+(defn all-scopes
+ "All supported OAuth scopes: those declared on agent-api endpoints via
+ defendpoint metadata, plus scopes from MCP UI resources (e.g. visualize_query)."
+ []
+ (into (mcp.resources/resource-scopes)
+ (comp (keep #(get-in % [:form :metadata :scope]))
+ (filter string?))
+ (vals (api.macros/ns-routes 'metabase.agent-api.api))))
diff --git a/src/metabase/mcp/models/mcp_query_handle.clj b/src/metabase/mcp/models/mcp_query_handle.clj
new file mode 100644
index 00000000000..e120be10f92
--- /dev/null
+++ b/src/metabase/mcp/models/mcp_query_handle.clj
@@ -0,0 +1,10 @@
+(ns metabase.mcp.models.mcp-query-handle
+ (:require
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/McpQueryHandle [_model] :mcp_query_handle)
+
+(doto :model/McpQueryHandle
+ (derive :metabase/model)
+ (derive :hook/created-at-timestamped?))
diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.clj
index 34e6323956a..512a1e4e86e 100644
--- a/src/metabase/mcp/resources.clj
+++ b/src/metabase/mcp/resources.clj
@@ -1,6 +1,6 @@
(ns metabase.mcp.resources
"MCP resource registry. Resources let clients fetch supplementary content (docs,
- reference material) by URI without inflating tool descriptions.
+ reference material) and UI resources by URI without inflating tool descriptions.
Each entry in the registry is a map with `:uri`, `:name`, `:description`,
`:mimeType`, an optional `:scope`, and a `:render-fn` that returns the textual
@@ -11,12 +11,80 @@
(:require
[clojure.java.io :as io]
[metabase.mcp.scope :as mcp.scope]
- [metabase.util.malli :as mu]))
+ [metabase.mcp.session :as mcp.session]
+ [metabase.system.core :as system]
+ [metabase.util.json :as json]
+ [metabase.util.malli :as mu]
+ [stencil.core :as stencil]))
(set! *warn-on-reflection* true)
-;; Single map keyed by URI; `register-resource!` overwrites so REPL reload is idempotent.
-(defonce ^:private registry (atom (sorted-map)))
+(def ^:private embed-mcp-template-path "frontend_client/embed-mcp.html")
+
+;; The built template is emitted by HtmlWebpackPlugin into resources/frontend_client/
+;; during the frontend build. Backend-only test runs (e.g. CI app-db tests) don't produce
+;; it, so tests install a minimal inline template via `with-fallback-template`.
+(def ^:private test-fallback-template
+ (str "<!doctype html><html><body><script>"
+ "window.metabaseConfig = {"
+ "instanceUrl: {{{instanceUrl}}},"
+ "sessionToken: {{{sessionToken}}}"
+ "};</script></body></html>"))
+
+;; An atom rather than a dynamic var because `resources/read` is invoked from the
+;; HTTP handler thread, which doesn't inherit thread-local bindings from the test
+;; thread that installs the fallback.
+(defonce ^:private fallback-template (atom nil))
+
+(defn do-with-fallback-template
+ "Implementation detail of [[with-fallback-template]]."
+ [thunk]
+ (try
+ (reset! fallback-template test-fallback-template)
+ (thunk)
+ (finally
+ (reset! fallback-template nil))))
+
+(defmacro with-fallback-template
+ "Test-only: install an inline Mustache fallback for the embed-mcp template for
+ the duration of `body`. Backend-only test runs don't produce the built template,
+ so tests that exercise `resources/read` need this."
+ [& body]
+ `(do-with-fallback-template (fn [] ~@body)))
+
+(defn render-embed-mcp-template
+ "Render the embed-mcp.html Mustache template with the given vars map.
+ Expected keys: :instanceUrl (JSON-encoded), :instanceUrlRaw, :sessionToken (JSON-encoded or nil),
+ :mcpSessionId (JSON-encoded or nil)."
+ [vars]
+ (cond
+ (io/resource embed-mcp-template-path)
+ (stencil/render-file embed-mcp-template-path vars)
+
+ @fallback-template
+ (stencil/render-string @fallback-template vars)
+
+ :else
+ (throw (ex-info (str "Missing MCP embed template: " embed-mcp-template-path
+ ". Run the frontend build to produce it.")
+ {:path embed-mcp-template-path}))))
+
+;; The registry holds two indexes:
+;; `:uri->resource` — URI is unique, one resource (iframe) per URI
+;; `:tools` — keyed by tool name, which is also unique. Multiple tools may
+;; target the same resource via :_meta.ui.resourceUri (the iframe
+;; doesn't care which tool delivered the payload).
+;; Both maps overwrite on re-registration so REPL reload is idempotent.
+(defonce ^:private registry
+ (atom {:key->uri {}
+ :uri->resource (sorted-map)
+ :tools (sorted-map)}))
+
+(defn- ui-csp-meta []
+ (let [url (system/site-url)]
+ {:ui {:csp {:connectDomains [url]
+ :resourceDomains [url]
+ :frameDomains [url]}}}))
(mu/defn register-resource!
"Register an MCP resource. Overwrites any existing entry with the same `:uri`."
@@ -28,29 +96,80 @@
[:mimeType {:optional true} :string]
[:scope {:optional true} [:maybe :string]]]]
(let [resource (update resource :mimeType #(or % "text/markdown"))]
- (swap! registry assoc (:uri resource) resource)
+ (swap! registry assoc-in [:uri->resource (:uri resource)] resource)
resource))
+(mu/defn- register-ui-resource!
+ [key :- :keyword
+ uri :- :string
+ scope :- :string
+ resource :- [:map
+ [:name :string]
+ [:description :string]
+ [:render-fn fn?]]]
+ (let [resource (-> (assoc resource :uri uri :scope scope :ui? true)
+ (update :mimeType #(or % "text/html;profile=mcp-app")))]
+ (swap! registry #(-> %
+ (assoc-in [:key->uri key] uri)
+ (assoc-in [:uri->resource uri] resource)))
+ resource))
+
+(mu/defn- register-ui-tool!
+ [resource-key :- :keyword
+ tool :- [:map
+ [:name :string]
+ [:description :string]
+ [:inputSchema :map]
+ [:response-fn fn?]]]
+ (if-let [uri (get-in @registry [:key->uri resource-key])]
+ (let [scope (get-in @registry [:uri->resource uri :scope])
+ tool (assoc tool :scope scope :_meta {:ui {:resourceUri uri}})]
+ (swap! registry assoc-in [:tools (:name tool)] tool)
+ tool)
+ (throw (ex-info "Unknown resource" {:resource-key resource-key}))))
+
+(defn resource-scopes
+ "Return the distinct set of scopes registered across all UI resources."
+ []
+ (into (sorted-set) (keep :scope) (vals (:uri->resource @registry))))
+
+(defn list-ui-tools
+ "Return the list of MCP tools corresponding to UI components."
+ []
+ (vals (:tools @registry)))
+
(defn list-resources
"Return the MCP `resources/list` payload, filtered by `token-scopes`."
[token-scopes]
{:resources (into []
(comp (filter #(mcp.scope/public-or-matches? token-scopes (:scope %)))
- (map #(select-keys % [:uri :name :description :mimeType])))
- (vals @registry))})
+ (map (fn [resource]
+ (cond-> (select-keys resource [:uri :name :description :mimeType])
+ (:ui? resource) (assoc :_meta (ui-csp-meta))))))
+ (vals (:uri->resource @registry)))})
+
+(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 (mcp.scope/public-or-matches? token-scopes scope)
+ :ok
+ :scope-denied)
+ :not-found))
(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 — no race window where the registry could change between an access
- check and the read, and no way for direct callers to bypass the scope check."
+ render, so callers cannot bypass the scope check."
[uri token-scopes opts]
- (if-let [{:keys [render-fn scope] :as resource} (get @registry uri)]
+ (if-let [{:keys [render-fn scope ui?] :as resource} (get-in @registry [:uri->resource uri])]
(if (mcp.scope/public-or-matches? token-scopes scope)
{:status :ok
- :contents [(-> (select-keys resource [:uri :mimeType])
- (assoc :text (render-fn opts)))]}
+ :contents [(cond-> (select-keys resource [:uri :mimeType])
+ true (assoc :text (render-fn opts))
+ ui? (assoc :_meta (ui-csp-meta)))]}
{:status :scope-denied})
{:status :not-found}))
@@ -58,7 +177,7 @@
(defn classpath-text-resource
"Build a `:render-fn` that returns the contents of `path` on the classpath.
- Throws on registration if the file is missing — surfaces a clear error at boot
+ Throws on registration if the file is missing, surfacing a clear error at boot
rather than the first `resources/read` call."
[path]
(let [url (io/resource path)]
@@ -80,3 +199,83 @@
"ref shapes, joins, metric/date handling).")
:mimeType "text/markdown"
:render-fn (classpath-text-resource "metabase/agent_api/construct_query.md")})
+
+(register-ui-resource!
+ :visualize-query
+ "ui://metabase/visualize-query.html"
+ "agent:visualize"
+ {:name "Visualize Query"
+ :description "Interactive Metabase SDK visualization for a query"
+ :render-fn (fn [opts]
+ (let [site-url (system/site-url)
+ session-key (:session-key opts)
+ session-id (:session-id opts)]
+ (render-embed-mcp-template
+ {:instanceUrl (json/encode site-url)
+ :instanceUrlRaw site-url
+ :sessionToken (when session-key (json/encode session-key))
+ :mcpSessionId (when session-id (json/encode session-id))})))})
+
+(register-ui-tool!
+ :visualize-query
+ {:name "visualize_query"
+ :description (str "Visualize a previously constructed query as an interactive chart or table. "
+ "Use this for prompts that ask to show, display, visualize, plot, chart, "
+ "or present results, for example: `Show me customers in Metabase`, "
+ "`Show me orders by month`, `Display revenue by region`, or "
+ "`Visualize active users over time`. This renders the final answer in the UI. "
+ "Do not call execute_query after visualize_query; showing the visualization "
+ "is enough.")
+ ;; Both fields are optional rather than expressing "at least one of" via a top-level `anyOf`.
+ ;; This is because some MCP clients, e.g. the MCP inspector (mcpjam) rejects top-level combinators.
+ ;; The response-fn enforces the at-least-one contract at runtime.
+ :inputSchema {:type "object"
+ :properties {:query {:type "string" :minLength 1
+ :description "Base64-encoded MBQL query (use query_handle instead when available)"}
+ :query_handle {:type "string" :format "uuid"
+ :description "Handle returned by construct_query; preferred over raw query"}}}
+ :response-fn (fn [arguments {:keys [session-id]}]
+ (let [query (:query arguments)
+ handle (:query_handle arguments)
+ resolved (some->> handle (mcp.session/resolve-query-handle session-id))
+ encoded (or query (:encoded_query resolved))
+ prompt (:prompt resolved)]
+ (cond
+ (and (nil? query) (nil? handle))
+ {:content [{:type "text" :text "Provide either 'query' or 'query_handle'."}]
+ :isError true}
+
+ encoded
+ {:content [{:type "text" :text (str "Visualizing query in the interactive UI. "
+ "Do not call execute_query after this; "
+ "the visualization is the final result.")}]
+ ;; If visualize_query was called with a handle, use the stored prompt so the iframe can
+ ;; include the user's original request when submitting visualization feedback.
+ :structuredContent (cond-> {:query encoded}
+ prompt (assoc :prompt prompt))}
+
+ :else
+ {:content [{:type "text" :text "Query handle not found. Try running construct_query again."}]
+ :isError true})))})
+
+(register-ui-tool!
+ :visualize-query
+ {:name "render_drill_through"
+ :description (str "Render the drill-through visualization the user just navigated into. "
+ "Use this tool, not execute_query, when the user asks to show the result and "
+ "their message includes a `handle` UUID. This is the exact follow-up for the "
+ "phrase `Show me the result`. Do not execute the query yourself; pass the "
+ "`handle` UUID as the `handle` argument.")
+ :inputSchema {:type "object"
+ :properties {:handle {:type "string" :format "uuid"
+ :description "Handle UUID from the user's drill-through message."}}
+ :required ["handle"]}
+ :response-fn (fn [arguments {:keys [session-id]}]
+ (if-let [handle (:handle arguments)]
+ (if-let [encoded (mcp.session/read-handle session-id handle)]
+ {:content [{:type "text" :text "Rendering drill-through visualization..."}]
+ :structuredContent {:query encoded}}
+ {:content [{:type "text" :text "No drill-through found for that handle."}]
+ :isError true})
+ {:content [{:type "text" :text "No drill-through found for that handle."}]
+ :isError true}))})
diff --git a/src/metabase/mcp/scope.clj b/src/metabase/mcp/scope.clj
index 9bfed7ac00a..96728ae61d1 100644
--- a/src/metabase/mcp/scope.clj
+++ b/src/metabase/mcp/scope.clj
@@ -1,25 +1,24 @@
(ns metabase.mcp.scope
"Scope matching for MCP tools and resources.
- Wraps [[metabase.api-scope.core/scope-matches?]] with the conventions used by
+ Wraps [[metabase.api.macros.scope/scope-satisfied?]] with the conventions used by
MCP entry points: nil token-scopes (internal callers) and the `::scope/unrestricted`
sentinel (session auth or unscoped JWT) both bypass the check."
(:require
- [metabase.api-scope.core :as api-scope]
- [metabase.api.macros.scope :as scope]))
+ [metabase.api.macros.scope :as api.scope]))
(defn matches?
"Does `token-scopes` grant access to an entity with the given `required-scope`?
- nil `token-scopes` always matches (internal callers).
- - `::scope/unrestricted` in `token-scopes` always matches.
+ - `::api.scope/unrestricted` in `token-scopes` always 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-matches?]]."
+ - Otherwise delegates wildcard/exact matching to [[api.scope/scope-satisfied?]]."
[token-scopes required-scope]
(or (nil? token-scopes)
- (contains? token-scopes ::scope/unrestricted)
+ (contains? token-scopes ::api.scope/unrestricted)
(boolean (and (some? required-scope)
- (api-scope/scope-matches? token-scopes 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
new file mode 100644
index 00000000000..0ce762e9661
--- /dev/null
+++ b/src/metabase/mcp/session.clj
@@ -0,0 +1,203 @@
+(ns metabase.mcp.session
+ "Lightweight MCP session management.
+
+ An MCP session ID is just a random UUID handed out on `initialize` — no database
+ row is created. When a resource read needs an embedding session, we HMAC-derive a
+ separate session key from an instance-wide signing secret and lazily upsert a
+ `core_session` row keyed by its hash.
+
+ The derivation (rather than using the MCP session id directly as the session key)
+ is so that the id we put on the wire in the `Mcp-Session-Id` header is *not* itself
+ a live embedding session secret: capturing the header should not be enough to
+ impersonate the embedded SDK iframe. Any webserver can recompute the same derived
+ key on demand without any per-session plaintext sitting at rest.
+
+ MCP sessions themselves do not expire. The underlying `core_session` row has
+ its own TTL and will be reaped independently; if a subsequent resource read
+ finds it missing, `get-or-create-session-key!` will re-insert it."
+ (:require
+ [metabase.app-db.core :as app-db]
+ [metabase.mcp.models.mcp-query-handle]
+ [metabase.mcp.settings :as mcp.settings]
+ [metabase.session.core :as session]
+ [toucan2.core :as t2])
+ (:import
+ (java.nio ByteBuffer)
+ (java.util UUID)
+ (javax.crypto Mac)
+ (javax.crypto.spec SecretKeySpec)))
+
+(set! *warn-on-reflection* true)
+
+;;; ---------------------------------------------- Key Derivation -------------------------------------------------
+
+(defn- hmac-sha256
+ ^bytes [^String secret ^String message]
+ (let [mac (Mac/getInstance "HmacSHA256")]
+ (.init mac (SecretKeySpec. (.getBytes secret "UTF-8") "HmacSHA256"))
+ (.doFinal mac (.getBytes message "UTF-8"))))
+
+(defn derive-embedding-session-key
+ "Deterministically derive the embedding session key for `mcp-session-id` from the
+ instance-wide signing secret. See ns docstring for rationale.
+
+ The output is formatted as a UUID string because `metabase.server.middleware.session`
+ rejects non-UUID session keys up-front. Specifically we emit a version-8 UUID
+ (RFC 9562), which is the version reserved for \"custom / vendor-defined\"
+ constructions — i.e. exactly our case: 128 bits produced by our own HMAC-SHA256
+ derivation rather than by the standard v1/v3/v4/v5 algorithms. v4 would lie
+ about randomness, v5 would lie about the hash algorithm; v8 is the only version
+ that's actually honest here.
+
+ Trade-offs to be aware of:
+ - Masking the variant (2 bits) and version (4 bits) costs 6 bits of entropy, so
+ we end up with 122 bits of randomness — identical to `UUID/randomUUID`, and
+ plenty for the ~2^61 birthday bound the rest of the session model already
+ relies on.
+ - Some older UUID inspection tools predate RFC 9562 and may render v8 as
+ \"unknown version\". `java.util.UUID/fromString` and our `valid-uuid?` are
+ format-only, so nothing in Metabase breaks.
+ - The output is deterministic in `mcp-session-id` and the signing secret. That's
+ intentional (so any webserver can recompute it) — don't treat two of these as
+ independently random just because they look like UUIDs."
+ [mcp-session-id]
+ (let [bytes (hmac-sha256 (mcp.settings/unobfuscated-mcp-embedding-signing-secret) mcp-session-id)
+ buf (ByteBuffer/wrap bytes)
+ ;; .getLong is stateful: each call consumes 8 bytes and advances the position,
+ ;; so `raw-high` reads bytes 0-7 and `raw-low` reads bytes 8-15.
+ raw-high (.getLong buf)
+ raw-low (.getLong buf)
+ ;; Force RFC 9562 v8 bits: version nibble = 1000, variant = 10.
+ high (bit-or (bit-and raw-high -61441) ; clear version nibble (bits 12-15 of high)
+ 0x0000000000008000) ; set version = 8
+ low (bit-or (bit-and raw-low 0x3fffffffffffffff) ; clear variant (top 2 bits of low)
+ (unchecked-long 0x8000000000000000))] ; set RFC 4122 variant (10)
+ (str (UUID. high low))))
+
+;;; -------------------------------------------------- Lifecycle --------------------------------------------------
+
+(defn valid-id?
+ "Return true if `session-id` looks like a UUID (the format `create!` produces).
+ Format check only — authentication is handled separately by cookie or bearer token,
+ not by the session ID itself."
+ [session-id]
+ (and (string? session-id)
+ (try (UUID/fromString session-id) true
+ (catch IllegalArgumentException _ false))))
+
+(defn create!
+ "Create a new MCP session. Returns a UUID string.
+ No database row is written — the session is just an opaque correlator until
+ a resource read materializes it into a `core_session`.
+
+ `user-id` is accepted but not persisted: since MCP sessions are currently
+ stateless (no server-side token store), we don't validate the user against
+ future requests. This parameter exists so we can add durable, user-scoped
+ sessions in the future without changing the call-site contract."
+ [_user-id]
+ (str (UUID/randomUUID)))
+
+(defn- get-or-create-embedding-session!
+ "Materialize and return the `core_session` row backing this MCP session.
+ Idempotent — repeated calls collapse to the same row in the common case."
+ [session-id user-id]
+ (let [session-key (derive-embedding-session-key session-id)
+ key-hashed (session/hash-session-key session-key)]
+ ;; Scoped to (key_hashed, user_id) so same-user races collapse to one row in the
+ ;; common case. A concurrent race can still produce duplicates (no DB constraint;
+ ;; see `select-or-insert!` docstring) but they're harmless — both rows belong to
+ ;; the right user, both satisfy lookups, both TTL-reap.
+ ;;
+ ;; Do NOT add a unique constraint to "fix" this. On key_hashed alone, a cross-user
+ ;; UUID collision would silently hand user B's row to user A. On (user_id,
+ ;; key_hashed), downstream auth lookups by key_hashed alone would pick one of the
+ ;; colliding rows arbitrarily. Cross-user UUID collisions are an unaddressed risk
+ ;; across the whole session model (cookie sessions included) — it belongs in the
+ ;; auth layer, not here, and no constraint shape at this call site can fix it.
+ ;;
+ ;; Raw :core_session (not :model/Session) to bypass the after-insert hook, which
+ ;; would publish spurious :event/user-login events.
+ (app-db/select-or-insert!
+ :core_session
+ {:key_hashed key-hashed
+ :user_id user-id}
+ (fn []
+ {:id (session/generate-session-id)
+ :anti_csrf_token nil
+ :created_at :%now}))))
+
+(defn get-or-create-session-key!
+ "Ensure a `core_session` exists for this MCP session and return its (plaintext)
+ session key, HMAC-derived from the MCP session id."
+ [session-id user-id]
+ (get-or-create-embedding-session! session-id user-id)
+ (derive-embedding-session-key session-id))
+
+(defn owned-by-user?
+ "Return true if no `core_session` has been materialized for this session yet
+ (i.e. no ownership to violate), or if the existing row belongs to `user-id`."
+ [session-id user-id]
+ (let [key-hashed (session/hash-session-key (derive-embedding-session-key session-id))
+ owner (t2/select-one-fn :user_id :core_session :key_hashed key-hashed)]
+ (or (nil? owner) (= owner user-id))))
+
+;;; -------------------------------------------- Query Handle Store -----------------------------------------------
+;; DB-backed store for base64-encoded MBQL query payloads referenced by MCP tool
+;; calls. Each row carries a fresh UUID handle that the iframe (drill-through) or
+;; agent (construct_query) passes through downstream so the LLM never carries the
+;; encoded query.
+
+(defn store-handle!
+ "Insert a new handle row binding `encoded-query` to the MCP session, and return
+ the freshly minted handle UUID.
+
+ When `user-id` is non-nil, materializes the backing `core_session` so cleanup
+ happens via cascade when the session row is reaped. When nil — e.g. agent flows
+ that don't render an iframe — the row is stored without a `core_session_id` and
+ relies on explicit `delete!` for cleanup.
+
+ `prompt` is optional, but should be supplied for construct_query handles so
+ visualize_query can later return both the query and original user prompt to
+ the MCP iframe for feedback submission."
+ ([session-id user-id encoded-query]
+ (store-handle! session-id user-id encoded-query nil))
+ ([session-id user-id encoded-query prompt]
+ (let [core-session-id (when user-id
+ (:id (get-or-create-embedding-session! session-id user-id)))
+ handle-id (str (UUID/randomUUID))]
+ (t2/insert! :model/McpQueryHandle
+ (cond-> {:id handle-id
+ :mcp_session_id session-id
+ :core_session_id core-session-id
+ :encoded_query encoded-query}
+ prompt (assoc :prompt prompt)))
+ handle-id)))
+
+(defn read-handle
+ "Return the encoded query for `handle-id` in `session-id`, or nil if no row exists."
+ [session-id handle-id]
+ (t2/select-one-fn :encoded_query :model/McpQueryHandle :id handle-id, :mcp_session_id session-id))
+
+(defn resolve-query-handle
+ "Return {:encoded_query ... :prompt ...} for `handle-id`, or nil if not found.
+ Used by visualize_query and execute_query to resolve construct_query handles."
+ [session-id handle-id]
+ (when-let [row (t2/select-one :model/McpQueryHandle :id handle-id, :mcp_session_id session-id)]
+ (select-keys row [:encoded_query :prompt])))
+
+(defn delete!
+ "Delete the `core_session` backing this MCP session (if one was ever created)
+ and any associated query handles. Scoped to `user-id` so that one user cannot
+ delete another user's session.
+
+ Handles tied to a `core_session` are also reaped by the FK cascade when the
+ session row goes; the explicit handle-delete here covers handles whose
+ `core_session_id` was never set — e.g. handles for regular query payloads that
+ aren't backed by an MCP iframe and so never materialize a `core_session`."
+ [session-id user-id]
+ (let [key-hashed (session/hash-session-key (derive-embedding-session-key session-id))]
+ (t2/query {:delete-from :core_session
+ :where [:and
+ [:= :key_hashed key-hashed]
+ [:= :user_id user-id]]})
+ (t2/delete! :model/McpQueryHandle :mcp_session_id session-id)))
diff --git a/src/metabase/mcp/settings.clj b/src/metabase/mcp/settings.clj
index c147628115c..9e4941b3f35 100644
--- a/src/metabase/mcp/settings.clj
+++ b/src/metabase/mcp/settings.clj
@@ -1,10 +1,37 @@
(ns metabase.mcp.settings
- "Settings for MCP Apps CORS origins."
+ "Settings for MCP Apps CORS origins and MCP session key derivation."
(:require
[clojure.string :as str]
[metabase.llm.settings :as llm.settings]
[metabase.settings.core :as setting :refer [defsetting]]
- [metabase.util.i18n :refer [deferred-tru]]))
+ [metabase.util.i18n :refer [deferred-tru]]
+ [metabase.util.string :as u.str]))
+
+;; NOTE: uuid-nonce-base sets :setter :none, so this secret is not rotatable via the normal settings API.
+;; If rotation is needed (e.g. after a DB breach), an admin action should regenerate the secret and
+;; invalidate existing MCP-backed core_session rows. See also: premium-embedding-token-signing-key.
+;;
+;; The getter is obfuscated so that the raw secret can never leak via settings APIs, the admin UI,
+;; logs, or audit events — only a masked form is exposed. Internal callers that actually need to
+;; HMAC with the secret must use `unobfuscated-mcp-embedding-signing-secret`.
+(defsetting mcp-embedding-signing-secret
+ (deferred-tru "Instance-wide secret used to derive embedding session keys for MCP sessions.")
+ :encryption :when-encryption-key-set
+ :visibility :internal
+ :sensitive? true
+ :base setting/uuid-nonce-base
+ :export? false
+ :audit :no-value
+ :doc false
+ :getter (fn []
+ (-> (setting/get-value-of-type :string :mcp-embedding-signing-secret)
+ (u.str/mask 4))))
+
+(defn unobfuscated-mcp-embedding-signing-secret
+ "Get the unobfuscated value of [[mcp-embedding-signing-secret]]. Callers must only
+ use this for in-process key derivation, never to expose the secret externally."
+ []
+ (setting/get-value-of-type :string :mcp-embedding-signing-secret))
;;; ------------------------------------------------ Client → Domain Mapping --------------------------------
diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.clj
index 6ec7691b8d2..0e9071a499e 100644
--- a/src/metabase/mcp/tools.clj
+++ b/src/metabase/mcp/tools.clj
@@ -8,10 +8,13 @@
[metabase.api.common :as api]
[metabase.api.macros.defendpoint.tools-manifest :as tools-manifest]
[metabase.config.core :as config]
+ [metabase.mcp.resources :as mcp.resources]
[metabase.mcp.scope :as mcp.scope]
+ [metabase.mcp.session :as mcp.session]
[metabase.server.streaming-response :as streaming-response]
[metabase.util :as u]
- [metabase.util.json :as json])
+ [metabase.util.json :as json]
+ [metabase.util.log :as log])
(:import
(java.io ByteArrayOutputStream)
(java.net URLEncoder)
@@ -43,12 +46,8 @@
(into []
(comp (filter #(mcp.scope/matches? token-scopes (:scope %)))
(map (fn [tool]
- (cond-> {:name (:name tool)
- :title (:title tool)
- :description (:description tool)
- :inputSchema (:inputSchema tool)}
- (:annotations tool) (assoc :annotations (:annotations tool))))))
- tools)))
+ (select-keys tool [:name :title :description :inputSchema :annotations :_meta]))))
+ (concat tools (mcp.resources/list-ui-tools)))))
(defn- build-tool-index
"Build name->tool lookup from manifest tools."
@@ -102,6 +101,46 @@
body-str body-str
:else (str "Agent API error: " (:status response)))))
+;;; ------------------------------------------- Query Handle Transforms -------------------------------------------
+
+(defn- resolve-query-arg
+ "Resolve the query argument for tools that accept a handle.
+ If :query_handle is present, look it up and replace with :query.
+ If :query is itself a UUID (the LLM passed the handle in the wrong field), resolve
+ it too — but log a warning so we can track how often this antipattern fires.
+ Returns updated arguments, or ::handle-not-found if the handle doesn't exist."
+ [session-id tool-name arguments]
+ (cond
+ (:query_handle arguments)
+ (if-let [{:keys [encoded_query]} (mcp.session/resolve-query-handle session-id (:query_handle arguments))]
+ (-> arguments (dissoc :query_handle) (assoc :query encoded_query))
+ ::handle-not-found)
+
+ (mcp.session/valid-id? (:query arguments))
+ (do (log/warnf "MCP tool %s: agent passed a UUID handle in :query; resolving as :query_handle"
+ tool-name)
+ (if-let [{:keys [encoded_query]} (mcp.session/resolve-query-handle session-id (:query arguments))]
+ (assoc arguments :query encoded_query)
+ ::handle-not-found))
+
+ :else
+ arguments))
+
+(defn- make-store-construct-query-result
+ "Build a body-transform fn for construct_query. Stores the base64 payload server-side
+ under the calling MCP session and returns {:query_handle uuid} instead of {:query base64},
+ so the LLM carries a short opaque UUID rather than the full base64 string.
+ Also stores the optional prompt with the handle, used for submitting feedback on visualizations."
+ [session-id user-id]
+ (fn [body]
+ (if-let [encoded (:query body)]
+ {:query_handle (mcp.session/store-handle! session-id user-id encoded (:prompt body))}
+ body)))
+
+;; Tools that accept :query_handle as an alternative to a raw base64 :query string.
+(def ^:private tools-accepting-query-handle
+ #{"execute_query" "visualize_query"})
+
;;; ------------------------------------------------- Tool Dispatch -------------------------------------------------
(defn- text-content
@@ -158,8 +197,11 @@
For POST, `params` becomes the request body; for GET/DELETE, `params` becomes query-params.
Propagates `token-scopes` from the original MCP request so that scope restrictions
- are preserved through the synthetic request."
- [method path token-scopes params]
+ are preserved through the synthetic request.
+
+ `body-transform-fn`, when provided, is applied to the 200 response body before
+ wrapping with text-content. Used to post-process construct_query results."
+ [method path token-scopes params & {:keys [body-transform-fn]}]
(let [result (promise)]
(deliver-agent-api-response result method path token-scopes params)
(let [response (deref result 30000 {:status 504 :body {:message "Timeout"}})]
@@ -169,7 +211,8 @@
response
(= 200 (:status response))
- (text-content (:body response))
+ (text-content (cond-> (:body response)
+ body-transform-fn (body-transform-fn)))
:else
(error-content (extract-error-message response))))))
@@ -201,24 +244,41 @@
Looks up method/path from the tool definition, interpolates path params,
and calls `invoke-agent-api`. For POST requests, remaining args are sent as the
request body. For GET/DELETE requests, remaining args are sent as query params."
- [tool-def arguments token-scopes]
+ [tool-def arguments token-scopes session-id]
(let [{:keys [method path]} (:endpoint tool-def)
+ tool-name (:name tool-def)
method (keyword (u/lower-case-en method))
[resolved-path
remaining-args] (interpolate-path path arguments)
- api-path (strip-api-prefix resolved-path)]
- (invoke-agent-api method api-path token-scopes remaining-args)))
+ api-path (strip-api-prefix resolved-path)
+ body-transform-fn (when (= tool-name "construct_query")
+ (make-store-construct-query-result
+ session-id api/*current-user-id*))]
+ (invoke-agent-api method api-path token-scopes remaining-args
+ :body-transform-fn body-transform-fn)))
(defn call-tool
"Dispatch an MCP `tools/call` request to the appropriate handler.
`token-scopes` from the original MCP session are propagated to the synthetic
agent-api request so that scope restrictions are enforced by the agent API's
- `defendpoint` middleware.
+ `defendpoint` middleware. UI tool response-fns receive `{:session-id session-id}`
+ as opts in case a tool needs to scope reads to the calling MCP session.
Returns MCP content on success, or error content on failure."
- [token-scopes tool-name arguments]
- (if-let [tool-def (get (tool-index) tool-name)]
- (try
- (dispatch-via-agent-api tool-def arguments token-scopes)
- (catch Exception e
- (error-content (or (ex-message e) "Internal error"))))
- (error-content (str "Unknown tool: " tool-name))))
+ [token-scopes session-id tool-name arguments]
+ (if-let [ui-tool (some #(when (= tool-name (:name %)) %) (mcp.resources/list-ui-tools))]
+ (if-not (mcp.scope/matches? token-scopes (:scope ui-tool))
+ (error-content (str "Insufficient scope to call tool: " tool-name))
+ ((:response-fn ui-tool) arguments {:session-id session-id}))
+ (if-let [tool-def (get (tool-index) tool-name)]
+ (if-not (mcp.scope/matches? token-scopes (:scope tool-def))
+ (error-content (str "Insufficient scope to call tool: " tool-name))
+ (let [arguments (if (tools-accepting-query-handle tool-name)
+ (resolve-query-arg session-id tool-name arguments)
+ arguments)]
+ (if (= arguments ::handle-not-found)
+ (error-content "Query handle not found. The query may have expired — try running construct_query again.")
+ (try
+ (dispatch-via-agent-api tool-def arguments token-scopes session-id)
+ (catch Exception e
+ (error-content (or (ex-message e) "Internal error")))))))
+ (error-content (str "Unknown tool: " tool-name)))))
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index 6679b0ee688..92c1b5ef907 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -263,7 +263,13 @@
[:issue_type {:optional true} [:maybe :string]]
[:freeform_feedback {:optional true} [:maybe :string]]]]
(metabot.config/check-metabot-enabled!)
- (metabot.feedback/persist-feedback! body)
+ (let [message (metabot.feedback/persist-feedback! body)]
+ (try
+ (api/check-400 (metabot.feedback/submit-to-harbormaster!
+ (metabot.feedback/harbormaster-payload body message))
+ "Cannot submit feedback. The license token and/or Store API URL are missing!")
+ (catch Exception e
+ (log/error "Failed to submit feedback to Harbormaster: " (ex-message e)))))
api/generic-204-no-content)
(api.macros/defendpoint :post "/source-feedback" :- [:map
diff --git a/src/metabase/metabot/feedback.clj b/src/metabase/metabot/feedback.clj
index d3cadc61063..5621324e15d 100644
--- a/src/metabase/metabot/feedback.clj
+++ b/src/metabase/metabot/feedback.clj
@@ -1,13 +1,72 @@
(ns metabase.metabot.feedback
- "Persistence of Metabot feedback."
+ "Local persistence of Metabot feedback, plus a Harbormaster submission path."
(:require
+ [clj-http.client :as http]
+ [clojure.string :as str]
[metabase.api.common :as api]
[metabase.app-db.core :as app-db]
+ [metabase.config.core :as config]
+ [metabase.metabot.persistence :as metabot.persistence]
[metabase.models.interface :as mi]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.store-api.core :as store-api]
+ [metabase.util.json :as json]
[toucan2.core :as t2]))
(set! *warn-on-reflection* true)
+(def ^:private harbormaster-conn-timeout-ms
+ 2000)
+
+(def ^:private harbormaster-socket-timeout-ms
+ 5000)
+
+(defn submit-to-harbormaster!
+ "Submit metabot feedback to Harbormaster via the Store API.
+ Returns the HTTP response on success, or nil if the token or Store API URL is missing."
+ [feedback]
+ (let [token (premium-features/premium-embedding-token)
+ base-url (store-api/store-api-url)]
+ (when-not (or (str/blank? token) (str/blank? base-url))
+ (http/post (str base-url "/api/v2/metabot/feedback/" token)
+ {:content-type :json
+ :conn-timeout harbormaster-conn-timeout-ms
+ :socket-timeout harbormaster-socket-timeout-ms
+ :body (json/encode feedback)}))))
+
+(defn harbormaster-payload
+ "Build the Harbormaster feedback payload from the request body, the resolved
+ `metabot_message` row, and the submitter (defaults to the current user)."
+ ([body message]
+ (harbormaster-payload body message api/*current-user-id*))
+ ([{:keys [metabot_id message_id positive issue_type freeform_feedback]}
+ {:keys [conversation_id]}
+ submitter-user-id]
+ {:metabot_id metabot_id
+ :feedback {:message_id message_id
+ :positive positive
+ :issue_type issue_type
+ :freeform_feedback freeform_feedback}
+ :conversation_data (metabot.persistence/conversation-detail conversation_id)
+ :version config/mb-version-info
+ :submission_time (str (java.time.OffsetDateTime/now))
+ :submitter_user_id submitter-user-id
+ :is_admin (boolean (t2/select-one-fn :is_superuser :model/User :id submitter-user-id))}))
+
+(defn mcp-harbormaster-payload
+ "Build a Harbormaster feedback payload for MCP Apps visualization feedback.
+ MCP Apps do not create `metabot_message` rows, so this path intentionally
+ skips local `metabot_feedback` persistence and forwards the MCP context
+ supplied by the client."
+ ([body]
+ (mcp-harbormaster-payload body api/*current-user-id*))
+ ([body submitter-user-id]
+ (assoc body
+ :version config/mb-version-info
+ :submission_time (str (java.time.OffsetDateTime/now))
+ :submitter_user_id submitter-user-id
+ :is_admin (boolean (t2/select-one-fn :is_superuser :model/User :id submitter-user-id)))))
+
(defn- resolve-rated-message
"Return the `metabot_message` row (`:id` + `:conversation_id`) identified by
`external-id`, plus the enclosing `:model/MetabotConversation` as `:conversation`.
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 5ea0c57ca61..2a0b3f69846 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -56,6 +56,7 @@
:model/HTTPAction metabase.actions.models
:model/ImplicitAction metabase.actions.models
:model/LoginHistory metabase.login-history.models.login-history
+ :model/McpQueryHandle metabase.mcp.models.mcp-query-handle
:model/Measure metabase.measures.models.measure
:model/Metabot metabase.metabot.models.metabot
:model/MetabotConversation metabase.metabot.models.metabot-conversation
diff --git a/src/metabase/oauth_server/api/metadata.clj b/src/metabase/oauth_server/api/metadata.clj
index 05bc7515f3c..85348467a2b 100644
--- a/src/metabase/oauth_server/api/metadata.clj
+++ b/src/metabase/oauth_server/api/metadata.clj
@@ -53,5 +53,5 @@
:headers {"Content-Type" "application/json"}
:body {:resource (str site-url "/api/mcp")
:authorization_servers [site-url]
- :scopes_supported (oauth-server/all-agent-scopes)
+ :scopes_supported (vec (oauth-server/all-agent-scopes))
:bearer_methods_supported ["header"]}}))
diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.clj
index 7bc4ee9fd64..9bfcd4d0084 100644
--- a/src/metabase/oauth_server/core.clj
+++ b/src/metabase/oauth_server/core.clj
@@ -1,7 +1,7 @@
(ns metabase.oauth-server.core
(:require
[clojure.string :as str]
- [metabase.api.macros :as api.macros]
+ [metabase.mcp.core :as mcp]
[metabase.oauth-server.settings :as oauth-settings]
[metabase.oauth-server.store :as store]
[metabase.system.core :as system]
@@ -13,13 +13,10 @@
(defonce ^:private provider (atom nil))
(defn all-agent-scopes
- "All supported OAuth scopes derived from defendpoint metadata on the agent API."
+ "All supported OAuth scopes derived from defendpoint metadata on the agent API,
+ plus scopes from MCP UI resources (e.g. visualize_query)."
[]
- (into []
- (comp (keep #(get-in % [:form :metadata :scope]))
- (filter string?)
- (distinct))
- (vals (api.macros/ns-routes 'metabase.agent-api.api))))
+ (mcp/all-scopes))
(defn- build-provider-config
"Build the configuration map for the OAuth provider from Metabase settings."
@@ -36,7 +33,8 @@
:client-store (store/create-client-store)
:code-store (store/create-authorization-code-store)
:token-store (store/create-token-store)
- :scopes-supported (all-agent-scopes)
+ ;; OIDC provider requires a vector; all-scopes returns a sorted set.
+ :scopes-supported (vec (all-agent-scopes))
:rotate-refresh-tokens true}))
(defn- create-provider
diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.clj
index 397e477485e..c64d797675b 100644
--- a/test/metabase/agent_api/api_test.clj
+++ b/test/metabase/agent_api/api_test.clj
@@ -257,18 +257,35 @@
(let [table-id (mt/id :orders)
response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
{:source {:type "table" :id table-id}
- :operations []})]
+ :operations []
+ :prompt "show orders"})]
(is (string? (:query response)) "Response should contain a query string")
+ (is (= "show orders" (:prompt response)) "Response should echo the prompt")
(let [decoded (decode-query response)]
(is (= :mbql/query (lib/normalized-query-type decoded)))
(is (= (mt/id) (lib/database-id decoded)))
(is (= (mt/id :orders) (lib/primary-source-table-id decoded))))))
+ (testing "Does not require prompt"
+ (let [table-id (mt/id :orders)
+ response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:source {:type "table" :id table-id}
+ :operations []})]
+ (is (string? (:query response)) "Response should contain a query string")
+ (is (not (contains? response :prompt)) "Response should only echo prompt when supplied")))
+
+ (testing "Rejects oversized prompts before they can be persisted on MCP query handles"
+ (mt/user-http-request :rasta :post 400 "agent/v2/construct-query"
+ {:source {:type "table" :id (mt/id :orders)}
+ :operations []
+ :prompt (apply str (repeat 10001 "x"))}))
+
(testing "Respects explicit limit operation"
(let [table-id (mt/id :orders)
response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
{:source {:type "table" :id table-id}
- :operations [["limit" 10]]})
+ :operations [["limit" 10]]
+ :prompt "show 10 orders"})
decoded (decode-query response)]
(is (= 10 (lib/current-limit decoded)))))
@@ -276,14 +293,16 @@
(is (= "Not found."
(mt/user-http-request :rasta :post 404 "agent/v2/construct-query"
{:source {:type "table" :id 999999}
- :operations []})))))
+ :operations []
+ :prompt "show orders"})))))
(deftest execute-query-test
(testing "Executes a query and returns results with column metadata"
(let [table-id (mt/id :orders)
construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
{:source {:type "table" :id table-id}
- :operations [["limit" 5]]})
+ :operations [["limit" 5]]
+ :prompt "show 5 orders"})
;; Streaming response returns 202 (accepted) since it starts streaming before completion
execute-resp (mt/user-http-request :rasta :post 202 "agent/v1/execute"
{:query (:query construct-resp)})]
@@ -300,7 +319,8 @@
(let [table-id (mt/id :orders)
construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
{:source {:type "table" :id table-id}
- :operations [["limit" 300]]})
+ :operations [["limit" 300]]
+ :prompt "show all orders"})
execute-resp (mt/user-http-request :rasta :post 202 "agent/v1/execute"
{:query (:query construct-resp)})]
(is (=? {:status "completed" :row_count 200}
@@ -338,7 +358,8 @@
(testing "Constructs a query from a metric"
(let [response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
{:source {:type "metric" :id (:id metric)}
- :operations []})]
+ :operations []
+ :prompt "show metric"})]
(is (string? (:query response)) "Response should contain a query string")
(let [decoded (decode-query response)]
(is (= :mbql/query (lib/normalized-query-type decoded)))
@@ -348,7 +369,8 @@
(is (= "Not found."
(mt/user-http-request :rasta :post 404 "agent/v2/construct-query"
{:source {:type "metric" :id 999999}
- :operations []}))))))
+ :operations []
+ :prompt "show metric"}))))))
(deftest construct-query-with-count-aggregation-test
(testing "Count aggregation produces a valid query"
@@ -356,7 +378,8 @@
response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
{:source {:type "table" :id table-id}
:operations [["aggregate" ["count"]]
- ["limit" 10]]})]
+ ["limit" 10]]
+ :prompt "count orders"})]
(is (string? (:query response)))
(let [decoded (decode-query response)]
(is (= 1 (count (lib/aggregations decoded))))))))
@@ -368,7 +391,8 @@
response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
{:source {:type "table" :id table-id}
:operations [["filter" ["not-null" ["field" field-id]]]
- ["limit" 10]]})]
+ ["limit" 10]]
+ :prompt "show filtered orders"})]
(is (string? (:query response)))
(let [decoded (decode-query response)]
(is (seq (lib/filters decoded)) "Query should have filters")))))
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index a5e0d2cba94..8df396d1969 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -38,13 +38,14 @@
:model/DatabaseRouter
:model/Dependency
:model/DependencyStatus
+ :model/McpQueryHandle
:model/MetabotConversation
:model/MetabotGroupLimit
:model/MetabotInstanceLimit
:model/MetabotMessage
:model/MetabotPermissions
- :model/PythonLibrary
:model/PremiumFeaturesCache
+ :model/PythonLibrary
:model/Query
:model/QueryCache
:model/QueryExecution
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index 8274d014e5a..c662c8dfb93 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -1,5 +1,6 @@
(ns metabase.mcp.api-test
(:require
+ [clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.agent-api.settings :as agent-api.settings]
@@ -8,6 +9,7 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.mcp.api :as mcp.api]
[metabase.mcp.resources :as mcp.resources]
+ [metabase.mcp.session :as mcp.session]
[metabase.mcp.settings :as mcp.settings]
[metabase.mcp.tools :as mcp.tools]
[metabase.oauth-server.core :as oauth-server]
@@ -24,6 +26,11 @@
(use-fixtures :once (fixtures/initialize :db :test-users))
+;; Backend-only test runs don't produce embed-mcp.html; install the inline fallback.
+(use-fixtures :each
+ (fn [thunk]
+ (mcp.resources/with-fallback-template (thunk))))
+
;;; --------------------------------------------------- Helpers ----------------------------------------------------
(defn- mcp-request
@@ -152,36 +159,43 @@
(testing "requests without a session ID return 400"
(let [response (mcp-request (jsonrpc-request "tools/list"))]
(is (= 400 (:status response)))
- (is (= -32600 (get-in response [:body :error :code]))))))
+ (is (= -32600 (get-in response [:body :error :code])))))
-(deftest degenerate-session-id-test
- (testing "requests with any nonblank session ID are accepted"
+ (testing "requests with an invalid session ID return 404"
(let [response (mcp-request (jsonrpc-request "tools/list")
{"mcp-session-id" "bogus-session-id"})]
- (is (= 200 (:status response)))
- (is (some? (get-in response [:body :result :tools]))))))
+ (is (= 404 (:status response)))
+ (is (= -32600 (get-in response [:body :error :code]))))))
(deftest session-delete-test
- (testing "DELETE succeeds but does not invalidate a degenerate session ID"
+ (testing "DELETE succeeds for a valid session"
(let [[session-id _] (initialize!)
- delete-response (mcp-delete {"mcp-session-id" session-id})
- post-response (mcp-request (jsonrpc-request "tools/list")
- {"mcp-session-id" session-id})]
- (is (= 200 (:status delete-response)))
- (is (= 200 (:status post-response))))))
+ delete-response (mcp-delete {"mcp-session-id" session-id})]
+ (is (= 200 (:status delete-response))))))
+
+(def ^:private all-tool-names
+ #{"construct_query"
+ "create_dashboard"
+ "create_question"
+ "execute_query"
+ "get_metric"
+ "get_metric_field_values"
+ "get_table"
+ "get_table_field_values"
+ "query"
+ "render_drill_through"
+ "search"
+ "visualize_query"})
(deftest tools-list-test
- (testing "tools/list returns the 10 agent tools"
+ (testing "tools/list returns the agent and UI tools"
(let [[session-id _] (initialize!)
response (mcp-request (jsonrpc-request "tools/list")
{"mcp-session-id" session-id})
tools (get-in response [:body :result :tools])]
(is (= 200 (:status response)))
(is (pos? (count tools)))
- (is (= #{"search" "get_table" "get_metric" "get_table_field_values"
- "get_metric_field_values" "construct_query" "execute_query" "query"
- "create_question" "create_dashboard"}
- (set (map :name tools))))
+ (is (= all-tool-names (set (map :name tools))))
(testing "each tool has a description and inputSchema"
(doseq [tool tools]
(is (string? (:description tool)))
@@ -205,7 +219,20 @@
(is (contains? (leaf-types (property-schema "search" "term_queries")) "array"))
(is (= "string" (get-in (array-branch (property-schema "search" "term_queries")) [:items :type])))
(is (contains? (leaf-types (property-schema "search" "semantic_queries")) "array"))
- (is (= "string" (get-in (array-branch (property-schema "search" "semantic_queries")) [:items :type]))))))))
+ (is (= "string" (get-in (array-branch (property-schema "search" "semantic_queries")) [:items :type])))))
+ (testing "construct_query exposes the optional user prompt"
+ (let [tools-by-name (into {} (map (juxt :name identity)) tools)
+ construct-query-tool (get tools-by-name "construct_query")
+ construct-query-schema (:inputSchema construct-query-tool)
+ prompt-schema (or (get-in construct-query-schema [:properties "prompt"])
+ (get-in construct-query-schema [:properties :prompt]))
+ required-fields (set (:required construct-query-schema))
+ reference (slurp (io/resource "metabase/agent_api/construct_query.md"))]
+ (is (str/includes? (:description construct-query-tool) "include `\"prompt\""))
+ (is (not (contains? required-fields "prompt")))
+ (is (str/includes? (:description prompt-schema) "exact original message"))
+ (is (str/includes? reference "MCP clients should include it whenever they have the user's message"))
+ (is (str/includes? reference "{\"query_handle\": \"<uuid>\"}")))))))
(deftest ping-test
(testing "ping returns empty result"
@@ -354,11 +381,12 @@
(is (string? content-text))
;; Parse the content text as JSON and verify snake_case keys from Malli encoding
(let [table-data (json/decode+kw content-text)]
- (is (some? (:name table-data)))
- (is (some? (:display_name table-data)))
- (is (some? (:database_id table-data)))
- (is (= "table" (:type table-data)))
- (is (seq (:fields table-data)))))))
+ (is (=? {:name string?
+ :display_name string?
+ :database_id int?
+ :type "table"
+ :fields sequential?}
+ table-data))))))
(deftest initialized-notification-compatibility-test
(testing "requests succeed without notifications/initialized"
@@ -369,7 +397,7 @@
(is (= 200 (:status list-response)))
(is (some? (get-in list-response [:body :result :tools])))))
- (testing "notifications/initialized remains accepted for compatibility"
+ (testing "notifications/initialized is accepted as a no-op for compatibility"
(let [response (mcp-request (jsonrpc-request "initialize"))
session-id (get-in response [:headers "Mcp-Session-Id"])]
(is (= 202 (:status (mcp-request (jsonrpc-notification "notifications/initialized")
@@ -377,14 +405,11 @@
(deftest full-handshake-test
(testing "complete MCP handshake flow"
- (let [[session-id init-response] (initialize!)
- _ (is (= 200 (:status init-response)))
- _ (is (some? session-id))
- ;; tools/list should work after full handshake
- list-response (mcp-request (jsonrpc-request "tools/list")
- {"mcp-session-id" session-id})]
+ (let [[session-id _] (initialize!)
+ list-response (mcp-request (jsonrpc-request "tools/list")
+ {"mcp-session-id" session-id})]
(is (= 200 (:status list-response)))
- (is (pos? (count (get-in list-response [:body :result :tools])))))))
+ (is (seq (get-in list-response [:body :result :tools]))))))
(deftest batch-with-notifications-test
(testing "batch with mix of notifications and requests returns only request responses"
@@ -437,7 +462,8 @@
"must not fall through to the bare-status fallback"))))
(deftest tools-list-no-refs-test
- (testing "tool inputSchemas have no $ref, no $defs, and root type is always object"
+ (testing "tool inputSchemas have no $ref, no $defs, root type is always object,
+ and no top-level oneOf/anyOf/allOf (rejected by mcpjam)"
(let [tools (mcp.tools/list-tools nil)]
(doseq [tool tools]
(when-let [schema (:inputSchema tool)]
@@ -448,19 +474,22 @@
(is (not (contains? schema :$defs))
(str (:name tool) " should have no $defs"))
(is (= "object" (:type schema))
- (str (:name tool) " root type should be object")))))))))
+ (str (:name tool) " root type should be object"))
+ (doseq [k [:oneOf :anyOf :allOf]]
+ (is (not (contains? schema k))
+ (str (:name tool) " should have no top-level " k))))))))))
(deftest tools-call-get-table-query-params-test
(testing "get_table passes query params correctly (with-fields default true)"
(let [result (mt/with-current-user (mt/user->id :crowberto)
- (mcp.tools/call-tool nil "get_table" {:id (mt/id :orders)}))]
+ (mcp.tools/call-tool nil nil "get_table" {:id (mt/id :orders)}))]
(is (not (:isError result)))
(let [table-data (json/decode+kw (:text (first (:content result))))]
(is (seq (:fields table-data))
"with-fields defaults to true, so fields should be present"))))
(testing "get_table with with-fields=false omits fields"
(let [result (mt/with-current-user (mt/user->id :crowberto)
- (mcp.tools/call-tool nil "get_table" {:id (mt/id :orders) :with-fields false}))]
+ (mcp.tools/call-tool nil nil "get_table" {:id (mt/id :orders) :with-fields false}))]
(is (not (:isError result)))
(let [table-data (json/decode+kw (:text (first (:content result))))]
(is (empty? (:fields table-data))
@@ -475,15 +504,17 @@
(def ^:private smoke-tested-tools
"Tools exercised by `tools-call-smoke-test`. New tools must be added here (and
- below) — the test compares this set against `mcp.tools/list-tools` and fails
- when they diverge, ensuring no tool ships without a basic invocation check."
+ below) — the test compares this set against the Agent API-backed tools and
+ fails when they diverge, ensuring no Agent API tool ships without a basic
+ invocation check."
#{"get_table" "get_table_field_values" "get_metric" "get_metric_field_values"
"search" "construct_query" "query" "execute_query"
"create_question" "create_dashboard"})
(deftest tools-call-smoke-test
- (testing "every registered tool is exercised by the smoke test"
- (is (= (set (map :name (mcp.tools/list-tools nil)))
+ (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"])
smoke-tested-tools)
"Add the missing tool to `smoke-tested-tools` and the call sequence below."))
(testing "every tool returns a successful response with valid parameters"
@@ -512,17 +543,18 @@
;; Query construction + execution
construct-data (call-tool session-id "construct_query"
{:source {:type "table" :id orders-id}
- :operations [["limit" 5]]})
+ :operations [["limit" 5]]
+ :prompt "show 5 orders"})
_ (call-tool session-id "query"
{:source {:type "table" :id orders-id}
:operations [["limit" 5]]})
_ (call-tool session-id "execute_query"
- {:query (:query construct-data)})
+ {:query_handle (:query_handle construct-data)})
;; Write tools — record IDs as soon as they're known so the `finally` block
;; can clean up even if a later step throws.
question-data (call-tool session-id "create_question"
{:name "Smoke Question"
- :query (:query construct-data)})
+ :query (mcp.session/read-handle session-id (:query_handle construct-data))})
_ (reset! question-id (:id question-data))
dash-data (call-tool session-id "create_dashboard"
{:name "Smoke Dashboard"})]
@@ -531,6 +563,14 @@
(when-let [qid @question-id] (t2/delete! :model/Card :id qid))
(when-let [did @dash-id] (t2/delete! :model/Dashboard :id did)))))))))
+(deftest tools-call-visualize-query-direct-test
+ (testing "visualize_query returns UI structured content"
+ (let [result (mcp.tools/call-tool nil nil "visualize_query" {:query "card__1"})]
+ (is (not (:isError result)))
+ (is (=? {:content [{:type "text"}]
+ :structuredContent {:query "card__1"}}
+ result)))))
+
(deftest tools-call-execute-query-test
(testing "execute_query returns a streaming response captured as MCP text content"
(let [streamed? (atom false)
@@ -542,9 +582,10 @@
(let [[session-id _] (initialize!)
construct-data (call-tool session-id "construct_query"
{:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 5]]})
+ :operations [["limit" 5]]
+ :prompt "show 5 orders"})
execute-data (call-tool session-id "execute_query"
- {:query (:query construct-data)})]
+ {:query_handle (:query_handle construct-data)})]
(is (true? @streamed?) "execute_query should use the streaming response path")
(is (=? {:status "completed"
:row_count 5
@@ -552,6 +593,133 @@
:rows (fn [rows] (= 5 (count rows)))}}
execute-data)))))))
+;;; ----------------------------------------------- Drill Handles ---------------------------------------------------
+
+(deftest tools-call-render-drill-through-test
+ (testing "render_drill_through resolves a stored handle to its encoded query"
+ (let [user-id (mt/user->id :crowberto)
+ [session-id _] (initialize!)
+ handle (mt/with-current-user user-id
+ (mcp.session/store-handle! session-id user-id "ZW5jb2RlZA=="))]
+ ;; The error path returns no :structuredContent, so asserting it is present is
+ ;; equivalent to asserting :isError is not set.
+ (is (=? {:status 200
+ :body {:result {:structuredContent {:query "ZW5jb2RlZA=="}}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "render_drill_through"
+ :arguments {:handle handle}})
+ {"mcp-session-id" session-id})))))
+
+ (testing "render_drill_through returns an error when the handle is unknown"
+ (let [[session-id _] (initialize!)]
+ (is (=? {:status 200
+ :body {:result {:isError true}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "render_drill_through"
+ :arguments {:handle (str (random-uuid))}})
+ {"mcp-session-id" session-id})))))
+
+ (testing "render_drill_through does not resolve a handle from another session"
+ (let [user-id (mt/user->id :crowberto)
+ [owner-session _] (initialize!)
+ [attacker-session _] (initialize!)
+ handle (mt/with-current-user user-id
+ (mcp.session/store-handle! owner-session user-id "ZW5jb2RlZA=="))]
+ (is (=? {:status 200
+ :body {:result {:isError true
+ :content [{:text #(str/includes? % "No drill-through found")}]}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "render_drill_through"
+ :arguments {:handle handle}})
+ {"mcp-session-id" attacker-session}))))))
+
+(deftest tools-call-visualize-query-test
+ (testing "visualize_query echoes the inline query"
+ (let [[session-id _] (initialize!)]
+ (is (=? {:status 200
+ :body {:result {:structuredContent {:query "ZW5jb2RlZA=="}}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {:query "ZW5jb2RlZA=="}})
+ {"mcp-session-id" session-id})))))
+
+ (testing "visualize_query resolves a stored handle"
+ (let [user-id (mt/user->id :crowberto)
+ [session-id _] (initialize!)
+ handle (mt/with-current-user user-id
+ (mcp.session/store-handle! session-id user-id "ZW5jb2RlZA=="))]
+ (is (=? {:status 200
+ :body {:result {:structuredContent {:query "ZW5jb2RlZA=="}}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {:query_handle handle}})
+ {"mcp-session-id" session-id})))))
+
+ (testing "visualize_query includes the prompt stored with a construct_query handle"
+ (let [[session-id _] (initialize!)
+ construct-data (call-tool session-id "construct_query"
+ {:source {:type "table" :id (mt/id :orders)}
+ :operations [["limit" 5]]
+ :prompt "show 5 orders"})
+ response (mcp-request (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {:query_handle (:query_handle construct-data)}})
+ {"mcp-session-id" session-id})]
+ (is (=? {:status 200
+ :body {:result {:structuredContent {:query string?
+ :prompt "show 5 orders"}}}}
+ response))))
+
+ (testing "visualize_query asks for an argument when neither query nor handle is provided"
+ (let [[session-id _] (initialize!)]
+ (is (=? {:status 200
+ :body {:result {:isError true
+ :content [{:text #(str/includes? % "Provide either")}]}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {}})
+ {"mcp-session-id" session-id})))))
+
+ (testing "visualize_query returns 'handle not found' when query_handle is unknown"
+ (let [[session-id _] (initialize!)]
+ (is (=? {:status 200
+ :body {:result {:isError true
+ :content [{:text #(str/includes? % "Query handle not found")}]}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {:query_handle (str (random-uuid))}})
+ {"mcp-session-id" session-id})))))
+
+ (testing "visualize_query does not resolve a query_handle from another session"
+ (let [user-id (mt/user->id :crowberto)
+ [owner-session _] (initialize!)
+ [attacker-session _] (initialize!)
+ handle (mt/with-current-user user-id
+ (mcp.session/store-handle! owner-session user-id "ZW5jb2RlZA=="))]
+ (is (=? {:status 200
+ :body {:result {:isError true
+ :content [{:text #(str/includes? % "Query handle not found")}]}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {:query_handle handle}})
+ {"mcp-session-id" attacker-session})))))
+
+ (testing "execute_query does not resolve a query_handle from another session"
+ (let [[owner-session _] (initialize!)
+ [attacker-session _] (initialize!)
+ construct-data (call-tool owner-session "construct_query"
+ {:source {:type "table" :id (mt/id :orders)}
+ :operations [["limit" 5]]
+ :prompt "show 5 orders"})
+ response (mcp-request (jsonrpc-request "tools/call"
+ {:name "execute_query"
+ :arguments {:query_handle (:query_handle construct-data)}})
+ {"mcp-session-id" attacker-session})]
+ (is (=? {:status 200
+ :body {:result {:isError true
+ :content [{:text #(str/includes? % "Query handle not found")}]}}}
+ response)))))
+
;;; --------------------------------------------- OAuth Bearer Auth -------------------------------------------------
(deftest unauthenticated-returns-401-test
@@ -630,6 +798,10 @@
(def ^:private scoped-test-uri "test://mcp/api-test/scoped")
+(defn- dispatch-initialized-request [msg token-scopes]
+ (let [session-id (str (random-uuid))]
+ (#'mcp.api/dispatch-request msg session-id token-scopes)))
+
(defn- with-scoped-test-resource! [f]
(let [registry @#'mcp.resources/registry
snapshot @registry]
@@ -645,13 +817,12 @@
(finally
(reset! registry snapshot)))))
-(deftest resources-read-scope-denied-test
+(deftest ui-resource-read-not-found-test
(testing "resources/read returns -32602 \"Resource not found\" when caller lacks the required scope"
(with-scoped-test-resource!
(fn []
- (let [response (#'mcp.api/dispatch-request
+ (let [response (dispatch-initialized-request
(jsonrpc-request "resources/read" {:uri scoped-test-uri})
- "session-id"
#{"agent:other"})]
(is (=? {:jsonrpc "2.0"
:id 1
@@ -661,9 +832,8 @@
(testing "resources/read for a scoped resource succeeds when the caller has a matching scope"
(with-scoped-test-resource!
(fn []
- (let [response (#'mcp.api/dispatch-request
+ (let [response (dispatch-initialized-request
(jsonrpc-request "resources/read" {:uri scoped-test-uri})
- "session-id"
#{"agent:search"})]
(is (=? {:result {:contents [{:uri scoped-test-uri
:text "secret body"}]}}
@@ -697,7 +867,7 @@
(deftest tools-list-scope-filtering-test
(testing "tools/list with unrestricted scopes returns all tools"
(let [tools (mcp.tools/list-tools #{::scope/unrestricted})]
- (is (= 10 (count tools)))))
+ (is (= all-tool-names (set (map :name tools))))))
(testing "tools/list with specific scope only returns matching tools"
(let [tools (mcp.tools/list-tools #{"agent:search"})
@@ -708,17 +878,17 @@
(is (not (contains? tool-names "get_table")))
(is (not (contains? tool-names "construct_query")))))
- (testing "tools/list with wildcard scope matches all agent tools"
+ (testing "tools/list with wildcard scope matches all agent and UI tools"
(let [tools (mcp.tools/list-tools #{"agent:*"})]
- (is (= 10 (count tools)))))
+ (is (= all-tool-names (set (map :name tools))))))
(testing "tools/list with nil scopes returns all tools"
(let [tools (mcp.tools/list-tools nil)]
- (is (= 10 (count tools)))))
+ (is (= all-tool-names (set (map :name tools))))))
(testing "tools/list with empty scopes does not return all tools"
(let [tools (mcp.tools/list-tools #{})]
- (is (zero? (count tools))
+ (is (empty? tools)
"Empty scopes should not grant access to scoped tools"))))
(defn- insert-expired-oauth-token!
@@ -752,21 +922,44 @@
(deftest tools-call-scope-enforcement-test
(testing "tool call is rejected when token scopes don't include the required scope"
(let [result (mt/with-current-user (mt/user->id :crowberto)
- (mcp.tools/call-tool #{"agent:search"} "get_table" {:id (mt/id :orders)}))]
+ (mcp.tools/call-tool #{"agent:search"} nil "get_table" {:id (mt/id :orders)}))]
(is (=? {:isError true} result))
(is (str/includes? (-> result :content first :text) "Insufficient scope")
"Scope enforcement error from defendpoint middleware")))
(testing "tool call with matching scope is not rejected by scope enforcement"
(let [result (mt/with-current-user (mt/user->id :crowberto)
- (mcp.tools/call-tool #{"agent:table:read"} "get_table" {:id (mt/id :orders)}))]
+ (mcp.tools/call-tool #{"agent:table:read"} nil "get_table" {:id (mt/id :orders)}))]
(is (not (:isError result)))))
(testing "tool call with empty scopes is rejected for scoped tools"
(let [result (mt/with-current-user (mt/user->id :crowberto)
- (mcp.tools/call-tool #{} "get_table" {:id (mt/id :orders)}))]
+ (mcp.tools/call-tool #{} nil "get_table" {:id (mt/id :orders)}))]
(is (=? {:isError true} result))
(is (str/includes? (-> result :content first :text) "Insufficient scope")
"Scope enforcement error from defendpoint middleware"))))
+(deftest check-resource-access-test
+ (testing "returns :ok for a known URI with matching scope"
+ (is (= :ok (mcp.resources/check-resource-access "ui://metabase/visualize-query.html" #{"agent:visualize"}))))
+ (testing "returns :ok with wildcard scope"
+ (is (= :ok (mcp.resources/check-resource-access "ui://metabase/visualize-query.html" #{"agent:*"}))))
+ (testing "returns :scope-denied for a known URI with non-matching scope"
+ (is (= :scope-denied (mcp.resources/check-resource-access "ui://metabase/visualize-query.html" #{"agent:search"}))))
+ (testing "returns :scope-denied for a known URI with empty scopes"
+ (is (= :scope-denied (mcp.resources/check-resource-access "ui://metabase/visualize-query.html" #{}))))
+ (testing "returns :not-found for an unknown URI"
+ (is (= :not-found (mcp.resources/check-resource-access "ui://metabase/nonexistent.html" #{"agent:*"})))))
+
+(deftest resources-read-scope-denied-test
+ (testing "resources/read returns -32602 for unknown URI"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "resources/read"
+ {:uri "ui://metabase/nonexistent.html"})
+ {"mcp-session-id" session-id})]
+ (is (= 200 (:status response)))
+ (is (= -32602 (get-in response [:body :error :code])))
+ (is (= "Resource not found"
+ (get-in response [:body :error :message]))))))
+
(deftest agent-api-preserves-token-scopes-test
(testing "scoped token restrictions are enforced by the Agent API layer (defense-in-depth)"
(testing "restricted scopes that don't match the endpoint are rejected by Agent API"
@@ -791,7 +984,7 @@
(testing "MCP tool calls still work when the external Agent API is disabled"
(mt/with-temporary-setting-values [agent-api.settings/agent-api-enabled? false]
(let [result (mt/with-current-user (mt/user->id :crowberto)
- (mcp.tools/call-tool #{::scope/unrestricted} "get_table" {:id (mt/id :orders)}))]
+ (mcp.tools/call-tool #{::scope/unrestricted} nil "get_table" {:id (mt/id :orders)}))]
(is (not (:isError result)))))))
;;; ------------------------------------------------- Throttling ---------------------------------------------------
@@ -812,3 +1005,36 @@
:message #(str/starts-with? % "Too many attempts!")}}}
(mcp-request (jsonrpc-request "ping")
{"mcp-session-id" session-id})))))))
+
+;;; -------------------------------------------- Session Lifecycle -------------------------------------------------
+
+(deftest session-embedding-reuse-test
+ (testing "multiple resources/read calls within one session reuse the same embedding session"
+ (let [[session-id _] (initialize!)
+ read1 (mcp-request (jsonrpc-request "resources/read"
+ {:uri "ui://metabase/visualize-query.html"} 1)
+ {"mcp-session-id" session-id})
+ read2 (mcp-request (jsonrpc-request "resources/read"
+ {:uri "ui://metabase/visualize-query.html"} 2)
+ {"mcp-session-id" session-id})]
+ (is (= 200 (:status read1)))
+ (is (= 200 (:status read2)))
+ ;; Both responses should contain the same session token in the rendered HTML
+ (let [html1 (-> (get-in read1 [:body :result :contents]) first :text)
+ html2 (-> (get-in read2 [:body :result :contents]) first :text)]
+ (is (some? html1))
+ (is (= html1 html2)
+ "Same embedding session should produce identical HTML output")))))
+
+(deftest batch-initialized-then-resources-read-test
+ (testing "batch containing notifications/initialized + resources/read succeeds"
+ (let [response (mcp-request (jsonrpc-request "initialize"))
+ session-id (get-in response [:headers "Mcp-Session-Id"])
+ batch-response (mcp-request [(jsonrpc-notification "notifications/initialized")
+ (jsonrpc-request "resources/read"
+ {:uri "ui://metabase/visualize-query.html"} 1)]
+ {"mcp-session-id" session-id})]
+ (is (=? {:status 200
+ :body [{:id 1
+ :result {:contents some?}}]}
+ batch-response)))))
diff --git a/test/metabase/mcp/callback_api_test.clj b/test/metabase/mcp/callback_api_test.clj
new file mode 100644
index 00000000000..ce1ed81ea43
--- /dev/null
+++ b/test/metabase/mcp/callback_api_test.clj
@@ -0,0 +1,184 @@
+(ns metabase.mcp.callback-api-test
+ (:require
+ [clj-http.client :as http]
+ [clojure.test :refer :all]
+ [metabase.mcp.session :as mcp.session]
+ [metabase.metabot.config :as metabot.config]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.test :as mt]
+ [metabase.test.data.users :as test.users]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.test.http-client :as client]
+ [metabase.util.json :as json]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :db :test-users))
+
+(defn- post-drill
+ "POST /api/embed-mcp/drills as `user` (default :crowberto), with optional headers
+ and an `expected-status` for non-200 cases."
+ ([body extra-headers]
+ (post-drill :crowberto 200 body extra-headers))
+ ([user expected-status body extra-headers]
+ (client/client-full-response (test.users/username->token user)
+ :post expected-status "embed-mcp/drills"
+ {:request-options {:headers extra-headers}}
+ body)))
+
+(defn- post-mcp-feedback
+ ([user expected-status body session-id]
+ (client/client-full-response (test.users/username->token user)
+ :post expected-status "embed-mcp/feedback"
+ {:request-options {:headers {"mcp-session-id" session-id}}}
+ body))
+ ([user expected-status body]
+ (client/client-full-response (test.users/username->token user)
+ :post expected-status "embed-mcp/feedback"
+ body)))
+
+(deftest drills-post-stores-handle-test
+ (testing "POST returns a UUID handle"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ response (post-drill {:encodedQuery "ZW5jb2RlZA=="}
+ {"mcp-session-id" session-id})]
+ (is (=? {:status 200
+ :body {:handle parse-uuid}}
+ response)))))
+
+(deftest drills-post-validates-session-header-test
+ (testing "missing Mcp-Session-Id header returns 400"
+ (is (=? {:status 400}
+ (post-drill :crowberto 400 {:encodedQuery "ZW5jb2RlZA=="} {}))))
+
+ (testing "non-UUID Mcp-Session-Id returns 404"
+ (is (=? {:status 404}
+ (post-drill :crowberto 404 {:encodedQuery "ZW5jb2RlZA=="}
+ {"mcp-session-id" "not-a-uuid"}))))
+
+ (testing "session owned by a different user returns 404"
+ (let [owner (mt/user->id :crowberto)
+ session (mcp.session/create! owner)
+ _ (mcp.session/get-or-create-session-key! session owner)]
+ (is (=? {:status 404}
+ (post-drill :rasta 404 {:encodedQuery "ZW5jb2RlZA=="}
+ {"mcp-session-id" session}))))))
+
+(deftest drills-post-rejects-blank-body-test
+ (testing "blank encodedQuery returns 400"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)]
+ (is (=? {:status 400}
+ (post-drill :crowberto 400 {:encodedQuery ""}
+ {"mcp-session-id" session-id}))))))
+
+(deftest drills-post-requires-auth-test
+ (testing "unauthenticated request returns 401"
+ (is (=? {:status 401}
+ (client/client-full-response :post 401 "embed-mcp/drills"
+ {:encodedQuery "ZW5jb2RlZA=="})))))
+
+(deftest feedback-post-submits-mcp-visualization-context-test
+ (testing "MCP feedback accepts visualization context without a Metabot message row"
+ (let [store-url "http://hm.example"
+ fake-token "test-fake-token-for-feedback"
+ session-id (mcp.session/create! (mt/user->id :rasta))
+ captured (atom nil)
+ body {:feedback {:message_id (str (random-uuid))
+ :positive false
+ :issue_type "wrong-visualization"
+ :freeform_feedback "wrong chart"}
+ :conversation_data {:source "mcp"
+ :prompt "show orders"
+ :query "encoded-query"}}
+ expected-url (str store-url "/api/v2/metabot/feedback/" fake-token)]
+ (mt/with-temporary-setting-values [store-api-url store-url]
+ (mt/with-dynamic-fn-redefs
+ [premium-features/premium-embedding-token (constantly fake-token)
+ http/post (fn [url opts]
+ (reset! captured {:url url
+ :opts opts
+ :body (json/decode+kw (:body opts))}))]
+ (post-mcp-feedback :rasta 204 body session-id)
+ (is (=? {:url expected-url
+ :opts {:conn-timeout pos-int?
+ :socket-timeout pos-int?}
+ :body {:metabot_id (metabot.config/normalize-metabot-id
+ metabot.config/embedded-metabot-id)
+ :feedback (:feedback body)
+ :conversation_data (:conversation_data body)
+ :version some?
+ :submission_time some?
+ :is_admin false}}
+ @captured)))))))
+
+(deftest feedback-post-returns-400-when-harbormaster-cannot-be-reached-test
+ (testing "MCP feedback fails when there is no Harbormaster fallback"
+ (let [store-url "http://hm.example"
+ session-id (mcp.session/create! (mt/user->id :rasta))
+ body {:feedback {:message_id (str (random-uuid))
+ :positive true}
+ :conversation_data {:source "mcp"
+ :prompt "show orders"
+ :query "encoded-query"}}
+ posted? (atom false)]
+ (mt/with-temporary-setting-values [store-api-url store-url]
+ (mt/with-dynamic-fn-redefs
+ [premium-features/premium-embedding-token (constantly nil)
+ http/post (fn [& _] (reset! posted? true))]
+ (is (=? {:status 400}
+ (post-mcp-feedback :rasta 400 body session-id)))
+ (is (false? @posted?)
+ "Harbormaster must not be contacted when the premium token is missing"))))))
+
+(deftest feedback-post-returns-502-when-harbormaster-submission-fails-test
+ (testing "MCP feedback surfaces Harbormaster submission failures without pretending the feedback was saved"
+ (let [store-url "http://hm.example"
+ session-id (mcp.session/create! (mt/user->id :rasta))
+ body {:feedback {:message_id (str (random-uuid))
+ :positive true}
+ :conversation_data {:source "mcp"
+ :prompt "show orders"
+ :query "encoded-query"}}]
+ (mt/with-temporary-setting-values [store-api-url store-url]
+ (mt/with-dynamic-fn-redefs
+ [premium-features/premium-embedding-token (constantly "test-fake-token-for-feedback")
+ http/post (fn [& _] (throw (ex-info "Harbormaster unavailable" {})))]
+ (is (=? {:status 502}
+ (post-mcp-feedback :rasta 502 body session-id))))))))
+
+(deftest feedback-post-rejects-oversized-free-text-test
+ (testing "MCP feedback bounds user-controlled free text before proxying to Harbormaster"
+ (let [session-id (mcp.session/create! (mt/user->id :rasta))
+ too-large (apply str (repeat 10001 "x"))
+ base-body {:feedback {:message_id (str (random-uuid))
+ :positive true}
+ :conversation_data {:source "mcp"}}
+ posted? (atom false)]
+ (mt/with-dynamic-fn-redefs
+ [http/post (fn [& _] (reset! posted? true))]
+ (doseq [[path label] [[[:feedback :freeform_feedback] "freeform feedback"]
+ [[:conversation_data :prompt] "prompt"]
+ [[:conversation_data :query] "query"]]]
+ (testing label
+ (is (=? {:status 400}
+ (post-mcp-feedback :rasta 400 (assoc-in base-body path too-large) session-id))))))
+ (is (false? @posted?)
+ "Harbormaster must not be contacted for oversized feedback payloads"))))
+
+(deftest feedback-post-validates-session-header-test
+ (testing "MCP feedback validates the MCP session header"
+ (let [body {:feedback {:message_id (str (random-uuid))
+ :positive true}
+ :conversation_data {:source "mcp"
+ :prompt "show orders"
+ :query "encoded-query"}}]
+ (is (=? {:status 400}
+ (post-mcp-feedback :rasta 400 body)))
+ (is (=? {:status 404}
+ (post-mcp-feedback :rasta 404 body "not-a-uuid")))
+ (let [owner-session (mcp.session/create! (mt/user->id :crowberto))]
+ (mcp.session/get-or-create-session-key! owner-session (mt/user->id :crowberto))
+ (is (=? {:status 404}
+ (post-mcp-feedback :rasta 404 body owner-session)))))))
diff --git a/test/metabase/mcp/session_test.clj b/test/metabase/mcp/session_test.clj
new file mode 100644
index 00000000000..400186c8363
--- /dev/null
+++ b/test/metabase/mcp/session_test.clj
@@ -0,0 +1,149 @@
+(ns metabase.mcp.session-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.events.core :as events]
+ [metabase.mcp.session :as mcp.session]
+ [metabase.session.core :as session]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :db :test-users))
+
+(defn- derived-hash
+ "Derives the embedding session key from an MCP session id, then hashes it."
+ [session-id]
+ (session/hash-session-key (mcp.session/derive-embedding-session-key session-id)))
+
+(deftest create-returns-uuid-string-test
+ (testing "create! returns a UUID string without writing to the database"
+ (let [session-id (mcp.session/create! (mt/user->id :crowberto))]
+ (is (string? session-id))
+ (is (some? (parse-uuid session-id)))
+ (is (not (t2/exists? :core_session :key_hashed (derived-hash session-id)))
+ "No core_session should exist yet"))))
+
+(deftest derive-embedding-session-key-is-uuid-formatted-test
+ (testing "derived key is UUID-formatted so it passes server.middleware.session/valid-session-key?"
+ ;; If this regresses, the embedding SDK iframe will get 403s from /api when it sends the
+ ;; derived key as X-Metabase-Session, because the middleware rejects non-UUID keys up-front.
+ (let [session-id (mcp.session/create! (mt/user->id :crowberto))
+ key (mcp.session/derive-embedding-session-key session-id)
+ parsed (parse-uuid key)]
+ (is (some? parsed)
+ "derive-embedding-session-key must return a UUID-formatted string")
+ (is (= 8 (.version ^java.util.UUID parsed))
+ "should be a v8 (custom/vendor-defined) UUID per RFC 9562")
+ (is (= 2 (.variant ^java.util.UUID parsed))
+ "should carry the RFC 4122 variant (10xx)"))))
+
+(deftest get-or-create-session-key-test
+ (testing "first call creates a core_session and returns the derived embedding key"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ key (mcp.session/get-or-create-session-key! session-id user-id)]
+ (is (= (mcp.session/derive-embedding-session-key session-id) key))
+ (is (not= session-id key)
+ "Derived key must not equal the MCP session id that travels on the wire")
+ (is (t2/exists? :core_session :key_hashed (derived-hash session-id))
+ "core_session should now exist")
+ (testing "subsequent calls return the same key and don't create duplicates"
+ (is (= key (mcp.session/get-or-create-session-key! session-id user-id)))
+ (is (= 1 (t2/count :core_session :key_hashed (derived-hash session-id))))))))
+
+(deftest delete-test
+ (testing "delete! removes the core_session if one was created"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ _ (mcp.session/get-or-create-session-key! session-id user-id)]
+ (is (t2/exists? :core_session :key_hashed (derived-hash session-id)))
+ (mcp.session/delete! session-id user-id)
+ (is (not (t2/exists? :core_session :key_hashed (derived-hash session-id)))))))
+
+(deftest delete-scoped-to-user-test
+ (testing "delete! only removes sessions owned by the given user"
+ (let [user-id (mt/user->id :crowberto)
+ other-id (mt/user->id :rasta)
+ session-id (mcp.session/create! user-id)
+ _ (mcp.session/get-or-create-session-key! session-id user-id)]
+ (is (t2/exists? :core_session :key_hashed (derived-hash session-id)))
+ (mcp.session/delete! session-id other-id)
+ (is (t2/exists? :core_session :key_hashed (derived-hash session-id))
+ "Session should still exist — wrong user")
+ (mcp.session/delete! session-id user-id)
+ (is (not (t2/exists? :core_session :key_hashed (derived-hash session-id)))
+ "Session should be deleted by the owning user"))))
+
+(deftest owned-by-user-test
+ (testing "returns true when no core_session exists yet"
+ (let [session-id (mcp.session/create! (mt/user->id :crowberto))]
+ (is (true? (mcp.session/owned-by-user? session-id (mt/user->id :crowberto))))
+ (is (true? (mcp.session/owned-by-user? session-id (mt/user->id :rasta))))))
+
+ (testing "returns true for the owning user, false for others"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ _ (mcp.session/get-or-create-session-key! session-id user-id)]
+ (is (true? (mcp.session/owned-by-user? session-id user-id)))
+ (is (false? (mcp.session/owned-by-user? session-id (mt/user->id :rasta)))))))
+
+(deftest delete-noop-without-session-test
+ (testing "delete! is a no-op when no core_session was ever created"
+ (let [session-id (mcp.session/create! (mt/user->id :crowberto))]
+ ;; Should not throw — just a no-op delete
+ (mcp.session/delete! session-id (mt/user->id :crowberto)))))
+
+(deftest store-and-read-handle-test
+ (testing "store-handle! returns a UUID handle that read-handle resolves to the encoded query"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ h1 (mcp.session/store-handle! session-id user-id "first")
+ h2 (mcp.session/store-handle! session-id user-id "second")]
+ (is (some? (parse-uuid h1)) "store-handle! must return a UUID string")
+ (is (some? (parse-uuid h2)))
+ (is (not= h1 h2) "successive calls must produce distinct handles")
+ (is (= "first" (mcp.session/read-handle session-id h1)))
+ (is (= "second" (mcp.session/read-handle session-id h2)))
+ (is (nil? (mcp.session/read-handle session-id (str (random-uuid))))
+ "read-handle returns nil for unknown handles"))))
+
+(deftest read-handle-is-scoped-to-session-test
+ (testing "read-handle does not resolve handles from another MCP session"
+ (let [user-id (mt/user->id :crowberto)
+ owner-session (mcp.session/create! user-id)
+ other-session (mcp.session/create! user-id)
+ handle (mcp.session/store-handle! owner-session user-id "payload")]
+ (is (= "payload" (mcp.session/read-handle owner-session handle)))
+ (is (nil? (mcp.session/read-handle other-session handle))))))
+
+(deftest store-handle-cascades-with-core-session-test
+ (testing "deleting the backing core_session cascades to its handles"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ handle (mcp.session/store-handle! session-id user-id "payload")]
+ (is (= "payload" (mcp.session/read-handle session-id handle)))
+ (t2/delete! :core_session :key_hashed (derived-hash session-id))
+ (is (nil? (mcp.session/read-handle session-id handle))
+ "cascade should reap the handle when the core_session row goes"))))
+
+(deftest delete-removes-handles-test
+ (testing "delete! removes handles for the session"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ handle (mcp.session/store-handle! session-id user-id "payload")
+ _ (mcp.session/delete! session-id user-id)]
+ (is (nil? (mcp.session/read-handle session-id handle))))))
+
+(deftest session-does-not-fire-login-event-test
+ (testing "Creating a core_session via get-or-create-session-key! does not publish :event/user-login"
+ (let [login-events (atom [])
+ user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)]
+ (mt/with-dynamic-fn-redefs [events/publish-event! (fn [topic payload]
+ (when (= topic :event/user-login)
+ (swap! login-events conj payload)))]
+ (mcp.session/get-or-create-session-key! session-id user-id))
+ (is (empty? @login-events)
+ "No :event/user-login should be published for MCP embedding sessions"))))
diff --git a/test/metabase/mcp/tools_test.clj b/test/metabase/mcp/tools_test.clj
new file mode 100644
index 00000000000..e6442d0537c
--- /dev/null
+++ b/test/metabase/mcp/tools_test.clj
@@ -0,0 +1,4 @@
+(ns metabase.mcp.tools-test
+ "scope-matches? tests moved to [[metabase.mcp.scope-test]]."
+ (:require
+ [clojure.test :refer :all]))