---
title: MCP Server Deployment & Authentication
hide_title: true
sidebar_position: 14
version: 1
---
# MCP Server Deployment & Authentication
Superset includes a built-in [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that lets AI assistants -- Claude, ChatGPT, and other MCP-compatible clients -- interact with your Superset instance. Through MCP, clients can list dashboards, query datasets, execute SQL, create charts, and more.
This guide covers how to run, secure, and deploy the MCP server.
:::tip Looking for user docs?
See **[Using AI with Superset](/user-docs/using-superset/using-ai-with-superset)** for a guide on what AI can do with Superset and how to connect your AI client.
:::
```mermaid
flowchart LR
A["AI Client
(Claude, ChatGPT, etc.)"] -- "MCP protocol
(HTTP + JSON-RPC)" --> B["MCP Server
(:5008/mcp)"]
B -- "Superset context
(app, db, RBAC)" --> C["Superset
(:8088)"]
C --> D[("Database
(Postgres)")]
```
## Tool deadlines and concurrency
Protected synchronous and asynchronous MCP tools run in isolated thread workers,
each with its own Flask app
context and metadata database session. Warehouse I/O does not run on the
transport event loop. This includes SQL execution, chart data and previews,
chart compilation, dataset queries, and tools that discover warehouse metadata.
`MCP_TOOL_WORKERS` sets the maximum admitted warehouse-capable calls per
application/process. A full pool immediately returns an **MCP server busy**
error; it does not queue requests behind slow queries.
Tools that only read Superset's metadata database (the `list_*` and
`get_*_info` tools, `get_schema`, `get_instance_info`, `health_check`, and
similar) are admitted under a separate bound, `MCP_METADATA_TOOL_WORKERS`, so
they keep answering while slow warehouse queries fill `MCP_TOOL_WORKERS`. A
metadata-only tool that does reach a warehouse must first take a
`MCP_TOOL_WORKERS` slot, and reports **MCP server busy** if none is free.
Setting `MCP_METADATA_TOOL_WORKERS = 0` admits every tool under
`MCP_TOOL_WORKERS`.
Both bounds come out of one budget: the metadata pool's capacity,
`pool_size + max_overflow`. A warehouse-capable call can hold a metadata
connection for the whole of its warehouse query and cancelling it needs
another; a metadata-only call holds at most one; and the server's own
metadata I/O (tool-list filtering, audit writes, error hooks) runs on one
bounded thread, and API-key lookups on another of their own, so requests
with unknown keys cannot delay audit writes or RBAC filtering. Admission keeps
`2 * MCP_TOOL_WORKERS + MCP_METADATA_TOOL_WORKERS + 2` within the capacity,
so even with every slot in use no metadata connection checkout waits for
another holder. By default (`None`) warehouse-capable calls get about a third
of the connections left after those two threads, and metadata-only calls
what remains, each up to 16. With SQLAlchemy's default pool (5 + 10
connections) that is 4 warehouse-capable and 5 metadata-only calls. To admit
more, raise the pool for the MCP process, for example
`SQLALCHEMY_ENGINE_OPTIONS = {"pool_size": 20, "max_overflow": 20}` (12 and
14). Explicit values above the budget are reduced with a startup warning, and
a pool with fewer than 4 connections is rejected at startup. The server never
waits for a metadata connection on its event loop.
Pool logs report initialization and connection-budget clamping without logging
configuration values or engine-derived counts. Successful transport-layer API-key
validation logs the user id rather than the username or API key.
Tool-list and search permission checks, success/error audit writes, response-size
audits, and error hooks run in metadata threads with independent Flask contexts
and scoped sessions. These sessions are cleaned up when the operation finishes,
including after failure or client disconnection; inherited request contexts do
not share their ORM user/session with the thread.
`execute_sql` uses its request's `timeout` (default: 30 seconds). Tools without
a timeout parameter use `SQLLAB_TIMEOUT`. The deadline covers the complete tool
call, including composed queries, and returns a clear timeout error with a call
ID. Superset requests warehouse cancellation using its engine cancellation
hooks, including for connection prequeries, on a separate bounded pool.
Cancellation connections run independently of the expired tool deadline, including
connection prequeries such as PostgreSQL schema selection. Trino's client only
learns a query's `queryId` once it is running and then blocks until results
arrive, so the cancellation thread reads that id from the live cursor and kills
the query with `system.runtime.kill_query`. Engines whose specs expose no
cancellation handle (for example BigQuery, Databricks native and Athena) are not
cancelled. Drivers without cancellation support can
continue running after the caller receives the timeout; the worker retains its
slot and owns session cleanup until it finishes, while metadata-only tools keep
their own bound. A stuck cancellation also
retains its call's slot rather than exhausting cancellation capacity for new
calls. One warning with the call ID records abandonment. A timeout does not guarantee that warehouse writes were
rolled back, so do not blindly retry mutating SQL.
## Externally managed dashboards
MCP dashboard mutation tools refuse changes to externally managed dashboards,
including ownership and access-role changes, layout and filter edits, chart
membership, certification, deletion, and restoration. Their responses set
`managed_externally: true` and explain that the external system is the source
of truth; changing Superset permissions or retrying does not override it.
Read-only dashboard tools and certification's inspect-only call remain available.
## Native filter defaults
`manage_native_filters` accepts `default_value` for select filters. An empty
list clears the selection. With `enable_empty_filter: true`, that explicit
empty default matches no rows in both the dashboard UI and server-side
dashboard chart queries, including for UI-created non-exact select filters.
Creating a required select filter without `default_value` also stores this
match-nothing default, unless `default_to_first_item` is enabled.
Inverse-selection filters retain the UI's no-predicate behavior for empty
selections. Disabling `enable_empty_filter` removes the empty default's
match-nothing predicate without requiring another `default_value` update.
Explicit defaults, including an empty list, cannot be combined with
`default_to_first_item: true`. Creating a first-item filter or enabling that
option on an existing filter leaves the stored selection unset so the dashboard
can choose the first available item after loading options. Toggling
`enable_empty_filter` on a first-item filter preserves that behavior rather than
storing an explicit empty selection or match-nothing predicate. Any update to
a first-item filter also clears a defined legacy stored selection (including
`null`) when first-item mode remains enabled, allowing automatic selection.
Select filters with legacy string-column
targets support both default updates and applied selections.
## Dashboard copying, ownership and data limits
`duplicate_dashboard` defaults to `duplicate_slices=true`, creating independent
charts for the new dashboard. Set it to `false` only when sharing charts is
intentional: edits to a shared chart also affect the source dashboard.
For `list_dashboards`, `list_charts`, `list_datasets` and `list_reports`,
`edited_by_me=true` selects direct user editors (owners), not access inherited
through roles or groups. Combining it with `created_by_me` returns their union.
These tools and `list_databases` reject unknown fields such as `owned_by_me`,
with suggestions for supported arguments. `list_databases` supports
`created_by_me`, not `edited_by_me`.
Each chart in `get_dashboard_data` includes `fetch_row_limit`, `sample_rows_limit`
and a short `completeness_note`; shared guidance appears once on `DashboardData`.
`fetch_row_limit` is the executed limit for the primary query, including server caps;
each query layer uses its own executed limit to assess completeness. Example rows
are not the full population. When an executed query uses post-processing that can collapse or replace input rows
(aggregate, boxplot, histogram, grouped pivot, prophet, resample, rolling, or an
unknown/custom operation), output row counts cannot establish input coverage. For these queries,
`total_rows` is null and `truncated=true` conservatively signals unverified input
coverage, not observed truncation. This applies to timeseries pivots with groupby
dimensions as well as distribution charts, including each layer of mixed charts.
Pivots without groupby columns and other row-preserving operations retain ordinary
row-count completeness checks. Check the saved chart configuration, `fetch_row_limit` and source aggregates before making
full-population claims. Distribution responses without operation metadata also
report unknown totals and unverified coverage conservatively.
Chart configuration examples use plain number formats. Currency formatting should
come from user instructions or verified source metadata, not a field name such
as sales, revenue or CPC.
## Metric discovery refusals
An unscoped `list_metrics` call returns usable metrics even when a visible semantic
view refuses discovery. Its response includes:
- `incomplete`: `true` if any source could not be fully discovered. Clients must
disclose partial coverage and must not infer that omitted metrics do not exist.
- `refused_views`: structured markers such as `[{"view_id": 5}]` for visible views
that refused discovery. Markers contain only the safe view ID, never provider
details, and apply to the whole scan regardless of the requested page.
A view that refuses while loading metrics, columns or compatible dimensions
contributes no metrics, including any collected before that refusal. `total_count`
and `total_pages` describe only the usable subset. An entirely refused catalog
returns no metrics with `incomplete: true`; it is not evidence of an empty catalog.
Successful discovery with no failures returns `incomplete: false` and
`refused_views: []`.
Continue discovery using the returned sources, or use `dataset_id` or `view_id`
to scope a request to a known source. A scoped semantic-view refusal still returns
`AccessDenied`. Unexpected provider failures retain safe warnings and partial
results from other sources, set `incomplete: true`, and do not create refusal markers.
## Bounding dashboard dataset metadata
`get_dashboard_datasets` lists a dashboard's datasets and semantic views with
column and metric details. Its optional `max_columns` and `max_metrics`
parameters limit the number of columns (0–100, default 100) and metrics (0–50,
default 50) returned **per dataset**. Columns and metrics are sorted by name
before the caps apply, so repeated calls return the same subset. For a wide
dashboard, start with smaller caps or omit the details entirely:
```json
{
"request": {
"identifier": 123,
"max_columns": 0,
"max_metrics": 0
}
}
```
Dataset identities, chart counts, and total column and metric counts are
retained. `columns_truncated` and `metrics_truncated` are true whenever fewer
items are returned than the dataset contains, including when a cap of 0 omits a
nonempty list. Use `get_dataset_info` to fetch details for an individual
dataset. Omitting both parameters returns up to 100 columns and 50 metrics per
dataset. The caps bound per-dataset details, not the number of datasets or the
entire response's byte size; a dashboard with many datasets can still exceed the
server's configured byte limit.
## Dashboard filter notifications
`apply_dashboard_filters` supports exact-match select filters without inverse
selection, time filters, numeric range filters, time-grain filters, and
time-column filters. Range
bounds must be finite numbers representable as floats, or null; booleans are
rejected. Range permalink labels use the dashboard's smart number formatting
with ASCII minus signs, falling back to plain numeric representations if
formatting overflows; time-grain labels come from
the target datasource's grain names when available. Time grains must be supported
by the filter's target dataset's database engine, as listed in the datasource's
`time_grain_sqla` options. If the filter has a nonempty configured allowlist, the
selected grain must also appear in that list. An unresolved target dataset is
rejected.
Inverse-selection configurations are rejected.
Select filters configured for contains, starts-with, or ends-with matching are
rejected rather than silently applying exact matching. A single-select filter
accepts at most one value; a longer list is rejected rather than stored as a
selection the control cannot render.
Select values are checked against the target column's distinct values under the
caller's dataset permissions and row-level security. Exact values are preserved;
a unique match ignoring case and whitespace uses the stored column value.
Missing values fail without creating a permalink. Unless an active dashboard
scope suppresses them, the error lists bounded candidate values (closest
matches, and up to ten values in label order), and the tool description directs
clients to propose the value the user most likely meant and ask before applying
it. No alias mapping or automatic substitution is applied; select values are
dataset-specific.
Ambiguous values and normalized matches whose uniqueness cannot be established
fail with exact alternatives, preserving their spelling and JSON type.
Lookups respect `FILTER_SELECT_ROW_LIMIT` and `SQL_MAX_ROW`. On a truncated
column, bounded containment searches check text values beyond the first page,
with at most ten search-query attempts per filter (including failed attempts).
Values needing additional searches are kept unchanged. A nonpositive effective
row limit disables validation rather than issuing an unlimited query.
Absence from another truncated page is not proof that a value is invalid. Values
that cannot be verified (including query failures, unreadable datasets, native
numbers/booleans, non-text columns, or non-ASCII text beyond a truncated page)
are applied unchanged, not certified as present. Clearing a selection does not
query the column. An active MCP dashboard scope, including a time range alone,
does not disable select-value validation: absence from the whole RLS-visible
column also proves absence from any scoped subset. Errors omit suggestions and
exact alternatives while scope restricts rows, since column options are not
queried within the active dashboard view. A known column value does not guarantee
matching rows in that view. Clearing a required select
filter with `values: []` matches no rows, including when opening the returned
permalink; an explicit clear does not restore its saved default.
Returned dashboard permalink URLs use `WEBDRIVER_BASEURL_USER_FRIENDLY` as
the public origin and respect `APPLICATION_ROOT` (or the request's WSGI
`SCRIPT_NAME` when mounted behind a proxy). Set the public URL to the
browser-accessible Superset host; the MCP service's own host may be different.
To stack filters across chat turns, pass the previous
`apply_dashboard_filters` response's `permalink_key` as `base_permalink_key`
in the next request for the same dashboard. For example, apply Region = EMEA,
then pass that key with a Time Range = `2024-01-01 : 2025-01-01` request to
keep EMEA and add the year constraint. Each new value replaces that filter's
entire prior entry; unmentioned filters persist. Omit the base key to start
from dashboard defaults. `applied_filters` summarizes only the new request,
not the inherited selections. Inherited entries for filters the dashboard no
longer defines are dropped, so a filter deleted or recreated between turns
does not carry a stale predicate forward.
Base state is resolved server-side under the calling user's dashboard access
and merged without display redaction; the raw base mask is not returned.
Missing or expired keys, resolution failures, access denial, and dashboard
mismatches fail explicitly without creating a replacement link. Missing and
expired keys share an error because the permalink store does not distinguish
them.
After creating a dashboard permalink, `apply_dashboard_filters` attempts a
best-effort `dashboard.filters_applied` realtime notification scoped to the
calling principal. Its payload contains only `dashboard_id` and `permalink_key`;
filter values and resolved state are not included. Consumers must resolve the
key through the dashboard's authorized permalink load path.
Live browser updates require `WEBSOCKET_ENABLE = True`, a configured
`DISTRIBUTED_COORDINATION_CONFIG` backend, a running `superset-websocket`
server, and a strong, non-default `WEBSOCKET_JWT_SECRET` of at least 32 bytes.
`WEBSOCKET_URL` must also point at a `ws://`/`wss://` endpoint the browser can
reach. Its default, `ws://127.0.0.1:8080/`, resolves to the browser's own
loopback, so a remote deployment that leaves it unchanged has every
server-side piece configured correctly while live updates never connect.
The browser user also needs
`can_read` on `Realtime`. With the default configuration the realtime half
is inert, but the tool still creates and returns a permalink URL.
The MCP process and websocket transport must use the same
`REALTIME_CHANNEL_PREFIX`. This publisher does not require the Global Task
Framework feature flag.
The response's `live_update_pushed` field reports publication success, not
browser receipt or application. When `WEBSOCKET_ENABLE` is disabled or unset,
no notification is published and this field is `false`. Without a backend,
`can_read` on `Realtime` for the calling principal, an identifiable principal,
or a successful publish, it is also `false`; the created
`dashboard_url` remains the fallback. An open dashboard resolves matching
notifications through the existing dashboard permalink API and applies the
returned filters without a reload. A “Filters applied from chat” toast offers **Undo**, restoring the
affected filters' previous selections. The toast carries an action, so it has
no auto-dismiss timer and stays up until Undo or its close button is used,
which keeps the action reachable for keyboard and assistive-technology users.
Undo restores only the filters whose current state still matches what the
notification applied, so a selection edited in the meantime is kept. Filters
not present in the notification's permalink keep their existing selections in
the open dashboard.
Reconnect deliberately does not fetch or replay filter state: there is no
latest-per-user permalink lookup, and replaying a previously received permalink
could overwrite manual changes or undo. If a notification is missed or its
permalink cannot be resolved, open `dashboard_url` from chat.
## Dashboard filter scope
A client that answers questions about a dashboard the user is viewing (for
example an assistant embedded next to it) can make every tool call honor that
dashboard's active filters by sending them in the `X-Superset-Dashboard-Scope`
request header on each MCP HTTP request of the conversation turn. The model
issuing tool calls never sees the header, so it cannot drop or loosen the
filters, and retried calls carry them again.
The header value is `base64url(zlib(JSON))` of:
```json
{
"version": 1,
"dashboard_id": 12,
"chart_filters": {
"101": {"filters": [{"col": "client", "op": "IN", "val": ["A"]}],
"time_range": "Last quarter"}
}
}
```
`chart_filters` maps each chart with active filters to the `extra_form_data`
the dashboard applies to it. A malformed header refuses every tool call rather
than being ignored. Without the header, behavior is unchanged.
While a scope with active filters is present:
- Chart data tools (`get_chart_data`, `get_chart_preview`, `get_dashboard_data`)
apply each chart's dashboard filters and AND any `extra_form_data` the model
supplies with them. Filters can be added but not removed, and time windows,
time columns and relative anchors the dashboard sets (including time-series
cross-filters) cannot be changed. Charts that are not on the scoped
dashboard, and unsaved chart state (`form_data_key`), are refused.
- `query_dataset`, `get_table` (datasets) and `execute_sql` apply the
filters from dashboard charts backed by the queried dataset, respecting
native-filter chart scoping. Datasets outside the dashboard use the combined
dashboard-wide filters. A model-supplied time range is intersected with the
applicable dashboard time range. `execute_sql` replaces each filtered table
read with a sub-query, the same way row-level security is applied, and refuses
SQL whose tables are not registered datasets that have every filtered column, as well
as SQL that could read tables it cannot see: opaque statements, functions
the SQL parser does not model, and table functions. For `execute_sql`, template
syntax in SQL or dashboard filter values is refused rather than rendered after
scoping.
For all three tools, the time-filter column is resolved from the affected
dashboard charts' temporal filters (or legacy chart time-column settings),
after dashboard overrides. The charts must agree on one column. A chart with
no temporal target, conflicting targets, or a dataset outside the dashboard
with an applicable time window causes a refusal; the dataset's main datetime
column and a model-supplied column are never used to guess the dashboard target.
Malformed saved chart filter lists also cause an explicit scope refusal before
dashboard overrides are merged; no query is run.
Without an applicable dashboard time window, no chart temporal target is
required, and model-supplied time filtering behaves as before.
- Writes that change what charts or datasets query (adding a chart to a
dashboard, saving a chart, defining a virtual dataset, editing a dataset or
metric, restoring a chart or dataset) are refused while the scope is
active.
- Where the filters cannot be applied (for example, a column the dataset lacks,
or a column filtered differently by different charts) the call fails with a
tool error beginning `Dashboard filter scope refused this call:`. Tools that
return no dataset rows are unaffected; any other tool, including extension
tools, is refused.
- MCP response caching is bypassed for scoped calls, and the scope is applied
before any query is built, so Superset's query cache never serves an
unscoped result.
The scope is a correctness control for answers, not an access control.
Permissions and row-level security apply exactly as they do without it.
---
## Semantic-view chart targets
`generate_chart` and `generate_explore_link` require exactly one source selector:
`dataset_id` for a table dataset, or `view_id` for a semantic view. View selectors
accept UUIDs or legacy numeric IDs. The numeric ID spaces are independent: a
dataset ID must not be reused as a view ID.
The legacy `datasource_id` alias defaults to a table when `datasource_type` is
omitted. With `datasource_type: "semantic_view"`, it selects a view instead.
For table-only requests, an explicit `dataset_id` takes precedence over
`datasource_id`. Unsupported types and conflicting semantic selectors are rejected.
Semantic configurations use saved metric names, for example
`{"name": "revenue", "saved_metric": true}`, and dimensions published by the view.
Ad-hoc aggregates and SQL expressions are rejected. Missing and inaccessible
views return the same `view_not_found` error without exposing view metadata.
`update_chart` accepts at most one replacement selector; omitting both retains
the chart's source. A `view_id` rebind validates retained query roles, except
Gauge, Treemap and geographic charts, which require a complete `config` for any
rebind. A `dataset_id` rebind, including from a view, requires a complete `config`.
Rebinding preserves the selected source family in previews and stored
parameters and clears stale query context. An incompatible retained
configuration must be replaced with a
configuration valid for the target. Validation includes the second series of
mixed-timeseries charts: saved metrics, dimensions, sort references and filters.
It also checks Gantt time and tooltip fields, histogram columns, and table
percentage metrics. Unknown visualization types are rejected because their
retained query roles cannot be validated. Bubble sorting accepts a published
saved metric in its native single-metric format.
Scalar saved dimension names are treated as singleton lists. A semantic-view-to-table
transition requires access to the replacement table before validation or
preview caching. Title-only updates of query-backed and saved-query-backed charts
retain their source family and chart authorization.
Saving semantic charts requires the host's semantic-view chart save/access
support ([#44169](https://github.com/apache/superset/pull/44169)). MCP delegates
writes to the existing chart commands and does not bypass that prerequisite or
chart edit permissions. Link generation alone does not establish that a chart
was saved or that a provider query executed successfully.
## Quick Start
Get the MCP server running locally and connect an AI client in three steps.
### 1. Start the MCP server
The MCP server runs as a separate process alongside Superset:
```bash
superset mcp run --host 127.0.0.1 --port 5008
```
| Flag | Default | Description |
| --------- | ----------- | -------------------- |
| `--host` | `127.0.0.1` | Host to bind to |
| `--port` | `5008` | Port to bind to |
| `--debug` | off | Enable debug logging |
The endpoint is available at `http://:/mcp`.
### 2. Set a development user
For local development, tell the MCP server which Superset user to impersonate (the user must already exist in your database):
```python
# superset_config.py
MCP_DEV_USERNAME = "admin"
```
### 3. Connect an AI client
Point your MCP client at the server. For **Claude Desktop**, edit the config file:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
```json
{
"mcpServers": {
"superset": {
"url": "http://localhost:5008/mcp"
}
}
}
```
Restart Claude Desktop. The hammer icon in the chat bar confirms the connection.
See [Connecting AI Clients](#connecting-ai-clients) for Claude Code, Claude Web, ChatGPT, and raw HTTP examples.
---
## Prerequisites
- Apache Superset 5.0+ running and accessible
- Python 3.11+
- The `fastmcp` package (`pip install fastmcp`)
---
## Authentication
The MCP server supports multiple authentication methods depending on your deployment scenario.
```mermaid
flowchart TD
R["Incoming MCP Request"] --> F{"MCP_AUTH_FACTORY
set?"}
F -- Yes --> CF["Custom Auth Provider"]
F -- No --> AE{"MCP_AUTH_ENABLED?"}
AE -- "True" --> JWT["JWT Validation"]
AE -- "False" --> DU["Dev Mode
(MCP_DEV_USERNAME)"]
JWT --> ALG{"MCP_JWT_ALGORITHM"}
ALG -- "RS256 + JWKS" --> JWKS["Fetch keys from
MCP_JWKS_URI"]
ALG -- "RS256 + static" --> PK["Use
MCP_JWT_PUBLIC_KEY"]
ALG -- "HS256" --> SEC["Use
MCP_JWT_SECRET"]
JWKS --> V["Validate token
(exp, iss, aud, scopes)"]
PK --> V
SEC --> V
V --> UR["Resolve Superset user
from token claims"]
UR --> OK["Authenticated request"]
CF --> OK
DU --> OK
```
### Development Mode (No Auth)
Disable authentication and use a fixed user:
```python
# superset_config.py
MCP_AUTH_ENABLED = False
MCP_DEV_USERNAME = "admin"
```
All operations run as the configured user.
:::warning
Never use development mode in production. Always enable authentication for any internet-facing deployment.
:::
### JWT Authentication
For production, enable JWT-based authentication. The MCP server validates a Bearer token on every request.
#### Option A: RS256 with JWKS endpoint
The most common setup for OAuth 2.0 / OIDC providers that publish a JWKS (JSON Web Key Set) endpoint:
```python
# superset_config.py
MCP_AUTH_ENABLED = True
MCP_JWT_ALGORITHM = "RS256"
MCP_JWKS_URI = "https://your-identity-provider.com/.well-known/jwks.json"
MCP_JWT_ISSUER = "https://your-identity-provider.com/"
MCP_JWT_AUDIENCE = "your-superset-instance"
```
#### Option B: RS256 with static public key
Use this when you have a fixed RSA key pair (e.g., self-signed tokens):
```python
# superset_config.py
MCP_AUTH_ENABLED = True
MCP_JWT_ALGORITHM = "RS256"
MCP_JWT_PUBLIC_KEY = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----"""
MCP_JWT_ISSUER = "your-issuer"
MCP_JWT_AUDIENCE = "your-audience"
```
#### Option C: HS256 with shared secret
Use this when both the token issuer and the MCP server share a symmetric secret:
```python
# superset_config.py
MCP_AUTH_ENABLED = True
MCP_JWT_ALGORITHM = "HS256"
MCP_JWT_SECRET = "your-shared-secret-key"
MCP_JWT_ISSUER = "your-issuer"
MCP_JWT_AUDIENCE = "your-audience"
```
:::warning
Store `MCP_JWT_SECRET` securely. Never commit it to version control. Use environment variables:
```python
import os
MCP_JWT_SECRET = os.environ.get("MCP_JWT_SECRET")
```
:::
#### JWT claims
The MCP server validates these standard claims:
| Claim | Config Key | Description |
| ----- | ------------------ | ---------------------------------------------------------- |
| `exp` | -- | Expiration time (always validated) |
| `iss` | `MCP_JWT_ISSUER` | Token issuer (optional but recommended) |
| `aud` | `MCP_JWT_AUDIENCE` | Token audience (optional but recommended) |
| `sub` | -- | Subject -- primary claim used to resolve the Superset user |
#### User resolution
After validating the token, the MCP server resolves a Superset username from the claims. It checks these in order, using the first non-empty value:
1. `subject` -- the standard `sub` claim (via the access token object)
2. `client_id` -- for machine-to-machine tokens
3. `payload["sub"]` -- fallback to raw payload
4. `payload["email"]` -- email-based lookup
5. `payload["username"]` -- explicit username claim
The resolved value must match a `username` in the Superset `ab_user` table.
#### Scoped access
Require specific scopes in the JWT to limit what MCP operations a token can perform:
```python
# superset_config.py
MCP_REQUIRED_SCOPES = ["mcp:read", "mcp:write"]
```
Only tokens that include **all** required scopes are accepted.
### Custom Auth Provider
For advanced scenarios (e.g., a proprietary auth system), provide a factory function. This takes precedence over all built-in JWT configuration:
```python
# superset_config.py
def my_custom_auth_factory(app):
"""Return a FastMCP auth provider instance."""
from fastmcp.server.auth.providers.jwt import JWTVerifier
return JWTVerifier(
jwks_uri="https://my-auth.example.com/.well-known/jwks.json",
issuer="https://my-auth.example.com/",
audience="superset-mcp",
)
MCP_AUTH_FACTORY = my_custom_auth_factory
```
### Embedded Guest Authentication
Superset's [embedded dashboards](/user-docs/using-superset/embedding) feature mints short-lived **guest tokens** for anonymous/embedded viewers. The MCP server can accept these same guest tokens, so an embedded guest (e.g. an in-app chatbot next to an embedded dashboard) can call MCP tools scoped to the dashboards/resources named in its token.
This is opt-in and reuses the existing core guest-token configuration -- there is no MCP-specific guest secret or audience.
```python
# superset_config.py
FEATURE_FLAGS = {"EMBEDDED_SUPERSET": True} # required -- guest tokens only exist when this is on
MCP_EMBEDDED_GUEST_AUTH_ENABLED = True # opt-in for the MCP transport (default False)
```
Present the guest token the same way as any other bearer token:
```bash
curl -X POST http://localhost:5008/mcp \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_GUEST_TOKEN' \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
```
**How it works**
- A dedicated guest-token verifier validates the token against the same `GUEST_TOKEN_JWT_SECRET` / `GUEST_TOKEN_JWT_ALGO` / `GUEST_TOKEN_JWT_AUDIENCE` config used by embedded dashboards, replays the embedded structural checks, and enforces revocation (global version bumps and per-dashboard `guest_token_revoked_before` cutoffs). It runs *before* the JWT verifier described above, since guest tokens are signed with a different key/algorithm and would otherwise be rejected at the transport.
- A verified guest resolves to a Superset guest user as the highest-priority identity, so it's never downgraded to API-key / `MCP_DEV_USERNAME` / dev-mode resolution. Data access is scoped by the same checks (dataset allowlist, dashboard access, row-level security) that apply to embedded dashboard views.
- Guest and API-key identity resolution supports FastMCP 3 and FastMCP 4, including verifier chains wrapped in `MultiAuth`. Guest resolution revalidates the bearer and core revocation checks on every identity resolution (including tool discovery), not just transport verification. These checks are not cached across resolutions: each dashboard resource can require a metadata lookup, but a previous successful resolution cannot mask subsequent expiry or revocation; API-key resolution trusts only FAB validation, not identity-routing claims supplied by an external JWT.
- Guests are restricted to a default-deny allow-list, `MCP_GUEST_ALLOWED_TOOLS`, regardless of `MCP_RBAC_ENABLED`. Sensitive enumeration tools like `find_users` and `get_instance_info` are denied simply by being absent from the default list.
- Setting `MCP_AUTH_FACTORY` bypasses this whole path: a configured factory is tried first, and the default factory that wires up the guest-token verifier is never reached. If you rely on a custom auth factory (e.g. your own OIDC provider) alongside guest auth, that factory must verify guest tokens itself -- otherwise they're rejected regardless of `MCP_EMBEDDED_GUEST_AUTH_ENABLED`.
```python
# superset_config.py
MCP_GUEST_ALLOWED_TOOLS = {
"get_dashboard_info",
"get_dashboard_layout",
"get_dashboard_data",
"list_dashboards",
"list_charts",
"get_chart_info",
"get_chart_data",
"get_chart_preview",
} # default
```
**Deployment requirements**
- The MCP server and the service that mints guest tokens (the Superset web app) must share `GUEST_TOKEN_JWT_SECRET` and `GUEST_TOKEN_JWT_AUDIENCE`. Set `GUEST_TOKEN_JWT_AUDIENCE` explicitly -- if it's unset, audience validation falls back to the URL host, which can differ between the two services and cause every guest token to fail validation.
- The `GUEST_ROLE_NAME` role (default `Public`) must exist -- a guest token is rejected if it does not.
- Don't set `MCP_DEV_USERNAME` on a deployment that also serves embedded guests.
- Restart the MCP process after toggling `EMBEDDED_SUPERSET` or `MCP_EMBEDDED_GUEST_AUTH_ENABLED` -- guest auth is wired up once at startup.
:::warning
`GUEST_TOKEN_JWT_SECRET` guards both the web embedding and MCP guest-auth surfaces. With `MCP_EMBEDDED_GUEST_AUTH_ENABLED` on, leaving it at its insecure default isn't just a forgery risk -- the MCP server refuses to start (`MCPAuthConfigError`) until you set a real secret shared with the guest-token minting service.
:::
---
## Connecting AI Clients
### Claude Desktop
**Local development (no auth):**
```json
{
"mcpServers": {
"superset": {
"url": "http://localhost:5008/mcp"
}
}
}
```
**With JWT authentication:**
```json
{
"mcpServers": {
"superset": {
"command": "npx",
"args": [
"-y",
"mcp-remote@latest",
"http://your-superset-host:5008/mcp",
"--header",
"Authorization: Bearer YOUR_TOKEN"
]
}
}
}
```
### Claude Code (CLI)
Add to your project's `.mcp.json`:
```json
{
"mcpServers": {
"superset": {
"type": "url",
"url": "http://localhost:5008/mcp"
}
}
}
```
With authentication:
```json
{
"mcpServers": {
"superset": {
"type": "url",
"url": "http://localhost:5008/mcp",
"headers": {
"Authorization": "Bearer YOUR_TOKEN"
}
}
}
}
```
### Claude Web (claude.ai)
1. Open [claude.ai](https://claude.ai)
2. Click the **+** button (or your profile icon)
3. Select **Connectors**
4. Click **Manage Connectors** > **Add custom connector**
5. Enter a name and your MCP URL (e.g., `https://your-superset-host/mcp`)
6. Click **Add**
:::info
Custom connectors on Claude Web require a Pro, Max, Team, or Enterprise plan.
:::
### ChatGPT
1. Click your profile icon > **Settings** > **Apps and Connectors**
2. Enable **Developer Mode** in Advanced Settings
3. In the chat composer, press **+** > **Add sources** > **App** > **Connect more** > **Create app**
4. Enter a name and your MCP server URL
5. Click **I understand and continue**
:::info
ChatGPT MCP connectors require a Pro, Team, Enterprise, or Edu plan.
:::
### Direct HTTP requests
Call the MCP server directly with any HTTP client:
```bash
curl -X POST http://localhost:5008/mcp \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_JWT_TOKEN' \
-d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
```
---
## Text input validation
Dashboard titles and chart names may contain punctuation and prose labels such
as `substitute data: Jira support tickets`. URL payloads using `javascript:`,
`vbscript:`, or `data:` remain rejected, including schemes with embedded ASCII
tabs, newlines, or carriage returns. A `data:` label is accepted only when
`data:` is followed by whitespace and no comma appears anywhere after it. A
value that starts with `data:`, or has a character other than whitespace right
after `data:`, is always rejected. Browsers read the text before the first comma
as the media type and load a data URL whose media type is invalid, such as
`data: Jira,`, as plain text, so a comma-bearing label such as
`substitute data: Jira, support` is rejected because it cannot be told apart
from a data URL. When title or name
sanitization fails, MCP validation errors identify the field, such as
`request.dashboard_title`, and provide a fixed disallowed-content reason,
including the comma restriction on `data:` labels, without echoing the supplied
value.
## Deployment
### Single Process
The simplest setup: run the MCP server alongside Superset on the same host.
```mermaid
flowchart TD
subgraph host["Host / VM"]
direction TB
S["Superset
:8088"] --> DB[("Postgres")]
M["MCP Server
:5008"] --> DB
end
C["AI Client"] -- "HTTPS" --> P["Reverse Proxy
(Nginx / Caddy)"]
U["Browser"] -- "HTTPS" --> P
P -- ":8088" --> S
P -- ":5008/mcp" --> M
```
**superset_config.py:**
```python
MCP_SERVICE_HOST = "0.0.0.0"
MCP_SERVICE_PORT = 5008
MCP_DEV_USERNAME = "admin" # or enable JWT auth
# If behind a reverse proxy, set the public-facing URL so
# MCP-generated links (chart previews, SQL Lab URLs) resolve correctly:
MCP_SERVICE_URL = "https://superset.example.com"
```
**Start both processes:**
```bash
# Terminal 1 -- Superset web server
superset run -h 0.0.0.0 -p 8088
# Terminal 2 -- MCP server
superset mcp run --host 0.0.0.0 --port 5008
```
**Nginx reverse proxy with TLS:**
```nginx
server {
listen 443 ssl;
server_name superset.example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# Superset web UI
location / {
proxy_pass http://127.0.0.1:8088;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# MCP endpoint
location /mcp {
proxy_pass http://127.0.0.1:5008/mcp;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Authorization $http_authorization;
}
}
```
### Docker Compose
Run Superset and the MCP server as separate containers sharing the same config:
```yaml
# docker-compose.yml
services:
superset:
image: apache/superset:latest
ports:
- '8088:8088'
volumes:
- ./superset_config.py:/app/superset_config.py
environment:
- SUPERSET_CONFIG_PATH=/app/superset_config.py
mcp:
image: apache/superset:latest
command: ['superset', 'mcp', 'run', '--host', '0.0.0.0', '--port', '5008']
ports:
- '5008:5008'
volumes:
- ./superset_config.py:/app/superset_config.py
environment:
- SUPERSET_CONFIG_PATH=/app/superset_config.py
depends_on:
- superset
```
Both containers share the same `superset_config.py`, so authentication settings, database connections, and feature flags stay in sync.
### Multi-Pod (Kubernetes)
For high-availability deployments, configure Redis so that replicas share session state:
```mermaid
flowchart TD
LB["Load Balancer"] --> M1["MCP Pod 1"]
LB --> M2["MCP Pod 2"]
LB --> M3["MCP Pod 3"]
M1 --> R[("Redis
(session store)")]
M2 --> R
M3 --> R
M1 --> DB[("Postgres")]
M2 --> DB
M3 --> DB
```
**superset_config.py:**
```python
MCP_STORE_CONFIG = {
"enabled": True,
"CACHE_REDIS_URL": "redis://redis-host:6379/0",
"event_store_max_events": 100,
"event_store_ttl": 3600,
}
```
When `CACHE_REDIS_URL` is set, the MCP server uses a Redis-backed EventStore for session management, allowing replicas to share state. Without Redis, each pod manages its own in-memory sessions and stateful MCP interactions may fail when requests hit different replicas.
`MCP_STATELESS_HTTP` (default `True`) controls whether requests get a fresh, ephemeral transport per HTTP round trip or a transport that stays alive for the session's lifetime. The default suits multi-pod deployments because it doesn't require session affinity -- any pod can handle any request. Its tradeoff: a client disconnecting mid-tool-call can crash not just its own session but other concurrent sessions on the same worker. Setting it to `False` avoids that, but it requires session-affinity (sticky session) routing on `Mcp-Session-Id` at the mesh/ingress layer, since a session's follow-up requests must land on the same pod that created it. See [`MCP_STATELESS_HTTP`](#core) below.
---
## Configuration Reference
All MCP settings go in `superset_config.py`. Defaults are defined in `superset/mcp_service/mcp_config.py`.
### Core
| Setting | Default | Description |
| -------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MCP_SERVICE_HOST` | `"localhost"` | Host the MCP server binds to |
| `MCP_SERVICE_PORT` | `5008` | Port the MCP server binds to |
| `MCP_SERVICE_URL` | `None` | Public base URL for MCP-generated links (set this when behind a reverse proxy) |
| `MCP_DEBUG` | `False` | Enable debug logging |
| `MCP_DEV_USERNAME` | -- | Superset username for development mode (no auth) |
| `MCP_STATELESS_HTTP` | `True` | Streamable-HTTP session mode. `True` gives each request a fresh, ephemeral transport, torn down as soon as that request completes; a client disconnecting mid-tool-call can crash not just its own session but other concurrent sessions on the same worker. `False` keeps the transport alive for the session's lifetime, avoiding that crash, but requires session-affinity routing on `Mcp-Session-Id` for multi-pod deployments (see [Multi-Pod (Kubernetes)](#multi-pod-kubernetes)). |
| `MCP_RBAC_ENABLED` | `True` | Enforce Superset's role-based access control on MCP tool calls. When `True`, each tool checks that the authenticated user has the required FAB permission before executing. Disable only for testing or trusted-network deployments. |
| `MCP_DISABLED_TOOLS` | `set()` | Set of tool names to remove from the MCP server at startup. Disabled tools are never advertised to AI clients during tool discovery. Useful when a custom extension tool should replace a built-in Superset tool. See [Disabling built-in tools](#disabling-built-in-tools). |
| `MCP_STRUCTURED_OUTPUT_ENABLED` | `False` | Advertise native tool `outputSchema` metadata and return matching `structuredContent`. The text-only default supports clients and transport bridges that cannot encode structured results. Enable only after validating every MCP client and bridge used by the deployment. |
| `MCP_DISABLED_CHART_PLUGINS` | `frozenset()` | Set of chart type plugin names (e.g. `"handlebars"`) to hide from `generate_chart`. Does not affect `get_chart_type_schema`. See [Disabling chart type plugins](#disabling-chart-type-plugins). |
| `MCP_CHART_PLUGIN_ENABLED_FUNC` | `None` | Callable `(chart_type: str) -> bool` evaluated per registry lookup for dynamic enable/disable decisions. Takes precedence over `MCP_DISABLED_CHART_PLUGINS` when set. See [Disabling chart type plugins](#disabling-chart-type-plugins). |
### Authentication
| Setting | Default | Description |
| ---------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MCP_AUTH_ENABLED` | `False` | Enable JWT authentication |
| `MCP_JWT_ALGORITHM` | `"RS256"` | JWT signing algorithm (`RS256` or `HS256`) |
| `MCP_JWKS_URI` | `None` | JWKS endpoint URL (RS256) |
| `MCP_JWT_PUBLIC_KEY` | `None` | Static RSA public key string (RS256) |
| `MCP_JWT_SECRET` | `None` | Shared secret string (HS256) |
| `MCP_JWT_ISSUER` | `None` | Expected `iss` claim |
| `MCP_JWT_AUDIENCE` | `None` | Expected `aud` claim |
| `MCP_REQUIRED_SCOPES` | `[]` | Required JWT scopes |
| `MCP_IGNORED_SCOPES` | `{}` | Ignored JWT scopes. Can be used to enable RBAC-only behaviour for identity providers which require to request a scope. |
| `MCP_JWT_DEBUG_ERRORS` | `False` | Log detailed JWT errors server-side (never exposed in HTTP responses per RFC 6750) |
| `MCP_AUTH_FACTORY` | `None` | Custom auth provider factory `(flask_app) -> auth_provider`. Takes precedence over built-in JWT |
| `MCP_USER_RESOLVER` | `None` | Custom function `(app, access_token) -> username` to extract a Superset username from a validated JWT token. Use `get_verifier_client_id(access_token)` from `superset.mcp_service.composite_token_verifier` instead of reading `access_token.client_id`: FastMCP 4 `MultiAuth` qualifies that field. The helper supports FastMCP 3 and 4 and identifies the originating verifier, not proof of bearer validity. When `None`, the default resolver checks `preferred_username`, `username`, `email`, and `sub` claims in that order. |
| `MCP_EMBEDDED_GUEST_AUTH_ENABLED` | `False` | Accept embedded [guest tokens](#embedded-guest-authentication) as Bearer auth. Also requires the `EMBEDDED_SUPERSET` feature flag. |
| `MCP_GUEST_ALLOWED_TOOLS` | see [default list](#embedded-guest-authentication) | The only tool names callable by embedded guests (default-deny), regardless of `MCP_RBAC_ENABLED`. |
### Response Size Guard
Limits response sizes to prevent exceeding LLM context windows:
```python
MCP_RESPONSE_SIZE_CONFIG = {
"enabled": True,
"max_bytes": 50000,
"warn_threshold_pct": 80,
"max_list_items": 100,
"excluded_tools": [
"health_check",
"generate_explore_link",
"open_sql_lab_with_context",
"search_tools",
],
}
```
| Key | Default | Description |
| -------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled` | `True` | Enable response size checking |
| `max_bytes` | `50000` | Maximum serialized response size, in bytes |
| `warn_threshold_pct` | `80` | Warn when response exceeds this percentage of the limit |
| `max_list_items` | `100` | Cap on list-field length (e.g. `charts`, `native_filters`) applied to the `get_*_info` tools before falling back to more aggressive truncation. Raised from a hardcoded 30 in earlier versions; the higher default only keeps more data before the same size-budget fallback kicks in, so it's not a breaking change, but tenants that tuned workflows around the old 30-item cap should lower this value explicitly. |
| `excluded_tools` | See above | Tools exempt from size checking (e.g., tools that return URLs, not data) |
Write tools that cannot fit after truncation return a minimal confirmation rather
than a size-limit error. This confirmation retains identifying fields, error
details, and short string lists such as `changed_fields` (at most 20 items and
200 total characters). Larger lists are omitted; use `_response_truncated` and
`_truncation_notes` to detect a partial response and re-read the object if needed.
This fallback does not slim `update_chart`'s default payload.
### Caching
Optional response caching for read-heavy workloads. Requires Redis when used with multiple replicas.
```python
MCP_CACHE_CONFIG = {
"enabled": False,
"CACHE_KEY_PREFIX": None,
"list_tools_ttl": 300, # 5 min
"list_resources_ttl": 300,
"list_prompts_ttl": 300,
"read_resource_ttl": 3600, # 1 hour
"get_prompt_ttl": 3600,
"call_tool_ttl": 3600,
"max_item_size": 1048576, # 1 MB
"excluded_tools": [
"execute_sql",
"generate_dashboard",
"generate_chart",
"update_chart",
],
}
```
| Key | Default | Description |
| -------------------- | --------- | ----------------------------------------------------------- |
| `enabled` | `False` | Enable response caching |
| `CACHE_KEY_PREFIX` | `None` | Base prefix for shared Redis; Superset appends an internal response-contract namespace |
| `list_tools_ttl` | `300` | Cache TTL in seconds for `tools/list` |
| `list_resources_ttl` | `300` | Cache TTL for `resources/list` |
| `list_prompts_ttl` | `300` | Cache TTL for `prompts/list` |
| `read_resource_ttl` | `3600` | Cache TTL for `resources/read` |
| `get_prompt_ttl` | `3600` | Cache TTL for `prompts/get` |
| `call_tool_ttl` | `3600` | Cache TTL for `tools/call` |
| `max_item_size` | `1048576` | Maximum cached item size in bytes (1 MB) |
| `excluded_tools` | See above | Tools that are never cached (mutating or non-deterministic) |
### Redis Store (Multi-Pod)
Enables Redis-backed session and event storage for multi-replica deployments:
```python
MCP_STORE_CONFIG = {
"enabled": False,
"CACHE_REDIS_URL": None,
"event_store_max_events": 100,
"event_store_ttl": 3600,
}
```
| Key | Default | Description |
| ------------------------ | ------- | -------------------------------------------------------- |
| `enabled` | `False` | Enable Redis-backed store |
| `CACHE_REDIS_URL` | `None` | Redis connection URL (e.g., `redis://redis-host:6379/0`) |
| `event_store_max_events` | `100` | Maximum events retained per session |
| `event_store_ttl` | `3600` | Event TTL in seconds |
### Tool discovery modes
The MCP server can advertise its tools in two ways. Both modes serve the same
registered tool definitions through the same middleware, authentication, and
permission checks; only the `tools/list` response differs.
| Mode | `MCP_TOOL_SEARCH_CONFIG["enabled"]` | `tools/list` returns | Calling tools |
| ------------------------- | ----------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------------- |
| Compatibility (default) | `True` | The pinned `always_visible` tools plus `search_tools` and `call_tool` | Through the `call_tool` proxy, or directly by name |
| Native | `False` | Every tool the caller may use, under its real name | Directly by name with `tools/call` |
Every registered tool can be called directly by name in both modes. In native
mode each listed tool carries its full description, input schema, and
read-only/destructive/idempotent/open-world annotations, plus its output schema
when `MCP_STRUCTURED_OUTPUT_ENABLED = True`. The listing is a single page with
no cursor. Schema `$ref` definitions are inlined on the wire, with nullable
unions and constraints preserved, and calls are validated against the same
server-side models in either mode.
The native listing is much larger than the compatibility listing, and it grows
when structured output is enabled. Per-tool description lengths, schema sizes,
and catalog totals for both structured-output settings are recorded in
`tests/unit_tests/mcp_service/native_tool_inventory.json` and enforced by
regression tests. Clients and gateways that cap the size of a single list
response should be checked against those totals before switching modes.
#### Authorization in both modes
- `tools/list` in native mode and `search_tools` in compatibility mode apply the
same visibility check: RBAC, token scopes, the restricted-principal tool
policy, and data-model metadata access.
- Each tool enforces the same checks again when it is called, so naming a
hidden tool directly, or passing it to `call_tool`, is rejected with the same
error. Revoked permissions take effect on the next request.
- Tools in `ALLOWED_UNPROTECTED` (`generate_bug_report`) intentionally run
without authentication for every caller in both modes.
- When no authentication source is configured at all (development only),
native `tools/list` shows every tool, while `search_tools` returns only tools
without a permission requirement. Protected calls are rejected in both modes
until a user can be resolved.
- `call_tool` returns the same result as a direct call, including `isError`,
validation details, and `structuredContent` when structured output is
enabled.
#### Migrating to native mode
1. Confirm that every client used with the deployment calls tools by name from
`tools/list` and accepts the size of the full listing. Clients that load
tool definitions lazily on their own side work with native mode.
2. Choose `MCP_STRUCTURED_OUTPUT_ENABLED` separately; it is independent of the
discovery mode.
3. Set `MCP_TOOL_SEARCH_CONFIG["enabled"] = False`. To roll back, set it to
`True`; no client or server state needs migrating.
Clients that call tools by name work against servers in either mode. Clients
that only know `search_tools` and `call_tool` fail against a server in native
mode, because those two tools are not served there. Keep compatibility mode
until such clients have migrated, and in multi-pod deployments switch every pod
together (or keep each client session on pods in one mode) so that a session
started in compatibility mode is not routed to a pod in native mode.
#### Compact native listing
Native mode can optionally bound each listed tool description, which shrinks
the `tools/list` response without changing what clients can call:
```python
MCP_NATIVE_TOOL_LIST_CONFIG = {
"compact": True, # default: False
"max_description_length": 300, # prose budget per tool
}
```
Descriptions keep whole paragraphs first, then whole sentences. Once a whole
paragraph fits the budget, a following heading, `IMPORTANT` block, or list is
not partly advertised. An overlong first paragraph can be cut at a sentence
boundary, even if it is structured. Calling instructions authored on a tool's
`request` parameter stay untruncated in the input schema and are not deducted
from the native prose budget. Names, input and output schemas (including nullable
unions, constraints, and definitions), and annotations are unchanged, and calls
are validated against the same server-side models, so only the listed prose
differs. Chart tools point to `get_chart_type_schema`, which returns each chart
type's fields, required fields, and examples. The setting has no effect in
compatibility mode, whose search results are bounded by
`MCP_TOOL_SEARCH_CONFIG["max_description_length"]`.
Both default and factory startup read `MCP_TOOL_SEARCH_CONFIG` and
`MCP_NATIVE_TOOL_LIST_CONFIG` from the Flask application configuration, falling
back to the module defaults when a setting is absent.
The recorded inventory includes catalog totals for both listings.
Compatibility mode remains supported. Any change to its default will be listed
in `UPDATING.md`, and setting `enabled` explicitly keeps the chosen mode
regardless of the default.
### Tool Search
In compatibility mode the MCP server exposes a lightweight tool-search interface instead of advertising every tool at once, which keeps the initial tool listing small. The AI client discovers tools on demand by calling `search_tools` and then invokes them via `call_tool`.
```python
MCP_TOOL_SEARCH_CONFIG = {
"enabled": True,
"strategy": "bm25", # "bm25" (natural language) or "regex"
"max_results": 5,
"always_visible": [ # Tools always listed (pinned)
"health_check",
"get_instance_info",
],
"search_tool_name": "search_tools",
"call_tool_name": "call_tool",
"include_schemas": True, # False=summary mode (name + parameters_hint)
"compact_schemas": True, # Default description limit when include_schemas=True
"max_description_length": 300,
}
```
| Key | Default | Description |
| ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `enabled` | `True` | Enable tool search. When `False`, all tools are listed upfront |
| `strategy` | `"bm25"` | Search ranking algorithm. `"bm25"` supports natural language; `"regex"` supports pattern matching |
| `max_results` | `5` | Maximum tools returned per search query |
| `always_visible` | See above | Tools that always appear in `list_tools`, regardless of search |
| `include_schemas` | `True` | Include the full `inputSchema` in search results by default. When `False` ("summary mode"), search results omit `inputSchema` entirely and include a lightweight `parameters_hint` listing top-level parameter names. Full schemas are always used when a tool is actually invoked via `call_tool`. |
| `compact_schemas` | `True` | Legacy setting selecting the default description limit (300 when `True`, 0 when `False`) if `max_description_length` is omitted. Input schemas preserve `$defs`, `$ref`, nullable unions, and constraints in either mode; titles are omitted. Clients should resolve references within each tool's `inputSchema`. |
| `max_description_length` | `300` | Budget for discovery prose alone (0 = no prose truncation). Complete paragraphs are retained, followed by complete sentences of the next paragraph unless it is a list, heading, or IMPORTANT block. Applies in both summary and full-schema modes. |
The no-query catalog uses the same bounded serializer as targeted search.
Chart creation/update and virtual-dataset tools keep request wrapping, save/preview
behavior, required URL display, and workflow guidance in request metadata rather
than relying on truncated introductory prose. Paragraph truncation never leaves a
partial IMPORTANT block or numbered workflow in the catalog.
Calling constraints are authored as a `Field(description=...)` on the tool's
`request` parameter and served as the `request` property's schema description, so
schema-first clients can identify the wrapper without remembering previous calls.
Summary mode preserves these instructions in `parameters_hint`. Instructions are
never truncated and do not consume the prose budget in either mode, matching
native compact listings. A request model's own docstring is not a calling
instruction. Built-in calling instructions are capped at 300
characters by regression tests, and the complete tool entries retain per-tool
size budgets. Field-level descriptions in the default full input schema also
preserve tool-specific search semantics, sortable columns, chart pagination, and
layout guidance. These details are not included in schema-free summary mode.
This setting does not change result-size limits or schema validation.
:::tip
Set `enabled: False` to revert to the traditional "show all tools at once" behavior, which some clients or workflows may prefer.
:::
With either the `bm25` or `regex` strategy, a query matching a tool name is
promoted ahead of other matches before the `max_results` limit is applied. Matching
ignores case and treats underscores and whitespace as equivalent separators
(including leading, trailing, or repeated whitespace). Only tools visible to
the caller are eligible. Pinned `always_visible` tools remain in `list_tools`
rather than search results. BM25 also promotes multi-word tool names spelled out
as a contiguous, in-order run in a longer query. These matches are ordered by
name length (longest first), then by where the name starts in the query, then
by BM25 rank. A name contained in another covered name is not promoted separately:
`create dataset metric for revenue` promotes `create_dataset_metric`, not
`create_dataset`. Other candidates retain BM25 ranking; regex searches retain
catalog ordering for non-exact matches.
Tool search keeps the initial listing to the pinned tools and the search
interface; see the recorded inventory above for the size of the full native
catalog it replaces.
### Session & CSRF
These values are flat-merged into the Flask app config used by the MCP server process:
```python
MCP_SESSION_CONFIG = {
"SESSION_COOKIE_HTTPONLY": True,
"SESSION_COOKIE_SECURE": False,
"SESSION_COOKIE_SAMESITE": "Lax",
"SESSION_COOKIE_NAME": "superset_session",
"PERMANENT_SESSION_LIFETIME": 86400,
}
MCP_CSRF_CONFIG = {
"WTF_CSRF_ENABLED": True,
"WTF_CSRF_TIME_LIMIT": None,
}
```
---
## Access Control
### RBAC Enforcement
The MCP server respects Superset's full role-based access control (RBAC). Every authenticated user can only access the data and operations their Superset roles permit — the same rules that apply in the Superset UI apply through MCP.
Each tool declares one or more required FAB permissions. The table below maps tool groups to their permission requirements:
| Tool group | Required FAB permission |
| -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `list_charts`, `get_chart_info`, `get_chart_data`, `get_chart_preview`, `generate_chart`, `update_chart` | `can_read` on `Chart` (read), `can_write` on `Chart` (mutate) |
| `list_dashboards`, `get_dashboard_info`, `generate_dashboard`, `add_chart_to_existing_dashboard` | `can_read` on `Dashboard` (read), `can_write` on `Dashboard` (mutate) |
| `get_dashboard_data` | `can_read` on `Dashboard` **and** `can_read` on `Chart` (it reads chart data across the dashboard) |
| `list_datasets`, `get_dataset_info`, `create_virtual_dataset` | `can_read` on `Dataset` (read), `can_write` on `Dataset` (mutate) |
| `list_metrics`, `get_table`, `get_compatible_dimensions`, `get_compatible_metrics` | `can_read` on `Dataset`, plus a data-model metadata permission (`can_get_drill_info`, `can_get_or_create_dataset`, or `can_write` on `Dataset`); external semantic views also enforce their own datasource access check |
| `list_databases`, `get_database_info` | `can_read` on `Database` |
| `get_catalog` | `can_read` on the requested asset class (`Database`, `Dataset`, `Chart`, or `Dashboard`); databases and datasets also require data-model metadata access, otherwise the page is marked `restricted` |
| `execute_sql` | `can_execute_sql_query` on `SQLLab` |
| `open_sql_lab_with_context` | `can_read` on `SQLLab` |
| `save_sql_query` | `can_write` on `SavedQuery` |
| `health_check` | None (public) |
To disable RBAC checking globally (for trusted-network deployments or testing), set:
```python
# superset_config.py
MCP_RBAC_ENABLED = False
```
:::warning
Disabling RBAC removes all permission checks from MCP tool calls. Only do this on isolated, internal deployments where all MCP users are trusted admins.
:::
### Audit Log
All MCP tool calls are recorded in Superset's action log. You can view them at **Settings → Action Log** (admin only). Each log entry records:
- The tool name (e.g., `mcp.generate_chart.db_write`)
- The authenticated user
- A timestamp
This makes MCP activity fully auditable alongside regular Superset activity. The action log uses the same event logger as the rest of Superset, so existing log ingestion pipelines (e.g., sending logs to Elasticsearch or a SIEM) capture MCP events automatically.
### Middleware Pipeline
Every MCP request passes through a middleware stack before reaching the tool function. The default stack (assembled in `build_middleware_list()` in `server.py`) is:
| Middleware | Purpose | Default |
| ----------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| `ToolResultCompatibilityMiddleware` | Gates structured results and sanitizes errors that escape the inner error handler | Enabled |
| `LoggingMiddleware` | Logs each tool call with user, parameters, and duration | Enabled |
| `GlobalErrorHandlerMiddleware` | Catches unhandled exceptions and sanitizes sensitive data before it reaches the client | Enabled |
| `ResponseSizeGuardMiddleware` | Measures serialized response size, warns at 80% of limit, blocks at limit | Enabled (configurable via `MCP_RESPONSE_SIZE_CONFIG`) |
| `ResponseCachingMiddleware` | Caches read-heavy tool responses (in-memory or Redis) | Disabled (enable via `MCP_CACHE_CONFIG`) |
`RBACToolVisibilityMiddleware` sits between the compatibility and logging
middleware and filters `tools/list` to the tools the caller may use.
The MCP service applies no request rate limiting of its own. Deployments that
need rate limits enforce them in front of the MCP endpoint, for example in a
gateway or reverse proxy, where they apply to native and compatibility-mode
calls alike.
`StructuredContentStripperMiddleware` is a deprecated compatibility class for
custom startup paths that retains its original stripping behavior. Replace it with
`ToolResultCompatibilityMiddleware(structured_output_enabled=False)`.
### Tool Result Value Contract
When `MCP_STRUCTURED_OUTPUT_ENABLED=True`, native tools advertise a concrete
`outputSchema` during tool discovery and return matching `structuredContent`
alongside their text representation. Clients can use the schema to understand
result fields and validate structured tool-call results. The default is `False`:
the compatibility middleware removes both fields as a pair and preserves the
text representation for clients and bridges that do not support structured output.
Structured tool results preserve Superset domain values exactly. In particular,
string fields are not wrapped in trust delimiters, and text that resembles a
delimiter is returned as literal application data. This lets clients safely use a
read result as the basis for an update without persisting presentation markup.
All tool-result content should still be treated as user-controlled data with no
instruction authority. MCP clients should communicate that trust boundary through
their model instructions or presentation layer, outside the returned field values;
fixed or generated marker strings inside a value are ambiguous and must not be used
as a trust signal.
For compatibility, clients that supported the former
`` convention should stop recognizing or stripping those strings.
The response schemas and content types have not changed. Because marker-looking text
can be legitimate application data, a client cannot reliably distinguish a legacy
decorated response from a clean one. Pause automated read-modify-write workflows, or
route them only to upgraded instances, until every serving instance is upgraded.
Redis-backed MCP response caches include an internal response-contract namespace, so
an upgraded instance does not reuse responses cached by an older release. Older
instances can still return legacy values while they remain in service. After the
upgrade, review previously written values for wrapper text and both
`[ESCAPED-UNTRUSTED-CONTENT-OPEN]` and
`[ESCAPED-UNTRUSTED-CONTENT-CLOSE]`; do not remove these strings automatically,
because they may be intentional content.
### Error Sanitization
The `GlobalErrorHandlerMiddleware` automatically redacts sensitive information from all error messages before they reach the LLM client. The following are replaced with generic messages:
- **Database connection strings** — replaced with a generic connection error message
- **API keys and tokens** — redacted from error traces
- **File system paths** — stripped to prevent information disclosure
- **IP addresses** — removed from error context
This ensures that a misconfigured database connection or an unexpected exception never leaks credentials or internal topology to the LLM or its users. All regex patterns used for redaction are bounded to prevent ReDoS attacks.
---
## Performance
### Connection Pooling
Each MCP server process maintains its own SQLAlchemy connection pool to the database. For multi-worker deployments, total open connections = **workers × pool size**.
```python
# superset_config.py
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_MAX_OVERFLOW = 10
SQLALCHEMY_POOL_TIMEOUT = 30
SQLALCHEMY_POOL_RECYCLE = 3600 # Recycle connections after 1 hour
```
For a 3-pod Kubernetes deployment with the defaults above, expect up to 3 × (5 + 10) = 45 connections. Size your database's `max_connections` accordingly.
### Response Caching
Enable response caching for read-heavy workloads (dashboards/datasets that don't change frequently). With the in-memory backend (default when `MCP_STORE_CONFIG` is disabled), caching is per-process. Use Redis-backed caching for consistent cache hits across multiple pods:
```python
MCP_CACHE_CONFIG = {
"enabled": True,
# Cache keys don't include the requesting principal and hits are served
# ahead of auth/RBAC, so a shared cache can return one caller's response
# to another. Required for caching to actually start -- only appropriate
# when every request is guaranteed to come from the same principal.
"dangerously_share_cache_across_principals": True,
"CACHE_KEY_PREFIX": "mcp_cache_",
"call_tool_ttl": 3600,
}
MCP_STORE_CONFIG = {"enabled": True, "CACHE_REDIS_URL": "redis://redis:6379/0"}
```
Every tool with a side effect (create/update/delete/execute) is always excluded from caching regardless of this setting -- see the `excluded_tools` default in `superset/mcp_service/mcp_config.py` for the current list.
---
## Chart previews
Saved and unsaved Vega-Lite previews return `NoDataError` for empty query
results unless the chart plugin declares `allows_empty_result` (for example,
Gantt renders an empty task list).
For basic Vega-Lite previews, the y-axis uses the first configured metric whose
result label is present and whose first value is numeric or null. Boolean and
string metric values are skipped. If metric labels match but none has a suitable
value, the y-axis is omitted. Only when no metric label matches does the preview
fall back to the first numeric, non-boolean column; aggregation words in column
names do not make nonnumeric values eligible.
## Troubleshooting
### Server won't start
- Verify `fastmcp` is installed: `pip install fastmcp`
- Check that `MCP_DEV_USERNAME` is set if auth is disabled -- the server requires a user identity
- Confirm the port is not already in use: `lsof -i :5008`
### 401 Unauthorized
- Verify your JWT token has not expired (`exp` claim)
- Check that `MCP_JWT_ISSUER` and `MCP_JWT_AUDIENCE` match the token's `iss` and `aud` claims exactly
- For RS256 with JWKS: confirm the JWKS URI is reachable from the MCP server
- For RS256 with static key: confirm the public key string includes the `BEGIN`/`END` markers
- For HS256: confirm the secret matches between the token issuer and `MCP_JWT_SECRET`
- Enable `MCP_JWT_DEBUG_ERRORS = True` for detailed server-side logging (errors are never leaked to the client)
### Tool not found
- Ensure the MCP server and Superset share the same `superset_config.py`
- Check server logs at startup -- tool registration errors are logged with the tool name and reason
- In native mode (`MCP_TOOL_SEARCH_CONFIG["enabled"] = False`) `search_tools` and `call_tool` are not served; call tools by name or re-enable compatibility mode
### Client can't connect
- Verify the MCP server URL is reachable from the client machine
- For Claude Desktop: fully quit the app (not just close the window) and restart after config changes
- For remote access: ensure your firewall and reverse proxy allow traffic to the MCP port
- Confirm the URL path ends with `/mcp` (e.g., `http://localhost:5008/mcp`)
### Permission errors on tool calls
- The MCP server enforces Superset's RBAC permissions -- the authenticated user must have the required roles
- In development mode, ensure `MCP_DEV_USERNAME` maps to a user with appropriate roles (e.g., Admin)
- Check `superset/security/manager.py` for the specific permission tuples required by each tool domain (e.g., `("can_execute_sql_query", "SQLLab")`)
### Rejected text fields
Text-sanitization errors identify the rejected field and provide a fixed reason
without echoing its value. This applies to titles, certification text, chart
column names and labels, filter values, temporal and Gantt sort columns, Bullet
labels, and time-range or comparison-period text. A `data:` label followed by a
comma is rejected as a possible data URL; rewrite the label without `data:` or
without the comma. Bullet labels cannot contain commas at all because their
frontend controls use comma-separated values. Empty certification text must be
cleared with an explicit empty string rather than text that sanitizes to nothing.
### Response too large
Two independent limits can reject a large result. Check the error type to tell them apart:
- **Response size guard (configurable).** An error about exceeding the response size limit comes from `ResponseSizeGuardMiddleware`, which measures the serialized tool response.
- Reduce `page_size` or `limit` parameters, use `select_columns` to exclude large fields, or add filters to narrow results
- To adjust the threshold, change `max_bytes` in `MCP_RESPONSE_SIZE_CONFIG`
- To disable the guard entirely, set `MCP_RESPONSE_SIZE_CONFIG = {"enabled": False}`
- **Chart query result limits (mandatory).** An `InvalidQueryResult` error such as "Chart query returned too many rows" or "hostile or oversized row data" comes from validation of the chart query result itself, before any response is built. These limits are fixed safety bounds and are **not** affected by `MCP_RESPONSE_SIZE_CONFIG`; raising `max_bytes` or disabling the guard does not change them. They cap a result at 50,000 rows per query and 100,000 rows in total, 4,096 columns, 2,500,000 values, 16 MiB of JSON, and 65,536 UTF-8 bytes per text cell (binary cells are bounded by the same per-cell limit). To resolve them, reduce the chart's row limit, add filters, select fewer or narrower columns, or aggregate the data.
---
## Audit Events
All MCP tool calls are logged to Superset's event logger, the same system used by the web UI (viewable at **Settings → Action Log**). Each event captures:
- **Action**: `mcp..` (e.g., `mcp.list_databases.query`)
- **User**: the resolved Superset username from the JWT or dev config
- **Timestamp**: when the operation ran
This means MCP activity is auditable alongside normal user activity. No additional configuration is required — logging is on by default whenever the event logger is enabled in your Superset deployment.
### Tool Metrics
The configured stats logger records one outcome counter
(`mcp.tool..success`, `.warning`, or `.error`) and one timing
(`mcp.tool..time`) per tool execution. Calls forwarded through the
tool-search proxy, including a custom `call_tool_name`, use the target tool's
metrics without a second counter or timing from the proxy. This applies to both
successful and failed calls; exceptions raised by the proxy itself are still
counted.
## Tool Pagination
MCP list tools (`list_datasets`, `list_charts`, `list_dashboards`, `list_databases`) use **offset pagination** via `page` (1-based) and `page_size` parameters. Responses include `page`, `page_size`, `total_count`, `total_pages`, `has_previous`, and `has_next`. To iterate through all results:
```python
# Example: fetch all charts across pages
all_charts = []
page = 1
while True:
result = mcp.list_charts(page=page, page_size=50)
all_charts.extend(result["charts"])
if not result.get("has_next"):
break
page += 1
```
### Asset Catalog
`get_catalog` returns a compact catalog page for one asset type (`databases`, `datasets`, `charts`, or `dashboards`). It is designed for assistants that need an inventory of what a user can see without calling the full list tools repeatedly:
- **Per-user and live**: every call reads through the same DAO visibility filters as the matching list tool, as the calling user. Nothing is cached or stored, and the tool is always excluded from MCP response caching, so a revoked grant is reflected on the next call. This also applies through the tool-search `call_tool` proxy (including a custom `call_tool_name`): proxy responses are never cached, leaving cache policy to the target tool.
- **Field allowlist**: each item has only `id`, `uuid`, `name`, `description`, `changed_on`, and `url`. SQL, `extra`, template parameters, metric expressions, and connection details are never read or returned.
- **Restricted marker**: users without data-model metadata access receive `restricted: true` with no items for `databases` and `datasets`.
- **Bounded**: `page_size` is at most 100, and each response stays under 32 KiB. Pages use an opaque keyset `next_cursor`, bound to the asset type and search term, that stays stable when assets are added or removed between pages. `truncated: true` means byte-bound pagination held entries back, not that fields were shortened; otherwise `truncated` is `false`. Use `next_cursor` as the continuation signal: pass it back as `cursor` to fetch the next page, or stop when it is `null`.
- **Field shortening**: `fields_shortened: true` means a long name or description was shortened, or a URL longer than 2,048 characters was returned as `null` rather than shortened into an unusable link. It does not mean entries are missing.
```python
page = mcp.get_catalog(request={"asset_type": "dashboards", "page_size": 50})
while page["next_cursor"]:
page = mcp.get_catalog(
request={"asset_type": "dashboards", "cursor": page["next_cursor"]}
)
```
## Chart datasource metadata
For roles allowed to view data-model metadata, `get_chart_info` includes
`datasource_id` in its default columns. Dashboard chart summaries include
`datasource_type` alongside `datasource_id`, which is only unique within its type.
Both fields are redacted for users without data-model metadata access.
Chart and dashboard chart summaries resolve dataset names from the live table
or semantic view, so renames are reflected without resaving the chart. Query and
saved-query charts retain their stored datasource names; missing tables or
semantic views do not fall back to stale names. Saved-chart `get_chart_data`
and `get_chart_info` prechecks, and the chart access checks in
`add_chart_to_existing_dashboard`, `generate_dashboard`, and `update_chart`,
resolve semantic-view sources by type and ID, then check access before
continuing. `update_chart` then refuses semantic-view charts, which it cannot
yet edit. SQL-dataset charts retain their existing dataset validation.
Adding charts to a dashboard with `add_chart_to_existing_dashboard` or
`generate_dashboard` requires access to each chart as well as its datasource.
A datasource grant alone does not override a chart's explicit viewer restrictions.
For `generate_dashboard`, every chart referenced in a custom `position_json`
must also appear in `chart_ids`, where its access is checked. This includes
chart nodes outside the connected layout tree.
`list_charts` filters on `datasource_name` use these same live names before
pagination and counting. For tables with a schema, filter using
`schema.table_name`. Data-model metadata permission checks also apply to these
filters and returned identifiers.
`list_charts` filters on `datasource_id` support `eq`, `ne`, `in`, and `nin`.
These dataset ID filters apply only to table-backed charts, excluding charts
on other datasource types even when their numeric IDs overlap.
## Trash Listing (Soft-Deleted Objects)
When the `SOFT_DELETE` feature flag is enabled, deleting a chart, dashboard or dataset moves it to trash rather than removing it outright. The `list_charts`, `list_dashboards` and `list_datasets` tools accept a `deleted_state` parameter to surface those trashed objects:
- `deleted_state="only"` — return only trashed objects
- `deleted_state="include"` — return live and trashed objects together
- Omitted (default) — live objects only; trashed objects are excluded
```python
# List only trashed charts
result = mcp.list_charts(request={"deleted_state": "only"})
```
Trashed rows carry a non-null `deleted_at` timestamp in the response (populated only when `deleted_state` is used). Visibility follows the same restore-audience scoping as the equivalent REST API filters (`chart_deleted_state` / `dashboard_deleted_state` / `dataset_deleted_state`): a non-admin caller sees only the trashed objects they can edit (the same audience that can restore them), not merely the ones they own; admins see all trashed objects. That scoping is narrower than the true restore audience in two cases it can't express in SQL: editorship granted via `EXTRA_EDITORS_RESOLVER` and guest users whose editorship derives from roles. Callers in either case may be able to restore a trashed object via `POST /restore` yet not see it listed here.
`deleted_state` is only defined on `list_charts`, `list_dashboards` and `list_datasets`.
Other list tools do not define this parameter and cannot use it to return trashed
objects. In particular, `list_reports` and `list_databases` reject it as an unknown
argument.
## Disabling built-in tools
If you have deployed a custom tool via a Superset extension that supersedes one of the built-in Superset tools, you can suppress the built-in version so AI clients only discover your replacement. Disabled tools are removed from the server at startup and are never advertised during tool discovery.
Set `MCP_DISABLED_TOOLS` in your `superset_config.py` to a set of tool names:
```python
# superset_config.py
# Disable one tool
MCP_DISABLED_TOOLS = {"execute_sql"}
# Disable multiple tools
MCP_DISABLED_TOOLS = {"execute_sql", "health_check"}
```
Tool names match the function name used in the `@tool` decorator (e.g., `execute_sql`, `list_charts`, `health_check`). Extension-prefixed tools can also be disabled using their full prefixed name:
```python
MCP_DISABLED_TOOLS = {"extensions.myorg.myextension.some_tool"}
```
:::note
Specifying a tool name that does not exist logs a warning at startup and is otherwise ignored — it will not prevent the server from starting.
:::
## Bullet chart compatibility
The MCP Bullet plugin uses `chart_type: "bullet"` and the native ECharts
`viz_type: "bullet"`. Its optional `dimensions` hierarchy maps to `groupby`.
Omit `dimensions` (or use `null`) to create a single-metric Bullet without a
breakdown. On updates, omission or `null` preserves the saved hierarchy; use
`dimensions: []` to clear it explicitly. An `order_by` update can reference the
saved dimensions without resending them; unknown targets are rejected after
resolving the saved hierarchy. Replacing the dataset follows the shared rebind
contract: saved query roles are not inherited, so resend the hierarchy.
Inherited native SQL dimensions remain query expressions when updating metrics
or `order_by`; reference their output labels to sort by them. Caller-supplied
`dimensions` must still be physical columns, not SQL expressions.
Dimension and metric output names are case-sensitive: quoted physical columns
such as `Region` and `region` remain distinct. Reference lookup prefers exact
names and uses case-insensitive matching only when there is a single candidate;
ambiguous references require the exact spelling. Bullet metric strings use
JavaScript numeric spellings: underscore separators and non-ASCII digits are
rejected rather than interpreted as numbers. Bounded array-valued dimensions
retain their raw values in data reads and exports; preview category labels use
JavaScript string conversion (for example, `[1, 2]` displays as `1,2`). Native
SQL metrics without a label use their SQL expression as the output label.
Native metric objects in `orderby` or `order_by_cols` use the same output-label
fallback, so an unlabeled SQL metric can also be used as its own sort target.
Presentation-only updates preserve saved predicates, including legacy top-level
`where`, `having`, and `filters`, and normalize the native `order_by_cols` alias.
When both `orderby` and `order_by_cols` are saved, their sort entries are
concatenated in form-data key order, including when `orderby` is empty.
Explicit `filters: []` and `order_by: []` clear those inherited controls.
Range, marker, and marker-line label lists may be shorter than their value lists.
Labels that become empty after sanitization retain their slots so later labels
remain aligned with their corresponding values.
As in Explore, missing or empty range labels are not displayed, and missing or
empty marker labels use the formatted numeric value. Extra labels have no value
to annotate and are ignored. These rules also apply to saved-chart previews and
updates. Omitted label controls preserve the saved state only when their
corresponding value controls (`ranges`, `markers`, or `marker_lines`) are also
omitted. Replacing a value control without its labels clears the saved labels;
resend the labels to retain annotations with the replacement values.
Saved native `ranges`, `markers`, and `marker_lines` controls ignore empty,
non-numeric, and NaN tokens, matching Explore. If no numeric range remains, the
preview uses the default band up to 110% of the largest measure. Unrelated
updates preserve these saved controls. Newly authored typed lists must contain
finite numbers; infinite native values and oversized controls remain errors.
On same-dataset chart updates, `filters: []` clears both user filters and the
generated dashboard-time binding. `temporal_column: null` clears only that
generated binding, preserving user filters. Omitting those controls preserves
the saved binding. Bullet Vega previews keep separate indexed rows even when
dimension display labels are identical, and support both `SMART_NUMBER` and
`SMART_NUMBER_SIGNED` number formats. Bullet preview numeric format
precision is limited to 20 digits before formatting; raw data reads do not
validate presentation formats.
Native Bullet temporal filters retain the active filter's subject and range as a
pair; `No filter` placeholders do not supply the subject of another active range.
Typed configs support one such pair. Multiple active native temporal filters, or
conflicts with explicit `temporal_column`/`time_range`, are rejected rather than
silently dropping or moving a predicate.
## Disabling chart type plugins
The `generate_chart` tool dispatches per chart type (`xy`, `table`, `pie`, `gauge`, `treemap_v2`, `pivot_table`, `interactive_pivot`, `mixed_timeseries`, `handlebars`, `big_number`, `histogram`, `box_plot`, `waterfall`, `bullet`) to a registered chart type plugin. Gauge requests use the public MCP discriminator `chart_type: "gauge"`; Superset stores the corresponding native Explore visualization as `viz_type: "gauge_chart"`. Two settings let operators enable or disable individual chart type plugins at runtime, without a code deploy.
Saved Bubble and Histogram Vega-Lite previews with zero rows return an empty
specification instead of `NoDataError`, matching their unsaved previews.
Gauge data inspection and JSON/CSV/XLSX exports preserve source groups using the same row-count and completeness semantics as other chart types. Shared result normalization converts non-finite floats to null before export: JSON returns null, and CSV and both XLSX writers produce blank cells. These values are indistinguishable from SQL NULL; exports do not retain `nan`, `inf`, or `-inf` text. An overflowing aggregate can therefore appear as a missing value. Only previews and compile checks skip NULL, NaN, non-finite, and other nonnumeric dial values while preserving finite groups. In preview/compile paths, a nonempty result containing no finite dial returns an error; genuinely empty results retain the no-data behavior. Compile checks inspect the configured dial limit (at most 10), rather than only two groups. Grouped Vega previews center each needle within its own facet and extend it to the midpoint of the dial band. Automatic all-zero ranges span 0–1. Empty or whitespace-only temporal ranges, like `No filter`, are neutral sentinels; missing or non-string native temporal comparators are invalid.
Gauge previews retain data-derived automatic bounds even when configured interval thresholds extend beyond the visible range; Vega previews clip those thresholds into adjacent, non-overlapping bands. Explicit min/max bounds still constrain intervals. All-zero data with both bounds omitted uses a nondegenerate preview range of 0–1. On same-dataset Gauge updates, clearing or changing the dashboard temporal binding preserves user-authored temporal ranges; dataset rebinds discard old query roles and filters. The native `"No filter"` sentinel is a neutral dashboard temporal binding, not a conflicting restriction. Duplicate generated neutral bindings self-heal on updates without removing user-authored ranges. Restating the existing dataset ID without a config is allowed; changing the Gauge dataset still requires a complete config. Native restrictive temporal filters that conflict with the top-level range or another restrictive temporal filter are rejected rather than silently dropped. Unsupported native filter operators are rejected with an indexed error. Native `TEMPORAL_RANGE` adhoc filters require an explicit string comparator; `"No filter"`, empty strings, and whitespace represent an unrestricted range.
### Static deny-list
Set `MCP_DISABLED_CHART_PLUGINS` in your `superset_config.py` to a set of chart type names:
```python
# superset_config.py
# Emergency kill switch: hide "handlebars" from all callers
MCP_DISABLED_CHART_PLUGINS = {"handlebars"}
```
Disabled chart types stay registered but are filtered out at lookup time: they're never listed in `generate_chart`'s supported chart types, and `generate_chart` calls for them are rejected. `get_chart_type_schema` consults its own static schema/example map rather than the registry filter, so a disabled chart type's schema remains queryable through that tool even though `generate_chart` will reject it.
### Dynamic predicate
For per-request control (A/B tests, gradual rollout, entitlement checks), set `MCP_CHART_PLUGIN_ENABLED_FUNC` to a callable. It's evaluated as `enabled_func(chart_type: str) -> bool` on every registry lookup, and it takes precedence over `MCP_DISABLED_CHART_PLUGINS` when set:
```python
# superset_config.py
from flask import g
def MCP_CHART_PLUGIN_ENABLED_FUNC(chart_type: str) -> bool:
flags = getattr(g, "feature_flags", {})
return flags.get(f"mcp_chart_{chart_type}", True)
```
The callable must be cheap and in-process (consult already-loaded feature flags or request-local context) -- do not perform network I/O per call. If it raises, the registry fails closed (the plugin is hidden) and logs a warning.
Disabling a plugin only stops new charts of that type from being created. Existing saved charts of that type keep their plugin's query, result-validation and preview behavior in `get_chart_data`, `get_chart_preview` and `get_chart_sql`. Updates through `update_chart` and `update_chart_preview` also retain the plugin's configuration completion, column validation, merge rules, and compile checks. Gauge and Treemap compile checks use a safe 10-row fallback for malformed (including boolean) or nonpositive saved row limits. Malformed Gantt query fields return a validation error rather than a generic data-retrieval error. Funnel Vega-Lite previews return `InvalidFormData` when a stage reference has no resolvable result label. Mixed timeseries queries keep each axis's series grouping separate from the time-axis column. Saved charts with a scalar `groupby` retain the full column name in Waterfall queries and Funnel/Histogram Vega-Lite previews.
Saved Histogram and Gantt charts apply `time_range` to the date column selected
by `granularity_sqla`. A normalized `granularity` override takes precedence,
including an explicit clear.
## Security Best Practices
- **Use TLS** for all production MCP endpoints -- place the server behind a reverse proxy with HTTPS
- **Enable JWT authentication** for any internet-facing deployment
- **RBAC enforcement** -- The MCP server respects Superset's role-based access control. Users can only access data their roles permit
- **Secrets management** -- Store `MCP_JWT_SECRET`, database credentials, and API keys in environment variables or a secrets manager, never in config files committed to version control
- **Scoped tokens** -- Use `MCP_REQUIRED_SCOPES` to limit what operations a token can perform
- **Network isolation** -- In Kubernetes, restrict MCP pod network policies to only allow traffic from your AI client endpoints
- Review the **[Security documentation](/developer-docs/extensions/security)** for additional extension security guidance
---
## Next Steps
- **[Using AI with Superset](/user-docs/using-superset/using-ai-with-superset)** -- What AI can do with Superset and how to get started
- **[MCP Integration](/developer-docs/extensions/mcp)** -- Build custom MCP tools and prompts via Superset extensions
- **[Security](/developer-docs/extensions/security)** -- Security best practices for extensions
- **[Deployment](/developer-docs/extensions/deployment)** -- Package and deploy Superset extensions
### Reporting query dates
`query_dataset` and `get_table` return `from_dttm` (inclusive) and `to_dttm`
(exclusive): the primary time boundaries from the query engine's result payload,
including cached and empty results. Callers should quote these ISO 8601 values
when explaining the numbers, rather than calculate dates from the request again.
For example, `previous calendar month` evaluated on July 17, 2026 resolves to
`2026-06-01T00:00:00` through, but not including, `2026-07-01T00:00:00`.
`Last month` is a rolling month, not the previous calendar month.
On a cache hit, these bounds reflect the current request, not necessarily the
original cached execution. A cached result can outlive a relative-range rollover;
check `cache_status.cache_hit` before describing the bounds as execution dates.
Relative expressions use Superset's server clock and configured
`DEFAULT_RELATIVE_START_TIME` / `DEFAULT_RELATIVE_END_TIME` (both default to
`today`, meaning midnight). Valid explicit dates are used as supplied; the server
cannot determine whether a model intended a different year.
These fields describe the engine's **primary logical range**, not the observed
minimum/maximum dates in the rows or every SQL predicate. A null boundary means
no primary bound is available; it does not prove the absence of other filters.
Additional column filters and virtual dataset SQL can further constrain the
data. MCP validation rejects open-ended `time_range` strings such as
`"2025-01-01 : "` or `" : 2025-02-01"` before execution; use explicit comparison
filters for one-sided constraints. Those comparisons are not primary bounds. Naive
boundaries are not labeled UTC: dataset timezone or legacy hour-offset settings
can adjust the SQL comparisons. Use the applied filters and datasource settings
as well when explaining such queries. `query_dataset.applied_filters` retains the
original expressions so callers can compare the requested and resolved ranges.
### Overriding a saved chart's time grain
Pass `extra_form_data={"time_grain_sqla": "P1M"}` to `get_chart_data` or
`get_chart_sql` to aggregate a saved chart by month instead of its saved grain.
For Generic Chart Axes charts, both MCP overrides and dashboard time-grain
filters update the `BASE_AXIS` column's `timeGrain`, regardless of its position
in the query's `columns` list. Other columns are left untouched. Queries without
a `BASE_AXIS` column continue to use `extras.time_grain_sqla`.
Same-visualization updates that supply only a non-null `time_grain` preserve saved
temporal range filters. Explicitly setting `time_grain` to null clears saved
temporal state, including `time_range` and temporal range filters; it does not
preserve the date restriction. Supply `time_range` or `temporal_column` to change
the temporal restriction or binding.
### Exploring large dashboard layouts
`get_dashboard_layout` returns the full parsed layout by default. For large
dashboards, pass `tabs_only=true` to retrieve just the tab tree in `tab_tree`:
`id`, `name` (the title), `parent_tab_id`, zero-based `depth`, and
`chart_count` (distinct charts in the tab and its descendants). In this mode
`tabs` and `charts` are empty by request, not because the dashboard is empty.
Then pass `tab=""` to retrieve that tab and its descendants
with chart positions. Matching is case-sensitive; IDs take precedence and
ambiguous titles require an ID. Both options can be combined to summarize a
subtree. Parent IDs, depths, and chart paths retain their full-dashboard context.
Charts placed outside every tab are counted in `untabbed_chart_count` in every
response; pass `untabbed_only=true` (without `tab` or `tabs_only`) to list only
those charts. The `scope` field echoes the applied `tabs_only`, resolved
`tab_id`, and `untabbed_only` values, and is `null` for the full layout.
Scoping only removes tabs and chart placements from the layout the caller can
already retrieve. Conflicting scope options return an actionable
`invalid_scope` error naming the options to remove; blank tab selectors return
`tab_not_found` rather than widening the scope. On dashboards without tabs,
`tabs_only=true` returns `tab_not_found` with guidance to use
`untabbed_only=true` or request the full layout instead.
Permalink active-tab and filter state remain unchanged; only an explicit `tab`
scopes the response. Oversized layout errors suggest the next narrower scope:
the tab tree and untabbed charts for a full tabbed layout, a top-level tab for
an oversized tab tree, a nested tab for a tab that has one, and `list_charts`
paging when a dashboard without tabs or a tab without nested tabs is still too
large.
### Reading applied dashboard filters
When answering about a filtered dashboard, call `get_dashboard_info` with the
dashboard's `permalink_key` (a saved snapshot) or caller-supplied `filter_state`.
This value projection is provided by `get_dashboard_info`;
`get_dashboard_layout` retains its existing metadata-redacted layout state and
does not return native filter values.
The tool cannot observe browser state without one of these inputs. Its response
includes `filter_state` by default; an explicit `select_columns` must include it.
For users without Dataset drill/write metadata permissions, including embedded
guests, raw `dataMask` and `chartStates` remain hidden. Instead,
`filter_state.native_filter_values` contains configured native filter IDs, display
names, types, and scalar or flat-list selections for select, numeric range, time
range, and time-grain filters, plus display labels and exclusion flags when present.
It does not expose filter targets, dataset IDs, columns from query metadata, or
arbitrary nested filter state. Time-column filters, custom filters, unknown IDs,
and chart cross-filter state are not projected. Historical masks containing
time-column metadata are also omitted, even if the configured filter type has
changed; malformed type-specific value shapes are omitted rather than interpreted.
`native_filter_values_incomplete` flags omitted or malformed context, including SQL or wildcard predicates that
cannot be represented by selected values alone. It also flags retained selections
without query predicates (for example, a cleared or not-yet-applied mask). These
display values are not proof that a predicate is active.
These values describe a snapshot, not automatically enforced query predicates or
a complete account of filter scope. An empty or missing summary must not be
treated as permission to query unfiltered or workspace-wide data. Respect chart
scope and ask for clarification when the context cannot safely constrain an
answer. Dashboard access checks and row-level security remain independent of this
display-context projection. Integrations must ensure the lookup actually happens
and the assistant uses the result; tool guidance alone cannot guarantee this.
## Tool-call errors
For exceptions raised by tools, the shared error handler distinguishes permission
denials, invalid arguments, datasource failures, invalid SQL, and internal errors.
Datasource responses include an enumerated reason rather than raw driver output;
internal errors return an error ID rather than implementation details. Tools such
as `get_chart_data` that return structured error envelopes instead of raising do
not pass through this handler. `get_chart_data` reports a refused query as
`AccessDenied`, and a query rejected by a semantic layer provider or by query
validation while it runs as `ValidationError`, the categories of the chart-data
API's 403 and 400 responses.
Missing tables, columns, and schemas log at `WARNING` without invoking
`MCP_ERROR_HOOK`, even when the exception inherits status 500. Connection failures
with status 500 or higher remain `ERROR` and invoke the hook. An explicitly
sub-500 exception remains a warning even if it carries a connection error reason:
the generic engine reason can also describe a caller's malformed column, and a
connection access denial is still a permission failure.
The error hook runs off the transport loop in its own application and metadata
session scope, without reloading the request user. Reporting an error therefore
does not require metadata database access unless the hook itself uses it. Use the
provided hook context for caller identity rather than `g.user`.
## SQL execution query history
`execute_sql` records executed runs in SQL Lab query history and returns their
`query_id`, including failures and OAuth authentication errors after a run is
created. Recorded runs include execution timestamps, the executed statement,
status and row count. A worker deadline or client disconnect finishes the run as
`timed_out`; a concurrent Stop keeps its `stopped` outcome. A Stop issued while
the statement is running commits immediately: the run holds no pending metadata
write while it waits for the warehouse. It does not cancel the warehouse query.
When a worker deadline ends the tool call, the error reply names the run as
`Query history id: ` if the run was recorded before the deadline. A reply
for a call whose run was not yet recorded at that point carries no ID.
Synchronous results-cache hits create a separate successful history entry marked
as cached. Its executed statement is the cached run's last statement, including
any SQL query mutation, matching a warehouse-executed run. If that history write
fails, the cached data is still returned, with `query_id: null`. Dry runs and
requests rejected before a run is created also return no query ID. Other MCP data
tools use the chart-data path and do not create SQL Lab query-history entries.
Async executor cache hits do not create entries. A failure to populate the results
cache does not discard a successful warehouse result or change its history status.
Async broker-submission failures finish the pending history entry with an end time.
## SQL execution row limits
The `execute_sql` tool treats an explicit request `limit` as a safety cap on the
last statement's outer SQL LIMIT. The smaller limit wins: SQL `LIMIT 5` with
request `limit: 10` returns at most five rows, while SQL `LIMIT 10` with request
`limit: 5` also returns at most five. Equal limits and SQL `LIMIT 0` are preserved.
If SQL has no outer limit, the explicit request cap is applied. Inner query and
CTE limits and SQL offsets are preserved. Literal `FETCH FIRST` counts and
parenthesized literal limits follow the same rule. `PERCENT`, `WITH TIES`, and
limit expressions that cannot be interpreted as a fixed row count are preserved
inside a subquery with an outer row cap, rather than replaced. This conservative
fallback cannot increase the original result's row count. For SQL Server, these
restrictions are left unchanged instead: a derived table could reject duplicate
or unnamed output columns. The executor caps the last statement's returned rows
at the smaller of the explicit request limit and `SQL_MAX_ROW`, without changing
percentage, tie, or expression semantics. Cursor reads are bounded by the same
cap plus one probe row, including across multiple fetch batches, preserving
engine-specific result processing. Only successfully returned rows count against the cursor
budget, so a failed fetch leaves that budget available for an engine fallback.
BigQuery only falls back if its initial fetch fails; errors after a successful
sample, including during the EOF probe, fail the query rather than silently
discarding buffered rows.
This does not bound the work performed by the database.
Because this cap applies to any row-returning last statement, a non-query
statement such as `SHOW TABLES` or DML with `RETURNING` can also be capped. Each
statement reports `truncated: true` when a fetch cap omits rows from the
executed SQL result, including engine memory caps such as `BQ_FETCH_MAX_MB`.
Exactly-at-cap and smaller results report `false` when no rows are omitted. This
flag does not indicate rows excluded by a SQL LIMIT visible in `executed_sql`,
and does not bound or count affected rows for a write with `RETURNING`. In
`dry_run`, the SQL Server restriction remains unchanged because no results are
fetched.
Omitting `limit` leaves the SQL limit unchanged. Explicit request caps remain
subject to the server's `SQL_MAX_ROW` configuration. This behavior also applies
to `dry_run`, which returns the transformed SQL without executing it.
The SQL-only `Database.apply_limit_to_sql()` helper used by dataset column
discovery and alerts does not use the executor's bounded cursor. It retains the
legacy SQL Server behavior of replacing `PERCENT`, `WITH TIES`, and non-fixed
limit expressions with a fixed `TOP` cap, without introducing derived tables
that could reject unnamed or duplicate columns. Smaller fixed limits, including
zero, are preserved unless the caller explicitly requests `force=True`. This
legacy helper's replacement semantics are separate from MCP execution's
preservation of complex SQL restrictions.
## Result serialization
Data-bearing tool responses sanitize row values, column samples, and statistics.
Tuple-valued cells and NumPy arrays (including arrays materialized by Arrow) are
returned as JSON arrays. Nested values share the same depth, item, and byte
limits as list-valued cells; unsupported containers and subclasses are rejected.
Nested maps stringify exact built-in string, integer, float, boolean, and null
keys within the key-size budget; arbitrary key objects and subclasses are rejected.
Missing and non-finite floating-point values become JSON `null`; non-UTF-8 binary
values become base64 strings prefixed with `base64:`. Boolean row counts are treated as
unavailable, producing `null` for nullable counts and `0` for non-nullable counts,
rather than being interpreted as one or zero rows.
Concrete psycopg2 and psycopg PostgreSQL ranges, including ranges nested in
array cells, become bounded driver-style text (for example, `"[1, 10)"`).
Range subclasses and unsupported or oversized endpoints are rejected; arbitrary
objects are not stringified.
Finite SQL Decimal values retain their precision during chart validation and
CSV export, but use the existing JSON number format in rows, query results,
column samples, and statistics. As with other floating-point JSON numbers,
clients should not rely on exact decimal precision in that projection.
Excel exports write text values as text cells, so a value that starts with `=`
keeps its text instead of becoming a formula.
Rebuilt `get_chart_data` queries retrieve the requested row limit rather than
a saved Table's server-pagination page size. CSV and Excel exports are not
restricted to the first Explore page, and explicit limits apply before execution.
Same-visualization Bubble updates preserve omitted `series`, `row_limit`, and
`color_scheme`; `series: null` explicitly removes grouping.
Saved Mixed Timeseries Vega-Lite previews honor the requested width and height.
Both Mixed Timeseries queries validate SIMPLE filter clauses and column references;
unsupported SIMPLE HAVING filters are rejected rather than silently discarded.
Same-visualization Mixed Timeseries updates preserve omitted secondary-query
controls, including time range, row limits, time grain, rolling/resample settings,
and saved or adhoc ranking metrics. New typed Mixed Timeseries charts default
secondary grouping to empty rather than inheriting primary grouping.
Omitted primary and secondary grouping on updates retain their saved values;
`group_by: []`/`null` and `group_by_secondary: []`/`null` clear only that query's
grouping. Explicit secondary controls and clears replace the saved values.
Same-visualization aggregate Table updates preserve native percent-metric columns;
raw-mode updates, visualization changes, and dataset rebinds do not carry them over.
Same-visualization Table updates preserve saved ordering when `sort_by` is
omitted; `sort_by: []` clears it. Same-visualization XY updates preserve saved
series grouping when `group_by` is omitted; `group_by: []` clears it. Omitted
`series_limit_metric` and `timeseries_limit_metric` preserve saved series ranking.
Either spelling replaces the saved ranking when supplied; `null` clears it. Native XY
`BASE_AXIS` SQL x-axis objects carry their `timeGrain` into the chart's
`time_grain` unless a panel-level `time_grain` or `time_grain_sqla` is supplied.
Table compile and preview row caps take precedence over saved row limits;
server pagination can reduce a cap only when its page size is positive.
Grouped Mixed Timeseries Vega-Lite previews fold all flattened series columns,
so every primary-query group remains visible rather than only the first numeric
column. Saved Big Number axes using `column_name` mappings retain time-range
bindings and time-grain bucketing like string axes.
Sort-only Timeseries metrics retain their raw values when displayed metrics
undergo rolling or cumulative processing.
Timeseries compile checks skip rolling windows and forecasting on their bounded
two-row sample; full previews and data queries still apply those analytics, so
compile success does not validate their full-history behavior.
If a successful `generate_chart` or `update_chart` write produces response
content beyond serialization limits, the response retains `success: true` and
the saved `chart.id`, with a warning and optional content omitted. Retrieve the
chart by that ID instead of retrying the write. Unsaved responses that exceed
these limits still return a structured failure.
## Chart data column counts
For saved and unsaved charts, `get_chart_data` column metadata excludes missing
values from `unique_count`. Values serialized as JSON `null`, including NaN,
NaT, and non-finite numbers, contribute to `null_count` instead.
## Geographic chart generation
`generate_chart`, `update_chart`, and `generate_explore_link` accept the same
bounded geographic configs. Call `get_chart_type_schema` with `country_map`,
`world_map`, or `deck_scatter` to discover availability and complete examples.
The `chart_type` discriminator belongs **inside** `config`. Existing chart
validation contracts and legacy native map behavior are unchanged, but tool
**discovery schemas have changed for every chart type**, including existing
types such as gauge and treemap. The `config` input schema on `generate_chart`,
`update_chart`, `update_chart_preview`, and `generate_explore_link` advertises
only the `chart_type` enum and allows additional properties; it does not expose
each type's required fields or bounds. Schema-driven clients must first call
`get_chart_type_schema(chart_type)` for the complete per-type schema and
examples. See the compact chart config schema migration note in `UPDATING.md`.
```json
{
"dataset_id": 3,
"config": {
"chart_type": "country_map",
"country": "usa",
"region_format": "abbreviation",
"entity": {"name": "state"},
"metric": {"name": "sales", "aggregate": "SUM"},
"filters": [{"column": "country", "op": "IN", "value": ["USA"]}]
}
}
```
- **Country map:** supported boundary sets are `usa`, `canada`, `australia`,
`japan`, and `uk`. Select the source `region_format`: `name` (e.g.
`California`), `abbreviation` (ISO suffix, e.g. `CA`), or `iso_3166_2`
(e.g. `US-CA`). Identifiers are limited to Superset's bundled boundaries,
not the entire ISO registry. Japanese abbreviation values are numeric
**strings**, such as `13`. Names are exact-first, then case/diacritic-insensitive
only when the result is unique. No fuzzy matching or geocoding is performed.
A name that folds onto more than one boundary is rejected as ambiguous and
needs an abbreviation or ISO code instead. After an Explore switch to
**Legacy ISO values**, saved MCP reads and exports validate full ISO 3166-2
codes (e.g. `US-CA`); this option does not accept abbreviation-only values.
- **World map:** set `country_format` to `name`, `cca2`, `cca3`, or `cioc`,
plus `entity` and `metric`. Choropleth color uses `metric`. For bubbles set
`show_bubbles: true` and supply `secondary_metric` for size (it may be the
same metric). Same-type saved and cached-preview updates can enable bubbles
while omitting `secondary_metric` when the existing chart already has one;
the size-metric requirement is checked against the merged configuration.
A `secondary_metric` kept with `show_bubbles: false` is not
rendered, so its values are not validated. Superset's bundled
world topology defines choropleth coverage, not the broader country
dictionary. Countries without a polygon (such as Singapore) require bubbles
or an explicit dataset filter; otherwise MCP validation returns an error.
- **Geographic points:** set `chart_type: "deck_scatter"`,
`latitude: {"name": "latitude"}`, and `longitude: {"name": "longitude"}`.
Numeric coordinates must be within ±90 and ±180 respectively. Optional
`dimension` groups/colors points; `radius_metric` aggregates a nonnegative
size at each location. Otherwise `radius` is fixed in `point_unit`: `radius_m` (default), `radius_km`,
`radius_miles`, `square_m`, `square_km`, or `square_miles`. Native minimum
and maximum on-screen radii are 2 and 250 pixels. Spatial null filters
exclude rows without coordinates. Dimension columns and radius
metric aliases cannot be `position`,
`weight`, or `extraProps`, which are reserved native spatial feature fields.
A dimension must also differ from both coordinate columns. Updates validate
the merged roles, including saved dimensions and radius metrics omitted
from the request. Explicitly clear or replace a dimension when changing a
coordinate to that column, or a saved radius metric with a reserved label.
Explore saves preserve generated dashboard-time binding provenance. Explicit
`temporal_column: null` clears that binding, and a replacement column removes
the old generated predicate without removing user-authored time filters.
Region values that cannot resolve for the selected country/format return an
`InvalidGeographicResult` error (`INVALID_GEOGRAPHIC_RESULT` during compilation).
For example, `BC` does not resolve for USA; choose Canada or explicitly filter
the dataset. No unrecognized returned rows are silently discarded. Multiple
query groups resolving to one boundary also fail: normalize source values
before aggregation rather than incorrectly adding averages or distinct counts.
When rendering in Explore, country maps with an explicit region format omit
rows with missing, NULL, non-numeric, or non-finite metrics, leaving those
regions blank. Region identifiers are still validated for every row, and blank
regions still cross-filter and drill on their original source value.
Typed geographic point maps omit rows with invalid coordinates or missing,
non-numeric, non-finite, or negative radius metrics rather than failing the
chart, and log a browser-console warning with the number of skipped points.
After switching a point map to Geohash or delimited coordinates in Explore,
coordinates use the native spatial decoder rather than the typed latitude/longitude
guard; radius-metric validation remains active. This display behavior does not
relax MCP generation's result validation. Preserved numeric-string radii are
interpreted as fixed values only for typed MCP point maps (`mcp_geographic`).
Native Scatter charts continue to interpret bare strings as saved metric names,
including numeric names such as `100`.
Country and world maps edited in Explore can use Custom SQL entities; MCP
reads and exports resolve the saved entity's output label (or SQL expression).
Source values remain intact for data/export and country-map cross-filtering.
Database `NUMERIC`/Decimal query coordinates and metrics are supported when
finite and representable as JSON numbers. Coordinate bounds are checked before
JSON conversion; numeric strings and booleans are not accepted as coordinates.
Generation validates the configured result (up to `row_limit`, bounded at
10,000), not just the first two rows. This is not an audit of rows excluded by
filters or limits. Saved and cached-preview updates preserve omitted controls;
explicit null optional roles and empty filters clear them. Native saved maps
with null `adhoc_filters` are treated as having no filters. Preserved numeric-string
point radii (for example, `"100"`) render as fixed sizes, not metric names. Dataset rebinding
requires a complete typed config and discards old dataset roles and filters.
Geographic updates cap inherited native row limits at 10,000 so compilation
validates the same rows the native query renders. Explicit
`temporal_column: null` removes generated dashboard time bindings, including
dataset defaults, while preserving user-authored predicates. Subsequent same-dataset
updates that omit `temporal_column` preserve that cleared state. Explicit `filters`
replace inherited predicates, including native `filters`, `where`, and `having`,
whether the replacement list is empty or nonempty. Disabled types
cannot be used for fresh previews or type conversions; an existing cached
preview or saved chart of the same type can still be updated, including charts
whose visualization type is stored only on the saved chart. Explicit temporal
changes override inherited native time controls on same-type updates and type
conversions. Saved point charts switched in Explore to Geohash or comma-delimited
coordinates remain readable through MCP data and JSON/CSV/Excel exports; exports
retain the original spatial column values. Delimited coordinates accept the
same leading numeric prefixes as the native decoder (for example,
`-122.4 W,37.8 N`). Values the native decoder skips still fail MCP result
validation, consistent with invalid latitude/longitude and geohash values.
Country/world map interactions use original source identifiers rather than
normalized rendering codes or names. With an explicit region format, boundaries
absent from the result do not emit cross-filters or drill filters. Empty country
identifiers are rejected rather than matched to a country with no code.
ASCII/table previews show source data and do not reproduce geography. Vega
previews return `UnsupportedGeographicPreview` rather than an unrelated chart.
Use the returned Explore link for the native map. Point maps use a public
Carto basemap; browser network access and deployment basemap policy still apply.
## Big Number headlines
For Big Number charts (`big_number` and `big_number_total`), `get_chart_data`
and `get_dashboard_data` return a `headline` object holding the number the chart
displays. Agents should report `headline.value` rather than reading or summing
the data rows: for the trendline variant the rows are a time series, and the
displayed number is derived from the whole series by the chart's aggregation.
| Field | Contents |
| --- | --- |
| `value` | The displayed number, or `null` when it cannot be computed exactly |
| `aggregation` | `total` for `big_number_total`; otherwise the chart's aggregation (`LAST_VALUE`, `sum`, `mean`, `min`, `max`, `median`, or `raw`) |
| `rows_used` | The number of non-null values aggregated |
| `reason` | Why `value` is `null` |
A headline is only returned when it matches the rendered chart, so `value` is
`null` with a `reason` when:
- The query returned no rows, the metric column is missing, or every metric
value is null.
- The chart applies a rolling window or resampling that the executed query did
not include, or the fetch was truncated at the row limit.
- The aggregation picks the latest value (`LAST_VALUE`) and some rows have no
usable timestamp. The chart's ordering of such rows depends on row order, so
the value it shows cannot be determined exactly. Order-independent
aggregations still include those rows.
- The aggregation is `raw` ("Overall value") and the chart has no saved query
context. That value comes from a second query that only a saved query context
carries, so unsaved and `form_data_key` requests return `null`.
When `form_data_key` is supplied, the headline follows the unsaved visualization
type, including when switching to or from a Big Number chart.
## Dataset query dimensions and nested fields
The `query_dataset` tool accepts exact column names registered on the selected
Superset dataset. Use `get_dataset_info` with the same `dataset_id` to discover
those names; a column available on one dataset may not exist on another.
A dotted name such as `address.city.name` can be used as a GROUP BY
column when that exact name is registered. Registering only the parent
`address` column does not register its nested fields. If a field is missing,
refresh the dataset columns when the database exposes nested-field metadata,
or add a calculated column with the warehouse-appropriate field-access
expression and query its registered name. For ad-hoc expressions, use
`execute_sql` instead.
Unknown dimensions return the selected dataset's name and ID, up to ten
available column names, and a pointer to `get_dataset_info` for the full list.
Unregistered dotted dimensions also include shared nested-field setup guidance
once, even when multiple dimensions are missing.
The tool does not rewrite dots into SQL path separators: quoting and nested-field
support depend on the dataset's database dialect, and dots can also be literal
characters in column names.
### Treemap charts
Saved and cached previews honor the configured Treemap row limit across ASCII,
table, and Vega representations. SQL Decimal metrics are accepted when finite;
booleans and nonfinite values are rejected. Categories with identical display
names but distinct raw types retain separate geometry groups. Currency settings
use the native `symbolPosition` property. Adding filters while omitting the
temporal column preserves saved predicates and the existing neutral time binding;
explicit empty filters or a cleared temporal column remove those controls.
Use `chart_type: "treemap_v2"` with an ordered `groupby` hierarchy and one
`metric`. Hierarchy columns accept typed references (`{"name": "region"}`)
or native strings. Metrics accept typed column references with an aggregate,
saved metric names, or native SIMPLE/SQL metric objects. SQL metrics still
require a label and pass the shared SQL-expression validation. Unknown controls
and executable JavaScript hooks are not accepted.
```json
{
"dataset_id": 7,
"config": {
"chart_type": "treemap_v2",
"groupby": ["region", "product"],
"metric": {"name": "revenue", "aggregate": "SUM"},
"row_limit": 100,
"sort_by_metric": true,
"show_labels": true,
"show_upper_labels": true,
"label_type": "key_value",
"number_format": ",.2f"
}
}
```
Bounded queries sort by the metric descending when requested, then by hierarchy
columns ascending to break ties, matching the frontend query contract.
`update_chart` and `update_chart_preview` preserve omitted same-dataset Treemap
controls, including hierarchy, metrics, formatting, filters, temporal state and
`template_params`. Partial configurations are accepted only for updates; a new
chart still requires hierarchy and metric roles. Explicit empty filters clear
filters, and explicit null clears nullable controls. Rebinding to another dataset
requires complete roles and inherits only supported presentation controls.
ASCII and table previews show hierarchy and values. Vega-Lite previews use
bounded slice-and-dice rectangles with metric-proportional areas, hierarchy
paths, categorical colors, labels and tooltips. This is not the native ECharts
layout: use the Explore URL for native formatting and interactions. The preview
supports up to 1,000 nonnegative rows, 20 hierarchy levels, and the built-in
`supersetColors` and `lyftColors` schemes. Unsupported color/currency formats,
negative values, zero totals and over-limit geometry return
`UnsupportedTreemapPreview` rather than a substitute scatter or bar chart.
`SMART_NUMBER` is approximated with SI formatting in this preview.
Queries must return every hierarchy output and the metric's exact output label.
Malformed/error envelopes and nonnumeric or nonfinite metric outputs return
structured errors instead of apparently successful previews, charts or exports.
## Dataset discovery and routing
`list_datasets`, `get_dataset_info`, `update_dataset`, and `query_dataset`
operate on registered **SQL datasets** (physical tables or virtual SQL queries),
not external semantic views. `create_dataset` registers a physical table as a
SQL dataset; it does not create or register semantic views. The `certified`
filter in `list_datasets` selects certified SQL datasets, not external views.
For existing semantic views, use `list_metrics` to discover metrics and
`get_table` to query them, retaining the returned source and view identity.
These tools do not provision or edit semantic views. A dataset not-found error
offers this routing guidance without establishing whether a semantic view
exists or is accessible. Numeric IDs can overlap across source types; do not
reuse a semantic-view ID as a SQL-dataset ID or substitute another source.
All tool permissions, feature flags, and datasource access checks still apply.
`get_compatible_metrics` and `get_compatible_dimensions` reject unknown selected
metric or dimension names with a `ValidationError` naming the invalid fields,
rather than returning suggestions for a reduced selection. This applies to both
SQL datasets and external semantic views. Use names returned by discovery,
not display labels or provider IDs. `get_table` also validates filter names
before running a query.
`list_datasets` searches table name, **description**, schema, and SQL using
escaped, case-insensitive substring matching. Write descriptions with business
terminology to make differently named datasets discoverable. A complete UUID
passed as `search` is treated as an exact UUID filter; an explicit `uuid` filter
can also look up one or more datasets by UUID. Matching
datasets are candidates, ordered by the requested sort (last modified by default), not
ranked recommendations. Compare descriptions and metrics, present alternatives
when ambiguous, and clarify before querying. No matches does not prove that data
does not exist; search only covers accessible datasets and the configured scope.
`query_dataset` returns `dataset_id` and `dataset_name`; `get_table` additionally
returns `source` and the corresponding dataset or external-view identity. Cite
these fields in answers rather than guessing the source from the query text.
Neither tool selects an alternative dataset automatically.
### Optional per-role dataset scope
Set `MCP_DATASET_ROLE_ALLOWLIST` in `superset_config.py` to constrain MCP to a
curated set of registered datasets:
```python
MCP_DATASET_ROLE_ALLOWLIST = {
"Finance Readers": ["00000000-0000-0000-0000-000000000001"],
"Operations Readers": ["00000000-0000-0000-0000-000000000002"],
}
```
Obtain dataset UUIDs from `get_dataset_info` (or request `uuid` in
`list_datasets.select_columns`). Use UUIDs, not names or numeric IDs, in config.
Effective roles, including group roles, contribute the **union** of their lists.
That union is **intersected with existing dataset access**. Unconfigured roles
contribute nothing; Admin has no routing exemption. `None` (the default) disables
this feature; `{}` allows no datasets. Invalid entries cause a configuration
error at startup rather than silently disabling the restriction.
A static mapping cannot express per-tenant policy when one MCP deployment
serves many workspaces with their own roles and dataset UUIDs. For that case,
set `MCP_DATASET_ROLE_ALLOWLIST` to a callable instead of a dict:
```python
def resolve_dataset_scope(user):
# Import inside the callable: MCP modules cannot be imported while the
# config itself is loading.
from superset.mcp_service.dataset_scope import UNSCOPED
workspace = lookup_workspace_for(user) # cheap, in-process lookup only
if workspace is None:
return None # unknown tenant: deny every dataset
if not workspace.dataset_scoping_enabled:
return UNSCOPED # tenant has not opted in: no routing constraints
return workspace.allowed_dataset_uuids
MCP_DATASET_ROLE_ALLOWLIST = resolve_dataset_scope
```
The callable receives the current request's user and returns one of:
- an iterable of dataset UUID strings or `UUID` objects — the caller is scoped
to those datasets (an empty iterable allows none);
- `superset.mcp_service.dataset_scope.UNSCOPED` — the caller is not scoped:
the full MCP tool surface (including tools such as `execute_sql` that scoped
mode refuses) and no dataset filter, exactly as if the setting were `None`.
Use this when only some tenants of a shared deployment opt into scoping;
- `None` — no grants: the caller is denied every dataset.
It is called on every tool call that needs routing enforcement — sometimes
more than once per call, for example when `list_datasets` both checks and
filters by the scope — so it must be cheap, side-effect free and in-process,
with no network I/O per call. It fails **closed**: if the callable raises
(including while consuming a lazy iterable), returns `None` or an empty
iterable, or returns a value that cannot be parsed as dataset UUIDs, that
request is denied every dataset. Only the explicit `UNSCOPED` sentinel lifts
the constraints, so a failed or missed lookup can never widen access. The
static mapping form keeps its startup validation; a configured callable is not
validated until it runs, since its result depends on per-request state.
Scoped mode supports the dataset tools that name a registered dataset —
`list_datasets`, `get_dataset_info`, `query_dataset`, and, with a built-in
dataset, `get_table`, `list_metrics`, `get_compatible_dimensions` and
`get_compatible_metrics` — plus `health_check` and `get_schema`.
Discovery filters before counting and pagination. Every other **authenticated**
tool refuses in this mode, including SQL Lab, chart/dashboard previews and data,
cached query results, external semantic sources, mutations, and extension tools.
The one exception is `generate_bug_report`, which is deliberately public
(`protect=False`, listed in `ALLOWED_UNPROTECTED`) so diagnostics stay available
even when authentication is broken. Scoped mode is enforced in the
authentication wrapper, so that tool keeps working; it reports environment and
user-supplied diagnostics and reads no dataset rows. These paths cannot
all be attributed reliably to registered dataset UUIDs; scoped mode deliberately
refuses them instead of attempting SQL lineage inference. Unsupported tools stay
listed and refuse when called, so the assistant reads an explanation it can pass
on rather than finding the tool missing. Prompts and resources are unaffected:
they expose schema and instance metadata, not dataset rows. This restriction
applies to every caller of the MCP tools, not just a particular chat client.
The default `MCP_GUEST_ALLOWED_TOOLS` contains only chart/dashboard tools,
none of which supports dataset-scoped mode. Enabling this allowlist therefore
also makes all of those embedded-guest tool calls refuse.
An out-of-scope request returns an explicit refusal. The assistant must explain
that limitation, never silently substitute an allowed but different dataset.
This feature controls routing and usability, **not authorization or SQL table
access**. Existing dataset permissions, query validation, and row-level security
remain mandatory and unchanged. A registered virtual dataset may itself query
multiple physical tables; this configuration selects registered dataset objects,
not their underlying SQL dependencies. It does not restrict the Superset UI/API.
Description search adds one text predicate to an existing catalog substring
scan, without joins or additional queries, and replaces the `uuid` substring
predicate, whose behavior varied by database. It is not an indexed
full-text search: large catalogs and long descriptions can increase scan time.
Benchmark with your metadata database and catalog size when tuning discovery
latency.
### Managing and applying dashboard native filters
Time-column and time-grain filters target a dataset, not a column. When adding
one with `manage_native_filters`, omit `column`, `default_value`, and the
select-only flags (`multi_select`, `default_to_first_item`, `sort_ascending`,
`search_all_options`). Both add and update reject non-null fields that do not
apply to the filter type, including `False` and empty lists. `default_value` is
supported only by select filters, not time-range or numerical-range filters.
Use `default_time_range` for time-range defaults. Updating
`dataset_id` binds the filter to that SQL dataset, removing any semantic-view
binding. Defaults from a semantic view are cleared; SQL temporal defaults are
retained only when the replacement dataset supports them.
For `apply_dashboard_filters`, pass `time_column` as a list containing one temporal
column name or its unique filter-bar label (verbose name). An exact column name
wins over case-insensitive names, which win over case-insensitive labels;
ambiguous matches are rejected. The permalink stores the underlying column name.
Pass `[]` to clear an optional time-column filter; required filters cannot be
cleared. Callers without metadata access do not receive underlying column names
in the result or available-column lists in errors.
`manage_native_filters` requires a numeric dataset column when adding a
`filter_range` filter or changing its dataset/column target. Select filters
continue to accept nonnumeric columns.
A native filter can depend on other filters so that its choices are narrowed by
their values. `get_dashboard_info` lists each filter's direct parents in
`cascade_parent_ids`. With `manage_native_filters`, pass `cascade_parent_ids` when
adding or updating a `filter_select`, `filter_range`, or `filter_time` filter;
on update it replaces the current parents and `[]` clears them. Each parent must
be an existing native filter on the same dashboard (not a time-grain filter,
time-column filter, or divider), and a filter cannot depend on itself or create a cycle. Removing a filter also removes
it from the parents of any filter that depended on it, and reports those children
in `updated_filter_ids`. Reads omit parent IDs absent from the dashboard. When
updating dependencies, already-stored absent parent IDs are silently dropped;
genuinely new unknown IDs are rejected. Existing custom native filters can also
be updated and used as parents. The backend cannot inspect frontend plugin
capability metadata, so custom types use the native-filter cascade default.
If dashboard metadata changes between validation and persistence, the tool
rejects the write; re-read the dashboard and retry.
Dividers are visual separators and are always in scope. When adding or updating
a `divider` with `manage_native_filters`, use `name` for its title and
`description` for its description; type-specific fields and `scope_chart_ids`
are rejected when non-null.
`apply_dashboard_filters` excludes dividers from its available-filter error lists.
For `apply_dashboard_filters`, pass `time_grain` as a list containing at most
one datasource-supported duration (for example, `["P1D"]`). Custom engine
durations are accepted when exposed in the datasource's time-grain options,
rather than limited to a fixed enum.
A nonempty `time_grains` list in the saved filter configuration restricts the
allowed selection to grains that appear in both that list and the target dataset's
supported time grains; missing or empty lists use the dataset's supported grains.
Pass `[]` to clear an optional time-grain filter; required filters cannot be
cleared.
## Reselecting fields on an existing semantic chart
`update_chart` can certify complete field reselection for table and interactive
table charts whose semantic selection marker is missing or outdated. Supply all
columns using the target view's member IDs and explicitly supply `filters`
(`[]` clears them). Supply sorting explicitly if the chart retains sorting.
Certification applies only when the final merged query contains no unverified
retained selections; sending `config` alone is not enough.
Table display settings and dashboard associations may be retained. Empty
conditional-formatting and annotation settings are supported, but unclassified
non-empty plugin state still requires Explore recovery. An explicitly selected
`temporal_column` is checked against the target view's temporal metadata and the
generated query filter; a saved internal time-binding marker alone is not proof
of a fresh selection.
Explore's boolean temporal-column lookup describes datasource metadata, not
selected fields, so old names in that lookup may be retained. Target temporal
metadata must be available. A recognized duration grain is omitted only with a
well-formed saved lookup, no reselected temporal member and no time axis set.
Active grains, malformed lookup metadata, and unknown grain formats still
require Explore recovery. An unpublished explicit `temporal_column` is refused
rather than silently ignored.
Only an explicit `filters: []` authorizes clearing saved WHERE/HAVING predicate
aliases, including legacy and adhoc filters. A non-empty filter replacement that
would discard those unclassified predicates is refused; reselect in Explore, or
explicitly clear filters if removing the saved constraints is intended.
The canonical SIMPLE/WHERE `TEMPORAL_RANGE` entry with comparator `No filter`
is an inactive placeholder, not a saved predicate. Real ranges, SQL expressions
and unclassified filter entries still require explicit clearing.
If native controls, temporal bindings, external filters, secondary queries or
unsupported plugin state cannot be verified, the update refuses without changing
the saved chart. The error names the incomplete category and directs you to
reselect it in Explore and save there. Omitted state is not silently reset.
For example: “Cannot verify temporal selections; reselect them in Explore and
save the chart.”
Renaming a chart or using `add_columns` does not upgrade its selection marker.
Ordinary partial updates on the same source with a current marker keep their
existing behavior. Changing the source requires fresh target selections even if
the two sources use the same marker string. On versioned providers, a source-only
rebind without a complete table config is refused as “no reselection supplied”;
retry with complete selections or reselect in Explore. A preview is a snapshot, not a lease:
a concurrent saved-chart change can cause a direct update to refuse and require
a reload. Providers without a selection-version contract and physical datasets
do not receive an invented marker.
## Missing chart columns
`generate_chart`, `update_chart`, `update_chart_preview` and
`generate_explore_link` all validate column references through
`validate_and_compile` and return the same structured errors.
A reference to a missing column returns `column_not_found` with up to three
similar physical column names ("Did you mean: ..."), or explicit no-match
guidance when nothing is close enough. Saved metrics — both names and
expressions — are excluded from these candidates for dimension and `WHERE`
references, because only a physical column is legal there and suggesting a
metric leads to invalid `SUM(metric)` SQL. SIMPLE `HAVING` filters are
unsupported, so their column errors do not suggest saved metrics either. When a
reference in a metric slot (`y`, `metric`, Sunburst `secondary_metric`, or an
aggregated table column, for example) near-misses a saved metric name, the error
adds a hint to reference it as `{"name": "", "saved_metric": true}`
instead. Dimension references never receive this hint, even when they carry an
`aggregate`.
When more than one distinct column is missing, the error type is
`multiple_invalid_columns`. The invalid names appear in escaped, length-limited
details, and the three-candidate cap is **shared across all missing columns**,
filled round-robin so each missing column gets a turn.
Column errors carry a bounded `dataset_context`: up to ten column names and ten
saved-metric names from the authorized dataset, names only — never SQL
expressions. Suggested candidates are listed first so they are never cut by the
bound (a hinted saved metric leads `available_metrics` the same way), and the
error says `Showing 10 of N columns` or `Showing 10 of N saved metrics` when a
list is partial.
Context names are returned verbatim per the Tool Result Value Contract.
"Did you mean" column candidates also preserve dataset spelling, including
quotes and ampersands, with a 200-character bound per candidate. Use
`get_dataset_info` for the complete schema.
### Title validation errors
Rejected MCP titles report a field-specific reason without echoing the input.
Titles exceeding 500 characters for dashboards or 250 characters for charts
report "String exceeds the allowed maximum length". `duplicate_dashboard`
requires a non-blank title and reports "Text must not be empty" for blank or
whitespace-only input. A title containing only removed HTML/script content
(such as ``) reports "Contains disallowed content"
(`unsafe_text`), not an empty-text error. Optional titles on creation retain
their existing empty-value behavior, including whitespace-only values longer
than the title limit. On creation, blank chart names fall back to generated
names; `generate_dashboard` falls back to chart-based titles when
`dashboard_title` (or its `title` / `name` alias) is omitted, empty, or
whitespace-only. `update_dashboard` rejects explicit blank
or whitespace-only dashboard renames with "Text must not be empty"; omitting
`dashboard_title` leaves the stored title unchanged.
Blank names in `create_virtual_dataset`, `create_theme`, `create_dataset_metric`,
`update_dataset_metric`, `create_dataset_column`, `update_dataset_column`, and
`update_dataset`, and whitespace-only labels in
`save_sql_query`, report "Text must not be empty" at the corresponding name field.
Blank-name checks precede length checks, including whitespace-only inputs longer
than the field limit.
Explicit null metric, column, or dataset names remain invalid; omitting them from updates
leaves the stored name unchanged.
### Chart and dashboard titles
MCP chart names and dashboard titles preserve literal comparisons such as
`Users aged <30`, `Revenue <$1M`, and `Love <3 charts`. HTML tags are stripped;
script-only names, dangerous URL schemes, and entity-encoded markup that would
leave tag-shaped text or rebuild entities that would change on resubmission
are rejected. A title altered by sanitization
includes a warning. Python callers supplying UTF-8 bytes or bytearrays receive
the same title normalization as string inputs; invalid UTF-8 reports an error on
the title field. Names are sanitized once before
persistence, including by
`generate_chart`'s schema revalidation, so a stored name does not change when
it is sent back.
### Object-name validation
MCP object names must fit their persisted model columns: chart and dataset names
and theme names allow 250 characters, dashboard titles allow 500, saved-query
labels and SQL Lab tab titles allow 256, and dashboard slugs allow 255.
For fields that trim whitespace, length validation applies after trimming.
Physical-dataset `schema` and `catalog` values trim whitespace and treat blanks
as omitted namespaces, including UTF-8 bytes supplied by Python callers.
For fields using the shared user-text sanitizer (including chart names, dashboard
titles, column names, labels, and certification text), the limit applies to the
trimmed sanitized text, not removed markup, entity encoding, or surrounding
whitespace exposed by tag removal. Raw user-text sanitizer
input has a separate 10,000-character resource bound (or the field limit, if larger).
Nonblank theme names, saved-metric names, and dataset renames retain their
whitespace and count it toward the limit.
Blank saved-query labels and explicit blank dashboard renames return
`Text must not be empty`, matching virtual-dataset names and duplicated dashboard
titles. Omit an update field to retain the existing value.
Chart creation and updates reject names reduced entirely to disallowed content;
partial sanitization returns a warning alongside the normalized name.