codeant-ai-for-open-source[bot] commented on code in PR #40975:
URL: https://github.com/apache/superset/pull/40975#discussion_r3569469093


##########
superset/mcp_service/dataset/tool/update_dataset_metric.py:
##########
@@ -0,0 +1,294 @@
+# 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.
+
+"""Update a saved metric on a dataset (FastMCP tool)."""
+
+import difflib
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset import security_manager
+from superset.extensions import event_logger
+from superset.mcp_service.dataset.schemas import (
+    DatasetMetricDetail,
+    MetricCurrency,
+    UpdateDatasetMetricRequest,
+    UpdateDatasetMetricResponse,
+)
+from superset.mcp_service.utils import (
+    escape_llm_context_delimiters,
+    sanitize_for_llm_context,
+)
+
+logger = logging.getLogger(__name__)

Review Comment:
   **Suggestion:** Add an explicit type annotation for the module logger 
variable to satisfy the type-hint requirement for annotatable variables. 
[custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   The new module-level variable `logger` is unannotated even though it can be 
given a concrete type such as `logging.Logger`. This matches the type-hint rule 
for annotatable variables in new Python code.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d0a31082d15c46339591026cfaf4bbeb&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d0a31082d15c46339591026cfaf4bbeb&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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/update_dataset_metric.py
   **Line:** 40:40
   **Comment:**
        *Custom Rule: Add an explicit type annotation for the module logger 
variable to satisfy the type-hint requirement for annotatable variables.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=5d3b7d3974679cf020fde45030b87c1aa8343519446e2cc774dccac3638d34eb&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=5d3b7d3974679cf020fde45030b87c1aa8343519446e2cc774dccac3638d34eb&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/mcp_service/dataset/tool/update_dataset_metric.py:
##########
@@ -0,0 +1,294 @@
+# 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.
+
+"""Update a saved metric on a dataset (FastMCP tool)."""
+
+import difflib
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset import security_manager
+from superset.extensions import event_logger
+from superset.mcp_service.dataset.schemas import (
+    DatasetMetricDetail,
+    MetricCurrency,
+    UpdateDatasetMetricRequest,
+    UpdateDatasetMetricResponse,
+)
+from superset.mcp_service.utils import (
+    escape_llm_context_delimiters,
+    sanitize_for_llm_context,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _find_metric(metrics: list[Any], identifier: int | str) -> Any | None:
+    """Find a saved metric by ID, UUID, or metric_name."""
+    if isinstance(identifier, str):
+        try:
+            identifier = int(identifier)
+        except ValueError:
+            pass
+
+    if isinstance(identifier, int):
+        return next((m for m in metrics if m.id == identifier), None)
+
+    lowered = identifier.lower()
+    by_uuid = next(
+        (m for m in metrics if m.uuid and str(m.uuid).lower() == lowered), None
+    )
+    if by_uuid is not None:
+        return by_uuid
+    return next((m for m in metrics if m.metric_name == identifier), None)
+
+
+def _metric_not_found_message(metrics: list[Any], identifier: int | str) -> 
str:
+    """Build a "metric not found" error, escaping caller- and stored-supplied
+    text so it can't break out of the LLM context delimiters (same treatment as
+    the success path in ``_serialize_metric``)."""
+    names = [m.metric_name for m in metrics]
+    safe_identifier = escape_llm_context_delimiters(str(identifier))
+    msg = f"Metric '{safe_identifier}' not found on this dataset."
+    if not names:
+        return f"{msg} This dataset has no saved metrics."
+    suggestions = difflib.get_close_matches(str(identifier), names, n=3, 
cutoff=0.6)
+    if suggestions:
+        safe_suggestions = [escape_llm_context_delimiters(n) for n in 
suggestions]
+        return f"{msg} Did you mean: {', '.join(safe_suggestions)}?"
+    safe_names = [escape_llm_context_delimiters(n) for n in sorted(names)]
+    return f"{msg} Available metrics: {', '.join(safe_names)}."
+
+
+def _serialize_metric(metric: Any) -> DatasetMetricDetail:
+    """Build a ``DatasetMetricDetail`` from a ``SqlMetric`` model.
+
+    Returns the metric's identifiers (id, uuid) and all updatable properties,
+    wrapping free-text fields in LLM-context sanitization the same way the
+    dataset read path does.
+    """
+    currency = getattr(metric, "currency", None)
+    return DatasetMetricDetail(
+        id=getattr(metric, "id", None),
+        uuid=str(metric.uuid) if getattr(metric, "uuid", None) else None,
+        metric_name=escape_llm_context_delimiters(metric.metric_name) or "",
+        verbose_name=sanitize_for_llm_context(
+            getattr(metric, "verbose_name", None),
+            field_path=("metric", "verbose_name"),
+        ),
+        expression=sanitize_for_llm_context(
+            getattr(metric, "expression", None),
+            field_path=("metric", "expression"),
+        ),
+        description=sanitize_for_llm_context(
+            getattr(metric, "description", None),
+            field_path=("metric", "description"),
+        ),
+        d3format=getattr(metric, "d3format", None),
+        metric_type=getattr(metric, "metric_type", None),
+        currency=MetricCurrency.model_validate(currency)
+        if isinstance(currency, dict)
+        else None,
+        warning_text=sanitize_for_llm_context(
+            getattr(metric, "warning_text", None),
+            field_path=("metric", "warning_text"),
+        ),
+        extra=sanitize_for_llm_context(
+            getattr(metric, "extra", None),
+            field_path=("metric", "extra"),
+        ),
+    )
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Dataset",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update dataset metric",
+        readOnlyHint=False,
+        # Overwrites an existing metric's definition and affects every chart
+        # that uses it โ€” non-additive, like update_chart.
+        destructiveHint=True,
+    ),
+)
+async def update_dataset_metric(  # noqa: C901
+    request: UpdateDatasetMetricRequest, ctx: Context
+) -> UpdateDatasetMetricResponse:
+    """Update a saved metric on a dataset.
+
+    Modifies properties of an existing saved metric (the named, reusable
+    aggregations stored on a dataset, e.g. SUM(revenue)) โ€” such as its SQL
+    expression, name, display label, or number format. Changes apply to
+    every chart that uses the metric.
+
+    Only the properties you pass are changed; everything else on the metric,
+    and all other metrics on the dataset, is left untouched. This tool cannot
+    create or delete metrics. Requires ownership of the dataset (or Admin).
+
+    Workflow:
+    1. Call get_dataset_info to inspect the dataset's saved metrics
+    2. Call this tool with the dataset ID, the metric identifier, and only
+       the properties to change
+
+    Example usage:
+    ```json
+    {
+        "dataset_id": 123,
+        "metric": "sum_revenue",
+        "expression": "SUM(net_revenue)",
+        "d3format": "$,.2f"
+    }
+    ```
+    """
+    updates = request.updates()

