Skip to content

Commit 34c542e

Browse files
authored
Merge branch 'master' into feat/arrow-native-result-set
2 parents 334e2e2 + bb88764 commit 34c542e

11 files changed

Lines changed: 360 additions & 13 deletions

File tree

‎docs/admin_docs/configuration/mcp-server.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,6 +1003,7 @@ All MCP settings go in `superset_config.py`. Defaults are defined in `superset/m
10031003
| `MCP_JWT_ISSUER` | `None` | Expected `iss` claim |
10041004
| `MCP_JWT_AUDIENCE` | `None` | Expected `aud` claim |
10051005
| `MCP_REQUIRED_SCOPES` | `[]` | Required JWT scopes |
1006+
| `MCP_IGNORED_SCOPES` | `{}` | Ignored JWT scopes. Can be used to enable RBAC-only behaviour for identity providers which require to request a scope. |
10061007
| `MCP_JWT_DEBUG_ERRORS` | `False` | Log detailed JWT errors server-side (never exposed in HTTP responses per RFC 6750) |
10071008
| `MCP_AUTH_FACTORY` | `None` | Custom auth provider factory `(flask_app) -> auth_provider`. Takes precedence over built-in JWT |
10081009
| `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. |

‎superset/connectors/sqla/models.py‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,42 @@ def _physical_display_column(reference: dict[str, Any]) -> str | None:
335335
return None
336336

337337

