codeant-ai-for-open-source[bot] commented on code in PR #38411: URL: https://github.com/apache/superset/pull/38411#discussion_r2885713092
########## superset/mcp_service/sql_lab/tool/save_sql_query.py: ########## @@ -0,0 +1,121 @@ +# 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. + +""" +MCP tool: save_sql_query + +Save a SQL query so it appears in the Saved Queries list and can be +opened in SQL Lab via a direct URL. +""" + +import logging + +from fastmcp import Context +from superset_core.mcp import tool + +from superset.exceptions import SupersetSecurityException +from superset.extensions import event_logger +from superset.mcp_service.sql_lab.schemas import ( + SaveSqlQueryRequest, + SaveSqlQueryResponse, +) +from superset.mcp_service.utils.schema_utils import parse_request +from superset.mcp_service.utils.url_utils import get_superset_base_url + +logger = logging.getLogger(__name__) + + +@tool(tags=["mutate"]) +@parse_request(SaveSqlQueryRequest) +def save_sql_query(request: SaveSqlQueryRequest, ctx: Context) -> SaveSqlQueryResponse: + """Save a SQL query as a named saved query. + + The saved query appears in the Saved Queries list and can be opened + directly in SQL Lab via the returned URL. + + Typical workflow: + 1. execute_sql(database_id, sql) — run and verify the query + 2. save_sql_query(database_id, sql, label) — persist it + + Returns: + - Saved query ID, label, and SQL Lab URL + """ + try: + from flask import g + + from superset import db, security_manager + from superset.models.core import Database + from superset.models.sql_lab import SavedQuery + + # Validate database exists and user has access + with event_logger.log_context(action="mcp.save_sql_query.db_validation"): + database = ( + db.session.query(Database).filter_by(id=request.database_id).first() + ) + if not database: + return SaveSqlQueryResponse( + id=0, + label=request.label, + sql_lab_url="", + error=f"Database with ID {request.database_id} not found", + ) + + if not security_manager.can_access_database(database): + return SaveSqlQueryResponse( + id=0, + label=request.label, + sql_lab_url="", + error=f"Access denied to database {database.database_name}", + ) + + # Create the saved query + with event_logger.log_context(action="mcp.save_sql_query.create"): + saved_query = SavedQuery( + db_id=request.database_id, + sql=request.sql, + label=request.label, + description=request.description or "", + schema=request.schema_name or "", + catalog=request.catalog, + template_parameters=request.template_parameters, + user_id=g.user.id if hasattr(g, "user") and g.user else None, + ) Review Comment: **Suggestion:** The `SavedQuery` model likely expects the keyword argument `template_params`, but the code passes `template_parameters`, which will cause a runtime `TypeError` for an unexpected keyword argument when constructing a `SavedQuery` instance. [type error] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ `save_sql_query` MCP tool crashes on every invocation. - ❌ Saved queries cannot be created via MCP interface. - ⚠️ MCP workflows depending on persisted queries are broken. - ⚠️ New feature advertised in PR is effectively unusable. ``` </details> ```suggestion saved_query = SavedQuery( db_id=request.database_id, sql=request.sql, label=request.label, description=request.description or "", schema=request.schema_name or "", catalog=request.catalog, template_params=request.template_parameters, user_id=g.user.id if hasattr(g, "user") and g.user else None, ) ``` <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Start Superset with the MCP service enabled so FastMCP can expose the `save_sql_query` tool defined in `superset/mcp_service/sql_lab/tool/save_sql_query.py:45`. 2. From an MCP client (e.g. Claude Code), invoke the `save_sql_query` tool with a valid `SaveSqlQueryRequest` (see `superset/mcp_service/sql_lab/schemas.py`) containing at least `database_id`, `sql`, and `label` so that database validation passes and execution reaches the creation block at `save_sql_query.py:85-96`. 3. The call path is: FastMCP → `parse_request(SaveSqlQueryRequest)` decorator in `superset/mcp_service/utils/schema_utils.py:404-507` → wrapped function → `save_sql_query()` implementation, which then executes the `SavedQuery(...)` constructor at `save_sql_query.py:87-96`. 4. At runtime, SQLAlchemy's `SavedQuery` model (imported from `superset.models.sql_lab`) does not define a `template_parameters` mapped attribute (it uses `template_params`), so `SavedQuery(template_parameters=...)` raises `TypeError: 'template_parameters' is an invalid keyword argument for SavedQuery`, causing the MCP tool call to fail and the saved query not to be created. ``` </details> <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/mcp_service/sql_lab/tool/save_sql_query.py **Line:** 87:96 **Comment:** *Type Error: The `SavedQuery` model likely expects the keyword argument `template_params`, but the code passes `template_parameters`, which will cause a runtime `TypeError` for an unexpected keyword argument when constructing a `SavedQuery` instance. 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%2F38411&comment_hash=197e1f06239ceb6609bedd47694f56f2e77a2b1a2f9b304bdc1e64f3df117d89&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38411&comment_hash=197e1f06239ceb6609bedd47694f56f2e77a2b1a2f9b304bdc1e64f3df117d89&reaction=dislike'>👎</a> ########## tests/unit_tests/mcp_service/sql_lab/tool/test_save_sql_query.py: ########## @@ -0,0 +1,112 @@ +# 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. + +"""Unit tests for MCP save_sql_query tool.""" + +import pytest + +from superset.mcp_service.sql_lab.schemas import ( + SaveSqlQueryRequest, + SaveSqlQueryResponse, +) + + +class TestSaveSqlQuerySchemas: + """Tests for save_sql_query request/response schemas.""" + + def test_valid_request(self): + """Test creating a valid SaveSqlQueryRequest.""" + request = SaveSqlQueryRequest( + database_id=1, + sql="SELECT * FROM users", + label="All Users", + ) + assert request.database_id == 1 + assert request.sql == "SELECT * FROM users" + assert request.label == "All Users" + assert request.description is None + assert request.schema_name is None + assert request.catalog is None + assert request.template_parameters is None + + def test_request_with_all_fields(self): + """Test request with all optional fields populated.""" + request = SaveSqlQueryRequest( + database_id=1, + sql="SELECT * FROM {{ table }}", + label="Parameterized Query", + description="A query with Jinja2 templates", + schema="public", + catalog="main", + template_parameters='{"table": "users"}', + ) + assert request.description == "A query with Jinja2 templates" + assert request.schema_name == "public" + assert request.catalog == "main" + assert request.template_parameters == '{"table": "users"}' + + def test_request_rejects_empty_sql(self): + """Test that empty SQL is rejected.""" + with pytest.raises(ValueError, match="SQL query cannot be empty"): + SaveSqlQueryRequest( + database_id=1, + sql=" ", + label="Bad Query", + ) + + def test_request_rejects_empty_label(self): + """Test that empty label is rejected.""" + with pytest.raises(ValueError): Review Comment: **Suggestion:** The tests for invalid SQL and empty label expect a ValueError, but Pydantic model validation raises a ValidationError when constraints fail, so these tests will fail at runtime because they are asserting the wrong exception type. Updating them to expect ValidationError (while still matching the error message for SQL) will align the tests with the actual behavior of the schema. [logic error] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ Unit tests for save_sql_query schema consistently fail. - ❌ CI for this PR will be red and block merge. - ⚠️ Tests no longer validate real Pydantic behavior. ``` </details> ```suggestion from pydantic import ValidationError from superset.mcp_service.sql_lab.schemas import ( SaveSqlQueryRequest, SaveSqlQueryResponse, ) def test_request_rejects_empty_sql(self): """Test that empty SQL is rejected.""" with pytest.raises(ValidationError, match="SQL query cannot be empty"): SaveSqlQueryRequest( database_id=1, sql=" ", label="Bad Query", ) def test_request_rejects_empty_label(self): """Test that empty label is rejected.""" with pytest.raises(ValidationError): ``` <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Run the unit tests as instructed in the PR description: `pytest tests/unit_tests/mcp_service/sql_lab/tool/test_save_sql_query.py -v`. 2. Test `test_request_rejects_empty_sql` in `tests/unit_tests/mcp_service/sql_lab/tool/test_save_sql_query.py:62-69` constructs `SaveSqlQueryRequest(database_id=1, sql=" ", label="Bad Query")` inside `with pytest.raises(ValueError, ...)`. 3. Model `SaveSqlQueryRequest` defined in `superset/mcp_service/sql_lab/schemas.py:144-182` inherits from `pydantic.BaseModel` and uses a `@field_validator("sql")` that raises `ValueError("SQL query cannot be empty")`; Pydantic wraps this in a `pydantic.ValidationError` when instantiating the model, so the outer exception is `ValidationError`, not `ValueError`. 4. Pytest therefore sees a `ValidationError` escaping `SaveSqlQueryRequest(...)` rather than the expected `ValueError`, causing `test_request_rejects_empty_sql` (and similarly `test_request_rejects_empty_label` at lines 71-78) to fail because `pytest.raises(ValueError)` does not match the actual exception type. ``` </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/sql_lab/tool/test_save_sql_query.py **Line:** 21:73 **Comment:** *Logic Error: The tests for invalid SQL and empty label expect a ValueError, but Pydantic model validation raises a ValidationError when constraints fail, so these tests will fail at runtime because they are asserting the wrong exception type. Updating them to expect ValidationError (while still matching the error message for SQL) will align the tests with the actual behavior of the schema. 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%2F38411&comment_hash=7bdcd04a65c1054f836683553f5b6a49e2756a5e3ef7a64954b97286133ef4be&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38411&comment_hash=7bdcd04a65c1054f836683553f5b6a49e2756a5e3ef7a64954b97286133ef4be&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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