Review Comment:
   **Suggestion:** Add a concrete type annotation for the local updates 
container returned from the request so this new variable is explicitly typed. 
[custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   The local variable `updates` is introduced without an explicit type 
annotation, and it is a value whose type can reasonably be annotated (for 
example as a mapping of updated field names to values). This is a real omission 
under the Python type-hint rule.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cfcc89a21e444ce0a045eea74f668cff&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=cfcc89a21e444ce0a045eea74f668cff&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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/update_dataset_metric.py
   **Line:** 161:161
   **Comment:**
        *Custom Rule: Add a concrete type annotation for the local updates 
container returned from the request so this new variable is explicitly 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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=17bda467d9e6265a06fa85e6040331421b234511620b2d4b49dd9a0e94b4fcd3&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=17bda467d9e6265a06fa85e6040331421b234511620b2d4b49dd9a0e94b4fcd3&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/mcp_service/dataset/tool/test_update_dataset_metric.py:
##########
@@ -0,0 +1,537 @@
+# 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.
+
+from collections.abc import Iterator
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client, FastMCP
+from pydantic import ValidationError
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.dataset.schemas import UpdateDatasetMetricRequest
+from superset.mcp_service.utils.sanitization import (
+    LLM_CONTEXT_CLOSE_DELIMITER,
+    LLM_CONTEXT_OPEN_DELIMITER,
+)
+from superset.utils import json
+
+
+def _wrapped(value: str) -> str:
+    return 
f"{LLM_CONTEXT_OPEN_DELIMITER}\n{value}\n{LLM_CONTEXT_CLOSE_DELIMITER}"
+
+
[email protected]
+def mcp_server() -> FastMCP:
+    """Provide the shared FastMCP app instance for the in-process test 
client."""
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth() -> Iterator[MagicMock]:
+    """Mock authentication for all tests."""
+    from unittest.mock import Mock
+
+    with patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "admin"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
[email protected](autouse=True)
+def allow_ownership() -> Iterator[MagicMock]:
+    """Let ownership checks pass by default; override to simulate a non-owner.
+
+    Patches the security manager class method (rather than the module-level
+    proxy) so it resolves without an app context, as in CI.
+    """
+    with patch(
+        "superset.security.SupersetSecurityManager.raise_for_editorship",
+        return_value=None,
+    ) as mock_raise:
+        yield mock_raise
+
+
+def make_metric(
+    metric_id: int = 10,
+    metric_name: str = "count",
+    uuid: str = "a1b2c3d4-5678-90ab-cdef-1234567890ab",
+    **overrides: Any,
+) -> SimpleNamespace:
+    """Build a stand-in SqlMetric with all serialized attributes populated."""
+    metric = SimpleNamespace(
+        id=metric_id,
+        uuid=uuid,
+        metric_name=metric_name,
+        verbose_name=None,
+        expression="COUNT(*)",
+        description=None,
+        d3format=None,
+        metric_type=None,
+        currency=None,
+        warning_text=None,
+    )
+    for key, value in overrides.items():
+        setattr(metric, key, value)
+    return metric
+
+
+def make_dataset(
+    dataset_id: int = 1, metrics: list[SimpleNamespace] | None = None
+) -> MagicMock:
+    """Build a stand-in SqlaTable exposing an id, table_name, and metrics."""
+    dataset = MagicMock()
+    dataset.id = dataset_id
+    dataset.table_name = "my_table"
+    dataset.metrics = metrics if metrics is not None else [make_metric()]
+    return dataset
+
+
+# ---------------------------------------------------------------------------
+# Request schema validation
+# ---------------------------------------------------------------------------
+
+
+def test_request_requires_at_least_one_property() -> None:
+    with pytest.raises(ValidationError, match="At least one metric property"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count")
+
+
+def test_request_rejects_empty_expression() -> None:
+    with pytest.raises(ValidationError, match="expression cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", expression="  
 ")
+
+
+def test_request_rejects_null_metric_name() -> None:
+    with pytest.raises(ValidationError, match="metric_name cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", 
metric_name=None)
+
+
+def test_request_updates_only_includes_provided_properties() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "expression": "COUNT(1)"}
+    )
+    assert request.updates() == {"expression": "COUNT(1)"}
+
+
+def test_request_updates_keeps_explicit_nulls() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "description": None, "d3format": 
",.2f"}
+    )
+    assert request.updates() == {"description": None, "d3format": ",.2f"}
+
+
+def test_request_rejects_invalid_extra_json() -> None:
+    with pytest.raises(ValidationError, match="extra must be a valid JSON"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", extra="{not 
json")
+
+
+def test_request_accepts_valid_extra_json() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "extra": '{"warning_markdown": 
"hi"}'}
+    )
+    assert request.updates() == {"extra": '{"warning_markdown": "hi"}'}
+
+
+def test_request_updates_dumps_nested_currency() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {
+            "dataset_id": 1,
+            "metric": 10,
+            "currency": {"symbol": "USD", "symbolPosition": "prefix"},
+        }
+    )
+    assert request.updates() == {
+        "currency": {"symbol": "USD", "symbolPosition": "prefix"}
+    }
+
+
+# ---------------------------------------------------------------------------
+# Tool behavior
+# ---------------------------------------------------------------------------
+
+
[email protected]
+async def test_update_dataset_metric_success(mcp_server) -> None:

Review Comment:
   **Suggestion:** Add a concrete type annotation for the test fixture argument 
in this async test signature. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This new test function takes the fixture argument `mcp_server` without a 
type annotation, so it matches the custom rule requiring Python type hints on 
annotatable function parameters.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6672a299b9914469882b0fe1e76d266e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=6672a299b9914469882b0fe1e76d266e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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_update_dataset_metric.py
   **Line:** 173:173
   **Comment:**
        *Custom Rule: Add a concrete type annotation for the test fixture 
