Skip to content

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

Prepare the MCP for ChatGPT app (#74435)

Timofey Kachalov5bfdd32be3b1
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 35074be78cb..817d56836bf 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -178,6 +178,7 @@
clojure.core.async/take!
clojure.core.async/to-chan!
clojure.core.async/to-chan!!
+ metabase.api.macros.defendpoint.tools-manifest/assert-optional-fields-nullable!
metabase.channel.core/send!
metabase.warehouses.models.database/assert-not-h2!
metabase.driver.sql-jdbc.execute/execute-prepared-statement!
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 0f982949f03..4fe0cf58537 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1933,6 +1933,7 @@
{:team "UX West"
:api #{metabase.server.core
metabase.server.init
+ metabase.server.middleware.security
metabase.server.middleware.session
metabase.server.settings
metabase.server.streaming-response} ; TODO -- too many API namespaces
diff --git a/resources/metabase/agent_api/construct_query.md b/resources/metabase/agent_api/construct_query.md
index 83e1c962bf3..2f9ad96b21d 100644
--- a/resources/metabase/agent_api/construct_query.md
+++ b/resources/metabase/agent_api/construct_query.md
@@ -8,7 +8,7 @@ Construct a Metabase MBQL query from a structured program. The body is the progr
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.
+In MCP, this returns `{"query_handle": "<uuid>"}` — pass `query_handle` to `execute_query` or `visualize_query`. 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.
@@ -16,7 +16,7 @@ IMPORTANT: field IDs must come from entity-detail endpoints (`/v1/table/{id}`, `
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. 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`.
+3. Pass `query_handle` to the follow-up `execute_query` or `visualize_query` call.
Never embed IDs you did not read from a metadata endpoint — invented IDs will fail at execution.
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index fc345f43420..a69981ca248 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -397,7 +397,7 @@
capturing the user's original intent when a caller has one."
(mut/merge agent-lib/program-schema
[:map
- [:prompt {:optional true} ConstructQueryPrompt]]))
+ [:prompt {:optional true} [:maybe ConstructQueryPrompt]]]))
(mr/def ::construct-query-response
"Response containing a base64-encoded MBQL query and, when supplied, the original prompt for use with /v1/execute."
@@ -420,7 +420,7 @@
"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"
+ "Returns `{\"query_handle\": \"<uuid>\"}` — pass `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}`). "
@@ -430,7 +430,7 @@
"## 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"
+ "3. Pass `query_handle` to the follow-up `execute_query` or `visualize_query` call.\n"
"Never embed IDs you did not read from a metadata endpoint — invented IDs will fail at execution.\n"
"\n"
"## Source\n"
@@ -761,7 +761,9 @@
"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.")
+ "instead. "
+ "Pass `query_handle` (preferred) from construct_query rather than constructing the "
+ "base64 query yourself.")
:annotations {:read-only? true :idempotent? true}}}
[_route-params
_query-params
diff --git a/src/metabase/api/macros/defendpoint/tools_manifest.clj b/src/metabase/api/macros/defendpoint/tools_manifest.clj
index fe2ba267737..652eb6572d7 100644
--- a/src/metabase/api/macros/defendpoint/tools_manifest.clj
+++ b/src/metabase/api/macros/defendpoint/tools_manifest.clj
@@ -7,7 +7,7 @@
- `name`, `description` — tool identity
- `endpoint` — HTTP method + path
- `inputSchema` — merged route + query + body parameters
- - `responseSchema` — from the endpoint's response schema
+ - `outputSchema` — derived from the endpoint's response schema
- `annotations` — MCP ToolAnnotations (readOnlyHint, destructiveHint, etc.)"
(:require
[clojure.string :as str]
@@ -160,28 +160,28 @@
:open-world? :openWorldHint})
(defn- method-default-annotations
- "Infer default MCP ToolAnnotations from HTTP method. POST defaults to non-destructive — opt
- in with `:destructive? true` for endpoints that actually destroy data."
+ "Default MCP ToolAnnotations for an HTTP method."
[method]
- (case method
- (:get :head) {:readOnlyHint true
- :idempotentHint true}
- :post {:destructiveHint false}
- :put {:destructiveHint false
- :idempotentHint true}
- :delete {:destructiveHint true
- :idempotentHint true}
- {}))
+ ;; `readOnlyHint`, `destructiveHint`, and `openWorldHint` are always present — some MCP clients
+ ;; (e.g. the ChatGPT Apps SDK) reject tools that omit them.
+ (merge {:readOnlyHint false
+ :destructiveHint false
+ ;; `openWorldHint` signals whether a tool reaches arbitrary external entities (e.g. a
+ ;; web-search tool) — false because Metabase tools stay within the user's own instance.
+ :openWorldHint false}
+ (case method
+ (:get :head) {:readOnlyHint true
+ :idempotentHint true}
+ :put {:idempotentHint true}
+ :delete {:destructiveHint true
+ :idempotentHint true}
+ {})))
(defn infer-annotations
"Compute MCP ToolAnnotations from HTTP method defaults merged with explicit `:annotations`.
- Returns `{:annotations <merged> :redundant <pairs> :contradictory? <bool>}`. Callers should
- reject `:redundant` entries (explicit declarations must add information beyond the
- HTTP-method default) and `:contradictory?` (a tool can't be both read-only and destructive).
-
- `destructiveHint` is dropped from `:annotations` when `readOnlyHint` is true since per the
- MCP spec it's only meaningful for non-read-only tools — but if both were `true` before the
- drop, the result is flagged `:contradictory?` rather than silently coalesced."
+ Returns `{:annotations <merged> :redundant <pairs> :contradictory? <bool>}`.
+ Callers should reject `:redundant` entries (explicit declarations must add information beyond
+ the HTTP-method default) and `:contradictory?` (a tool can't be both read-only and destructive)."
[method explicit-annotations]
(let [method-defaults (method-default-annotations method)
explicit (into {}
@@ -198,9 +198,9 @@
(when-let [mcp-key (annotation-key-mapping k)]
(when (= v (get method-defaults mcp-key))
[k v]))))
- explicit-annotations)]
- (cond-> {:annotations (cond-> merged
- read-only? (dissoc :destructiveHint))
+ explicit-annotations)
+ annotations merged]
+ (cond-> {:annotations annotations
:redundant redundant}
(and read-only? (true? (:destructiveHint merged)))
(assoc :contradictory? true))))
@@ -214,6 +214,56 @@
(when (:properties jss)
(select-keys jss [:properties :required])))))
+(defn strict-tool-input-schema
+ "Make an MCP inputSchema compatible with stricter LLM clients.
+
+ MCP allows normal JSON Schema optional object properties.
+ OpenAI's strict tool schema validation is narrower: every object property must be listed in `:required`.
+ The Malli source already models nullability via `[:maybe ...]` (see [[assert-optional-fields-nullable!]]),
+ so this only needs to widen `:required` and close the object — property types are left alone."
+ [schema]
+ (letfn [(strict-schema [schema]
+ (let [schema (cond-> schema
+ (:properties schema) (update :properties update-vals strict-schema)
+ (:items schema) (update :items strict-schema)
+ (:oneOf schema) (update :oneOf #(mapv strict-schema %))
+ (:anyOf schema) (update :anyOf #(mapv strict-schema %))
+ (:allOf schema) (update :allOf #(mapv strict-schema %)))]
+ (if (and (= "object" (:type schema)) (seq (:properties schema)))
+ (assoc schema
+ :required (vec (keys (:properties schema)))
+ :additionalProperties false)
+ schema)))]
+ (strict-schema schema)))
+
+(defn- nullable-malli?
+ "True when `schema` accepts `nil` (e.g. `[:maybe X]`, `:any`, `:nil`)."
+ [schema]
+ (try (mr/validate schema nil) (catch Throwable _ false)))
+
+(defn assert-optional-fields-nullable!
+ "Throw if any optional field reachable from `malli-schema` rejects an explicit null.
+ The strict-tool transform forces every property into `:required` (it does not widen property types),
+ so the only way for a strict MCP client to express \"no value\" is by sending null. If the Malli source
+ marks a field `:optional true` without `[:maybe ...]`, the published JSON Schema is required-and-non-
+ nullable — the `:optional` marker has no observable effect and the contract drifts from what the
+ schema says. The fix is at the schema definition: pair `:optional true` with `[:maybe ...]`."
+ [malli-schema tool-name]
+ (when malli-schema
+ (mc/walk
+ (mr/resolve-schema malli-schema)
+ (fn [schema _path children _opts]
+ (when (= :map (mc/type schema))
+ (doseq [[k props value-schema] children
+ :when (and (true? (:optional props))
+ (not (nullable-malli? value-schema)))]
+ (throw (ex-info (str "Tool " tool-name " input has optional non-nullable field "
+ (pr-str k) ". Mark it `[:maybe ...]` so the published JSON "
+ "Schema is nullable; otherwise `:optional` has no observable effect "
+ "under the strict-tool transform.")
+ {:tool tool-name :field k}))))
+ schema))))
+
(defn- merge-input-schemas
"Merge route, query, and body param schemas into a single inputSchema object.
Route params are always required. For body schemas that aren't simple maps (e.g. `:or`),
@@ -239,6 +289,17 @@
(seq all-props) (cond-> {:type "object" :properties all-props}
(seq all-req) (assoc :required all-req)))))
+(defn- tool-input-schema
+ "Derive a tool's MCP `inputSchema` from the endpoint's route/query/body Malli.
+ Linted by [[assert-optional-fields-nullable!]]: every optional field must be `[:maybe ...]` so the
+ published JSON Schema is already nullable, letting the strict transform leave property types alone.
+ Layers above (e.g. `metabase.mcp.tools`) may patch this for tools whose MCP input shape differs from
+ the endpoint's wire shape."
+ [tool-name form]
+ (doseq [k [:route :query :body]]
+ (assert-optional-fields-nullable! (get-in form [:params k :schema]) tool-name))
+ (some-> (merge-input-schemas form) strict-tool-input-schema))
+
(defn- response-schema->json-schema
"Convert an endpoint's response schema to JSON Schema for the tools manifest."
[response-schema]
@@ -248,6 +309,14 @@
response-schema)]
(malli->json-schema content))))
+(defn- tool-output-schema
+ "Derive a tool's MCP `outputSchema` from the endpoint's `:response-schema`.
+ No strict transform — outputs aren't constrained by OpenAI's strict-tool rules.
+ Layers above (e.g. `metabase.mcp.tools`) may patch this for tools whose MCP body transform
+ reshapes the endpoint response."
+ [form]
+ (response-schema->json-schema (:response-schema form)))
+
(defn- route-path->endpoint-path
"Convert Clout-style route path (`:id`) to curly-brace path (`{id}`)."
[path]
@@ -290,8 +359,8 @@
description (or (:description tool-md)
(:docstr form))
full-path (str prefix (route-path->endpoint-path route-path))
- input-schema (merge-input-schemas form)
- resp-schema (response-schema->json-schema (:response-schema form))
+ input-schema (tool-input-schema tool-name form)
+ output-schema (tool-output-schema form)
inferred (infer-annotations method (:annotations tool-md))
annotations (:annotations inferred)
_ (when (:contradictory? inferred)
@@ -312,7 +381,7 @@
:endpoint {:method (u/upper-case-en (name method))
:path full-path}}
input-schema (assoc :inputSchema input-schema)
- resp-schema (assoc :responseSchema resp-schema)
+ output-schema (assoc :outputSchema output-schema)
(seq annotations) (assoc :annotations annotations)
task-support (assoc :execution {:taskSupport (name task-support)})
(string? scope) (assoc :scope scope))))
diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.clj
index ddb71d6c12f..e9d8b13058e 100644
--- a/src/metabase/mcp/api.clj
+++ b/src/metabase/mcp/api.clj
@@ -9,21 +9,23 @@
[metabase.api.common :as api]
[metabase.api.macros.scope :as scope]
[metabase.api.open-api :as open-api]
+ [metabase.mcp.core :as mcp]
[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]
[metabase.request.core :as request]
+ [metabase.server.middleware.security :as mw.security]
[metabase.server.streaming-response :as streaming-response]
[metabase.system.core :as system]
+ [metabase.util :as u]
[metabase.util.json :as json]
[metabase.util.log :as log]
[oidc-provider.store :as oidc.store]
[throttle.core :as throttle])
(:import
(java.io BufferedWriter OutputStreamWriter)
- (java.net URI)
(java.nio.charset StandardCharsets)))
(set! *warn-on-reflection* true)
@@ -150,18 +152,40 @@
;;; ------------------------------------------------- Validation --------------------------------------------------
+(defn- normalize-domain
+ "Extract and lowercase the domain from a URL or Host-style header value.
+ Bracketed IPv6 forms (`[::1]:3000`) and ports are handled correctly. Returns nil for unparsable input.
+ Uses `try-parse-url` (the silent variant) — `Origin`/`Host` are client-controlled, so malformed inputs
+ are expected and shouldn't spam the error logs."
+ [url]
+ (some-> url str mw.security/try-parse-url :domain u/lower-case-en))
+
+(defn- same-origin-host? [origin host]
+ (let [origin-domain (normalize-domain origin)]
+ (and (some? origin-domain) (= origin-domain (normalize-domain host)))))
+
+(defn- approved-mcp-origin? [origin]
+ ;; Pre-lowercase both inputs so DNS hostname matching is case-insensitive (per RFC) and so mixed-case
+ ;; schemes still match `try-parse-url`'s lowercase-only `https?|app|capacitor` regex.
+ (boolean
+ (or (mcp/sandbox-origin? origin)
+ (when-let [approved-origins (not-empty (mcp/cors-origins))]
+ (when-let [origin-url (mw.security/try-parse-url (u/lower-case-en origin))]
+ (some (fn [approved-origin]
+ (and (mw.security/approved-domain? (:domain origin-url) (:domain approved-origin))
+ (mw.security/approved-protocol? (:protocol origin-url) (:protocol approved-origin))
+ (mw.security/approved-port? (:port origin-url) (:port approved-origin))))
+ (mw.security/parse-approved-origins (u/lower-case-en approved-origins))))))))
+
(defn- validate-origin
"Validate the Origin header to prevent DNS rebinding attacks (MCP spec requirement).
- Returns a 403 response if Origin is present and doesn't match the request's Host header.
- Non-browser clients that omit the Origin header are allowed through."
+ Returns a 403 response if Origin is present and is neither same-host nor an explicitly configured
+ MCP app origin. Non-browser clients that omit the Origin header are allowed through."
[request]
(when-let [origin (get-in request [:headers "origin"])]
(let [host (get-in request [:headers "host"])]
- (when-not (try
- (let [origin-host (.getHost (URI. origin))
- request-host (first (str/split (str host) #":"))]
- (= origin-host request-host))
- (catch Exception _ false))
+ (when-not (or (same-origin-host? origin host)
+ (approved-mcp-origin? origin))
(json-response 403 (jsonrpc-error nil -32600 "Origin not allowed"))))))
(defn- require-valid-session
diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.clj
index d34da839b19..5023279914f 100644
--- a/src/metabase/mcp/resources.clj
+++ b/src/metabase/mcp/resources.clj
@@ -10,12 +10,19 @@
nil scope is treated as internal-only."
(:require
[clojure.java.io :as io]
+ [clojure.string :as str]
+ [metabase.api.common :as api]
+ [metabase.api.macros.defendpoint.tools-manifest :as tools-manifest]
[metabase.mcp.scope :as mcp.scope]
[metabase.mcp.session :as mcp.session]
+ [metabase.request.core :as request]
[metabase.system.core :as system]
[metabase.util.json :as json]
[metabase.util.malli :as mu]
- [stencil.core :as stencil]))
+ [metabase.util.malli.schema :as ms]
+ [stencil.core :as stencil])
+ (:import
+ (java.net URI)))
(set! *warn-on-reflection* true)
@@ -80,13 +87,56 @@
:uri->resource (sorted-map)
:tools (sorted-map)}))
-(defn- ui-meta [resource]
- (let [url (system/site-url)]
+(defn- chatgpt-client?
+ "True when the in-flight request's User-Agent identifies the ChatGPT MCP/Apps
+ client. ChatGPT empirically sends `openai-mcp/...`; Claude rejects
+ `_meta.ui.domain` unless it's a Claude-issued subdomain, so we gate the field
+ on this check."
+ []
+ (boolean (some-> (request/current-request)
+ (get-in [:headers "user-agent"])
+ (str/includes? "openai-mcp"))))
+
+(defn- site-origin
+ "Origin (scheme://host[:port]) extracted from `site-url`, dropping any path segment.
+ ChatGPT's MCP host treats `_meta.ui.domain` and the CSP domain lists as origins, so an instance
+ hosted under a subpath would otherwise leak the path and fail validation. Returns nil when
+ `site-url` is unset — callers degrade gracefully rather than NPE on a misconfigured instance."
+ []
+ (when-let [url (system/site-url)]
+ (let [^URI uri (URI. url)
+ scheme (.getScheme uri)
+ host (.getHost uri)
+ port (.getPort uri)]
+ (cond-> (str scheme "://" host)
+ (not (neg? port)) (str ":" port)))))
+
+(defn- ui-meta
+ "MCP `_meta.ui` block returned alongside UI resources.
+ Hosts that render the resource in a sandboxed iframe (notably ChatGPT's MCP app surface) use this
+ to pick a sandbox configuration:
+
+ - `prefersBorder` — presentation hint asking the host to draw a frame border
+ - `domain` — origin the iframe content is anchored at. ChatGPT-only:
+ Claude validates this against its own namespace
+ (`*.claudemcpcontent.com`) and rejects anything else,
+ so we emit it only for ChatGPT (gated by [[chatgpt-client?]]).
+ - `csp.connectDomains` — hosts the iframe may XHR/fetch/WebSocket to
+ (the embedded SDK calls back to this Metabase instance)
+ - `csp.resourceDomains` — hosts the iframe may load scripts/styles/images from
+ (the SDK bundle is served from this Metabase instance)
+
+ `frameDomains` is intentionally omitted — we don't nest iframes inside the visualization, and leaving
+ it out narrows the CSP for security review."
+ [resource]
+ (let [url (site-origin)]
{:ui (cond-> {:csp {:connectDomains [url]
- :resourceDomains [url]
- :frameDomains [url]}}
+ :resourceDomains [url]}}
(contains? resource :prefersBorder)
- (assoc :prefersBorder (:prefersBorder resource)))}))
+ (assoc :prefersBorder (:prefersBorder resource))
+
+ (chatgpt-client?)
+ (assoc :domain url))}))
(mu/defn register-resource!
"Register an MCP resource. Overwrites any existing entry with the same `:uri`."
@@ -117,16 +167,33 @@
(assoc-in [:uri->resource uri] resource)))
resource))
+(defn- malli->ui-input-schema
+ "Convert a Malli schema for a UI-tool input into the published JSON Schema."
+ [schema]
+ (-> schema tools-manifest/malli->json-schema tools-manifest/strict-tool-input-schema))
+
+(defn- malli->ui-output-schema
+ "Convert a Malli schema for a UI-tool output into the published JSON Schema.
+ No strict transform — outputs aren't constrained by OpenAI's strict-tool rules."
+ [schema]
+ (tools-manifest/malli->json-schema schema))
+
(mu/defn- register-ui-tool!
+ "Register a UI tool. `inputSchema` and `outputSchema` are Malli schemas (not JSON Schema)."
[resource-key :- :keyword
tool :- [:map
[:name :string]
[:description :string]
- [:inputSchema :map]
+ [:inputSchema :any]
+ [:outputSchema {:optional true} :any]
+ [:annotations {:optional true} :map]
[:response-fn fn?]]]
(if-let [uri (get-in @registry [:key->uri resource-key])]
(let [scope (get-in @registry [:uri->resource uri :scope])
- tool (assoc tool :scope scope :_meta {:ui {:resourceUri uri}})]
+ tool (-> tool
+ (update :inputSchema malli->ui-input-schema)
+ (cond-> (:outputSchema tool) (update :outputSchema malli->ui-output-schema))
+ (assoc :scope scope :_meta {:ui {:resourceUri uri}}))]
(swap! registry assoc-in [:tools (:name tool)] tool)
tool)
(throw (ex-info "Unknown resource" {:resource-key resource-key}))))
@@ -233,17 +300,32 @@
;; 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"}}}
+ :inputSchema
+ [:map
+ [:query {:optional true
+ :description "Base64-encoded MBQL query (use query_handle instead when available)"}
+ [:maybe ms/NonBlankString]]
+ [:query_handle {:optional true
+ :description "Handle returned by construct_query; preferred over raw query"}
+ [:maybe ms/UUIDString]]]
+ :outputSchema
+ [:map
+ [:query {:description "Base64-encoded MBQL query that the visualization is rendering."}
+ :string]
+ [:prompt {:optional true
+ :description "User's original request, when stored alongside the handle."}
+ [:maybe :string]]]
+ :annotations {:readOnlyHint true
+ :destructiveHint false
+ :idempotentHint true
+ :openWorldHint false}
: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)]
+ (let [query (:query arguments)
+ handle (:query_handle arguments)
+ resolved (some->> handle (mcp.session/resolve-query-handle
+ session-id api/*current-user-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'."}]
@@ -270,14 +352,22 @@
"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"]}
+ :inputSchema
+ [:map
+ [:handle {:description "Handle UUID from the user's drill-through message."}
+ ms/UUIDString]]
+ :outputSchema
+ [:map
+ [:query {:description "Base64-encoded MBQL query bound to the drill-through handle."}
+ :string]]
+ :annotations {:readOnlyHint true
+ :destructiveHint false
+ :idempotentHint true
+ :openWorldHint false}
: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..."}]
+ (if-let [encoded (mcp.session/read-handle session-id api/*current-user-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})
diff --git a/src/metabase/mcp/session.clj b/src/metabase/mcp/session.clj
index 0ce762e9661..91983ddf470 100644
--- a/src/metabase/mcp/session.clj
+++ b/src/metabase/mcp/session.clj
@@ -20,6 +20,7 @@
[metabase.mcp.models.mcp-query-handle]
[metabase.mcp.settings :as mcp.settings]
[metabase.session.core :as session]
+ [metabase.util.log :as log]
[toucan2.core :as t2])
(:import
(java.nio ByteBuffer)
@@ -148,41 +149,63 @@
;; 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)))
+ "Insert a new handle row binding `encoded-query` to the calling user, and return the handle UUID.
+
+ `mcp-session-id` is recorded so DELETE /api/mcp can sweep the session's handles, and so reads can log
+ when a handle is resolved across sessions (see [[find-handle-row]]) — the read path itself is purely
+ user-scoped, since handle UUIDs are globally unique.
+
+ `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."
+ ([mcp-session-id user-id encoded-query]
+ (store-handle! mcp-session-id user-id encoded-query nil))
+ ([mcp-session-id user-id encoded-query prompt]
+ ;; Materializing a core_session here serves two purposes: its FK is what makes handles
+ ;; cascade-delete when the session row is reaped, and its user_id is what find-handle-row
+ ;; filters on for cross-session ownership.
+ (let [core-session-id (:id (get-or-create-embedding-session! mcp-session-id user-id))
handle-id (str (UUID/randomUUID))]
(t2/insert! :model/McpQueryHandle
(cond-> {:id handle-id
- :mcp_session_id session-id
+ :mcp_session_id mcp-session-id
:core_session_id core-session-id
:encoded_query encoded-query}
prompt (assoc :prompt prompt)))
handle-id)))
+(defn- find-handle-row
+ "Look up the handle row by `handle-id`, scoped to `user-id`.
+ Handle ids are globally unique UUIDs, so the join's `WHERE mqh.id = handle-id` returns at most one
+ row by definition — no ordering or session-preference logic is needed. `mcp-session-id` is recorded
+ on the row only so harnesses that rotate MCP sessions between calls (e.g. ChatGPT) can be logged as
+ cross-session resolutions for telemetry."
+ [mcp-session-id user-id handle-id]
+ (when (and user-id handle-id)
+ ;; Single round-trip: join `mcp_query_handle` to `core_session` and filter on
+ ;; `core_session.user_id`, so ownership is enforced in the WHERE clause.
+ (let [row (t2/select-one :model/McpQueryHandle
+ {:select [:mqh.*]
+ :from [[:mcp_query_handle :mqh]]
+ :join [[:core_session :cs] [:= :cs.id :mqh.core_session_id]]
+ :where [:and
+ [:= :mqh.id handle-id]
+ [:= :cs.user_id user-id]]})]
+ (when (and row (not= mcp-session-id (:mcp_session_id row)))
+ (log/debugf "MCP handle %s resolved across sessions for user %s"
+ handle-id user-id))
+ row)))
+
(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))
+ "Return the encoded query for `handle-id` owned by `user-id`, or nil if no row exists.
+ Lookup is user-scoped — see [[find-handle-row]] for how `mcp-session-id` is used."
+ [mcp-session-id user-id handle-id]
+ (:encoded_query (find-handle-row mcp-session-id user-id handle-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)]
+ "Return {:encoded_query ... :prompt ...} for `handle-id` owned by `user-id`, or nil.
+ Lookup is user-scoped — see [[find-handle-row]] for how `mcp-session-id` is used."
+ [mcp-session-id user-id handle-id]
+ (when-let [row (find-handle-row mcp-session-id user-id handle-id)]
(select-keys row [:encoded_query :prompt])))
(defn delete!
diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.clj
index 0e9071a499e..4b7288706e6 100644
--- a/src/metabase/mcp/tools.clj
+++ b/src/metabase/mcp/tools.clj
@@ -14,7 +14,9 @@
[metabase.server.streaming-response :as streaming-response]
[metabase.util :as u]
[metabase.util.json :as json]
- [metabase.util.log :as log])
+ [metabase.util.log :as log]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms])
(:import
(java.io ByteArrayOutputStream)
(java.net URLEncoder)
@@ -22,11 +24,130 @@
(set! *warn-on-reflection* true)
+;;; ---------------------------- MCP schema overrides -------------------------------
+;;
+;; A few tools have an MCP-visible input or output shape that differs from the wire shape declared
+;; on the defendpoint. Owning the override here keeps `agent-api` ignorant of MCP: the endpoint
+;; describes its own wire schema, and this layer patches the manifest to publish the MCP-visible
+;; shape.
+
+;; Shared sub-shapes for the program-shaped tools (`construct_query`, `query`). Extracted so the two
+;; tools can't drift on what a program looks like to the LLM — both reuse the same `:source` map and
+;; the same flattened `:operations` (`[:sequential [:sequential :any]]`, no tuple-of-anys, no `:and`).
+;; The wire schemas under `agent_api` use the precise tuple/composite grammar; this layer publishes
+;; the permissive variant strict MCP clients (ChatGPT) accept.
+
+(def ^:private program-source-malli
+ [:map
+ [:type {:tool/description "Entity kind."}
+ [:enum "table" "card" "dataset" "metric"]]
+ [:id ms/PositiveInt]])
+
+(def ^:private program-operations-malli
+ [:sequential
+ [:sequential
+ {:tool/description (str "First element is the operator string; remaining "
+ "elements are operator-specific arguments (scalars, "
+ "references, or nested arrays).")}
+ :any]])
+
+(def ^:private operations-description
+ (str "Array of operator tuples like [\"filter\", clause] or [\"aggregate\", agg-clause]. "
+ "See metabase://docs/construct-query.md for the full grammar."))
+
+(def ^:private construct-query-mcp-input-malli
+ "MCP-visible input for `construct_query`.
+ Deliberately flatter than the wire schema — the operator/ref grammar is conveyed through the tool
+ description and the construct-query.md MCP resource, not the schema."
+ [:map
+ [:source {:tool/description "Database entity to query."}
+ program-source-malli]
+ [:operations {:tool/description operations-description}
+ program-operations-malli]
+ ;; Length bounds + description go on the inner `:string` so they end up on the JSON Schema branch
+ ;; (and not as an `:allOf`, which ChatGPT's strict validator rejects).
+ [:prompt {:optional true}
+ [:maybe [:string {:min 1
+ :max 10000
+ :tool/description (str "The user's exact original message, when available. "
+ "Pass it as-is without summarizing or rewriting.")}]]]])
+
+(def ^:private query-mcp-input-malli
+ "MCP-visible input for `query`. The wire body is a `:multi` whose `:program` branch references
+ agent-lib tuple/composite schemas — those emit `prefixItems`/`allOf` JSON Schema constructs that
+ strict MCP clients (ChatGPT) reject. This override publishes the same flattened program shape used
+ by `construct_query`, plus the `:continuation_token` alternative for pagination."
+ [:map
+ [:source {:optional true
+ :tool/description (str "Database entity to query. Omit when paginating via "
+ "`continuation_token`.")}
+ [:maybe program-source-malli]]
+ [:operations {:optional true
+ :tool/description operations-description}
+ [:maybe program-operations-malli]]
+ [:continuation_token {:optional true
+ :tool/description (str "Token returned by a previous `query` response — pass "
+ "it back to fetch the next page. Mutually exclusive "
+ "with `source`/`operations`.")}
+ [:maybe ms/NonBlankString]]])
+
+(def ^:private execute-query-mcp-input-malli
+ "MCP-visible input for `execute_query`.
+ The wire endpoint requires `:query`; the MCP tool also accepts `:query_handle`, resolved by
+ [[resolve-query-arg]] before dispatch."
+ [:map
+ [:query {:optional true
+ :tool/description "Base64-encoded MBQL query. Use `query_handle` instead when available."}
+ [:maybe ms/NonBlankString]]
+ [:query_handle {:optional true
+ :tool/description "Handle returned by construct_query — preferred over raw `query`."}
+ [:maybe ms/UUIDString]]])
+
+(def ^:private construct-query-mcp-output-malli
+ "MCP-visible output of `construct_query`.
+ The agent_api endpoint returns `{:query base64}`; the MCP body transform stores that and emits
+ `{:query_handle}`."
+ [:map
+ [:query_handle
+ {:tool/description (str "Opaque UUID handle for the stored query. "
+ "Pass as `query_handle` to `execute_query` or `visualize_query`.")}
+ ms/UUIDString]])
+
+(def ^:private mcp-input-overrides
+ "tool-name → Malli schema. Replaces the manifest's derived `:inputSchema`."
+ {"construct_query" construct-query-mcp-input-malli
+ "query" query-mcp-input-malli
+ "execute_query" execute-query-mcp-input-malli})
+
+(def ^:private mcp-output-overrides
+ "tool-name → Malli schema. Replaces the manifest's derived `:outputSchema`."
+ {"construct_query" construct-query-mcp-output-malli})
+
+(defn- override->input-json-schema [malli tool-name]
+ (tools-manifest/assert-optional-fields-nullable! malli tool-name)
+ (-> malli tools-manifest/malli->json-schema tools-manifest/strict-tool-input-schema))
+
+(defn- apply-schema-overrides
+ "Replace `:inputSchema`/`:outputSchema` on tools whose MCP-visible shape differs from the wire shape.
+ The `overrides-cover-known-tools-test` test asserts every key here matches a real tool name; a
+ misspelled or drifted key would otherwise silently no-op and leave the wire shape published."
+ [tools]
+ (mapv (fn [{tool-name :name :as tool}]
+ (cond-> tool
+ (mcp-input-overrides tool-name)
+ (assoc :inputSchema (override->input-json-schema (mcp-input-overrides tool-name) tool-name))
+
+ (mcp-output-overrides tool-name)
+ (assoc :outputSchema (tools-manifest/malli->json-schema (mcp-output-overrides tool-name)))))
+ tools))
+
(defn- generate-manifest
- "Generate tools manifest from agent API endpoint metadata."
+ "Generate tools manifest from agent API endpoint metadata, then patch input/output schemas for tools
+ whose MCP-visible shape differs from the wire shape."
[]
- (tools-manifest/generate-tools-manifest
- {'metabase.agent-api.api "/api/agent"}))
+ (-> (tools-manifest/generate-tools-manifest
+ {'metabase.agent-api.api "/api/agent"})
+ (update :tools apply-schema-overrides)))
(def ^:private manifest-delay
(delay (generate-manifest)))
@@ -46,7 +167,7 @@
(into []
(comp (filter #(mcp.scope/matches? token-scopes (:scope %)))
(map (fn [tool]
- (select-keys tool [:name :title :description :inputSchema :annotations :_meta]))))
+ (select-keys tool [:name :title :description :inputSchema :outputSchema :annotations :_meta]))))
(concat tools (mcp.resources/list-ui-tools)))))
(defn- build-tool-index
@@ -107,34 +228,51 @@
"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.
+ it too (and log a warning).
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))
+ (let [user-id api/*current-user-id*]
+ (cond
+ (:query_handle arguments)
+ (if-let [{:keys [encoded_query]} (mcp.session/resolve-query-handle
+ session-id user-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 user-id (:query arguments))]
+ (assoc arguments :query encoded_query)
+ ::handle-not-found))
+
+ :else
+ arguments)))
+
+(def ^:private construct-query-output-validator
+ (mr/validator construct-query-mcp-output-malli))
(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."
+ "Build a body-transform fn for construct_query.
+ The fn stores the base64 payload server-side under the calling user (with the current MCP session id
+ recorded for cleanup) and returns {:query_handle uuid} instead of {:query base64}, so the LLM carries
+ a short opaque UUID rather than the full base64 string.
+ The optional prompt is stored with the handle for later feedback submission.
+
+ The fn validates its emitted shape against `construct-query-mcp-output-malli` — the same schema the
+ manifest publishes as the tool's outputSchema — keeping the published schema and the actual emitted
+ body in lockstep."
[session-id user-id]
(fn [body]
(if-let [encoded (:query body)]
- {:query_handle (mcp.session/store-handle! session-id user-id encoded (:prompt body))}
+ (let [handle (mcp.session/store-handle! session-id user-id encoded (:prompt body))
+ new-body {:query_handle handle}]
+ (when-not (construct-query-output-validator new-body)
+ (throw (ex-info (str "construct_query body transform produced a shape that doesn't "
+ "match the declared outputSchema")
+ {:body new-body})))
+ new-body)
body)))
;; Tools that accept :query_handle as an alternative to a raw base64 :query string.
@@ -144,9 +282,13 @@
;;; ------------------------------------------------- Tool Dispatch -------------------------------------------------
(defn- text-content
- "Wrap a value as MCP text content."
+ "Wrap a value as an MCP tool-call result.
+ Map/sequential values are surfaced as `structuredContent` — MCP spec requires this for any tool that
+ declares an `outputSchema`.
+ The `content` array carries a text serialization for clients that don't consume structuredContent."
[v]
- {:content [{:type "text" :text (if (string? v) v (json/encode v))}]})
+ (cond-> {:content [{:type "text" :text (if (string? v) v (json/encode v))}]}
+ (or (map? v) (sequential? v)) (assoc :structuredContent v)))
(defn- error-content
"Wrap an error message as MCP error content."
@@ -257,6 +399,31 @@
(invoke-agent-api method api-path token-scopes remaining-args
:body-transform-fn body-transform-fn)))
+;; --- Design note: centralized null-stripping at the MCP boundary --------------------------------
+;; The MCP inputSchema we publish makes every optional field required-and-nullable, because strict
+;; MCP clients (notably ChatGPT) cannot represent absent fields — they always send every property
+;; the schema declares, with `null` for the ones the agent doesn't want to populate. We strip
+;; those nulls here so each downstream tool handler can use ordinary Clojure idioms (destructure
+;; `:or` defaults, `(when foo …)`, etc.) and treat missing and null identically.
+;;
+;; The alternative is per-tool auditing: every endpoint handler would need to coerce nil into the
+;; right default, and every wire schema's dispatch logic would need to tolerate explicit nulls. We
+;; chose centralization because (a) it's the layer that creates the strict-validator artifact, and
+;; (b) the codex review found that `query`'s `:multi` dispatch on `:continuation_token` already
+;; mishandled a client-sent `null`, so per-tool handling is easy to miss.
+;;
+;; TRADE-OFF: as a consequence, a top-level `null` argument is indistinguishable from omitted at
+;; the MCP boundary. If we ever expose a tool whose semantics genuinely require `null` to mean
+;; something different from "missing" (e.g. \"clear this field\" semantics), it must either model
+;; the distinction with a sentinel value (`{:clear true}`) or do the bespoke handling before this
+;; normalization runs (e.g. as a pre-processing step inside `call-tool`).
+(defn- drop-nil-args
+ "Strip nil-valued top-level keys from MCP tool arguments.
+ Nested values are left alone — the strict-tool transform only rewrites top-level properties."
+ [arguments]
+ (when arguments
+ (into {} (remove (comp nil? val)) arguments)))
+
(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
@@ -265,20 +432,21 @@
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 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))
+ (let [arguments (drop-nil-args 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))
- (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)))))
+ ((: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/server/middleware/security.clj b/src/metabase/server/middleware/security.clj
index 4c7e91e8a33..c89fb369207 100644
--- a/src/metabase/server/middleware/security.clj
+++ b/src/metabase/server/middleware/security.clj
@@ -60,20 +60,26 @@
the original request was HTTPS; if sent in response to an HTTP request, this is simply ignored)"
{"Strict-Transport-Security" "max-age=31536000"})
-(defn parse-url
- "Returns an object with protocol, domain and port for the given url"
+(defn try-parse-url
+ "Like `parse-url` but returns nil silently on unparsable input. Use this when the caller is parsing
+ client-controlled data (e.g. `Origin`/`Host` headers) where bad input is expected and shouldn't
+ fill the error logs."
[url]
(if (= url "*")
{:protocol nil :domain "*" :port "*"}
;; Pattern supports both regular hostnames/IPv4 and bracketed IPv6 addresses like [::1]
(let [pattern #"^(?:(https?|app|capacitor)://)?(\[[^\]]+\]|[^:/]+)(?::(\d+|\*))?$"
- matches (re-matches pattern url)]
- (if-not matches
- (do (log/errorf "Invalid URL: %s" url) nil)
- (let [[_ protocol domain port] matches]
- {:protocol protocol
- :domain domain
- :port port})))))
+ [_ protocol domain port] (re-matches pattern url)]
+ (when domain
+ {:protocol protocol :domain domain :port port}))))
+
+(defn parse-url
+ "Returns an object with protocol, domain and port for the given url. Logs an error when the input
+ doesn't parse — appropriate for server-side config (where bad input indicates a misconfiguration).
+ For client-controlled input prefer [[try-parse-url]]."
+ [url]
+ (or (try-parse-url url)
+ (do (log/errorf "Invalid URL: %s" url) nil)))
(defn- add-wildcard-entries
"Adds a wildcard prefix `.*` to the domain part of the given `domain-or-url` string.
diff --git a/test/metabase/api/macros/defendpoint/tools_manifest_test.clj b/test/metabase/api/macros/defendpoint/tools_manifest_test.clj
index a0e8d30a97f..94925ba8169 100644
--- a/test/metabase/api/macros/defendpoint/tools_manifest_test.clj
+++ b/test/metabase/api/macros/defendpoint/tools_manifest_test.clj
@@ -6,39 +6,78 @@
[metabase.util.malli.registry :as mr])
(:import (clojure.lang ExceptionInfo)))
+(deftest ^:parallel assert-optional-fields-nullable!-test
+ (testing "no throw when every :optional field is also nullable via [:maybe ...]"
+ (is (some? (tools-manifest/assert-optional-fields-nullable!
+ [:map [:foo {:optional true} [:maybe :string]]] "ok-tool"))))
+ (testing "no throw when there are no :optional fields"
+ (is (some? (tools-manifest/assert-optional-fields-nullable!
+ [:map [:foo :string] [:bar :int]] "no-optional-tool")))
+ (is (nil? (tools-manifest/assert-optional-fields-nullable! nil "nil-schema-tool"))))
+ (testing "throws when an :optional field rejects nil"
+ (let [ex (try (tools-manifest/assert-optional-fields-nullable!
+ [:map [:foo {:optional true} :string]] "bad-tool")
+ (catch ExceptionInfo e e))]
+ (is (instance? ExceptionInfo ex))
+ (is (= "bad-tool" (-> ex ex-data :tool)))
+ (is (= :foo (-> ex ex-data :field)))))
+ (testing "walks composites — `:or` of maps catches the offender inside a branch"
+ (let [schema [:or
+ [:map [:foo :string]]
+ [:map [:bar {:optional true} :int]]]
+ ex (try (tools-manifest/assert-optional-fields-nullable! schema "or-tool")
+ (catch ExceptionInfo e e))]
+ (is (instance? ExceptionInfo ex))
+ (is (= :bar (-> ex ex-data :field)))))
+ (testing "walks into nested map properties"
+ (let [schema [:map
+ [:outer [:map
+ [:inner {:optional true} :int]]]]
+ ex (try (tools-manifest/assert-optional-fields-nullable! schema "nested-tool")
+ (catch ExceptionInfo e e))]
+ (is (instance? ExceptionInfo ex))
+ (is (= :inner (-> ex ex-data :field))))))
+
(deftest ^:parallel infer-annotations-test
(testing "GET defaults"
- (is (= {:annotations {:readOnlyHint true :idempotentHint true}
+ (is (= {:annotations {:readOnlyHint true :idempotentHint true :destructiveHint false :openWorldHint false}
:redundant {}}
(tools-manifest/infer-annotations :get nil))))
(testing "DELETE defaults"
- (is (= {:annotations {:destructiveHint true :idempotentHint true}
+ (is (= {:annotations {:destructiveHint true :idempotentHint true :readOnlyHint false :openWorldHint false}
:redundant {}}
(tools-manifest/infer-annotations :delete nil))))
(testing "PUT defaults"
- (is (= {:annotations {:destructiveHint false :idempotentHint true}
+ (is (= {:annotations {:destructiveHint false :idempotentHint true :readOnlyHint false :openWorldHint false}
:redundant {}}
(tools-manifest/infer-annotations :put nil))))
(testing "POST defaults to non-destructive (opt in with :destructive? true)"
- (is (= {:annotations {:destructiveHint false} :redundant {}}
+ (is (= {:annotations {:destructiveHint false :readOnlyHint false :openWorldHint false}
+ :redundant {}}
(tools-manifest/infer-annotations :post nil)))
(is (= {:destructive? false}
(:redundant (tools-manifest/infer-annotations :post {:destructive? false})))))
- (testing "destructiveHint is dropped from output when readOnlyHint is true (per MCP spec it's only meaningful for non-read-only tools)"
- (is (= {:readOnlyHint true}
+ (testing "POST's method defaults carry destructiveHint false / openWorldHint false; explicit :read-only? true is merged on top"
+ (is (= {:readOnlyHint true :destructiveHint false :openWorldHint false}
(:annotations (tools-manifest/infer-annotations :post {:read-only? true})))))
(testing "Flags :contradictory? when readOnlyHint and destructiveHint would both be true before the cleanup"
(is (true? (:contradictory? (tools-manifest/infer-annotations :get {:destructive? true}))))
(is (true? (:contradictory? (tools-manifest/infer-annotations :delete {:read-only? true})))))
(testing "Explicit annotations are merged on top of method defaults"
- (is (= {:annotations {:readOnlyHint true :idempotentHint true}
+ (is (= {:annotations {:readOnlyHint true :idempotentHint true :destructiveHint false :openWorldHint false}
:redundant {}}
(tools-manifest/infer-annotations :post {:read-only? true :idempotent? true}))))
(testing "Reports redundant pairs that match what we'd already infer (using developer-facing keys)"
(is (= {:read-only? true}
(:redundant (tools-manifest/infer-annotations :get {:read-only? true}))))
(is (= {:destructive? false}
- (:redundant (tools-manifest/infer-annotations :put {:destructive? false}))))))
+ (:redundant (tools-manifest/infer-annotations :put {:destructive? false})))))
+ (testing "readOnlyHint, destructiveHint, openWorldHint are always present (some MCP clients reject tools without them)"
+ (doseq [method [:get :post :put :delete :head]]
+ (let [ann (:annotations (tools-manifest/infer-annotations method nil))]
+ (is (contains? ann :readOnlyHint) (str method " missing :readOnlyHint"))
+ (is (contains? ann :destructiveHint) (str method " missing :destructiveHint"))
+ (is (contains? ann :openWorldHint) (str method " missing :openWorldHint"))))))
(deftest ^:parallel prefer-tool-descriptions-test
(testing "tool/description replaces description in JSON schema output"
@@ -231,12 +270,15 @@
:endpoint {:method "GET" :path "/api/agent/v1/table/{id}"}
:inputSchema {:type "object"
:properties {:id {:type "integer"}}
- :required [:id]}
- :responseSchema {:type "object"
- :properties {:name {:type "string"}}
- :required [:name]}
- :annotations {:readOnlyHint true
- :idempotentHint true}}
+ :required [:id]
+ :additionalProperties false}
+ :outputSchema {:type "object"
+ :properties {:name {:type "string"}}
+ :required [:name]}
+ :annotations {:readOnlyHint true
+ :idempotentHint true
+ :destructiveHint false
+ :openWorldHint false}}
result))))
(testing "Scope is included when metadata has :scope"
@@ -331,8 +373,8 @@
{:keys [q limit]} :- [:map
[:q :string]
[:limit {:optional true}
- [:int {:description "Max results"
- :tool/description "Maximum number of results to return"}]]]]
+ [:maybe [:int {:description "Max results"
+ :tool/description "Maximum number of results to return"}]]]]]
{:results []})
;; 5. POST with route + body params, task-support, and registered schema in response
@@ -411,66 +453,72 @@
(is (= {:name "test_get_thing"
:title "Test Get Thing"
:description "A test endpoint for tools manifest generation."
- :annotations {:readOnlyHint true :idempotentHint true}
+ :annotations {:readOnlyHint true :idempotentHint true :destructiveHint false :openWorldHint false}
:endpoint {:method "GET" :path "/api/test/v1/test/{id}"}
:inputSchema {:type "object"
:properties {:id {:type "integer"}}
- :required [:id]}}
+ :required [:id]
+ :additionalProperties false}}
(test-tool "test_get_thing"))))
(deftest ^:parallel generate-tools-manifest-post-with-annotation-override-test
(is (= {:name "test_action"
:title "Test Action"
:description "A test POST action."
- :annotations {:readOnlyHint true}
+ :annotations {:readOnlyHint true :destructiveHint false :openWorldHint false}
:endpoint {:method "POST" :path "/api/test/v1/test-action"}
:inputSchema {:type "object"
:properties {:name {:type "string"}}
- :required [:name]}}
+ :required [:name]
+ :additionalProperties false}}
(test-tool "test_action"))))
(deftest ^:parallel generate-tools-manifest-delete-test
(is (= {:name "delete_test"
:title "Delete Test"
:description "Delete a test resource."
- :annotations {:destructiveHint true :idempotentHint true}
+ :annotations {:destructiveHint true :idempotentHint true :readOnlyHint false :openWorldHint false}
:endpoint {:method "DELETE" :path "/api/test/v1/test/{id}"}
:inputSchema {:type "object"
:properties {:id {:type "integer"}}
- :required [:id]}}
+ :required [:id]
+ :additionalProperties false}}
(test-tool "delete_test"))))
(deftest ^:parallel generate-tools-manifest-get-with-query-params-test
(is (= {:name "test_search"
:title "Test Search"
:description "Search for things."
- :annotations {:readOnlyHint true :idempotentHint true}
+ :annotations {:readOnlyHint true :idempotentHint true :destructiveHint false :openWorldHint false}
:endpoint {:method "GET" :path "/api/test/v1/test-search"}
:inputSchema {:type "object"
:properties {:q {:type "string"}
- :limit {:type "integer"
- :description "Maximum number of results to return"}}
- :required [:q]}
- :responseSchema {:type "object"
- :properties {:results {:type "array" :items {:type "string"}}}
- :required [:results]}}
+ :limit {:oneOf [{:type "integer"
+ :description "Maximum number of results to return"}
+ {:type "null"}]}}
+ :required [:q :limit]
+ :additionalProperties false}
+ :outputSchema {:type "object"
+ :properties {:results {:type "array" :items {:type "string"}}}
+ :required [:results]}}
(test-tool "test_search"))))
(deftest ^:parallel generate-tools-manifest-post-with-task-support-test
(is (= {:name "test_resource_action"
:title "Test Resource Action"
:description "Perform an action on a resource."
- :annotations {:readOnlyHint true}
+ :annotations {:readOnlyHint true :destructiveHint false :openWorldHint false}
:endpoint {:method "POST" :path "/api/test/v1/test-resource/{id}/action"}
:inputSchema {:type "object"
:properties {:id {:type "integer"}
:action {:type "string"}}
- :required [:id :action]}
- :responseSchema {:type "object"
- :properties {:id {:type "integer"}
- :status {:type "string"
- :enum ["active" "inactive" "pending"]}}
- :required [:id :status]}
+ :required [:id :action]
+ :additionalProperties false}
+ :outputSchema {:type "object"
+ :properties {:id {:type "integer"}
+ :status {:type "string"
+ :enum ["active" "inactive" "pending"]}}
+ :required [:id :status]}
:execution {:taskSupport "parallel"}}
(test-tool "test_resource_action"))))
@@ -478,11 +526,12 @@
(is (= {:name "test_resource"
:title "Test Resource"
:description "Update a test resource."
- :annotations {:destructiveHint false :idempotentHint true}
+ :annotations {:destructiveHint false :idempotentHint true :readOnlyHint false :openWorldHint false}
:endpoint {:method "PUT" :path "/api/test/v1/test-resource/{id}"}
:inputSchema {:type "object"
:properties {:id {:type "integer"}
:dry-run {:oneOf [{:type "boolean"} {:type "null"}]}
:name {:type "string"}}
- :required [:id :name]}}
+ :required [:id :dry-run :name]
+ :additionalProperties false}}
(test-tool "test_resource"))))
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index c662c8dfb93..aee7a2fe647 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -3,6 +3,7 @@
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer :all]
+ [clojure.walk :as walk]
[metabase.agent-api.settings :as agent-api.settings]
[metabase.api.macros.scope :as scope]
[metabase.lib.core :as lib]
@@ -44,6 +45,14 @@
{:request-options {:headers extra-headers}}
body)))
+(defn- mcp-request-as
+ "Like `mcp-request` but authenticates as the given test username."
+ [username body extra-headers]
+ (client/client-full-response (test.users/username->token username)
+ :post "mcp"
+ {:request-options {:headers extra-headers}}
+ body))
+
(defn- mcp-request-unauthenticated
"Make an unauthenticated POST request to /api/mcp."
([body]
@@ -96,10 +105,23 @@
{"mcp-session-id" session-id})
[session-id response]))
+(defn- initialize-as!
+ "Like `initialize!` but authenticates as the given test username."
+ [username]
+ (let [response (mcp-request-as username (jsonrpc-request "initialize") {})
+ session-id (get-in response [:headers "Mcp-Session-Id"])]
+ (mcp-request-as username
+ (jsonrpc-notification "notifications/initialized")
+ {"mcp-session-id" session-id})
+ [session-id response]))
+
(defn- call-tool
"Call an MCP tool within an initialized session. Returns the parsed MCP result
content (the JSON-decoded text from the first content block).
- Records test failures if the response status is not 200 or the tool returns an error."
+ Records test failures if the response status is not 200 or the tool returns an error.
+ Also enforces the MCP spec contract: every successful tool result with content
+ must include `structuredContent` (because every tool in our manifest declares
+ `outputSchema`, and the spec mandates structuredContent for those)."
[session-id tool-name arguments]
(let [response (mcp-request (jsonrpc-request "tools/call"
{:name tool-name :arguments arguments})
@@ -110,6 +132,9 @@
(is (not (:isError result))
(str "Tool " tool-name " error: " (some-> result :content first :text)))
(when-not (:isError result)
+ (is (contains? result :structuredContent)
+ (str "Tool " tool-name " declared an outputSchema in tools/list but did "
+ "not return structuredContent — MCP spec violation."))
(json/decode+kw (:text (first (:content result)))))))
;;; ---------------------------------------------------- Tests -----------------------------------------------------
@@ -121,6 +146,38 @@
(is (= 401 (:status response)))
(is (= -32603 (get-in response [:body :error :code]))))))
+(deftest origin-validation-test
+ (testing "cross-origin browser requests are rejected when the origin is not configured"
+ (let [response (mcp-request (jsonrpc-request "initialize")
+ {"host" "mbtest.poom.dev"
+ "origin" "http://127.0.0.1:6274"})]
+ (is (= 403 (:status response)))
+ (is (= "Origin not allowed" (get-in response [:body :error :message])))))
+ (testing "cross-origin browser requests are accepted for configured MCP client origins"
+ (mt/with-temporary-setting-values [mcp.settings/mcp-apps-cors-custom-origins "http://127.0.0.1:6274"]
+ (let [response (mcp-request (jsonrpc-request "initialize")
+ {"host" "mbtest.poom.dev"
+ "origin" "http://127.0.0.1:6274"})]
+ (is (= 200 (:status response)))
+ (is (some? (get-in response [:headers "Mcp-Session-Id"]))))))
+ (testing "same-origin requests with bracketed IPv6 hosts are accepted"
+ (let [response (mcp-request (jsonrpc-request "initialize")
+ {"host" "[::1]:3000"
+ "origin" "http://[::1]:3000"})]
+ (is (= 200 (:status response)))))
+ (testing "same-origin requests with mixed-case host/origin are accepted"
+ (let [response (mcp-request (jsonrpc-request "initialize")
+ {"host" "Example.com"
+ "origin" "https://example.COM"})]
+ (is (= 200 (:status response)))))
+ (testing "approved MCP origins match the Origin header case-insensitively"
+ (mt/with-temporary-setting-values [mcp.settings/mcp-apps-cors-custom-origins "https://Example.COM"]
+ (let [response (mcp-request (jsonrpc-request "initialize")
+ {"host" "mbtest.poom.dev"
+ "origin" "HTTPS://example.com"})]
+ (is (= 200 (:status response)))
+ (is (some? (get-in response [:headers "Mcp-Session-Id"])))))))
+
(deftest mcp-enabled-setting-test
(testing "external MCP requests return 403 when disabled"
(mt/with-temporary-setting-values [mcp.settings/mcp-enabled? false]
@@ -187,6 +244,68 @@
"search"
"visualize_query"})
+(deftest tools-list-all-tools-declare-required-hints-test
+ (testing "every tool advertises readOnlyHint, destructiveHint, openWorldHint (some MCP clients reject tools that omit them)"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "tools/list") {"mcp-session-id" session-id})
+ tools (get-in response [:body :result :tools])]
+ (is (seq tools) "tools/list should return at least one tool")
+ (doseq [{:keys [name annotations]} tools]
+ (is (contains? annotations :readOnlyHint) (str name " missing :readOnlyHint"))
+ (is (contains? annotations :destructiveHint) (str name " missing :destructiveHint"))
+ (is (contains? annotations :openWorldHint) (str name " missing :openWorldHint"))))))
+
+(deftest text-content-includes-structured-content-for-maps-test
+ (testing "text-content emits structuredContent for map values — MCP spec requires it for tools with outputSchema"
+ (let [text-content (var-get #'mcp.tools/text-content)]
+ (testing "map → both content and structuredContent"
+ (let [result (text-content {:foo "bar"})]
+ (is (= {:foo "bar"} (:structuredContent result)))
+ (is (= "{\"foo\":\"bar\"}" (-> result :content first :text)))))
+ (testing "sequential → structuredContent is the collection"
+ (is (= [1 2 3] (:structuredContent (text-content [1 2 3])))))
+ (testing "string → no structuredContent (nothing to structure)"
+ (let [result (text-content "ok")]
+ (is (not (contains? result :structuredContent)))
+ (is (= "ok" (-> result :content first :text))))))))
+
+(deftest tool-result-emits-structured-content-test
+ (testing "tools that declare outputSchema emit structuredContent — guards the regression where Claude Desktop got 500s because we declared outputSchema without matching structuredContent"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "tools/call"
+ {:name "get_table"
+ :arguments {:id (mt/id :orders)}})
+ {"mcp-session-id" session-id})
+ result (get-in response [:body :result])]
+ (is (= 200 (:status response)))
+ (is (not (:isError result))
+ (str "get_table should succeed: " (some-> result :content first :text)))
+ (is (contains? result :structuredContent)
+ "get_table declares outputSchema → MUST emit structuredContent")
+ (is (map? (:structuredContent result))
+ "structuredContent should be the parsed response object, not a string")
+ (is (= "ORDERS" (-> result :structuredContent :name))
+ "structuredContent should mirror the endpoint response shape"))))
+
+(deftest tools-list-strict-shape-test
+ (testing "no tool's inputSchema uses JSON-Schema constructs that ChatGPT's strict MCP validator rejects"
+ ;; Pins the strict-shape guarantee across the whole exposed tool surface. `construct_query` had
+ ;; this asserted before; broadening it to every tool catches drift in any wire schema (e.g.
+ ;; `query`'s `:multi` body referencing agent-lib `:tuple` schemas) that would silently leak
+ ;; `:allOf`/`:prefixItems`/`items:false` constructs into a tool that worked before the regression.
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "tools/list") {"mcp-session-id" session-id})
+ tools (get-in response [:body :result :tools])]
+ (is (pos? (count tools)))
+ (doseq [{:keys [name inputSchema]} tools]
+ (let [schema-keys (atom #{})]
+ (walk/postwalk (fn [x] (when (map? x) (swap! schema-keys into (keys x))) x) inputSchema)
+ (is (empty? (select-keys (frequencies @schema-keys) [:allOf :prefixItems]))
+ (str "Tool " name " inputSchema contains :allOf or :prefixItems"))
+ (is (not (some #(false? (:items %))
+ (->> (tree-seq coll? seq inputSchema) (filter map?))))
+ (str "Tool " name " inputSchema contains `items: false` (tuple closure)")))))))
+
(deftest tools-list-test
(testing "tools/list returns the agent and UI tools"
(let [[session-id _] (initialize!)
@@ -220,17 +339,45 @@
(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])))))
- (testing "construct_query exposes the optional user prompt"
+ (testing "construct_query exposes the nullable 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))
+ schema-keys (atom #{})
reference (slurp (io/resource "metabase/agent_api/construct_query.md"))]
+ (walk/postwalk (fn [x]
+ (when (map? x)
+ (swap! schema-keys into (keys x)))
+ x)
+ construct-query-schema)
(is (str/includes? (:description construct-query-tool) "include `\"prompt\""))
- (is (not (contains? required-fields "prompt")))
- (is (str/includes? (:description prompt-schema) "exact original message"))
+ ;; Strict-tool-input-schema forces every property into :required and
+ ;; converts previously-optional ones (like :prompt) to nullable unions.
+ (is (or (contains? required-fields "prompt")
+ (contains? required-fields :prompt)))
+ (is (= false (:additionalProperties construct-query-schema)))
+ ;; Prompt is nullable. Either a `:type` union (hand-written form) or an
+ ;; `:anyOf`/`:oneOf` with a {:type "null"} branch (Malli `[:maybe …]`).
+ (is (or (= ["string" "null"] (:type prompt-schema))
+ (= #{"string" "null"} (set (:type prompt-schema)))
+ (some #(= "null" (:type %)) (:anyOf prompt-schema))
+ (some #(= "null" (:type %)) (:oneOf prompt-schema))))
+ ;; ChatGPT's MCP validator rejects exactly these JSON-Schema constructs.
+ ;; `:oneOf`/`:minLength`/`:maxLength` are accepted by ChatGPT and not asserted against.
+ (is (empty? (select-keys (frequencies @schema-keys)
+ [:allOf :prefixItems])))
+ ;; `items: false` (tuple closure) must not appear either.
+ (is (not (some #(false? (:items %))
+ (->> (tree-seq coll? seq construct-query-schema)
+ (filter map?)))))
+ (is (str/includes? (or (:description prompt-schema)
+ (some :description (:anyOf prompt-schema))
+ (some :description (:oneOf 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>\"}")))))))
@@ -554,7 +701,9 @@
;; can clean up even if a later step throws.
question-data (call-tool session-id "create_question"
{:name "Smoke Question"
- :query (mcp.session/read-handle session-id (:query_handle construct-data))})
+ :query (mcp.session/read-handle session-id
+ (mt/user->id :crowberto)
+ (:query_handle construct-data))})
_ (reset! question-id (:id question-data))
dash-data (call-tool session-id "create_dashboard"
{:name "Smoke Dashboard"})]
@@ -617,21 +766,7 @@
(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}))))))
+ {"mcp-session-id" session-id}))))))
(deftest tools-call-visualize-query-test
(testing "visualize_query echoes the inline query"
@@ -688,37 +823,108 @@
(mcp-request (jsonrpc-request "tools/call"
{:name "visualize_query"
:arguments {:query_handle (str (random-uuid))}})
- {"mcp-session-id" session-id})))))
+ {"mcp-session-id" session-id}))))))
- (testing "visualize_query does not resolve a query_handle from another session"
+;;; --------------------------------------- cross-session handle resolution -------------------------------------
+
+(deftest tools-expose-output-schema-test
+ (testing "MCP tools/list declares outputSchema for tools that emit structuredContent"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "tools/list") {"mcp-session-id" session-id})
+ tools (get-in response [:body :result :tools])
+ tools-by-name (into {} (map (juxt :name identity)) tools)]
+ (testing "construct_query advertises {query_handle} as its output"
+ (let [output-schema (get-in tools-by-name ["construct_query" :outputSchema])
+ prop-names (set (map name (keys (:properties output-schema))))]
+ (is (= "object" (:type output-schema)))
+ (is (contains? prop-names "query_handle"))
+ (is (not (contains? prop-names "widgetSessionId"))
+ "widgetSessionId was retired in favour of cross-session per-user lookup")))
+ (testing "visualize_query advertises its structuredContent shape"
+ (let [output-schema (get-in tools-by-name ["visualize_query" :outputSchema])]
+ (is (= "object" (:type output-schema)))
+ (is (contains? (set (map name (keys (:properties output-schema)))) "query"))))
+ (testing "render_drill_through advertises its structuredContent shape"
+ (let [output-schema (get-in tools-by-name ["render_drill_through" :outputSchema])]
+ (is (= "object" (:type output-schema)))
+ (is (contains? (set (map name (keys (:properties output-schema)))) "query")))))))
+
+(deftest construct-query-returns-bare-handle-test
+ (testing "construct_query returns just `{:query_handle uuid}` — no widget session plumbing"
+ (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"})]
+ (is (some? (parse-uuid (:query_handle construct-data))))
+ (is (not (contains? construct-data :widgetSessionId))))))
+
+(deftest visualize-query-resolves-via-cross-session-fallback-test
+ (testing "visualize_query resolves a handle stored in another session of the same user — no widgetSessionId needed"
(let [user-id (mt/user->id :crowberto)
[owner-session _] (initialize!)
- [attacker-session _] (initialize!)
+ [rotated-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")}]}}}
+ :body {:result {:structuredContent {:query "ZW5jb2RlZA=="}}}}
(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})]
+ {"mcp-session-id" rotated-session}))))))
+
+(deftest execute-query-resolves-via-cross-session-fallback-test
+ (testing "execute_query resolves a handle stored in another session of the same user — no widgetSessionId needed"
+ (let [[owner-session _] (initialize!)
+ [rotated-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" rotated-session})]
+ (is (= 200 (:status response)))
+ (is (not (get-in response [:body :result :isError]))))))
+
+(deftest render-drill-through-resolves-via-cross-session-fallback-test
+ (testing "render_drill_through resolves a handle stored in another session of the same user"
+ (let [user-id (mt/user->id :crowberto)
+ [owner-session _] (initialize!)
+ [rotated-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")}]}}}
- response)))))
+ :body {:result {:structuredContent {:query "ZW5jb2RlZA=="}}}}
+ (mcp-request (jsonrpc-request "tools/call"
+ {:name "render_drill_through"
+ :arguments {:handle handle}})
+ {"mcp-session-id" rotated-session}))))))
+
+(deftest visualize-query-refuses-cross-user-handle-test
+ (testing "visualize_query refuses to resolve another user's handle"
+ (let [owner-id (mt/user->id :crowberto)
+ [owner-session _] (initialize!) ;; crowberto
+ ;; Fresh UUID-shaped sentinel for the stored payload so the leak
+ ;; assertion below can't accidentally match against any other test fixture.
+ encoded-payload (str (random-uuid))
+ handle (mt/with-current-user owner-id
+ (mcp.session/store-handle! owner-session owner-id encoded-payload))
+ [attacker-session _] (initialize-as! :rasta)
+ response (mcp-request-as :rasta
+ (jsonrpc-request "tools/call"
+ {:name "visualize_query"
+ :arguments {:query_handle handle}})
+ {"mcp-session-id" attacker-session})]
+ (testing "the response is an error, NOT crowberto's encoded query"
+ (is (=? {:status 200
+ :body {:result {:isError true
+ :content [{:text #(str/includes? % "Query handle not found")}]}}}
+ response))
+ (is (not= encoded-payload
+ (get-in response [:body :result :structuredContent :query]))
+ "cross-user handle resolution must fail")))))
;;; --------------------------------------------- OAuth Bearer Auth -------------------------------------------------
diff --git a/test/metabase/mcp/resources_test.clj b/test/metabase/mcp/resources_test.clj
index d68f7273cdc..60a636669fc 100644
--- a/test/metabase/mcp/resources_test.clj
+++ b/test/metabase/mcp/resources_test.clj
@@ -2,7 +2,9 @@
(:require
[clojure.test :refer :all]
[metabase.api.macros.scope :as scope]
- [metabase.mcp.resources :as mcp.resources]))
+ [metabase.mcp.resources :as mcp.resources]
+ [metabase.request.core :as request]
+ [metabase.system.core :as system]))
(set! *warn-on-reflection* true)
@@ -87,3 +89,39 @@
(mcp.resources/read-resource "ui://metabase/visualize-query.html"
#{"agent:visualize"}
{}))))))
+
+(deftest builtin-visualize-query-ui-resource-metadata-test
+ (testing "the visualize_query UI resource publishes bare origins; :domain is gated on the ChatGPT client"
+ ;; site-url is set with a subpath to confirm `_meta.ui.domain` and the CSP domain lists strip the
+ ;; path — ChatGPT's MCP host treats those fields as origins and would otherwise reject the value.
+ ;; `:domain` itself is only emitted for ChatGPT — Claude validates it against its own
+ ;; `*.claudemcpcontent.com` namespace and rejects anything else, so the field is suppressed for
+ ;; non-ChatGPT clients (detected via the in-flight request's User-Agent header).
+ (let [site-url "https://metabase.example.com/sub/path"
+ origin "https://metabase.example.com"
+ uri "ui://metabase/visualize-query.html"
+ read-ui (fn []
+ (mcp.resources/with-fallback-template
+ (mcp.resources/read-resource uri #{"agent:visualize"} {})))]
+ (with-redefs [system/site-url (constantly site-url)]
+ (testing "no request bound → CSP origins still emitted, :domain suppressed"
+ (let [ui-meta (-> (read-ui) :contents first :_meta :ui)]
+ (is (=? {:prefersBorder true
+ :csp {:connectDomains [origin]
+ :resourceDomains [origin]}}
+ ui-meta))
+ (is (not (contains? ui-meta :domain)))))
+ (testing "non-ChatGPT User-Agent → :domain suppressed"
+ (request/with-current-request {:headers {"user-agent" "claude-ai/0.1.0"}}
+ (let [ui-meta (-> (read-ui) :contents first :_meta :ui)]
+ (is (not (contains? ui-meta :domain))))))
+ (testing "ChatGPT User-Agent (`openai-mcp/...`) → :domain = origin"
+ (request/with-current-request {:headers {"user-agent" "openai-mcp/1.0.0 (ChatGPT)"}}
+ (is (=? {:status :ok
+ :contents [{:uri uri
+ :mimeType "text/html;profile=mcp-app"
+ :_meta {:ui {:prefersBorder true
+ :domain origin
+ :csp {:connectDomains [origin]
+ :resourceDomains [origin]}}}}]}
+ (read-ui)))))))))
diff --git a/test/metabase/mcp/session_test.clj b/test/metabase/mcp/session_test.clj
index 400186c8363..d0e340459c7 100644
--- a/test/metabase/mcp/session_test.clj
+++ b/test/metabase/mcp/session_test.clj
@@ -104,28 +104,45 @@
(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))))
+ (is (= "first" (mcp.session/read-handle session-id user-id h1)))
+ (is (= "second" (mcp.session/read-handle session-id user-id h2)))
+ (is (nil? (mcp.session/read-handle session-id user-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 read-handle-falls-back-across-the-users-sessions-test
+ (testing "read-handle resolves a handle stored in one session when called from another session of the same user"
+ (let [user-id (mt/user->id :crowberto)
+ owner-session (mcp.session/create! user-id)
+ rotated-session (mcp.session/create! user-id)
+ handle (mcp.session/store-handle! owner-session user-id "payload")]
+ (testing "same session → resolves"
+ (is (= "payload" (mcp.session/read-handle owner-session user-id handle))))
+ (testing "different session, same user → still resolves (cross-session fallback)"
+ (is (= "payload" (mcp.session/read-handle rotated-session user-id handle))))))
+
+ (testing "read-handle refuses to resolve handles owned by a different user"
+ (let [owner-id (mt/user->id :crowberto)
+ attacker-id (mt/user->id :rasta)
+ session-id (mcp.session/create! owner-id)
+ handle (mcp.session/store-handle! session-id owner-id "payload")]
+ (is (nil? (mcp.session/read-handle session-id attacker-id handle))))))
+
+(deftest resolve-query-handle-returns-encoded-query-and-prompt-test
+ (testing "resolve-query-handle returns the stored query and prompt"
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ handle (mcp.session/store-handle! session-id user-id "encoded" "what was my question")]
+ (is (= {:encoded_query "encoded" :prompt "what was my question"}
+ (mcp.session/resolve-query-handle session-id user-id 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)))
+ (is (= "payload" (mcp.session/read-handle session-id user-id handle)))
(t2/delete! :core_session :key_hashed (derived-hash session-id))
- (is (nil? (mcp.session/read-handle session-id handle))
+ (is (nil? (mcp.session/read-handle session-id user-id handle))
"cascade should reap the handle when the core_session row goes"))))
(deftest delete-removes-handles-test
@@ -134,7 +151,7 @@
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))))))
+ (is (nil? (mcp.session/read-handle session-id user-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"
diff --git a/test/metabase/mcp/tools_test.clj b/test/metabase/mcp/tools_test.clj
index e6442d0537c..e03fd55150e 100644
--- a/test/metabase/mcp/tools_test.clj
+++ b/test/metabase/mcp/tools_test.clj
@@ -1,4 +1,37 @@
(ns metabase.mcp.tools-test
"scope-matches? tests moved to [[metabase.mcp.scope-test]]."
(:require
- [clojure.test :refer :all]))
+ [clojure.test :refer :all]
+ [metabase.mcp.tools]))
+
+(deftest ^:parallel drop-nil-args-test
+ (testing "strips nil-valued top-level keys so 'missing' and 'explicit nil' are equivalent at the MCP boundary"
+ (let [drop-nil-args (var-get #'metabase.mcp.tools/drop-nil-args)]
+ (testing "removes top-level nils"
+ (is (= {:id 42 :flag false}
+ (drop-nil-args {:id 42 :flag false :extra nil}))))
+ (testing "keeps non-nil falsey values"
+ (is (= {:flag false :count 0 :text ""}
+ (drop-nil-args {:flag false :count 0 :text ""}))))
+ (testing "preserves nested nils (only top-level is rewritten)"
+ (is (= {:source {:type "table" :id nil}}
+ (drop-nil-args {:source {:type "table" :id nil} :continuation_token nil}))))
+ (testing "nil argument → nil"
+ (is (nil? (drop-nil-args nil))))
+ (testing "empty map stays empty"
+ (is (= {} (drop-nil-args {})))))))
+
+(deftest ^:parallel overrides-cover-known-tools-test
+ (testing "every key in `mcp-input-overrides` / `mcp-output-overrides` matches a real tool"
+ ;; Catches the silent-no-op failure mode if a tool gets renamed or an override key is misspelled:
+ ;; the override would otherwise be dropped on the floor and the wire-shape schema would be published
+ ;; in place of the intended MCP shape. Lives as a test (not a runtime check at manifest generation)
+ ;; so prod startup isn't burdened with a check that only catches developer mistakes.
+ (let [manifest-fn (#'metabase.mcp.tools/manifest)
+ tool-names (into #{} (map :name) (:tools manifest-fn))]
+ (doseq [[label override-map-var] [["mcp-input-overrides" #'metabase.mcp.tools/mcp-input-overrides]
+ ["mcp-output-overrides" #'metabase.mcp.tools/mcp-output-overrides]]]
+ (testing label
+ (let [unknown (remove tool-names (keys @override-map-var))]
+ (is (empty? unknown)
+ (str label " has keys that don't match any tool name: " (vec unknown)))))))))