338+
def _column_param_name(column_: Any) -> str | None:
339+
"""Return the column name a ``COLUMN_FORM_DATA_PARAMS`` entry refers to.
340+
341+
Entries are not uniformly shaped. Most params hold plain column names or
342+
adhoc-column dicts, but ``order_by_cols`` holds ``[column, ascending]``
343+
pairs -- canonically JSON *strings* (``'["col", false]'``), though older
344+
writers persisted them as real lists. A raw list reaching ``set.update()``
345+
raises ``TypeError: unhashable type: 'list'`` and 500s
346+
``GET /api/v1/dashboard/<id>/datasets``, which leaves the whole dashboard
347+
without datasource metadata. Mirror the tolerance that
348+
``superset.common.form_data_query_context`` already applies: accept the
349+
pair in either encoding and take the column half, which may itself be an
350+
adhoc column. A string that is not valid JSON is a plain column name
351+
(bracketed names such as ``[Revenue]`` are legal). Any other shape yields
352+
``None`` and is skipped rather than crashing the request.
353+
"""
354+
if utils.is_adhoc_column(column_):
355+
return utils.get_column_name(column_)
356+
if isinstance(column_, str):
357+
# A JSON-encoded ``[column, ascending]`` pair, or a plain column name.
358+
if column_.startswith("["):
359+
try:
360+
parsed = json.loads(column_)
361+
except (TypeError, ValueError):
362+
return column_
363+
return (
364+
_column_param_name(parsed[0])
365+
if parsed and isinstance(parsed, list)
366+
else None
367+
)
368+
return column_
369+
if isinstance(column_, (list, tuple)):
370+
return _column_param_name(column_[0]) if column_ else None
371+
return None
372+
373+
338374
class DatasourceKind(StrEnum):
339375
VIRTUAL = "virtual"
340376
PHYSICAL = "physical"
@@ -939,13 +975,10 @@ def data_for_slices( # pylint: disable=too-many-locals # noqa: C901
939975
column_names.update(query_context_column_names)
940976
else:
941977
_columns = [
942-
(
943-
utils.get_column_name(column_)
944-
if utils.is_adhoc_column(column_)
945-
else column_
946-
)
978+
name
947979
for column_param in COLUMN_FORM_DATA_PARAMS
948980
for column_ in utils.as_list(form_data.get(column_param) or [])
981+
if (name := _column_param_name(column_)) is not None
949982
]
950983
column_names.update(_columns)
951984

‎superset/db_engine_specs/base.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
from sqlalchemy.sql import literal_column, quoted_name, text
6060
from sqlalchemy.sql.expression import (
6161
BinaryExpression,
62+
ClauseElement,
6263
ColumnClause,
6364
ColumnElement,
6465
Select,
@@ -171,7 +172,11 @@
171172
def convert_inspector_columns(cols: list[SQLAColumnType]) -> list[ResultSetColumnType]:
172173
result_set_columns: list[ResultSetColumnType] = []
173174
for col in cols:
174-
result_set_columns.append({"column_name": col.get("name"), **col}) # type: ignore
175+
values = {
176+
key: str(value) if isinstance(value, ClauseElement) else value
177+
for key, value in col.items()
178+
}
179+
result_set_columns.append({"column_name": col.get("name"), **values}) # type: ignore
175180
return result_set_columns
176181

177182

‎superset/mcp_service/auth.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,11 +185,16 @@ def _get_token_scopes() -> set[str] | None:
185185
if access_token is None:
186186
return None
187187

188-
scopes = getattr(access_token, "scopes", None)
189-
if not scopes:
188+
scopes_from_token = getattr(access_token, "scopes", None)
189+
if not scopes_from_token:
190190
# Token present but no scopes advertised: do NOT enforce scope checks.
191191
return None
192-
return {str(s) for s in scopes}
192+
ignored_scopes = current_app.config.get("MCP_IGNORED_SCOPES", {})
193+
scopes = {str(s) for s in scopes_from_token if str(s) not in ignored_scopes}
194+
if not scopes:
195+
# Token where all scopes advertised are ignored: do NOT enforce scope checks.
196+
return None
197+
return scopes
193198

194199

195200
def _token_scope_allows(

‎superset/mcp_service/mcp_config.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,14 @@ class MCPAuthConfigError(ValueError):
197197
# the MCP response.
198198
MCP_ERROR_HOOK: Callable[[Exception, dict[str, Any]], None] | None = None
199199

200+
# MCP ignored scopes - a set of scopes ignored from the user token. This allows
201+
# to enable RBAC-only behaviour for security providers which force to provide
202+
# a scope when requesting a token
203+
#
204+
# Example:
205+
# MCP_IGNORED_SCOPES = {"openid", "profile", "email", "offline_access"}
206+
MCP_IGNORED_SCOPES: set[str] = set()
207+
200208
# =============================================================================
201209
# MCP Chart Plugin Filtering
202210
# =============================================================================
@@ -998,6 +1006,7 @@ def get_mcp_config(app_config: dict[str, Any] | None = None) -> dict[str, Any]:
9981006
"MCP_RBAC_ENABLED": MCP_RBAC_ENABLED,
9991007
"MCP_DISABLED_TOOLS": set(MCP_DISABLED_TOOLS),
10001008
"MCP_STRUCTURED_OUTPUT_ENABLED": MCP_STRUCTURED_OUTPUT_ENABLED,
1009+
"MCP_IGNORED_SCOPES": set(MCP_IGNORED_SCOPES),
10011010
"MCP_DISABLED_CHART_PLUGINS": MCP_DISABLED_CHART_PLUGINS,
10021011
"MCP_CHART_PLUGIN_ENABLED_FUNC": MCP_CHART_PLUGIN_ENABLED_FUNC,
10031012
"MCP_EMBEDDED_GUEST_AUTH_ENABLED": MCP_EMBEDDED_GUEST_AUTH_ENABLED,

‎superset/mcp_service/middleware.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,11 @@
2424
from typing import Any, Awaitable, Callable, Sequence
2525

2626
import mcp.types as mt
27-
from fastmcp.exceptions import ToolError, ValidationError as FastMCPValidationError
27+
from fastmcp.exceptions import (
28+
NotFoundError,
29+
ToolError,
30+
ValidationError as FastMCPValidationError,
31+
)
2832
from fastmcp.server.middleware import Middleware, MiddlewareContext
2933
from fastmcp.server.middleware.middleware import CallNext
3034
from fastmcp.tools import Tool, ToolResult
@@ -451,6 +455,7 @@ def _datasource_error_is_user_error(error: Exception) -> bool | None:
451455
MCPPermissionDeniedError,
452456
ValueError,
453457
FileNotFoundError,
458+
NotFoundError,
454459
CommandInvalidError,
455460
ObjectNotFoundError,
456461
ForbiddenError,
@@ -1433,6 +1438,17 @@ async def _handle_error( # noqa: C901
14331438
# raised deliberately by tool code (it carries no cause, or no
14341439
# FastMCP wrapper prefix) and is already formatted for MCP.
14351440
raise error
1441+
elif isinstance(error, NotFoundError):
1442+
# FastMCP's own lookup miss for an unknown resource, prompt or
1443+
# tool (e.g. "Unknown resource: 'foo://bar'"). FastMCP turns it
1444+
# into the matching protocol error, which names what was missing;
1445+
# the generic branch below would report an "Internal error". When
1446+
# it arrives wrapped (a tool such as the ``call_tool`` proxy
1447+
# looked up another tool), re-raising it bare would make FastMCP
1448+
# report the outer tool as the unknown one, so keep the message.
1449+
if error is wrapped_error:
1450+
raise error
1451+
raise ToolError(str(error)) from error
14361452
elif isinstance(error, (ValidationError, FastMCPValidationError)):
14371453
raise ToolError(await validation_message(error, context)) from error
14381454
elif isinstance(error, (OperationalError, TimeoutError)):

‎tests/testcontainers/db_engine_specs/test_clickhouse.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,47 @@ def test_get_columns_maps_native_types(engine: Engine) -> None:
137137
assert isinstance(spec.sqla_type, Integer)
138138

139139

140+
def test_physical_table_metadata_serializes_expression_columns(
141+
engine: Engine,
142+
) -> None:
143+
from tests.integration_tests.test_app import app
144+
145+
with app.app_context():
146+
from superset.connectors.sqla.utils import get_physical_table_metadata
147+
from superset.db_engine_specs.clickhouse import ClickHouseConnectEngineSpec
148+
from superset.utils import json
149+
150+
with engine.begin() as conn:
151+
conn.execute(
152+
text(
153+
"CREATE TABLE pilot_expressions ("
154+
"ts DateTime, price Float64, qty UInt32, "
155+
"total Float64 ALIAS price * qty, "
156+
"day Date MATERIALIZED toDate(ts), "
157+
"note String DEFAULT 'x'"
158+
") ENGINE = MergeTree ORDER BY ts"
159+
)
160+
)
161+
162+
database = MagicMock()
163+
database.db_engine_spec = ClickHouseConnectEngineSpec
164+
database.get_dialect.return_value = engine.dialect
165+
database.get_extra.return_value = {}
166+
database.get_columns.side_effect = (
167+
lambda table: ClickHouseConnectEngineSpec.get_columns(inspect(engine), table)
168+
)
169+
170+
columns = get_physical_table_metadata(
171+
database, Table("pilot_expressions"), normalize_columns=False
172+
)
173+
174+
by_name = {col["column_name"]: dict(col) for col in columns}
175+
assert by_name["total"]["clickhouse_alias"] == "price * qty"
176+
assert by_name["day"]["clickhouse_materialized"] == "toDate(ts)"
177+
assert by_name["note"]["server_default"] == "'x'"
178+
json.dumps(columns, default=json.json_int_dttm_ser, ignore_nan=True)
179+
180+
140181
def test_group_by_all_groups_correctly(engine: Engine) -> None:
141182
"""
142183
ClickHouse's `GROUP BY ALL` shorthand (group by every non-aggregated

‎tests/unit_tests/connectors/sqla/models_test.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1970,6 +1970,64 @@ def test_data_for_slices_falls_back_for_invalid_query_context(
19701970
mock_slice.get_query_context.assert_not_called()
19711971

19721972

1973+
@pytest.mark.parametrize(
1974+
"order_by_cols,expected",
1975+
[
1976+
# Canonical encoding: a list of JSON strings.
1977+
(['["price_per_sqm", false]'], ["price_per_sqm", "state"]),
1978+
# Persisted by older writers as a real list -- used to raise
1979+
# ``TypeError: unhashable type: 'list'`` and 500 the dashboard
1980+
# datasets endpoint, leaving every widget without metadata.
1981+
([["price_per_sqm", False]], ["price_per_sqm", "state"]),
1982+
# Non-ASCII column names must survive both encodings.
1983+
([["Δ медиана %", True]], ["state", "Δ медиана %"]),
1984+
# The column half may itself be an adhoc column.
1985+
(
1986+
[[{"label": "price_per_sqm", "sqlExpression": "price_per_sqm"}, True]],
1987+
["price_per_sqm", "state"],
1988+
),
1989+
# Junk entries are skipped rather than crashing the request.
1990+
([[123, False]], ["state"]),
1991+
([[]], ["state"]),
1992+
(['["unclosed'], ["state"]),
1993+
],
1994+
)
1995+
def test_data_for_slices_handles_order_by_cols_encodings(
1996+
mocker: MockerFixture,
1997+
order_by_cols: list[object],
1998+
expected: list[str],
1999+
) -> None:
2000+
"""Test ``order_by_cols`` pairs are accepted as JSON strings or raw lists.
2001+
2002+
``order_by_cols`` holds ``[column, ascending]`` pairs. They are canonically
2003+
stored as JSON strings, but real deployments contain raw lists. A raw list
2004+
reaching ``set.update()`` raises ``TypeError: unhashable type: 'list'``.
2005+
"""
2006+
database = mocker.MagicMock()
2007+
database.id = 1
2008+
2009+
table = SqlaTable(
2010+
table_name="test_table",
2011+
database=database,
2012+
columns=[
2013+
TableColumn(column_name="state"),
2014+
TableColumn(column_name="price_per_sqm"),
2015+
TableColumn(column_name="Δ медиана %"),
2016+
],
2017+
metrics=[],
2018+
)
2019+
2020+
mock_slice = mocker.MagicMock()
2021+
mock_slice.form_data = {"groupby": ["state"], "order_by_cols": order_by_cols}
2022+
mock_slice.query_context = None
2023+
2024+
result = table.data_for_slices([mock_slice])
2025+
2026+
assert sorted(column["column_name"] for column in result["columns"]) == sorted(
2027+
expected
2028+
)
2029+
2030+
19732031
def test_data_for_slices_skips_invalid_query_context_entries(
19742032
mocker: MockerFixture,
19752033
) -> None:

‎tests/unit_tests/db_engine_specs/test_base.py‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929

3030
import pytest
3131
from pytest_mock import MockerFixture
32-
from sqlalchemy import Boolean, Column, column, Integer, types
32+
from sqlalchemy import Boolean, Column, column, Integer, text, types
3333
from sqlalchemy.dialects import sqlite
3434
from sqlalchemy.engine.url import make_url, URL
3535
from sqlalchemy.sql import sqltypes
@@ -231,6 +231,55 @@ def test_convert_inspector_columns(
231231
assert convert_inspector_columns(cols) == expected_result
232232

233233

234+
def test_convert_inspector_columns_stringifies_sql_expressions() -> None:
235+
float_type = types.Float()
236+
date_type = types.Date()
237+
string_type = types.String()
238+
cols = cast(
239+
list[SQLAColumnType],
240+
[
241+
{
242+
"name": "total",
243+
"type": float_type,
244+
"nullable": False,
245+
"comment": None,
246+
"clickhouse_alias": text("price * qty"),
247+
},
248+
{
249+
"name": "day",
250+
"type": date_type,
251+
"clickhouse_materialized": text("toDate(ts)"),
252+
"clickhouse_ttl": text("day + toIntervalDay(30)"),
253+
},
254+
{"name": "note", "type": string_type, "server_default": text("'x'")},
255+
],
256+
)
257+
258+
assert convert_inspector_columns(cols) == [
259+
{
260+
"column_name": "total",
261+
"name": "total",
262+
"type": float_type,
263+
"nullable": False,
264+
"comment": None,
265+
"clickhouse_alias": "price * qty",
266+
},
267+
{
268+
"column_name": "day",
269+
"name": "day",
270+
"type": date_type,
271+
"clickhouse_materialized": "toDate(ts)",
272+
"clickhouse_ttl": "day + toIntervalDay(30)",
273+
},
274+
{
275+
"column_name": "note",
276+
"name": "note",
277+
"type": string_type,
278+
"server_default": "'x'",
279+
},
280+
]
281+
282+
234283
def test_select_star(mocker: MockerFixture) -> None:
235284
"""
236285
Test the ``select_star`` method.

0 commit comments

Comments
 (0)