argument in this async test signature.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=b66e5cebe468d020af13b3c57d06194d461db2db5e98977ebff4a4ccecbf3434&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=b66e5cebe468d020af13b3c57d06194d461db2db5e98977ebff4a4ccecbf3434&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/mcp_service/dataset/tool/test_update_dataset_metric.py:
##########
@@ -0,0 +1,537 @@
+# 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.
+
+from collections.abc import Iterator
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client, FastMCP
+from pydantic import ValidationError
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.dataset.schemas import UpdateDatasetMetricRequest
+from superset.mcp_service.utils.sanitization import (
+    LLM_CONTEXT_CLOSE_DELIMITER,
+    LLM_CONTEXT_OPEN_DELIMITER,
+)
+from superset.utils import json
+
+
+def _wrapped(value: str) -> str:
+    return 
f"{LLM_CONTEXT_OPEN_DELIMITER}\n{value}\n{LLM_CONTEXT_CLOSE_DELIMITER}"
+
+
[email protected]
+def mcp_server() -> FastMCP:
+    """Provide the shared FastMCP app instance for the in-process test 
client."""
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth() -> Iterator[MagicMock]:
+    """Mock authentication for all tests."""
+    from unittest.mock import Mock
+
+    with patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "admin"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
[email protected](autouse=True)
+def allow_ownership() -> Iterator[MagicMock]:
+    """Let ownership checks pass by default; override to simulate a non-owner.
+
+    Patches the security manager class method (rather than the module-level
+    proxy) so it resolves without an app context, as in CI.
+    """
+    with patch(
+        "superset.security.SupersetSecurityManager.raise_for_editorship",
+        return_value=None,
+    ) as mock_raise:
+        yield mock_raise
+
+
+def make_metric(
+    metric_id: int = 10,
+    metric_name: str = "count",
+    uuid: str = "a1b2c3d4-5678-90ab-cdef-1234567890ab",
+    **overrides: Any,
+) -> SimpleNamespace:
+    """Build a stand-in SqlMetric with all serialized attributes populated."""
+    metric = SimpleNamespace(
+        id=metric_id,
+        uuid=uuid,
+        metric_name=metric_name,
+        verbose_name=None,
+        expression="COUNT(*)",
+        description=None,
+        d3format=None,
+        metric_type=None,
+        currency=None,
+        warning_text=None,
+    )
+    for key, value in overrides.items():
+        setattr(metric, key, value)
+    return metric
+
+
+def make_dataset(
+    dataset_id: int = 1, metrics: list[SimpleNamespace] | None = None
+) -> MagicMock:
+    """Build a stand-in SqlaTable exposing an id, table_name, and metrics."""
+    dataset = MagicMock()
+    dataset.id = dataset_id
+    dataset.table_name = "my_table"
+    dataset.metrics = metrics if metrics is not None else [make_metric()]
+    return dataset
+
+
+# ---------------------------------------------------------------------------
+# Request schema validation
+# ---------------------------------------------------------------------------
+
+
+def test_request_requires_at_least_one_property() -> None:
+    with pytest.raises(ValidationError, match="At least one metric property"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count")
+
+
+def test_request_rejects_empty_expression() -> None:
+    with pytest.raises(ValidationError, match="expression cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", expression="  
 ")
+
+
+def test_request_rejects_null_metric_name() -> None:
+    with pytest.raises(ValidationError, match="metric_name cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", 
metric_name=None)
+
+
+def test_request_updates_only_includes_provided_properties() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "expression": "COUNT(1)"}
+    )
+    assert request.updates() == {"expression": "COUNT(1)"}
+
+
+def test_request_updates_keeps_explicit_nulls() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "description": None, "d3format": 
",.2f"}
+    )
+    assert request.updates() == {"description": None, "d3format": ",.2f"}
+
+
+def test_request_rejects_invalid_extra_json() -> None:
+    with pytest.raises(ValidationError, match="extra must be a valid JSON"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", extra="{not 
json")
+
+
+def test_request_accepts_valid_extra_json() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "extra": '{"warning_markdown": 
"hi"}'}
+    )
+    assert request.updates() == {"extra": '{"warning_markdown": "hi"}'}
+
+
+def test_request_updates_dumps_nested_currency() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {
+            "dataset_id": 1,
+            "metric": 10,
+            "currency": {"symbol": "USD", "symbolPosition": "prefix"},
+        }
+    )
+    assert request.updates() == {
+        "currency": {"symbol": "USD", "symbolPosition": "prefix"}
+    }
+
+
+# ---------------------------------------------------------------------------
+# Tool behavior
+# ---------------------------------------------------------------------------
+
+
[email protected]
+async def test_update_dataset_metric_success(mcp_server) -> None:
+    """Happy path: only the target metric is changed, others sent as stubs."""
+    target = make_metric(metric_id=10, metric_name="count")
+    other = make_metric(
+        metric_id=11,
+        metric_name="sum_revenue",
+        uuid="b2c3d4e5-6789-01bc-def0-234567890abc",
+        expression="SUM(revenue)",
+    )
+    dataset = make_dataset(dataset_id=1, metrics=[target, other])
+
+    updated_target = make_metric(
+        metric_id=10, metric_name="count", expression="COUNT(1)", d3format=",d"
+    )
+    updated_dataset = make_dataset(dataset_id=1, metrics=[updated_target, 
other])
+
+    mock_command = MagicMock()
+    mock_command.run.return_value = updated_dataset
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            return_value=mock_command,
+        ) as command_cls,
+        patch(
+            "superset.mcp_service.utils.url_utils.get_superset_base_url",
+            return_value="http://localhost:8088";,
+        ),
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "count",
+                        "expression": "COUNT(1)",
+                        "d3format": ",d",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    command_cls.assert_called_once_with(
+        1,
+        {
+            "metrics": [
+                {
+                    "id": 10,
+                    "metric_name": "count",
+                    "expression": "COUNT(1)",
+                    "d3format": ",d",
+                },
+                {"id": 11, "metric_name": "sum_revenue"},
+            ]
+        },
+    )
+    assert data["error"] is None
+    assert data["dataset_id"] == 1
+    assert data["dataset_name"] == "my_table"
+    assert data["updated_properties"] == ["d3format", "expression"]
+    assert data["metric"]["id"] == 10
+    assert data["metric"]["expression"] == _wrapped("COUNT(1)")
+    assert data["metric"]["d3format"] == ",d"
+    assert "datasource_id=1" in data["url"]
+
+
[email protected]
+async def test_update_dataset_metric_returns_extra(mcp_server) -> None:

Review Comment:
   **Suggestion:** Add an explicit type hint to the fixture parameter in this 
test function. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   The test signature includes the fixture parameter `mcp_server` without any 
type hint, which is a real omission under the stated Python type-hint rule.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=34d69c2e81464460a6613bf01394f87e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=34d69c2e81464460a6613bf01394f87e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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_update_dataset_metric.py
   **Line:** 245:245
   **Comment:**
        *Custom Rule: Add an explicit type hint to the fixture parameter in 
