alexandrusoare commented on code in PR #40975:
URL: https://github.com/apache/superset/pull/40975#discussion_r3552063311


##########
superset/mcp_service/dataset/tool/update_dataset_metric.py:
##########
@@ -0,0 +1,258 @@
+# 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.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:
+    names = [m.metric_name for m in metrics]
+    msg = f"Metric '{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:
+        return f"{msg} Did you mean: {', '.join(suggestions)}?"
+    return f"{msg} Available metrics: {', '.join(sorted(names))}."
+
+
+def _serialize_metric(metric: Any) -> DatasetMetricDetail:
+    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"),
+        ),
+    )
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Dataset",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update dataset metric",
+        readOnlyHint=False,
+        destructiveHint=False,
+    ),
+)
+async def update_dataset_metric(
+    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()
+    await ctx.info(
+        "Updating dataset metric: dataset_id=%s, metric=%r, properties=%s"
+        % (request.dataset_id, request.metric, sorted(updates))
+    )
+
+    try:
+        from sqlalchemy.orm import joinedload, subqueryload
+
+        from superset.commands.dataset.exceptions import (
+            DatasetForbiddenError,
+            DatasetInvalidError,
+            DatasetNotFoundError,
+            DatasetUpdateFailedError,
+        )
+        from superset.commands.dataset.update import UpdateDatasetCommand
+        from superset.connectors.sqla.models import SqlaTable
+        from superset.mcp_service.dataset.dataset_utils import resolve_dataset
+        from superset.mcp_service.utils.url_utils import get_superset_base_url
+
+        eager_options = [
+            subqueryload(SqlaTable.metrics),
+            joinedload(SqlaTable.database),
+        ]
+
+        with 
event_logger.log_context(action="mcp.update_dataset_metric.lookup"):
+            dataset = resolve_dataset(request.dataset_id, eager_options)
+
+        if dataset is None:
+            await ctx.warning("Dataset not found: %s" % (request.dataset_id,))
+            return UpdateDatasetMetricResponse(
+                error=(
+                    f"No dataset found with identifier: {request.dataset_id}."
+                    " Use list_datasets to get valid dataset IDs."
+                ),
+            )
+
+        metrics = list(dataset.metrics)
+        target = _find_metric(metrics, request.metric)
+        if target is None:
+            message = _metric_not_found_message(metrics, request.metric)
+            await ctx.warning("Metric not found: %s" % (request.metric,))
+            return UpdateDatasetMetricResponse(
+                dataset_id=dataset.id,
+                dataset_name=dataset.table_name,
+                error=message,
+            )

Review Comment:
   THis seems relevant



-- 
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