You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "gabotorresruiz (via GitHub)" <gi...@apache.org> on 2026/04/10 17:25:02 UTC
[PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
gabotorresruiz opened a new pull request, #39279:
URL: https://github.com/apache/superset/pull/39279
<!---
Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
Example:
fix(dashboard): load charts correctly
-->
### SUMMARY
<!--- Describe the change below, including rationale and design decisions -->
Adds a new MCP tool `create_virtual_dataset` that saves a SQL query as a Superset virtual dataset, enabling AI assistants to chart data from JOINs, CTEs, and aggregations that don't map to a single physical table.
The tool:
- Validates the target database exists and the current user has access to it
- Creates the dataset via the existing `CreateDatasetCommand`
- Returns the dataset ID, column names, and a direct edit URL, ready to be passed to `generate_chart` or `generate_explore_link`
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
<!--- Skip this if not applicable -->
N/A - backend-only MCP tool, no UI changes.
### TESTING INSTRUCTIONS
<!--- Required! What steps can be taken to manually verify the changes? -->
1. Call `create_virtual_dataset` with a valid database ID and a SQL JOIN query --> should return a dataset ID, column list, and edit URL with no error
2. Call `create_virtual_dataset` with an invalid database ID --> should return an error response containing the ID, not raise an exception
3. Call `create_virtual_dataset` followed by `generate_chart` using the returned dataset ID --> chart should be created successfully using the virtual dataset's columns
### ADDITIONAL INFORMATION
<!--- Check any relevant boxes with "x" -->
<!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
- [ ] Has associated issue:
- [ ] Required feature flags:
- [ ] Changes UI
- [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
- [ ] Migration is atomic, supports rollback & is backwards-compatible
- [ ] Confirm DB migration upgrade and downgrade tested
- [ ] Runtime estimates and downtime expectations provided
- [x] Introduces new feature or API
- [ ] Removes existing feature or API
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4253493093
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4225541203
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | 38c6bf334885aba4894029c26fcca866a129424a |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/69d9326f527165000869bac2 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-39279--superset-docs-preview.netlify.app](https://deploy-preview-39279--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-39279--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4238407557
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #39279:
URL: https://github.com/apache/superset/pull/39279#discussion_r3081394916
##########
tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py:
##########
@@ -1506,3 +1509,287 @@ async def test_default_ordering(self, mock_dataset_list, mcp_server):
data = json.loads(result.content[0].text)
assert data["count"] == 0
assert data["datasets"] == []
+
+
+# ---------------------------------------------------------------------------
+# create_virtual_dataset tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_db(database_name: str = "examples") -> MagicMock:
+ db = MagicMock()
Review Comment:
**Suggestion:** Add a docstring to this newly added helper function so it complies with the docstring requirement for new function definitions. [custom_rule]
**Severity Level:** Minor ⚠️
```suggestion
"""Create a mock database object with a configurable database name."""
```
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The helper is newly added and lacks a docstring, so it violates the documented-function rule.
The improved code adds a valid docstring without changing behavior and remains syntactically correct.
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py
**Line:** 1520:1520
**Comment:**
*Custom Rule: Add a docstring to this newly added helper function so it complies with the docstring requirement for new function definitions.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=65664e0ed69354a7f81d13207ed62c6496a86f3b2e7b5af79309b65513903da8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=65664e0ed69354a7f81d13207ed62c6496a86f3b2e7b5af79309b65513903da8&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py:
##########
@@ -1506,3 +1509,287 @@ async def test_default_ordering(self, mock_dataset_list, mcp_server):
data = json.loads(result.content[0].text)
assert data["count"] == 0
assert data["datasets"] == []
+
+
+# ---------------------------------------------------------------------------
+# create_virtual_dataset tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_db(database_name: str = "examples") -> MagicMock:
+ db = MagicMock()
+ db.database_name = database_name
+ return db
+
+
+def _make_mock_virtual_dataset(
+ id: int = 21,
+ table_name: str = "Customer Revenue",
+ column_names: list[str] | None = None,
+) -> MagicMock:
+ if column_names is None:
+ column_names = ["name", "revenue"]
+ dataset = MagicMock()
+ dataset.id = id
+ dataset.table_name = table_name
+ dataset.columns = [MagicMock(column_name=c) for c in column_names]
+ return dataset
+
+
+# --- Schema tests ---
+
+
+def test_create_virtual_dataset_request_valid() -> None:
+ req = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql="SELECT a.name, COUNT(*) FROM a JOIN b ON a.id = b.a_id GROUP BY a.name",
+ dataset_name="Customer Revenue",
+ )
+ assert req.database_id == 1
+ assert req.dataset_name == "Customer Revenue"
+ assert req.schema_name is None
+
+
+def test_create_virtual_dataset_request_empty_sql_fails() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError, match="sql must not be empty"):
+ CreateVirtualDatasetRequest(database_id=1, sql=" ", dataset_name="Test")
+
+
+def test_create_virtual_dataset_request_empty_name_fails() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError, match="dataset_name must not be empty"):
+ CreateVirtualDatasetRequest(database_id=1, sql="SELECT 1", dataset_name=" ")
+
+
+def test_create_virtual_dataset_request_name_too_long() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError):
+ CreateVirtualDatasetRequest(
+ database_id=1, sql="SELECT 1", dataset_name="a" * 251
+ )
+
+
+def test_create_virtual_dataset_request_optional_fields() -> None:
+ req = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql="SELECT 1",
+ dataset_name="Test",
+ schema_name="public",
+ catalog="main",
+ description="A virtual dataset",
+ )
+ assert req.schema_name == "public"
+ assert req.catalog == "main"
+ assert req.description == "A virtual dataset"
+
+
+# --- Tool logic tests ---
+
+
+@pytest.mark.asyncio
+async def test_create_virtual_dataset_success(mcp_server) -> None:
Review Comment:
**Suggestion:** Add an explicit type hint for the new test function parameter to satisfy the typing requirement for newly added functions. [custom_rule]
**Severity Level:** Minor ⚠️
```suggestion
async def test_create_virtual_dataset_success(mcp_server: object) -> None:
```
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The test function parameter is unannotated in the current code, so the type-hint rule is violated.
Adding `: object` is syntactically valid and does not alter test behavior.
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py
**Line:** 1594:1594
**Comment:**
*Custom Rule: Add an explicit type hint for the new test function parameter to satisfy the typing requirement for newly added functions.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=5ef3ad0ca9f6ac70538bab860d6b76cc4b11e8477d3b73c1688d38c17f55790e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=5ef3ad0ca9f6ac70538bab860d6b76cc4b11e8477d3b73c1688d38c17f55790e&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py:
##########
@@ -1506,3 +1509,287 @@ async def test_default_ordering(self, mock_dataset_list, mcp_server):
data = json.loads(result.content[0].text)
assert data["count"] == 0
assert data["datasets"] == []
+
+
+# ---------------------------------------------------------------------------
+# create_virtual_dataset tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_db(database_name: str = "examples") -> MagicMock:
+ db = MagicMock()
+ db.database_name = database_name
+ return db
+
+
+def _make_mock_virtual_dataset(
+ id: int = 21,
+ table_name: str = "Customer Revenue",
+ column_names: list[str] | None = None,
+) -> MagicMock:
+ if column_names is None:
+ column_names = ["name", "revenue"]
+ dataset = MagicMock()
+ dataset.id = id
+ dataset.table_name = table_name
+ dataset.columns = [MagicMock(column_name=c) for c in column_names]
+ return dataset
+
+
+# --- Schema tests ---
+
+
+def test_create_virtual_dataset_request_valid() -> None:
+ req = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql="SELECT a.name, COUNT(*) FROM a JOIN b ON a.id = b.a_id GROUP BY a.name",
+ dataset_name="Customer Revenue",
+ )
+ assert req.database_id == 1
+ assert req.dataset_name == "Customer Revenue"
+ assert req.schema_name is None
+
+
+def test_create_virtual_dataset_request_empty_sql_fails() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError, match="sql must not be empty"):
+ CreateVirtualDatasetRequest(database_id=1, sql=" ", dataset_name="Test")
+
+
+def test_create_virtual_dataset_request_empty_name_fails() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError, match="dataset_name must not be empty"):
+ CreateVirtualDatasetRequest(database_id=1, sql="SELECT 1", dataset_name=" ")
+
+
+def test_create_virtual_dataset_request_name_too_long() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError):
+ CreateVirtualDatasetRequest(
+ database_id=1, sql="SELECT 1", dataset_name="a" * 251
+ )
+
+
+def test_create_virtual_dataset_request_optional_fields() -> None:
+ req = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql="SELECT 1",
+ dataset_name="Test",
+ schema_name="public",
+ catalog="main",
+ description="A virtual dataset",
+ )
+ assert req.schema_name == "public"
+ assert req.catalog == "main"
+ assert req.description == "A virtual dataset"
+
+
+# --- Tool logic tests ---
+
+
+@pytest.mark.asyncio
+async def test_create_virtual_dataset_success(mcp_server) -> None:
+ """Happy path: dataset created, columns and URL returned."""
+ mock_dataset = _make_mock_virtual_dataset(
+ id=21, table_name="Customer Revenue", column_names=["name", "revenue"]
+ )
+ mock_command = MagicMock()
+ mock_command.run.return_value = mock_dataset
+
+ with (
+ patch(
+ "superset.commands.dataset.create.CreateDatasetCommand",
+ return_value=mock_command,
+ ),
+ patch(
+ "superset.mcp_service.utils.url_utils.get_superset_base_url",
+ return_value="http://localhost:8088",
+ ),
+ ):
+ async with Client(mcp_server) as client:
+ sql = (
+ "SELECT a.name, SUM(b.revenue) FROM a"
+ " JOIN b ON a.id = b.a_id GROUP BY a.name"
+ )
+ request = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql=sql,
+ dataset_name="Customer Revenue",
+ )
+ result = await client.call_tool(
+ "create_virtual_dataset", {"request": request.model_dump()}
+ )
+ data = json.loads(result.content[0].text)
+
+ assert data["id"] == 21
+ assert data["dataset_name"] == "Customer Revenue"
+ assert data["columns"] == ["name", "revenue"]
+ assert "datasource_type=table" in data["url"]
+ assert "datasource_id=21" in data["url"]
+ assert data["error"] is None
+
+
+@pytest.mark.asyncio
Review Comment:
**Suggestion:** Add an explicit type hint for the new test function parameter so the new function signature is fully typed. [custom_rule]
**Severity Level:** Minor ⚠️
```suggestion
async def test_create_virtual_dataset_db_not_found(mcp_server: object) -> None:
```
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The current function signature lacks a type annotation for `mcp_server`, which violates the stated typing rule.
The proposed annotation is valid and keeps the test executable.
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py
**Line:** 1635:1635
**Comment:**
*Custom Rule: Add an explicit type hint for the new test function parameter so the new function signature is fully typed.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=59371698db62fcb97b473ea4d4e75f18276cff03a234c51d2c09b904c1eadadd&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=59371698db62fcb97b473ea4d4e75f18276cff03a234c51d2c09b904c1eadadd&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py:
##########
@@ -1506,3 +1509,287 @@ async def test_default_ordering(self, mock_dataset_list, mcp_server):
data = json.loads(result.content[0].text)
assert data["count"] == 0
assert data["datasets"] == []
+
+
+# ---------------------------------------------------------------------------
+# create_virtual_dataset tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_db(database_name: str = "examples") -> MagicMock:
+ db = MagicMock()
+ db.database_name = database_name
+ return db
+
+
+def _make_mock_virtual_dataset(
+ id: int = 21,
+ table_name: str = "Customer Revenue",
+ column_names: list[str] | None = None,
+) -> MagicMock:
+ if column_names is None:
+ column_names = ["name", "revenue"]
+ dataset = MagicMock()
+ dataset.id = id
+ dataset.table_name = table_name
+ dataset.columns = [MagicMock(column_name=c) for c in column_names]
+ return dataset
+
+
+# --- Schema tests ---
+
+
+def test_create_virtual_dataset_request_valid() -> None:
+ req = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql="SELECT a.name, COUNT(*) FROM a JOIN b ON a.id = b.a_id GROUP BY a.name",
+ dataset_name="Customer Revenue",
+ )
+ assert req.database_id == 1
+ assert req.dataset_name == "Customer Revenue"
+ assert req.schema_name is None
+
+
+def test_create_virtual_dataset_request_empty_sql_fails() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError, match="sql must not be empty"):
+ CreateVirtualDatasetRequest(database_id=1, sql=" ", dataset_name="Test")
+
+
+def test_create_virtual_dataset_request_empty_name_fails() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError, match="dataset_name must not be empty"):
+ CreateVirtualDatasetRequest(database_id=1, sql="SELECT 1", dataset_name=" ")
+
+
+def test_create_virtual_dataset_request_name_too_long() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError):
+ CreateVirtualDatasetRequest(
+ database_id=1, sql="SELECT 1", dataset_name="a" * 251
+ )
+
+
+def test_create_virtual_dataset_request_optional_fields() -> None:
+ req = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql="SELECT 1",
+ dataset_name="Test",
+ schema_name="public",
+ catalog="main",
+ description="A virtual dataset",
+ )
+ assert req.schema_name == "public"
+ assert req.catalog == "main"
+ assert req.description == "A virtual dataset"
+
+
+# --- Tool logic tests ---
+
+
+@pytest.mark.asyncio
+async def test_create_virtual_dataset_success(mcp_server) -> None:
+ """Happy path: dataset created, columns and URL returned."""
+ mock_dataset = _make_mock_virtual_dataset(
+ id=21, table_name="Customer Revenue", column_names=["name", "revenue"]
+ )
+ mock_command = MagicMock()
+ mock_command.run.return_value = mock_dataset
+
+ with (
+ patch(
+ "superset.commands.dataset.create.CreateDatasetCommand",
+ return_value=mock_command,
+ ),
+ patch(
+ "superset.mcp_service.utils.url_utils.get_superset_base_url",
+ return_value="http://localhost:8088",
+ ),
+ ):
+ async with Client(mcp_server) as client:
+ sql = (
+ "SELECT a.name, SUM(b.revenue) FROM a"
+ " JOIN b ON a.id = b.a_id GROUP BY a.name"
+ )
+ request = CreateVirtualDatasetRequest(
+ database_id=1,
+ sql=sql,
+ dataset_name="Customer Revenue",
+ )
+ result = await client.call_tool(
+ "create_virtual_dataset", {"request": request.model_dump()}
+ )
+ data = json.loads(result.content[0].text)
+
+ assert data["id"] == 21
+ assert data["dataset_name"] == "Customer Revenue"
+ assert data["columns"] == ["name", "revenue"]
+ assert "datasource_type=table" in data["url"]
+ assert "datasource_id=21" in data["url"]
+ assert data["error"] is None
+
+
+@pytest.mark.asyncio
+async def test_create_virtual_dataset_db_not_found(mcp_server) -> None:
+ """When the database ID does not exist, CreateDatasetCommand raises
+ DatasetInvalidError containing DatabaseNotFoundValidationError."""
+ from superset.commands.dataset.exceptions import (
+ DatabaseNotFoundValidationError,
+ DatasetInvalidError,
+ )
+
+ invalid_exc = DatasetInvalidError()
+ invalid_exc.append(DatabaseNotFoundValidationError())
+ mock_command = MagicMock()
+ mock_command.run.side_effect = invalid_exc
+
+ with patch(
+ "superset.commands.dataset.create.CreateDatasetCommand",
+ return_value=mock_command,
+ ):
+ async with Client(mcp_server) as client:
+ request = CreateVirtualDatasetRequest(
+ database_id=999, sql="SELECT 1", dataset_name="Test"
+ )
+ result = await client.call_tool(
+ "create_virtual_dataset", {"request": request.model_dump()}
+ )
+ data = json.loads(result.content[0].text)
+
+ assert data["id"] is None
+ assert data["columns"] == []
+ assert data["error"] is not None
+
+
+@pytest.mark.asyncio
Review Comment:
**Suggestion:** Add an explicit type annotation to the parameter of this newly added async test to comply with the type-hinting rule. [custom_rule]
**Severity Level:** Minor ⚠️
```suggestion
async def test_create_virtual_dataset_invalid_error(mcp_server: object) -> None:
```
<details>
<summary><b>Why it matters? 🤔 </b></summary>
This new async test currently omits a parameter type annotation, matching the custom rule violation.
The fix is syntactically correct and does not introduce any new dependency or runtime issue.
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py
**Line:** 1667:1667
**Comment:**
*Custom Rule: Add an explicit type annotation to the parameter of this newly added async test to comply with the type-hinting rule.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=44ca7784a5c336f1a3c0570894bc76404c63747a4bdc40af7af61e71eca7b1cb&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=44ca7784a5c336f1a3c0570894bc76404c63747a4bdc40af7af61e71eca7b1cb&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py:
##########
@@ -1506,3 +1509,287 @@ async def test_default_ordering(self, mock_dataset_list, mcp_server):
data = json.loads(result.content[0].text)
assert data["count"] == 0
assert data["datasets"] == []
+
+
+# ---------------------------------------------------------------------------
+# create_virtual_dataset tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_db(database_name: str = "examples") -> MagicMock:
+ db = MagicMock()
+ db.database_name = database_name
+ return db
+
+
+def _make_mock_virtual_dataset(
+ id: int = 21,
+ table_name: str = "Customer Revenue",
+ column_names: list[str] | None = None,
+) -> MagicMock:
+ if column_names is None:
Review Comment:
**Suggestion:** Add a docstring to this newly added helper function so the new function definition is documented. [custom_rule]
**Severity Level:** Minor ⚠️
```suggestion
"""Create a mock virtual dataset object with optional mock columns."""
```
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The newly added helper has no docstring, which matches the custom rule violation.
The suggested docstring is valid and does not affect execution or surrounding code.
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py
**Line:** 1530:1530
**Comment:**
*Custom Rule: Add a docstring to this newly added helper function so the new function definition is documented.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=2b4ebb9897aec730515d4b502e56e4115213be97f6b7db489e54d8fac0a3cb22&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=2b4ebb9897aec730515d4b502e56e4115213be97f6b7db489e54d8fac0a3cb22&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz merged PR #39279:
URL: https://github.com/apache/superset/pull/39279
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #39279:
URL: https://github.com/apache/superset/pull/39279#discussion_r3065804999
##########
superset/mcp_service/dataset/schemas.py:
##########
@@ -306,6 +307,76 @@ class GetDatasetInfoRequest(MetadataCacheControl):
]
+class CreateVirtualDatasetRequest(BaseModel):
+ """Request schema for create_virtual_dataset."""
+
+ database_id: int = Field(
+ ...,
+ description="ID of the database connection to use. "
+ "Use list_databases to find valid IDs.",
+ )
+ sql: str = Field(
+ ...,
+ description="SQL query to save as a virtual dataset. "
+ "Can be a JOIN, CTE, aggregation, or any valid SELECT.",
+ )
+ dataset_name: str = Field(
+ ...,
+ min_length=1,
+ max_length=250,
+ description="Name for the new virtual dataset.",
+ )
+ schema_name: str | None = Field(
+ None,
+ description="Schema to associate with the dataset (optional).",
Review Comment:
**Suggestion:** The request model does not accept the standard `schema` key used across MCP SQL-related tools, so callers that send `schema` will have it silently ignored (Pydantic ignores unknown fields by default) and the dataset may be created against the wrong/default schema. Add an alias and enable population by field name to accept both `schema` and `schema_name`. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ create_virtual_dataset ignores `schema` parameter from MCP clients.
- ⚠️ Virtual datasets may be created in unintended/default database schemas.
- ⚠️ Inconsistent parameter naming with execute_sql/save_sql_query MCP tools.
```
</details>
```suggestion
model_config = ConfigDict(populate_by_name=True)
schema_name: str | None = Field(
None,
description="Schema to associate with the dataset (optional).",
alias="schema",
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Note that other MCP SQL tools use the `schema` key: `ExecuteSqlRequest` and
`SaveSqlQueryRequest` in `superset/mcp_service/sql_lab/schemas.py:10-31` both declare
`schema_name` with `alias="schema"` and `model_config =
ConfigDict(populate_by_name=True)`, establishing `schema` as the standard external
parameter name.
2. Start the MCP server (as done in tests) and create a FastMCP client; see
`tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py:145-157` where
`Client(mcp_server)` is used and `client.call_tool("create_virtual_dataset", {"request":
request.model_dump()})` calls the `create_virtual_dataset` tool.
3. Instead of building the request via `CreateVirtualDatasetRequest`, call the tool with a
raw payload that uses the common `schema` key, e.g.:
`await client.call_tool("create_virtual_dataset", {"request": {"database_id": 1, "sql":
"SELECT 1", "dataset_name": "My Dataset", "schema": "public"}})`.
At runtime FastMCP parses the `"request"` object into `CreateVirtualDatasetRequest`
(defined in `superset/mcp_service/dataset/schemas.py:51-81`), but since the model only
defines `schema_name` with no alias and no `model_config` override, Pydantic treats
`"schema"` as an unknown field and silently drops it, leaving `request.schema_name is
None`.
4. Inside the tool implementation `create_virtual_dataset` in
`superset/mcp_service/dataset/tool/create_virtual_dataset.py:112-124`, the properties
passed to `CreateDatasetCommand` only include `"schema"` when `request.schema_name` is
truthy (`if request.schema_name: properties["schema"] = request.schema_name`). Because
`schema_name` remained `None`, the dataset is created without the caller's intended schema
even though `"schema": "public"` was provided in the tool arguments.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/mcp_service/dataset/schemas.py
**Line:** 329:331
**Comment:**
*Logic Error: The request model does not accept the standard `schema` key used across MCP SQL-related tools, so callers that send `schema` will have it silently ignored (Pydantic ignores unknown fields by default) and the dataset may be created against the wrong/default schema. Add an alias and enable population by field name to accept both `schema` and `schema_name`.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=9f261e502133576af08ce365d58e1584029e69e92954404720bddd2dec25802a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=9f261e502133576af08ce365d58e1584029e69e92954404720bddd2dec25802a&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4225603263
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/39279?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `41.33333%` with `44 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 63.58%. Comparing base ([`69c8eef`](https://app.codecov.io/gh/apache/superset/commit/69c8eef78e98ef5f5ccd360f114877be58eb84ee?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`62b8747`](https://app.codecov.io/gh/apache/superset/commit/62b8747bb6f55993dca9fd23df0bbbc49795c5ad?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 1 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/39279?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...mcp\_service/dataset/tool/create\_virtual\_dataset.py](https://app.codecov.io/gh/apache/superset/pull/39279?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fdataset%2Ftool%2Fcreate_virtual_dataset.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvZGF0YXNldC90b29sL2NyZWF0ZV92aXJ0dWFsX2RhdGFzZXQucHk=) | 19.14% | [38 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39279?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/mcp\_service/dataset/schemas.py](https://app.codecov.io/gh/apache/superset/pull/39279?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fdataset%2Fschemas.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvZGF0YXNldC9zY2hlbWFzLnB5) | 77.77% | [6 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39279?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #39279 +/- ##
==========================================
- Coverage 64.40% 63.58% -0.83%
==========================================
Files 2553 2554 +1
Lines 132554 132629 +75
Branches 30745 30752 +7
==========================================
- Hits 85377 84330 -1047
- Misses 45691 46795 +1104
- Partials 1486 1504 +18
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [hive](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.96% <41.33%> (+<0.01%)` | :arrow_up: |
| [mysql](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [postgres](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [presto](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.75% <41.33%> (-0.01%)` | :arrow_down: |
| [python](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `60.42% <41.33%> (-1.85%)` | :arrow_down: |
| [sqlite](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `60.29% <41.33%> (-0.03%)` | :arrow_down: |
| [unit](https://app.codecov.io/gh/apache/superset/pull/39279/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/39279?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4225532077
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #39279:
URL: https://github.com/apache/superset/pull/39279#discussion_r3065808429
##########
superset/mcp_service/dataset/tool/create_virtual_dataset.py:
##########
@@ -0,0 +1,174 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.dataset.schemas import (
+ CreateVirtualDatasetRequest,
+ CreateVirtualDatasetResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@tool(
+ tags=["mutate"],
+ class_permission_name="Dataset",
+ method_permission_name="write",
+ annotations=ToolAnnotations(
+ title="Create virtual dataset from SQL",
+ readOnlyHint=False,
+ destructiveHint=False,
+ ),
+)
+async def create_virtual_dataset(
+ request: CreateVirtualDatasetRequest, ctx: Context
+) -> CreateVirtualDatasetResponse:
+ """Save a SQL query as a virtual dataset so it can be charted.
+
+ Use this tool when a user wants to visualize data from a SQL query
+ (e.g., a JOIN or complex aggregation) that doesn't map to a single
+ physical table.
+
+ Workflow:
+ 1. Call this tool with the SQL query and a dataset name
+ 2. Use the returned ``id`` as the ``dataset_id`` in generate_chart or
+ generate_explore_link
+ 3. Use the returned ``columns`` list to pick columns for the chart config
+ """
+ await ctx.info(
+ "Creating virtual dataset: database_id=%s, dataset_name=%r"
+ % (request.database_id, request.dataset_name)
+ )
+
+ try:
+ from superset import security_manager
+ from superset.commands.dataset.create import CreateDatasetCommand
+ from superset.commands.dataset.exceptions import (
+ DatasetCreateFailedError,
+ DatasetInvalidError,
+ )
+ from superset.daos.database import DatabaseDAO
+ from superset.mcp_service.utils.url_utils import get_superset_base_url
+
+ # 1. Validate the database exists and the user has access
+ with event_logger.log_context(
+ action="mcp.create_virtual_dataset.db_validation"
+ ):
+ database = DatabaseDAO.find_by_id(request.database_id)
+ if not database:
+ await ctx.error(
+ "Database not found: database_id=%s" % request.database_id
+ )
+ return CreateVirtualDatasetResponse(
+ id=0,
+ dataset_name=request.dataset_name,
+ sql=request.sql,
+ database_id=request.database_id,
+ columns=[],
+ url="",
+ error=(
+ f"Database with ID {request.database_id} not found. "
+ "Use list_databases to find valid database IDs."
+ ),
+ )
+
+ if not security_manager.can_access_database(database):
Review Comment:
**Suggestion:** The access check uses only database-level permission (`can_access_database`), which incorrectly rejects users who are authorized via schema/catalog permissions and would otherwise pass Superset's hierarchical SQL access checks. Use `raise_for_access` with the query context instead of a database-only permission check. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ MCP create_virtual_dataset denies users allowed by CreateDatasetCommand.
- ⚠️ AI assistants cannot create datasets for schema-only roles.
```
</details>
```suggestion
from superset.exceptions import SupersetSecurityException
try:
security_manager.raise_for_access(
database=database,
sql=request.sql,
catalog=request.catalog,
schema=request.schema_name,
)
except SupersetSecurityException:
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Configure Superset RBAC so that a user has schema/catalog-level access but not
database-level access on a given database (the permission model for catalog/schema access
is implemented in `superset/security/manager.py:19-28` and
`superset/security/manager.py:93-107`, where `can_access_catalog` and `can_access_schema`
rely on catalog/schema permissions without requiring `can_access_database`).
2. Start Superset with this PR and log in as that user, ensuring they can create virtual
datasets through the standard API via `CreateDatasetCommand` (called from
`superset/datasets/api.py:350-27`), which internally calls
`security_manager.raise_for_access(database=..., sql=..., catalog=..., schema=...)` in
`superset/commands/dataset/create.py:88-95` and permits access based on
schema/catalog-level permissions.
3. From an MCP client (e.g., an AI assistant using the MCP server), invoke the
`create_virtual_dataset` tool defined at
`superset/mcp_service/dataset/tool/create_virtual_dataset.py:43-144` with a
`CreateVirtualDatasetRequest` whose `database_id` points to that database, `sql`
references tables only in the permitted schema, and `schema_name`/`catalog` match the
user's allowed scope.
4. Inside `create_virtual_dataset`, the database is loaded via `DatabaseDAO.find_by_id` at
`create_virtual_dataset.py:77`, then the pre-check `if not
security_manager.can_access_database(database):` at `create_virtual_dataset.py:95-110`
executes; because `can_access_database` (implemented at
`superset/security/manager.py:5-17`) returns `False` for schema-only users, the function
returns a `CreateVirtualDatasetResponse` with `id=0` and an `"Access denied to database"`
error and never reaches `CreateDatasetCommand(properties).run()` at
`create_virtual_dataset.py:126`, meaning this MCP tool denies a user who would succeed via
the standard dataset creation flow.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/mcp_service/dataset/tool/create_virtual_dataset.py
**Line:** 95:95
**Comment:**
*Logic Error: The access check uses only database-level permission (`can_access_database`), which incorrectly rejects users who are authorized via schema/catalog permissions and would otherwise pass Superset's hierarchical SQL access checks. Use `raise_for_access` with the query context instead of a database-only permission check.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=df2750c655d1a2bf647a2f69ff80df27d4303195a232aab608c14a56bb743d2b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39279&comment_hash=df2750c655d1a2bf647a2f69ff80df27d4303195a232aab608c14a56bb743d2b&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4246338794
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4225673531
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | fa323d55ec26f98325680f8a09d044d71f072d55 |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/69d937c4c3212f00089dd7ee |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-39279--superset-docs-preview.netlify.app](https://deploy-preview-39279--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-39279--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4225905918
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add create_virtual_dataset tool to save SQL queries as datasets [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #39279:
URL: https://github.com/apache/superset/pull/39279#issuecomment-4245636735
Hey @gabotorresruiz, nice work on this! The tool design is clean and follows the existing MCP patterns well. Left a few observations:
**Worth addressing:**
1. **Database ID enumeration** — `DatabaseDAO.find_by_id()` runs before `CreateDatasetCommand`, so a user without DB access gets "Database with ID X not found" vs a different error for IDs that exist. This leaks valid database IDs. Consider removing the pre-check and letting `CreateDatasetCommand` handle both existence and permission validation, or catching the not-found case from the command's error instead.
2. **`id=0` as error sentinel** — Error responses return `id=0`, which an LLM agent could accidentally pass to `generate_chart(dataset_id=0)`. Using `int | None` with `None` default would be more explicit that no dataset was created.
3. **Legacy URL** — `/tablemodelview/edit/{id}` is the old FAB view. Modern Superset uses `/explore/?dataset_type=table&dataset_id={id}` or similar. Might be worth checking what other MCP tools use for dataset URLs.
4. **Validators don't strip whitespace** — `sql_must_not_be_empty` checks `not v.strip()` but returns `v` unmodified, so leading/trailing whitespace gets stored. Same for `dataset_name_must_not_be_empty`. Returning `v.strip()` would be a quick fix.
**Minor:**
5. Optional fields (`schema_name`, `catalog`, `description`) use truthiness checks (`if request.schema_name:`) — an empty string `""` would be silently dropped instead of forwarded. `if request.schema_name is not None:` would be more precise.
6. Test coverage is solid but missing a test for the `DatasetCreateFailedError` handler and a permission-denied scenario.
Overall this is a great addition — the workflow from SQL query to chartable dataset is a really useful capability for MCP clients.
*Review by Claude on behalf of @aminghadersohi*
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org