this test function.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=1f157bd83dba1b826878aaba254f0304d1886e18ead9047c17cef6adabd9c5de&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=1f157bd83dba1b826878aaba254f0304d1886e18ead9047c17cef6adabd9c5de&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/mcp_service/dataset/tool/test_update_dataset_metric.py:
##########
@@ -0,0 +1,537 @@
+# 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.
+
+from collections.abc import Iterator
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client, FastMCP
+from pydantic import ValidationError
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.dataset.schemas import UpdateDatasetMetricRequest
+from superset.mcp_service.utils.sanitization import (
+    LLM_CONTEXT_CLOSE_DELIMITER,
+    LLM_CONTEXT_OPEN_DELIMITER,
+)
+from superset.utils import json
+
+
+def _wrapped(value: str) -> str:
+    return 
f"{LLM_CONTEXT_OPEN_DELIMITER}\n{value}\n{LLM_CONTEXT_CLOSE_DELIMITER}"
+
+
[email protected]
+def mcp_server() -> FastMCP:
+    """Provide the shared FastMCP app instance for the in-process test 
client."""
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth() -> Iterator[MagicMock]:
+    """Mock authentication for all tests."""
+    from unittest.mock import Mock
+
+    with patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "admin"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
[email protected](autouse=True)
+def allow_ownership() -> Iterator[MagicMock]:
+    """Let ownership checks pass by default; override to simulate a non-owner.
+
+    Patches the security manager class method (rather than the module-level
+    proxy) so it resolves without an app context, as in CI.
+    """
+    with patch(
+        "superset.security.SupersetSecurityManager.raise_for_editorship",
+        return_value=None,
+    ) as mock_raise:
+        yield mock_raise
+
+
+def make_metric(
+    metric_id: int = 10,
+    metric_name: str = "count",
+    uuid: str = "a1b2c3d4-5678-90ab-cdef-1234567890ab",
+    **overrides: Any,
+) -> SimpleNamespace:
+    """Build a stand-in SqlMetric with all serialized attributes populated."""
+    metric = SimpleNamespace(
+        id=metric_id,
+        uuid=uuid,
+        metric_name=metric_name,
+        verbose_name=None,
+        expression="COUNT(*)",
+        description=None,
+        d3format=None,
+        metric_type=None,
+        currency=None,
+        warning_text=None,
+    )
+    for key, value in overrides.items():
+        setattr(metric, key, value)
+    return metric
+
+
+def make_dataset(
+    dataset_id: int = 1, metrics: list[SimpleNamespace] | None = None
+) -> MagicMock:
+    """Build a stand-in SqlaTable exposing an id, table_name, and metrics."""
+    dataset = MagicMock()
+    dataset.id = dataset_id
+    dataset.table_name = "my_table"
+    dataset.metrics = metrics if metrics is not None else [make_metric()]
+    return dataset
+
+
+# ---------------------------------------------------------------------------
+# Request schema validation
+# ---------------------------------------------------------------------------
+
+
+def test_request_requires_at_least_one_property() -> None:
+    with pytest.raises(ValidationError, match="At least one metric property"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count")
+
+
+def test_request_rejects_empty_expression() -> None:
+    with pytest.raises(ValidationError, match="expression cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", expression="  
 ")
+
+
+def test_request_rejects_null_metric_name() -> None:
+    with pytest.raises(ValidationError, match="metric_name cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", 
metric_name=None)
+
+
+def test_request_updates_only_includes_provided_properties() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "expression": "COUNT(1)"}
+    )
+    assert request.updates() == {"expression": "COUNT(1)"}
+
+
+def test_request_updates_keeps_explicit_nulls() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "description": None, "d3format": 
",.2f"}
+    )
+    assert request.updates() == {"description": None, "d3format": ",.2f"}
+
+
+def test_request_rejects_invalid_extra_json() -> None:
+    with pytest.raises(ValidationError, match="extra must be a valid JSON"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", extra="{not 
json")
+
+
+def test_request_accepts_valid_extra_json() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "extra": '{"warning_markdown": 
"hi"}'}
+    )
+    assert request.updates() == {"extra": '{"warning_markdown": "hi"}'}
+
+
+def test_request_updates_dumps_nested_currency() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {
+            "dataset_id": 1,
+            "metric": 10,
+            "currency": {"symbol": "USD", "symbolPosition": "prefix"},
+        }
+    )
+    assert request.updates() == {
+        "currency": {"symbol": "USD", "symbolPosition": "prefix"}
+    }
+
+
+# ---------------------------------------------------------------------------
+# Tool behavior
+# ---------------------------------------------------------------------------
+
+
[email protected]
+async def test_update_dataset_metric_success(mcp_server) -> None:
+    """Happy path: only the target metric is changed, others sent as stubs."""
+    target = make_metric(metric_id=10, metric_name="count")
+    other = make_metric(
+        metric_id=11,
+        metric_name="sum_revenue",
+        uuid="b2c3d4e5-6789-01bc-def0-234567890abc",
+        expression="SUM(revenue)",
+    )
+    dataset = make_dataset(dataset_id=1, metrics=[target, other])
+
+    updated_target = make_metric(
+        metric_id=10, metric_name="count", expression="COUNT(1)", d3format=",d"
+    )
+    updated_dataset = make_dataset(dataset_id=1, metrics=[updated_target, 
other])
+
+    mock_command = MagicMock()
+    mock_command.run.return_value = updated_dataset
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            return_value=mock_command,
+        ) as command_cls,
+        patch(
+            "superset.mcp_service.utils.url_utils.get_superset_base_url",
+            return_value="http://localhost:8088";,
+        ),
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "count",
+                        "expression": "COUNT(1)",
+                        "d3format": ",d",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    command_cls.assert_called_once_with(
+        1,
+        {
+            "metrics": [
+                {
+                    "id": 10,
+                    "metric_name": "count",
+                    "expression": "COUNT(1)",
+                    "d3format": ",d",
+                },
+                {"id": 11, "metric_name": "sum_revenue"},
+            ]
+        },
+    )
+    assert data["error"] is None
+    assert data["dataset_id"] == 1
+    assert data["dataset_name"] == "my_table"
+    assert data["updated_properties"] == ["d3format", "expression"]
+    assert data["metric"]["id"] == 10
+    assert data["metric"]["expression"] == _wrapped("COUNT(1)")
+    assert data["metric"]["d3format"] == ",d"
+    assert "datasource_id=1" in data["url"]
+
+
[email protected]
+async def test_update_dataset_metric_returns_extra(mcp_server) -> None:
+    """`extra` is an updatable property, so it is echoed back in the 
response."""
+    dataset = make_dataset(dataset_id=1, metrics=[make_metric(metric_id=10)])
+    updated = make_dataset(
+        dataset_id=1,
+        metrics=[make_metric(metric_id=10, extra='{"warning_markdown": 
"note"}')],
+    )
+    mock_command = MagicMock()
+    mock_command.run.return_value = updated
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            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:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": 10,
+                        "extra": '{"warning_markdown": "note"}',
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["error"] is None
+    assert data["updated_properties"] == ["extra"]
+    assert data["metric"]["extra"] == _wrapped('{"warning_markdown": "note"}')
+
+
[email protected]
+async def test_update_dataset_metric_by_id_and_uuid(mcp_server) -> None:
+    """The metric can be addressed by numeric ID (also as string) or UUID."""
+    target = make_metric(metric_id=10, metric_name="count")
+    dataset = make_dataset(dataset_id=1, metrics=[target])
+
+    mock_command = MagicMock()
+    mock_command.run.return_value = dataset
+
+    for identifier in (10, "10", "A1B2C3D4-5678-90ab-cdef-1234567890ab"):
+        mock_command.reset_mock()
+        with (
+            patch(
+                "superset.daos.dataset.DatasetDAO.find_by_id",
+                return_value=dataset,
+            ),
+            patch(
+                "superset.commands.dataset.update.UpdateDatasetCommand",
+                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:
+                result = await client.call_tool(
+                    "update_dataset_metric",
+                    {
+                        "request": {
+                            "dataset_id": 1,
+                            "metric": identifier,
+                            "verbose_name": "Count",
+                        }
+                    },
+                )
+                data = json.loads(result.content[0].text)
+
+        assert data["error"] is None, identifier
+        mock_command.run.assert_called_once()
+
+
[email protected]
+async def test_update_dataset_metric_not_found_suggests_names(mcp_server) -> 
None:
+    dataset = make_dataset(
+        dataset_id=1, metrics=[make_metric(metric_id=10, 
metric_name="sum_revenue")]
+    )
+
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=dataset,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "sum_revenu",
+                        "expression": "SUM(net_revenue)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "not found" in data["error"]
+    assert "sum_revenue" in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_not_found_escapes_names(mcp_server) -> 
None:
+    """Metric names in the not-found error are escaped like the success 
path."""
+    from superset.mcp_service.utils.sanitization import (
+        LLM_CONTEXT_ESCAPED_OPEN_DELIMITER,
+    )
+
+    hostile_name = f"{LLM_CONTEXT_OPEN_DELIMITER}evil"
+    dataset = make_dataset(
+        dataset_id=1, metrics=[make_metric(metric_id=10, 
metric_name=hostile_name)]
+    )
+
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=dataset,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "missing",
+                        "expression": "COUNT(1)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert LLM_CONTEXT_OPEN_DELIMITER not in data["error"]
+    assert LLM_CONTEXT_ESCAPED_OPEN_DELIMITER in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_dataset_not_found(mcp_server) -> None:
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=None,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 999,
+                        "metric": "count",
+                        "description": "desc",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "No dataset found" in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_forbidden_non_owner(
+    mcp_server, allow_ownership
+) -> None:

Review Comment:
   **Suggestion:** Provide explicit type annotations for all fixture parameters 
in this async test definition. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   Both fixture parameters in this new test function are unannotated, so the 
code does violate the type-hint requirement.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=3fa0a190684a4ac2a00ab1230de04b38&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=3fa0a190684a4ac2a00ab1230de04b38&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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_update_dataset_metric.py
   **Line:** 415:417
   **Comment:**
        *Custom Rule: Provide explicit type annotations for all fixture 
parameters in this async test definition.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=94d79d7f32a240591188e88688b58912df9e649674ccb8cf300920ff313d292d&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=94d79d7f32a240591188e88688b58912df9e649674ccb8cf300920ff313d292d&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/mcp_service/dataset/tool/test_update_dataset_metric.py:
##########
@@ -0,0 +1,537 @@
+# 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.
+
+from collections.abc import Iterator
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client, FastMCP
+from pydantic import ValidationError
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.dataset.schemas import UpdateDatasetMetricRequest
+from superset.mcp_service.utils.sanitization import (
+    LLM_CONTEXT_CLOSE_DELIMITER,
+    LLM_CONTEXT_OPEN_DELIMITER,
+)
+from superset.utils import json
+
+
+def _wrapped(value: str) -> str:
+    return 
f"{LLM_CONTEXT_OPEN_DELIMITER}\n{value}\n{LLM_CONTEXT_CLOSE_DELIMITER}"
+
+
[email protected]
+def mcp_server() -> FastMCP:
+    """Provide the shared FastMCP app instance for the in-process test 
client."""
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth() -> Iterator[MagicMock]:
+    """Mock authentication for all tests."""
+    from unittest.mock import Mock
+
+    with patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "admin"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
[email protected](autouse=True)
+def allow_ownership() -> Iterator[MagicMock]:
+    """Let ownership checks pass by default; override to simulate a non-owner.
+
+    Patches the security manager class method (rather than the module-level
+    proxy) so it resolves without an app context, as in CI.
+    """
+    with patch(
+        "superset.security.SupersetSecurityManager.raise_for_editorship",
+        return_value=None,
+    ) as mock_raise:
+        yield mock_raise
+
+
+def make_metric(
+    metric_id: int = 10,
+    metric_name: str = "count",
+    uuid: str = "a1b2c3d4-5678-90ab-cdef-1234567890ab",
+    **overrides: Any,
+) -> SimpleNamespace:
+    """Build a stand-in SqlMetric with all serialized attributes populated."""
+    metric = SimpleNamespace(
+        id=metric_id,
+        uuid=uuid,
+        metric_name=metric_name,
+        verbose_name=None,
+        expression="COUNT(*)",
+        description=None,
+        d3format=None,
+        metric_type=None,
+        currency=None,
+        warning_text=None,
+    )
+    for key, value in overrides.items():
+        setattr(metric, key, value)
+    return metric
+
+
+def make_dataset(
+    dataset_id: int = 1, metrics: list[SimpleNamespace] | None = None
+) -> MagicMock:
+    """Build a stand-in SqlaTable exposing an id, table_name, and metrics."""
+    dataset = MagicMock()
+    dataset.id = dataset_id
+    dataset.table_name = "my_table"
+    dataset.metrics = metrics if metrics is not None else [make_metric()]
+    return dataset
+
+
+# ---------------------------------------------------------------------------
+# Request schema validation
+# ---------------------------------------------------------------------------
+
+
+def test_request_requires_at_least_one_property() -> None:
+    with pytest.raises(ValidationError, match="At least one metric property"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count")
+
+
+def test_request_rejects_empty_expression() -> None:
+    with pytest.raises(ValidationError, match="expression cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", expression="  
 ")
+
+
+def test_request_rejects_null_metric_name() -> None:
+    with pytest.raises(ValidationError, match="metric_name cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", 
metric_name=None)
+
+
+def test_request_updates_only_includes_provided_properties() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "expression": "COUNT(1)"}
+    )
+    assert request.updates() == {"expression": "COUNT(1)"}
+
+
+def test_request_updates_keeps_explicit_nulls() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "description": None, "d3format": 
",.2f"}
+    )
+    assert request.updates() == {"description": None, "d3format": ",.2f"}
+
+
+def test_request_rejects_invalid_extra_json() -> None:
+    with pytest.raises(ValidationError, match="extra must be a valid JSON"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", extra="{not 
json")
+
+
+def test_request_accepts_valid_extra_json() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "extra": '{"warning_markdown": 
"hi"}'}
+    )
+    assert request.updates() == {"extra": '{"warning_markdown": "hi"}'}
+
+
+def test_request_updates_dumps_nested_currency() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {
+            "dataset_id": 1,
+            "metric": 10,
+            "currency": {"symbol": "USD", "symbolPosition": "prefix"},
+        }
+    )
+    assert request.updates() == {
+        "currency": {"symbol": "USD", "symbolPosition": "prefix"}
+    }
+
+
+# ---------------------------------------------------------------------------
+# Tool behavior
+# ---------------------------------------------------------------------------
+
+
[email protected]
+async def test_update_dataset_metric_success(mcp_server) -> None:
+    """Happy path: only the target metric is changed, others sent as stubs."""
+    target = make_metric(metric_id=10, metric_name="count")
+    other = make_metric(
+        metric_id=11,
+        metric_name="sum_revenue",
+        uuid="b2c3d4e5-6789-01bc-def0-234567890abc",
+        expression="SUM(revenue)",
+    )
+    dataset = make_dataset(dataset_id=1, metrics=[target, other])
+
+    updated_target = make_metric(
+        metric_id=10, metric_name="count", expression="COUNT(1)", d3format=",d"
+    )
+    updated_dataset = make_dataset(dataset_id=1, metrics=[updated_target, 
other])
+
+    mock_command = MagicMock()
+    mock_command.run.return_value = updated_dataset
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            return_value=mock_command,
+        ) as command_cls,
+        patch(
+            "superset.mcp_service.utils.url_utils.get_superset_base_url",
+            return_value="http://localhost:8088";,
+        ),
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "count",
+                        "expression": "COUNT(1)",
+                        "d3format": ",d",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    command_cls.assert_called_once_with(
+        1,
+        {
+            "metrics": [
+                {
+                    "id": 10,
+                    "metric_name": "count",
+                    "expression": "COUNT(1)",
+                    "d3format": ",d",
+                },
+                {"id": 11, "metric_name": "sum_revenue"},
+            ]
+        },
+    )
+    assert data["error"] is None
+    assert data["dataset_id"] == 1
+    assert data["dataset_name"] == "my_table"
+    assert data["updated_properties"] == ["d3format", "expression"]
+    assert data["metric"]["id"] == 10
+    assert data["metric"]["expression"] == _wrapped("COUNT(1)")
+    assert data["metric"]["d3format"] == ",d"
+    assert "datasource_id=1" in data["url"]
+
+
[email protected]
+async def test_update_dataset_metric_returns_extra(mcp_server) -> None:
+    """`extra` is an updatable property, so it is echoed back in the 
response."""
+    dataset = make_dataset(dataset_id=1, metrics=[make_metric(metric_id=10)])
+    updated = make_dataset(
+        dataset_id=1,
+        metrics=[make_metric(metric_id=10, extra='{"warning_markdown": 
"note"}')],
+    )
+    mock_command = MagicMock()
+    mock_command.run.return_value = updated
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            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:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": 10,
+                        "extra": '{"warning_markdown": "note"}',
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["error"] is None
+    assert data["updated_properties"] == ["extra"]
+    assert data["metric"]["extra"] == _wrapped('{"warning_markdown": "note"}')
+
+
[email protected]
+async def test_update_dataset_metric_by_id_and_uuid(mcp_server) -> None:
+    """The metric can be addressed by numeric ID (also as string) or UUID."""
+    target = make_metric(metric_id=10, metric_name="count")
+    dataset = make_dataset(dataset_id=1, metrics=[target])
+
+    mock_command = MagicMock()
+    mock_command.run.return_value = dataset
+
+    for identifier in (10, "10", "A1B2C3D4-5678-90ab-cdef-1234567890ab"):
+        mock_command.reset_mock()
+        with (
+            patch(
+                "superset.daos.dataset.DatasetDAO.find_by_id",
+                return_value=dataset,
+            ),
+            patch(
+                "superset.commands.dataset.update.UpdateDatasetCommand",
+                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:
+                result = await client.call_tool(
+                    "update_dataset_metric",
+                    {
+                        "request": {
+                            "dataset_id": 1,
+                            "metric": identifier,
+                            "verbose_name": "Count",
+                        }
+                    },
+                )
+                data = json.loads(result.content[0].text)
+
+        assert data["error"] is None, identifier
+        mock_command.run.assert_called_once()
+
+
[email protected]
+async def test_update_dataset_metric_not_found_suggests_names(mcp_server) -> 
None:
+    dataset = make_dataset(
+        dataset_id=1, metrics=[make_metric(metric_id=10, 
metric_name="sum_revenue")]
+    )
+
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=dataset,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "sum_revenu",
+                        "expression": "SUM(net_revenue)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "not found" in data["error"]
+    assert "sum_revenue" in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_not_found_escapes_names(mcp_server) -> 
None:
+    """Metric names in the not-found error are escaped like the success 
path."""
+    from superset.mcp_service.utils.sanitization import (
+        LLM_CONTEXT_ESCAPED_OPEN_DELIMITER,
+    )
+
+    hostile_name = f"{LLM_CONTEXT_OPEN_DELIMITER}evil"
+    dataset = make_dataset(
+        dataset_id=1, metrics=[make_metric(metric_id=10, 
metric_name=hostile_name)]
+    )
+
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=dataset,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "missing",
+                        "expression": "COUNT(1)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert LLM_CONTEXT_OPEN_DELIMITER not in data["error"]
+    assert LLM_CONTEXT_ESCAPED_OPEN_DELIMITER in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_dataset_not_found(mcp_server) -> None:
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=None,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 999,
+                        "metric": "count",
+                        "description": "desc",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "No dataset found" in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_forbidden_non_owner(
+    mcp_server, allow_ownership
+) -> None:
+    """A non-owner is rejected before the metric list is inspected, so the
+    error cannot be used to enumerate metric names."""
+    from superset.exceptions import SupersetSecurityException
+
+    allow_ownership.side_effect = SupersetSecurityException(
+        MagicMock(message="not an owner")
+    )
+
+    dataset = make_dataset(
+        dataset_id=1,
+        metrics=[make_metric(metric_id=10, metric_name="secret_metric")],
+    )
+    mock_command = MagicMock()
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            return_value=mock_command,
+        ) as command_cls,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "does_not_exist",
+                        "expression": "COUNT(1)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "owner" in data["error"]
+    # No metric names leak, and the command is never constructed/run.
+    assert "secret_metric" not in data["error"]
+    command_cls.assert_not_called()
+
+
[email protected]
+async def test_update_dataset_metric_invalid_error(mcp_server) -> None:
+    """Validation failures (e.g. duplicate name) surface as error responses."""
+    from superset.commands.dataset.exceptions import (
+        DatasetInvalidError,
+        DatasetMetricsDuplicateValidationError,
+    )
+
+    invalid_exc = DatasetInvalidError()
+    invalid_exc.append(DatasetMetricsDuplicateValidationError())
+
+    dataset = make_dataset()
+    mock_command = MagicMock()
+    mock_command.run.side_effect = invalid_exc
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            return_value=mock_command,
+        ),
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "count",
+                        "metric_name": "sum_revenue",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert data["error"] is not None
+
+
[email protected]
+async def test_update_dataset_metric_update_failed(mcp_server) -> None:

Review Comment:
   **Suggestion:** Specify the expected type of the fixture parameter in this 
async test declaration. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   The `mcp_server` parameter is not type-annotated in this new test function, 
so it fits the custom type-hint rule violation.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=0686fd0980d2405da8fc7f8f3c421cc8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=0686fd0980d2405da8fc7f8f3c421cc8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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_update_dataset_metric.py
   **Line:** 505:505
   **Comment:**
        *Custom Rule: Specify the expected type of the fixture parameter in 
this async test declaration.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=38e8487554d540dbc3b8cfee648175195d3443119699d53bb49c7daa342f02a9&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=38e8487554d540dbc3b8cfee648175195d3443119699d53bb49c7daa342f02a9&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/mcp_service/dataset/tool/test_update_dataset_metric.py:
##########
@@ -0,0 +1,537 @@
+# 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.
+
+from collections.abc import Iterator
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client, FastMCP
+from pydantic import ValidationError
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.dataset.schemas import UpdateDatasetMetricRequest
+from superset.mcp_service.utils.sanitization import (
+    LLM_CONTEXT_CLOSE_DELIMITER,
+    LLM_CONTEXT_OPEN_DELIMITER,
+)
+from superset.utils import json
+
+
+def _wrapped(value: str) -> str:
+    return 
f"{LLM_CONTEXT_OPEN_DELIMITER}\n{value}\n{LLM_CONTEXT_CLOSE_DELIMITER}"
+
+
[email protected]
+def mcp_server() -> FastMCP:
+    """Provide the shared FastMCP app instance for the in-process test 
client."""
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth() -> Iterator[MagicMock]:
+    """Mock authentication for all tests."""
+    from unittest.mock import Mock
+
+    with patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "admin"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
[email protected](autouse=True)
+def allow_ownership() -> Iterator[MagicMock]:
+    """Let ownership checks pass by default; override to simulate a non-owner.
+
+    Patches the security manager class method (rather than the module-level
+    proxy) so it resolves without an app context, as in CI.
+    """
+    with patch(
+        "superset.security.SupersetSecurityManager.raise_for_editorship",
+        return_value=None,
+    ) as mock_raise:
+        yield mock_raise
+
+
+def make_metric(
+    metric_id: int = 10,
+    metric_name: str = "count",
+    uuid: str = "a1b2c3d4-5678-90ab-cdef-1234567890ab",
+    **overrides: Any,
+) -> SimpleNamespace:
+    """Build a stand-in SqlMetric with all serialized attributes populated."""
+    metric = SimpleNamespace(
+        id=metric_id,
+        uuid=uuid,
+        metric_name=metric_name,
+        verbose_name=None,
+        expression="COUNT(*)",
+        description=None,
+        d3format=None,
+        metric_type=None,
+        currency=None,
+        warning_text=None,
+    )
+    for key, value in overrides.items():
+        setattr(metric, key, value)
+    return metric
+
+
+def make_dataset(
+    dataset_id: int = 1, metrics: list[SimpleNamespace] | None = None
+) -> MagicMock:
+    """Build a stand-in SqlaTable exposing an id, table_name, and metrics."""
+    dataset = MagicMock()
+    dataset.id = dataset_id
+    dataset.table_name = "my_table"
+    dataset.metrics = metrics if metrics is not None else [make_metric()]
+    return dataset
+
+
+# ---------------------------------------------------------------------------
+# Request schema validation
+# ---------------------------------------------------------------------------
+
+
+def test_request_requires_at_least_one_property() -> None:
+    with pytest.raises(ValidationError, match="At least one metric property"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count")
+
+
+def test_request_rejects_empty_expression() -> None:
+    with pytest.raises(ValidationError, match="expression cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", expression="  
 ")
+
+
+def test_request_rejects_null_metric_name() -> None:
+    with pytest.raises(ValidationError, match="metric_name cannot be empty"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", 
metric_name=None)
+
+
+def test_request_updates_only_includes_provided_properties() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "expression": "COUNT(1)"}
+    )
+    assert request.updates() == {"expression": "COUNT(1)"}
+
+
+def test_request_updates_keeps_explicit_nulls() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "description": None, "d3format": 
",.2f"}
+    )
+    assert request.updates() == {"description": None, "d3format": ",.2f"}
+
+
+def test_request_rejects_invalid_extra_json() -> None:
+    with pytest.raises(ValidationError, match="extra must be a valid JSON"):
+        UpdateDatasetMetricRequest(dataset_id=1, metric="count", extra="{not 
json")
+
+
+def test_request_accepts_valid_extra_json() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {"dataset_id": 1, "metric": "count", "extra": '{"warning_markdown": 
"hi"}'}
+    )
+    assert request.updates() == {"extra": '{"warning_markdown": "hi"}'}
+
+
+def test_request_updates_dumps_nested_currency() -> None:
+    request = UpdateDatasetMetricRequest.model_validate(
+        {
+            "dataset_id": 1,
+            "metric": 10,
+            "currency": {"symbol": "USD", "symbolPosition": "prefix"},
+        }
+    )
+    assert request.updates() == {
+        "currency": {"symbol": "USD", "symbolPosition": "prefix"}
+    }
+
+
+# ---------------------------------------------------------------------------
+# Tool behavior
+# ---------------------------------------------------------------------------
+
+
[email protected]
+async def test_update_dataset_metric_success(mcp_server) -> None:
+    """Happy path: only the target metric is changed, others sent as stubs."""
+    target = make_metric(metric_id=10, metric_name="count")
+    other = make_metric(
+        metric_id=11,
+        metric_name="sum_revenue",
+        uuid="b2c3d4e5-6789-01bc-def0-234567890abc",
+        expression="SUM(revenue)",
+    )
+    dataset = make_dataset(dataset_id=1, metrics=[target, other])
+
+    updated_target = make_metric(
+        metric_id=10, metric_name="count", expression="COUNT(1)", d3format=",d"
+    )
+    updated_dataset = make_dataset(dataset_id=1, metrics=[updated_target, 
other])
+
+    mock_command = MagicMock()
+    mock_command.run.return_value = updated_dataset
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            return_value=mock_command,
+        ) as command_cls,
+        patch(
+            "superset.mcp_service.utils.url_utils.get_superset_base_url",
+            return_value="http://localhost:8088";,
+        ),
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "count",
+                        "expression": "COUNT(1)",
+                        "d3format": ",d",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    command_cls.assert_called_once_with(
+        1,
+        {
+            "metrics": [
+                {
+                    "id": 10,
+                    "metric_name": "count",
+                    "expression": "COUNT(1)",
+                    "d3format": ",d",
+                },
+                {"id": 11, "metric_name": "sum_revenue"},
+            ]
+        },
+    )
+    assert data["error"] is None
+    assert data["dataset_id"] == 1
+    assert data["dataset_name"] == "my_table"
+    assert data["updated_properties"] == ["d3format", "expression"]
+    assert data["metric"]["id"] == 10
+    assert data["metric"]["expression"] == _wrapped("COUNT(1)")
+    assert data["metric"]["d3format"] == ",d"
+    assert "datasource_id=1" in data["url"]
+
+
[email protected]
+async def test_update_dataset_metric_returns_extra(mcp_server) -> None:
+    """`extra` is an updatable property, so it is echoed back in the 
response."""
+    dataset = make_dataset(dataset_id=1, metrics=[make_metric(metric_id=10)])
+    updated = make_dataset(
+        dataset_id=1,
+        metrics=[make_metric(metric_id=10, extra='{"warning_markdown": 
"note"}')],
+    )
+    mock_command = MagicMock()
+    mock_command.run.return_value = updated
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            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:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": 10,
+                        "extra": '{"warning_markdown": "note"}',
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["error"] is None
+    assert data["updated_properties"] == ["extra"]
+    assert data["metric"]["extra"] == _wrapped('{"warning_markdown": "note"}')
+
+
[email protected]
+async def test_update_dataset_metric_by_id_and_uuid(mcp_server) -> None:
+    """The metric can be addressed by numeric ID (also as string) or UUID."""
+    target = make_metric(metric_id=10, metric_name="count")
+    dataset = make_dataset(dataset_id=1, metrics=[target])
+
+    mock_command = MagicMock()
+    mock_command.run.return_value = dataset
+
+    for identifier in (10, "10", "A1B2C3D4-5678-90ab-cdef-1234567890ab"):
+        mock_command.reset_mock()
+        with (
+            patch(
+                "superset.daos.dataset.DatasetDAO.find_by_id",
+                return_value=dataset,
+            ),
+            patch(
+                "superset.commands.dataset.update.UpdateDatasetCommand",
+                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:
+                result = await client.call_tool(
+                    "update_dataset_metric",
+                    {
+                        "request": {
+                            "dataset_id": 1,
+                            "metric": identifier,
+                            "verbose_name": "Count",
+                        }
+                    },
+                )
+                data = json.loads(result.content[0].text)
+
+        assert data["error"] is None, identifier
+        mock_command.run.assert_called_once()
+
+
[email protected]
+async def test_update_dataset_metric_not_found_suggests_names(mcp_server) -> 
None:
+    dataset = make_dataset(
+        dataset_id=1, metrics=[make_metric(metric_id=10, 
metric_name="sum_revenue")]
+    )
+
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=dataset,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "sum_revenu",
+                        "expression": "SUM(net_revenue)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "not found" in data["error"]
+    assert "sum_revenue" in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_not_found_escapes_names(mcp_server) -> 
None:
+    """Metric names in the not-found error are escaped like the success 
path."""
+    from superset.mcp_service.utils.sanitization import (
+        LLM_CONTEXT_ESCAPED_OPEN_DELIMITER,
+    )
+
+    hostile_name = f"{LLM_CONTEXT_OPEN_DELIMITER}evil"
+    dataset = make_dataset(
+        dataset_id=1, metrics=[make_metric(metric_id=10, 
metric_name=hostile_name)]
+    )
+
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=dataset,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "missing",
+                        "expression": "COUNT(1)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert LLM_CONTEXT_OPEN_DELIMITER not in data["error"]
+    assert LLM_CONTEXT_ESCAPED_OPEN_DELIMITER in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_dataset_not_found(mcp_server) -> None:
+    with patch(
+        "superset.daos.dataset.DatasetDAO.find_by_id",
+        return_value=None,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 999,
+                        "metric": "count",
+                        "description": "desc",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "No dataset found" in data["error"]
+
+
[email protected]
+async def test_update_dataset_metric_forbidden_non_owner(
+    mcp_server, allow_ownership
+) -> None:
+    """A non-owner is rejected before the metric list is inspected, so the
+    error cannot be used to enumerate metric names."""
+    from superset.exceptions import SupersetSecurityException
+
+    allow_ownership.side_effect = SupersetSecurityException(
+        MagicMock(message="not an owner")
+    )
+
+    dataset = make_dataset(
+        dataset_id=1,
+        metrics=[make_metric(metric_id=10, metric_name="secret_metric")],
+    )
+    mock_command = MagicMock()
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id",
+            return_value=dataset,
+        ),
+        patch(
+            "superset.commands.dataset.update.UpdateDatasetCommand",
+            return_value=mock_command,
+        ) as command_cls,
+    ):
+        async with Client(mcp_server) as client:
+            result = await client.call_tool(
+                "update_dataset_metric",
+                {
+                    "request": {
+                        "dataset_id": 1,
+                        "metric": "does_not_exist",
+                        "expression": "COUNT(1)",
+                    }
+                },
+            )
+            data = json.loads(result.content[0].text)
+
+    assert data["metric"] is None
+    assert "owner" in data["error"]
+    # No metric names leak, and the command is never constructed/run.
+    assert "secret_metric" not in data["error"]
+    command_cls.assert_not_called()
+
+
[email protected]
+async def test_update_dataset_metric_invalid_error(mcp_server) -> None:

Review Comment:
   **Suggestion:** Add a type annotation to the fixture argument in this test 
function signature. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This test function has an untyped fixture parameter `mcp_server`, so the 
suggestion identifies a real missing type hint.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=646ed3cd4e164ed5bd7899e12cfa1826&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=646ed3cd4e164ed5bd7899e12cfa1826&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <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_update_dataset_metric.py
   **Line:** 463:463
   **Comment:**
        *Custom Rule: Add a type annotation to the fixture argument in this 
test function signature.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=f6efdf4470eb0adf1c1b72566f6f676550a51ea3026e8f1bab643727efec9e30&reaction=like'>๐Ÿ‘</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40975&comment_hash=f6efdf4470eb0adf1c1b72566f6f676550a51ea3026e8f1bab643727efec9e30&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]


Reply via email to