Skip to content

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

Use resources to give more detailed tool instructions (#73744)

Chris Truter4ed6548ec307
diff --git a/resources/metabase/agent_api/construct_query.md b/resources/metabase/agent_api/construct_query.md
new file mode 100644
index 00000000000..e64824c574c
--- /dev/null
+++ b/resources/metabase/agent_api/construct_query.md
@@ -0,0 +1,142 @@
+# Construct Query Reference
+
+Construct a Metabase MBQL query from a structured program. The body is the program itself — no envelope — shaped:
+
+```
+{"source": {...}, "operations": [...]}
+```
+
+Returns `{"query": "<base64>"}` — pass the string to `execute_query`.
+
+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`.
+
+Never embed IDs you did not read from a metadata endpoint — invented IDs will fail at execution.
+
+## Source
+
+One of `{"type": T, "id": N}`:
+
+- `table` — a database table
+- `card` — a saved question
+- `dataset` — a model (model card id)
+- `metric` — a metric (supplies its own aggregation and time dimension; extra aggregates usually unnecessary)
+
+## Top-level operations (applied in order)
+
+Each operation is `["op", arg, ...]`:
+
+- `["filter", clause]` — add a filter
+- `["aggregate", agg-clause]` — add an aggregation
+- `["breakout", ref-or-bucketed]` — add a grouping dimension
+- `["expression", "Name", expr]` — define a named computed column (reference later with `expression-ref`)
+- `["with-fields", [refs...]]` — restrict returned columns
+- `["order-by", ref]` or `["order-by", ref, "asc"|"desc"]` — sort
+- `["limit", N]` — cap rows
+- `["join", join-clause]` — join another entity
+- `["append-stage"]` — start a new query stage (needed to filter on aggregated values)
+- `["with-page", {"page": N, "items": M}]` — paginate
+
+## References (used as arguments inside operations)
+
+- `["field", N]` — database field by id. Do NOT put options in a third slot (no `["field", id, {...}]`); wrap instead
+- `["expression-ref", "Name"]` — a named expression defined earlier
+- `["aggregation-ref", N]` — the Nth `aggregate` defined earlier (0-based). REQUIRED when sorting by an aggregated value
+- `["measure", N]` — a pre-defined measure on the source entity
+- `["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)
+- `["with-binning", ref, {"strategy": "num-bins"|"bin-width"|"default", ...}]` — numeric binning. E.g. `{"strategy": "num-bins", "num-bins": 10}`
+
+## Filter operators
+
+`=`, `!=`, `<`, `<=`, `>`, `>=`, `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`.
+
+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"]`.
+
+## Aggregation operators
+
+`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"]]`.
+
+## Temporal helpers (for use in `expression` or as grouping)
+
+`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`.
+
+## Examples
+
+Top 5 customers by revenue:
+
+```
+{"source": {"type": "table", "id": 42},
+ "operations": [["aggregate", ["sum", ["field", 302]]],
+ ["breakout", ["field", 101]],
+ ["order-by", ["aggregation-ref", 0], "desc"],
+ ["limit", 5]]}
+```
+
+Monthly revenue from a metric (metric supplies the aggregation):
+
+```
+{"source": {"type": "metric", "id": 10},
+ "operations": [["breakout", ["with-temporal-bucket", ["field", 305], "month"]],
+ ["order-by", ["with-temporal-bucket", ["field", 305], "month"], "asc"]]}
+```
+
+Filter on an aggregated value (requires `append-stage`):
+
+```
+{"source": {"type": "table", "id": 42},
+ "operations": [["aggregate", ["sum", ["field", 302]]],
+ ["breakout", ["field", 101]],
+ ["append-stage"],
+ ["filter", [">", ["aggregation-ref", 0], 1000]]]}
+```
+
+Named expression referenced later:
+
+```
+{"source": {"type": "table", "id": 42},
+ "operations": [["expression", "Discount", ["-", ["field", 302], ["field", 303]]],
+ ["aggregate", ["sum", ["expression-ref", "Discount"]]]]}
+```
+
+Previous-period comparison with `offset` (stay in the SAME stage — do NOT add `append-stage`):
+
+```
+{"source": {"type": "table", "id": 42},
+ "operations": [["aggregate", ["sum", ["field", 302]]],
+ ["aggregate", ["offset", ["sum", ["field", 302]], -1]],
+ ["breakout", ["with-temporal-bucket", ["field", 305], "month"]]]}
+```
+
+## Rules & common pitfalls
+
+Stage boundaries (most common source of errors):
+
+- 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.
+- Defining an `expression` that uses `aggregation-ref` also REQUIRES `append-stage` first.
+- EXCEPTION: `offset` (previous-period comparison) stays in the same stage as its base aggregation and breakout — do NOT add `append-stage` for it.
+
+Refs & shapes:
+
+- Aggregation helpers take field refs, not bare IDs: `["sum", ["field", 201]]`, never `["sum", 201]`.
+- To sort by an aggregated value, use `["aggregation-ref", N]` — not the original expression.
+- 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], {...}]`.
+- `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.
+- JSON objects appear only where a helper explicitly calls for one (e.g. `with-page`, `with-binning`). Everywhere else, use operator tuples.
+
+Joins & related tables:
+
+- If the source table's detail response already surfaces a related table's fields, use those field refs directly — no explicit join needed.
+- Reach for `join` + `with-join-conditions` only for custom aliases, self-joins, explicit joined-field selection, or when direct related-field refs are unavailable.
+- If an explicit join returns a permission error, the underlying table is not accessible — surface the error, do not retry with implicit refs.
+
+Metrics & dates:
+
+- A `metric` source already provides its own aggregation and time dimension. Add only the additional breakouts/filters you need.
+- 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`.
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index 9302efb23f9..c92df35844c 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -374,130 +374,6 @@
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 is the program itself — no envelope — shaped:\n"
- "`{\"source\": {...}, \"operations\": [...]}`\n"
- "Returns `{\"query\": \"<base64>\"}` — pass the string to `execute_query`.\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. You get back `{\"query\": \"<base64>\"}`.\n"
- "3. Pass that string to `execute_query` or `visualize_query`.\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)."
@@ -525,7 +401,11 @@
/v1/execute. See the agent_api reference for the full program syntax."
{:scope metabot/agent-query-construct
:tool {:name "construct_query"
- :description construct-query-tool-description
+ :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).")
:annotations {:read-only? true :idempotent? true}}}
[_route-params
_query-params
@@ -644,12 +524,11 @@
{:scope "agent:query"
:tool {:name "query"
:title "Query Tables and Metrics"
- :description (str "Execute a Metabase query from a structured program and return "
- "results with column metadata. If more rows are available, the "
- "response includes a continuation_token — pass it back to get the "
- "next page.\n\n"
- "The body is either a structured program (see construct_query) or "
- "{\"continuation_token\": \"...\"} from a previous response.")
+ :description (str "Execute a structured program and return results with column metadata. "
+ "If more rows are available the response includes a continuation_token "
+ "— pass it back to fetch the next page. Body is either a program (same "
+ "shape as construct_query) or {\"continuation_token\": \"...\"}. See the "
+ "`metabase://docs/construct-query.md` resource for program syntax.")
:annotations {:read-only? true}}}
[_route-params
_query-params
diff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.md
index 4c262bbe2ff..416a4ccc239 100644
--- a/src/metabase/mcp/README.md
+++ b/src/metabase/mcp/README.md
@@ -57,7 +57,6 @@ Access tokens are scoped to limit what tools a client can use:
| `agent:query:construct` | `construct_query` |
| `agent:query` | `query` |
| `agent:query:execute` | `execute_query` |
-| `agent:visualize` | `visualize_query`, visualize-query resource |
Wildcard patterns (e.g. `agent:*`) match any scope with that prefix.
@@ -83,26 +82,18 @@ The MCP server exposes these tools, dynamically generated from the Agent API end
| `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. |
-| `visualize_query` | Visualize a previously constructed query as an interactive chart or table. |
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.
-## Resources (MCP Apps)
+## Resources
-The server also exposes MCP [resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources) that
-render interactive Metabase visualizations inside the client's UI.
+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 |
|---|---|
-| `ui://metabase/visualize-query.html` | Interactive Metabase SDK visualization for a query. |
-
-When a client calls `resources/read`, the server returns an HTML page that embeds the Metabase SDK to render a fully
-interactive visualization. The `visualize_query` tool works with this resource — it returns a reference to the resource
-URI along with the query to visualize, and supporting clients render the result as an embedded iframe.
-
-Resources include CSP metadata (`_meta.ui.csp`) so clients can set appropriate Content-Security-Policy headers for the
-embedded content.
+| `metabase://docs/construct-query.md` | Program syntax for `construct_query` and `query` — sources, operations, operator forms, worked examples, pitfalls. |
## Supported JSON-RPC methods
@@ -130,8 +121,9 @@ The implementation lives in these files:
- **[`tools.clj`](tools.clj)** — Tool dispatch and manifest generation. Builds the tool list from Agent API endpoint
metadata, checks scopes, and routes tool calls through synthetic Agent API requests.
-- **[`resources.clj`](resources.clj)** — MCP resource registry and handlers. Manages UI resources (like the
- visualize-query HTML page) and their associated tools, with scope-based access control.
+- **[`resources.clj`](resources.clj)** — MCP resource registry and handlers. Holds documentation resources (like
+ the `construct_query` reference) keyed by URI, with scope-based access control on `resources/list` and
+ `resources/read`.
- **[`scope.clj`](scope.clj)** — Scope matching logic. Supports exact matches, wildcard patterns, and the
`::unrestricted` sentinel for session-based auth.
diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.clj
index 4b9b9694a0d..a796b322626 100644
--- a/src/metabase/mcp/api.clj
+++ b/src/metabase/mcp/api.clj
@@ -9,6 +9,7 @@
[metabase.api.common :as api]
[metabase.api.macros.scope :as scope]
[metabase.api.open-api :as open-api]
+ [metabase.mcp.resources :as mcp.resources]
[metabase.mcp.tools :as mcp.tools]
[metabase.mcp.validation :as mcp.validation]
[metabase.oauth-server.core :as oauth-server]
@@ -74,7 +75,7 @@
(jsonrpc-response
id
{:protocolVersion protocol-version
- :capabilities {:tools {}}
+ :capabilities {:tools {} :resources {}}
:serverInfo server-info}))
(defn- handle-tools-list [id _params token-scopes]
@@ -85,6 +86,20 @@
arguments (or (:arguments params) {})]
(jsonrpc-response id (mcp.tools/call-tool token-scopes 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]
+ (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
+ (:not-found :scope-denied) (jsonrpc-error id -32602 "Resource not found")
+ :ok (jsonrpc-response id {:contents contents}))))))
+
(defn- handle-ping [id _params]
(jsonrpc-response id {}))
@@ -99,6 +114,8 @@
"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))
diff --git a/src/metabase/mcp/init.clj b/src/metabase/mcp/init.clj
index 42661aaa175..9033b8c340c 100644
--- a/src/metabase/mcp/init.clj
+++ b/src/metabase/mcp/init.clj
@@ -1,3 +1,4 @@
(ns metabase.mcp.init
(:require
+ [metabase.mcp.resources]
[metabase.mcp.settings]))
diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.clj
new file mode 100644
index 00000000000..34e6323956a
--- /dev/null
+++ b/src/metabase/mcp/resources.clj
@@ -0,0 +1,82 @@
+(ns metabase.mcp.resources
+ "MCP resource registry. Resources let clients fetch supplementary content (docs,
+ reference material) 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
+ payload. For resources, `:scope` uses [[metabase.mcp.scope/public-or-matches?]]:
+ nil means \"public\" (any authenticated caller), and a string is an MCP scope
+ checked against the token scopes. This intentionally differs from tools, where
+ nil scope is treated as internal-only."
+ (:require
+ [clojure.java.io :as io]
+ [metabase.mcp.scope :as mcp.scope]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+;; Single map keyed by URI; `register-resource!` overwrites so REPL reload is idempotent.
+(defonce ^:private registry (atom (sorted-map)))
+
+(mu/defn register-resource!
+ "Register an MCP resource. Overwrites any existing entry with the same `:uri`."
+ [resource :- [:map
+ [:uri :string]
+ [:name :string]
+ [:description :string]
+ [:render-fn fn?]
+ [:mimeType {:optional true} :string]
+ [:scope {:optional true} [:maybe :string]]]]
+ (let [resource (update resource :mimeType #(or % "text/markdown"))]
+ (swap! registry assoc (:uri resource) resource)
+ resource))
+
+(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))})
+
+(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."
+ [uri token-scopes opts]
+ (if-let [{:keys [render-fn scope] :as resource} (get @registry uri)]
+ (if (mcp.scope/public-or-matches? token-scopes scope)
+ {:status :ok
+ :contents [(-> (select-keys resource [:uri :mimeType])
+ (assoc :text (render-fn opts)))]}
+ {:status :scope-denied})
+ {:status :not-found}))
+
+;;; -------------------------------------------------- Helpers ----------------------------------------------------
+
+(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
+ rather than the first `resources/read` call."
+ [path]
+ (let [url (io/resource path)]
+ (when-not url
+ (throw (ex-info (str "Missing classpath resource: " path) {:path path})))
+ (let [content (delay (slurp url :encoding "UTF-8"))]
+ (fn [_opts] @content))))
+
+;;; ------------------------------------------------ Registrations ------------------------------------------------
+
+(register-resource!
+ {:uri "metabase://docs/construct-query.md"
+ :name "Construct Query Reference"
+ :description (str "Program syntax for `construct_query` and `query`: source shapes "
+ "(table/card/dataset/metric), top-level operations (filter, aggregate, "
+ "breakout, expression, with-fields, order-by, limit, join, append-stage, "
+ "with-page), reference forms, filter/aggregation/temporal operator "
+ "vocabularies, worked examples, and common pitfalls (stage boundaries, "
+ "ref shapes, joins, metric/date handling).")
+ :mimeType "text/markdown"
+ :render-fn (classpath-text-resource "metabase/agent_api/construct_query.md")})
diff --git a/src/metabase/mcp/scope.clj b/src/metabase/mcp/scope.clj
new file mode 100644
index 00000000000..9bfed7ac00a
--- /dev/null
+++ b/src/metabase/mcp/scope.clj
@@ -0,0 +1,31 @@
+(ns metabase.mcp.scope
+ "Scope matching for MCP tools and resources.
+
+ Wraps [[metabase.api-scope.core/scope-matches?]] 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]))
+
+(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.
+ - 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?]]."
+ [token-scopes required-scope]
+ (or (nil? token-scopes)
+ (contains? token-scopes ::scope/unrestricted)
+ (boolean (and (some? required-scope)
+ (api-scope/scope-matches? token-scopes required-scope)))))
+
+(defn public-or-matches?
+ "Like [[matches?]] but treats a nil `required-scope` as \"public to any caller\"
+ rather than \"internal-only.\" Use this for entities (e.g. MCP resources) whose
+ nil-scope contract is documented as public, instead of re-implementing the
+ nil-check at every call site."
+ [token-scopes required-scope]
+ (or (nil? required-scope)
+ (matches? token-scopes required-scope)))
diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.clj
index 27250a8131c..6ec7691b8d2 100644
--- a/src/metabase/mcp/tools.clj
+++ b/src/metabase/mcp/tools.clj
@@ -5,11 +5,10 @@
[clojure.core.async :as a]
[clojure.string :as str]
[metabase.agent-api.api :as agent-api]
- [metabase.api-scope.core :as api-scope]
[metabase.api.common :as api]
[metabase.api.macros.defendpoint.tools-manifest :as tools-manifest]
- [metabase.api.macros.scope :as scope]
[metabase.config.core :as config]
+ [metabase.mcp.scope :as mcp.scope]
[metabase.server.streaming-response :as streaming-response]
[metabase.util :as u]
[metabase.util.json :as json])
@@ -36,26 +35,13 @@
(generate-manifest)
@manifest-delay))
-(defn- scope-matches?
- "Does `token-scopes` grant access to a tool with the given `tool-scope`?
- - nil token-scopes → always matches (internal callers)
- - ::scope/unrestricted in token-scopes → always matches
- - nil tool-scope → only matches nil or unrestricted token-scopes
- - Delegates wildcard/exact matching to [[api-scope/scope-matches?]]"
- [token-scopes tool-scope]
- (or (nil? token-scopes)
- (contains? token-scopes ::scope/unrestricted)
- (when (and (some? tool-scope)
- (api-scope/scope-matches? token-scopes tool-scope))
- true)))
-
(defn list-tools
"Return the tool definitions suitable for MCP `tools/list` responses.
When `token-scopes` is provided, only tools whose scope matches are included."
[token-scopes]
(let [{:keys [tools]} (manifest)]
(into []
- (comp (filter #(scope-matches? token-scopes (:scope %)))
+ (comp (filter #(mcp.scope/matches? token-scopes (:scope %)))
(map (fn [tool]
(cond-> {:name (:name tool)
:title (:title tool)
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index 0ca9307256f..8274d014e5a 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -7,6 +7,7 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.mcp.api :as mcp.api]
+ [metabase.mcp.resources :as mcp.resources]
[metabase.mcp.settings :as mcp.settings]
[metabase.mcp.tools :as mcp.tools]
[metabase.oauth-server.core :as oauth-server]
@@ -137,7 +138,7 @@
(is (= 1 (get-in response [:body :id])))
(let [result (get-in response [:body :result])]
(is (= "2025-03-26" (:protocolVersion result)))
- (is (= {:tools {}} (:capabilities result)))
+ (is (= {:tools {} :resources {}} (:capabilities result)))
(is (= {:name "metabase" :version "0.1.0"} (:serverInfo result)))))))
(deftest notifications-initialized-test
@@ -575,6 +576,122 @@
(finally
(oauth-server/reset-provider!))))))
+;;; ---------------------------------------------- Resources -------------------------------------------------------
+
+(def ^:private construct-query-uri "metabase://docs/construct-query.md")
+
+(deftest resources-list-test
+ (testing "resources/list returns the registered construct-query reference resource"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "resources/list")
+ {"mcp-session-id" session-id})
+ resources (get-in response [:body :result :resources])]
+ (is (= 200 (:status response)))
+ (is (=? [{:uri construct-query-uri
+ :name "Construct Query Reference"
+ :description string?
+ :mimeType "text/markdown"}]
+ (filter #(= construct-query-uri (:uri %)) resources))))))
+
+(deftest resources-read-test
+ (testing "resources/read returns the markdown contents for the construct-query reference"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "resources/read"
+ {:uri construct-query-uri})
+ {"mcp-session-id" session-id})]
+ (is (= 200 (:status response)))
+ (is (=? {:contents [{:uri construct-query-uri
+ :mimeType "text/markdown"
+ :text #(str/starts-with? % "# Construct Query Reference")}]}
+ (get-in response [:body :result])))))
+ (testing "resources/read for an unknown URI returns -32602"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "resources/read"
+ {:uri "metabase://does/not/exist"})
+ {"mcp-session-id" session-id})]
+ (is (= 200 (:status response)))
+ (is (= -32602 (get-in response [:body :error :code])))))
+ (testing "resources/read with missing :uri reports the missing parameter"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "resources/read" {})
+ {"mcp-session-id" session-id})]
+ (is (= 200 (:status response)))
+ (is (=? {:error {:code -32602
+ :message #(str/starts-with? % "Missing required parameter")}}
+ (:body response)))))
+ (testing "resources/read with a blank :uri reports the missing parameter (not 'Resource not found')"
+ (let [[session-id _] (initialize!)
+ response (mcp-request (jsonrpc-request "resources/read" {:uri ""})
+ {"mcp-session-id" session-id})]
+ (is (= 200 (:status response)))
+ (is (=? {:error {:code -32602
+ :message #(str/starts-with? % "Missing required parameter")}}
+ (:body response))))))
+
+(def ^:private scoped-test-uri "test://mcp/api-test/scoped")
+
+(defn- with-scoped-test-resource! [f]
+ (let [registry @#'mcp.resources/registry
+ snapshot @registry]
+ (try
+ (mcp.resources/register-resource!
+ {:uri scoped-test-uri
+ :name "Scoped Test Resource"
+ :description "Requires the agent:search scope."
+ :scope "agent:search"
+ :mimeType "text/plain"
+ :render-fn (constantly "secret body")})
+ (f)
+ (finally
+ (reset! registry snapshot)))))
+
+(deftest resources-read-scope-denied-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
+ (jsonrpc-request "resources/read" {:uri scoped-test-uri})
+ "session-id"
+ #{"agent:other"})]
+ (is (=? {:jsonrpc "2.0"
+ :id 1
+ :error {:code -32602
+ :message "Resource not found"}}
+ response))))))
+ (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
+ (jsonrpc-request "resources/read" {:uri scoped-test-uri})
+ "session-id"
+ #{"agent:search"})]
+ (is (=? {:result {:contents [{:uri scoped-test-uri
+ :text "secret body"}]}}
+ response)))))))
+
+(deftest resources-list-scope-filtering-test
+ (testing "resources/list omits scoped resources the caller cannot access"
+ (with-scoped-test-resource!
+ (fn []
+ (let [response (#'mcp.api/dispatch-request
+ (jsonrpc-request "resources/list")
+ "session-id"
+ #{"agent:other"})
+ uris (set (map :uri (get-in response [:result :resources])))]
+ (is (contains? uris construct-query-uri)
+ "public construct-query reference is still listed")
+ (is (not (contains? uris scoped-test-uri))
+ "scoped resource must not leak via resources/list")))))
+ (testing "resources/list includes scoped resources for callers with matching scope"
+ (with-scoped-test-resource!
+ (fn []
+ (let [response (#'mcp.api/dispatch-request
+ (jsonrpc-request "resources/list")
+ "session-id"
+ #{"agent:search"})
+ uris (set (map :uri (get-in response [:result :resources])))]
+ (is (contains? uris scoped-test-uri)))))))
+
;;; --------------------------------------------- Scope Filtering ---------------------------------------------------
(deftest tools-list-scope-filtering-test
diff --git a/test/metabase/mcp/resources_test.clj b/test/metabase/mcp/resources_test.clj
new file mode 100644
index 00000000000..769b3379a83
--- /dev/null
+++ b/test/metabase/mcp/resources_test.clj
@@ -0,0 +1,78 @@
+(ns metabase.mcp.resources-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.api.macros.scope :as scope]
+ [metabase.mcp.resources :as mcp.resources]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private private-uri "test://mcp/resources-test/private")
+(def ^:private public-uri "test://mcp/resources-test/public")
+
+;; The registry is process-wide state; the fixture snapshots and restores it around each test.
+;; Safe because none of the tests below are marked ^:parallel.
+#_{:clj-kondo/ignore [:metabase/validate-deftest]}
+(use-fixtures :each
+ (fn [thunk]
+ (let [registry @#'mcp.resources/registry
+ snapshot @registry]
+ (try
+ (mcp.resources/register-resource!
+ {:uri public-uri
+ :name "Public Doc"
+ :description "Anyone authenticated can read this."
+ :mimeType "text/plain"
+ :render-fn (constantly "public body")})
+ (mcp.resources/register-resource!
+ {:uri private-uri
+ :name "Private Doc"
+ :description "Requires the agent:search scope."
+ :scope "agent:search"
+ :mimeType "text/plain"
+ :render-fn (constantly "private body")})
+ (thunk)
+ (finally
+ (reset! registry snapshot))))))
+
+(deftest list-resources-public-and-scoped-test
+ (testing "scopeless resources are listed for any caller, including empty scopes"
+ (let [uris (set (map :uri (:resources (mcp.resources/list-resources #{}))))]
+ (is (contains? uris public-uri))
+ (is (not (contains? uris private-uri)))))
+ (testing "scoped resources are listed only when the token-scopes match"
+ (let [uris (set (map :uri (:resources (mcp.resources/list-resources #{"agent:search"}))))]
+ (is (contains? uris public-uri))
+ (is (contains? uris private-uri))))
+ (testing "::scope/unrestricted token-scopes always match"
+ (let [uris (set (map :uri (:resources (mcp.resources/list-resources #{::scope/unrestricted}))))]
+ (is (contains? uris public-uri))
+ (is (contains? uris private-uri)))))
+
+(deftest read-resource-test
+ (testing "scopeless resources render :ok with the contents payload for any caller"
+ (is (=? {:status :ok
+ :contents [{:uri public-uri
+ :mimeType "text/plain"
+ :text "public body"}]}
+ (mcp.resources/read-resource public-uri #{} {}))))
+ (testing "scoped resources require a matching token-scope"
+ (is (=? {:status :scope-denied}
+ (mcp.resources/read-resource private-uri #{"agent:other"} {})))
+ (is (=? {:status :ok :contents [{:text "private body"}]}
+ (mcp.resources/read-resource private-uri #{"agent:search"} {})))
+ (is (=? {:status :ok}
+ (mcp.resources/read-resource private-uri #{"agent:*"} {}))))
+ (testing "::scope/unrestricted token-scopes match scoped resources"
+ (is (=? {:status :ok}
+ (mcp.resources/read-resource private-uri #{::scope/unrestricted} {}))))
+ (testing "unknown URIs return :not-found regardless of scope"
+ (is (=? {:status :not-found}
+ (mcp.resources/read-resource "test://nope" #{::scope/unrestricted} {})))))
+
+(deftest builtin-construct-query-resource-test
+ (testing "the construct-query reference is registered as a public markdown resource"
+ (is (=? {:uri "metabase://docs/construct-query.md"
+ :mimeType "text/markdown"
+ :name "Construct Query Reference"}
+ (some #(when (= "metabase://docs/construct-query.md" (:uri %)) %)
+ (:resources (mcp.resources/list-resources #{})))))))
diff --git a/test/metabase/mcp/scope_test.clj b/test/metabase/mcp/scope_test.clj
new file mode 100644
index 00000000000..2f354c9133b
--- /dev/null
+++ b/test/metabase/mcp/scope_test.clj
@@ -0,0 +1,26 @@
+(ns metabase.mcp.scope-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.api.macros.scope :as scope]
+ [metabase.mcp.scope :as mcp.scope]))
+
+(deftest matches?-test
+ (testing "nil token-scopes (internal callers) → always matches"
+ (is (true? (mcp.scope/matches? nil "agent:read")))
+ (is (true? (mcp.scope/matches? nil nil))))
+ (testing "unrestricted token-scopes → always matches"
+ (is (true? (mcp.scope/matches? #{::scope/unrestricted} "agent:read")))
+ (is (true? (mcp.scope/matches? #{::scope/unrestricted} nil))))
+ (testing "nil required-scope with scoped token → denied"
+ (is (false? (mcp.scope/matches? #{"agent:read"} nil)))
+ (is (false? (mcp.scope/matches? #{} nil))))
+ (testing "exact scope match"
+ (is (true? (mcp.scope/matches? #{"agent:read"} "agent:read")))
+ (is (false? (mcp.scope/matches? #{"agent:write"} "agent:read"))))
+ (testing "wildcard scope match"
+ (is (true? (mcp.scope/matches? #{"agent:*"} "agent:read")))
+ (is (true? (mcp.scope/matches? #{"agent:*"} "agent:write")))
+ (is (false? (mcp.scope/matches? #{"other:*"} "agent:read"))))
+ (testing "no match"
+ (is (false? (mcp.scope/matches? #{"foo:bar"} "agent:read")))
+ (is (false? (mcp.scope/matches? #{} "agent:read")))))
diff --git a/test/metabase/mcp/tools_test.clj b/test/metabase/mcp/tools_test.clj
deleted file mode 100644
index fc32b8dca7a..00000000000
--- a/test/metabase/mcp/tools_test.clj
+++ /dev/null
@@ -1,27 +0,0 @@
-(ns metabase.mcp.tools-test
- (:require
- [clojure.test :refer :all]
- [metabase.api.macros.scope :as scope]
- [metabase.mcp.tools :as mcp.tools]))
-
-(deftest scope-matches?-test
- (let [scope-matches? #'mcp.tools/scope-matches?]
- (testing "nil token-scopes (internal callers) → always matches"
- (is (true? (scope-matches? nil "agent:read")))
- (is (true? (scope-matches? nil nil))))
- (testing "unrestricted token-scopes → always matches"
- (is (true? (scope-matches? #{::scope/unrestricted} "agent:read")))
- (is (true? (scope-matches? #{::scope/unrestricted} nil))))
- (testing "nil tool-scope with scoped token → denied"
- (is (nil? (scope-matches? #{"agent:read"} nil)))
- (is (nil? (scope-matches? #{} nil))))
- (testing "exact scope match"
- (is (true? (scope-matches? #{"agent:read"} "agent:read")))
- (is (nil? (scope-matches? #{"agent:write"} "agent:read"))))
- (testing "wildcard scope match"
- (is (true? (scope-matches? #{"agent:*"} "agent:read")))
- (is (true? (scope-matches? #{"agent:*"} "agent:write")))
- (is (nil? (scope-matches? #{"other:*"} "agent:read"))))
- (testing "no match"
- (is (nil? (scope-matches? #{"foo:bar"} "agent:read")))
- (is (nil? (scope-matches? #{} "agent:read"))))))