You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "aminghadersohi (via GitHub)" <gi...@apache.org> on 2026/02/10 19:16:49 UTC

[PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

aminghadersohi opened a new pull request, #37859:
URL: https://github.com/apache/superset/pull/37859

   ### SUMMARY
   
   Adds two layers of observability instrumentation to MCP tool calls, matching the patterns used across Superset's REST API endpoints:
   
   **Layer 1 — Middleware duration tracking for ALL tool calls:**
   - Restructured `LoggingMiddleware` to use `on_call_tool()` (wraps execution) instead of only `on_message()` (fires before execution)
   - Tool calls now record `duration_ms` (was `None`) and `success` status in the audit log
   - `on_message()` retained for non-tool traffic (resource reads, prompts)
   
   **Layer 2 — Sub-operation timing inside 7 complex tools:**
   - Added `event_logger.log_context(action="mcp.<tool>.<phase>")` blocks that automatically measure duration and write `Log` rows
   - **generate_chart**: validation, dataset_lookup, db_write, form_data_cache, preview (5 phases)
   - **get_chart_data**: chart_lookup, query_execution, format_conversion (3 phases)
   - **get_chart_preview**: chart_lookup, preview_generation, metadata (3 phases)
   - **execute_sql**: db_validation, query_execution, response_conversion (3 phases)
   - **generate_dashboard**: chart_validation, layout, db_write (3 phases)
   - **update_chart**: chart_lookup, db_write, preview (3 phases)
   - **add_chart_to_existing_dashboard**: validation, layout, db_write (3 phases)
   
   12 simpler tools (list_*, get_*_info, get_schema, health_check, etc.) get automatic duration tracking from the middleware layer without per-tool changes.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   N/A — observability-only change, no UI impact.
   
   ### TESTING INSTRUCTIONS
   1. Start the MCP service
   2. Call any MCP tool (e.g., `list_charts`, `generate_chart`)
   3. Check the Superset `logs` table for `mcp_tool_call` action entries — they should now have `duration_ms` populated and `success` in the curated payload
   4. For complex tools, check for sub-operation log entries like `mcp.generate_chart.validation`, `mcp.execute_sql.query_execution`, etc.
   
   ### ADDITIONAL INFORMATION
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API
   - [ ] Removes existing feature or API


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37859:
URL: https://github.com/apache/superset/pull/37859#issuecomment-3886256125

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "Antonio-RiveroMartnez (via GitHub)" <gi...@apache.org>.
Antonio-RiveroMartnez merged PR #37859:
URL: https://github.com/apache/superset/pull/37859


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37859:
URL: https://github.com/apache/superset/pull/37859#issuecomment-3880615989

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #37859:
URL: https://github.com/apache/superset/pull/37859#issuecomment-3880199231

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | 51a288195d8f0fce914c84c5a467478b9fc96981 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/698b8422ab70a20007350937 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-37859--superset-docs-preview.netlify.app](https://deploy-preview-37859--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTM3ODU5LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.GJpUzMmUbpIeytEP-VKlYCu79EIowyVnbLlSNZcel2s)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-37859--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #37859:
URL: https://github.com/apache/superset/pull/37859#issuecomment-3880255969

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/37859?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `0%` with `27 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 64.78%. Comparing base ([`76aa91f`](https://app.codecov.io/gh/apache/superset/commit/76aa91f5ea23fcf0d51532d80c50db2686edadef?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`51a2881`](https://app.codecov.io/gh/apache/superset/commit/51a288195d8f0fce914c84c5a467478b9fc96981?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 2 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/37859?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/mcp\_service/middleware.py](https://app.codecov.io/gh/apache/superset/pull/37859?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fmiddleware.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvbWlkZGxld2FyZS5weQ==) | 0.00% | [16 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/37859?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/mcp\_service/sql\_lab/tool/execute\_sql.py](https://app.codecov.io/gh/apache/superset/pull/37859?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fsql_lab%2Ftool%2Fexecute_sql.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2Uvc3FsX2xhYi90b29sL2V4ZWN1dGVfc3FsLnB5) | 0.00% | [11 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/37859?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff             @@
   ##           master   #37859       +/-   ##
   ===========================================
   + Coverage        0   64.78%   +64.78%     
   ===========================================
     Files           0      668      +668     
     Lines           0    51306    +51306     
     Branches        0     5773     +5773     
   ===========================================
   + Hits            0    33241    +33241     
   - Misses          0    16672    +16672     
   - Partials        0     1393     +1393     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/37859/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/37859/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `64.64% <0.00%> (?)` | |
   | [python](https://app.codecov.io/gh/apache/superset/pull/37859/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `64.76% <0.00%> (?)` | |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/37859/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `64.23% <0.00%> (?)` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/37859?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #37859:
URL: https://github.com/apache/superset/pull/37859#discussion_r2789925839


##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -1807,66 +1808,72 @@ async def _get_chart_preview_internal(  # noqa: C901
         from superset.daos.chart import ChartDAO
 
         # Find the chart
-        chart: Any = None
-        if isinstance(request.identifier, int) or (
-            isinstance(request.identifier, str) and request.identifier.isdigit()
-        ):
-            chart_id = (
-                int(request.identifier)
-                if isinstance(request.identifier, str)
-                else request.identifier
-            )
-            await ctx.debug(
-                "Performing ID-based chart lookup: chart_id=%s" % (chart_id,)
-            )
-            chart = ChartDAO.find_by_id(chart_id)
-        else:
-            await ctx.debug(
-                "Performing UUID-based chart lookup: uuid=%s" % (request.identifier,)
-            )
-            # Try UUID lookup using DAO flexible method
-            chart = ChartDAO.find_by_id(request.identifier, id_column="uuid")
-
-            # If not found and looks like a form_data_key, try to create transient chart
-            if (
-                not chart
-                and isinstance(request.identifier, str)
-                and len(request.identifier) > 8
+        with event_logger.log_context(action="mcp.get_chart_preview.chart_lookup"):
+            chart: Any = None
+            if isinstance(request.identifier, int) or (
+                isinstance(request.identifier, str) and request.identifier.isdigit()
             ):
-                # This might be a form_data_key, try to get form data from cache
-                from superset.commands.explore.form_data.get import GetFormDataCommand
-                from superset.commands.explore.form_data.parameters import (
-                    CommandParameters,
+                chart_id = (
+                    int(request.identifier)
+                    if isinstance(request.identifier, str)
+                    else request.identifier
                 )
-
-                try:
-                    cmd_params = CommandParameters(key=request.identifier)
-                    cmd = GetFormDataCommand(cmd_params)
-                    form_data_json = cmd.run()
-                    if form_data_json:
-                        from superset.utils import json as utils_json
-
-                        form_data = utils_json.loads(form_data_json)
-
-                        # Create a transient chart object from form data
-                        class TransientChart:
-                            def __init__(self, form_data: Dict[str, Any]):
-                                self.id = None
-                                self.slice_name = "Unsaved Chart Preview"
-                                self.viz_type = form_data.get("viz_type", "table")
-                                self.datasource_id = None
-                                self.datasource_type = "table"
-                                self.params = utils_json.dumps(form_data)
-                                self.form_data = form_data
-                                self.uuid = None
-
-                        chart = TransientChart(form_data)
-                except Exception as e:
-                    # Form data key not found or invalid
-                    logger.debug(
-                        "Failed to get form data for key %s: %s", request.identifier, e
+                await ctx.debug(
+                    "Performing ID-based chart lookup: chart_id=%s" % (chart_id,)
+                )
+                chart = ChartDAO.find_by_id(chart_id)
+            else:
+                await ctx.debug(
+                    "Performing UUID-based chart lookup: uuid=%s"
+                    % (request.identifier,)
+                )
+                # Try UUID lookup using DAO flexible method
+                chart = ChartDAO.find_by_id(request.identifier, id_column="uuid")
+
+                # If not found and looks like a form_data_key, try transient
+                if (
+                    not chart
+                    and isinstance(request.identifier, str)
+                    and len(request.identifier) > 8
+                ):
+                    # This might be a form_data_key
+                    from superset.commands.explore.form_data.get import (
+                        GetFormDataCommand,
+                    )
+                    from superset.commands.explore.form_data.parameters import (
+                        CommandParameters,
                     )
 
+                    try:
+                        cmd_params = CommandParameters(key=request.identifier)
+                        cmd = GetFormDataCommand(cmd_params)
+                        form_data_json = cmd.run()
+                        if form_data_json:
+                            from superset.utils import json as utils_json
+
+                            form_data = utils_json.loads(form_data_json)
+
+                            # Create a transient chart object from form data
+                            class TransientChart:
+                                def __init__(self, form_data: Dict[str, Any]):
+                                    self.id = None
+                                    self.slice_name = "Unsaved Chart Preview"
+                                    self.viz_type = form_data.get("viz_type", "table")
+                                    self.datasource_id = None
+                                    self.datasource_type = "table"
+                                    self.params = utils_json.dumps(form_data)
+                                    self.form_data = form_data
+                                    self.uuid = None
+
+                            chart = TransientChart(form_data)
+                    except Exception as e:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Avoid catching blind Exception</b></div>
   <div id="fix">
   
   Replace bare `except Exception` with specific exception types (e.g., `except (ValueError, KeyError, AttributeError)`) to catch only expected errors.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
                       except (ValueError, KeyError, AttributeError, TypeError) as e:
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #141cfd</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/mcp_service/middleware.py:
##########
@@ -115,16 +117,76 @@ async def on_message(
             user_id = get_user_id()
         except Exception:
             user_id = None

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Blind exception catch without specificity</b></div>
   <div id="fix">
   
   Replace the bare `Exception` catch on line 118 with a more specific exception type (e.g., `RuntimeError`, `ValueError`) to avoid catching unexpected errors. Multiple similar issues exist on lines 263, 541, 738, 756, and 777.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
           except (RuntimeError, ValueError):
               user_id = None
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #141cfd</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37859:
URL: https://github.com/apache/superset/pull/37859#issuecomment-3880189992

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #37859:
URL: https://github.com/apache/superset/pull/37859#discussion_r2790162890


##########
superset/mcp_service/middleware.py:
##########
@@ -115,16 +117,76 @@ async def on_message(
             user_id = get_user_id()
         except Exception:
             user_id = None

Review Comment:
   <!-- Bito Reply -->
   The fix in middleware.py replaces the broad `except Exception` with `except (RuntimeError, AttributeError)`, matching the specific exceptions `get_user_id()` can throw. This avoids catching unintended errors, improving robustness.
   
   **superset/mcp_service/middleware.py**
   ```
   try:
               user_id = get_user_id()
           except (RuntimeError, AttributeError):
               user_id = None
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37859:
URL: https://github.com/apache/superset/pull/37859#issuecomment-3881343597

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #37859:
URL: https://github.com/apache/superset/pull/37859#issuecomment-3880943001

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #37859:
URL: https://github.com/apache/superset/pull/37859#discussion_r2790156512


##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -1807,66 +1808,72 @@ async def _get_chart_preview_internal(  # noqa: C901
         from superset.daos.chart import ChartDAO
 
         # Find the chart
-        chart: Any = None
-        if isinstance(request.identifier, int) or (
-            isinstance(request.identifier, str) and request.identifier.isdigit()
-        ):
-            chart_id = (
-                int(request.identifier)
-                if isinstance(request.identifier, str)
-                else request.identifier
-            )
-            await ctx.debug(
-                "Performing ID-based chart lookup: chart_id=%s" % (chart_id,)
-            )
-            chart = ChartDAO.find_by_id(chart_id)
-        else:
-            await ctx.debug(
-                "Performing UUID-based chart lookup: uuid=%s" % (request.identifier,)
-            )
-            # Try UUID lookup using DAO flexible method
-            chart = ChartDAO.find_by_id(request.identifier, id_column="uuid")
-
-            # If not found and looks like a form_data_key, try to create transient chart
-            if (
-                not chart
-                and isinstance(request.identifier, str)
-                and len(request.identifier) > 8
+        with event_logger.log_context(action="mcp.get_chart_preview.chart_lookup"):
+            chart: Any = None
+            if isinstance(request.identifier, int) or (
+                isinstance(request.identifier, str) and request.identifier.isdigit()
             ):
-                # This might be a form_data_key, try to get form data from cache
-                from superset.commands.explore.form_data.get import GetFormDataCommand
-                from superset.commands.explore.form_data.parameters import (
-                    CommandParameters,
+                chart_id = (
+                    int(request.identifier)
+                    if isinstance(request.identifier, str)
+                    else request.identifier
                 )
-
-                try:
-                    cmd_params = CommandParameters(key=request.identifier)
-                    cmd = GetFormDataCommand(cmd_params)
-                    form_data_json = cmd.run()
-                    if form_data_json:
-                        from superset.utils import json as utils_json
-
-                        form_data = utils_json.loads(form_data_json)
-
-                        # Create a transient chart object from form data
-                        class TransientChart:
-                            def __init__(self, form_data: Dict[str, Any]):
-                                self.id = None
-                                self.slice_name = "Unsaved Chart Preview"
-                                self.viz_type = form_data.get("viz_type", "table")
-                                self.datasource_id = None
-                                self.datasource_type = "table"
-                                self.params = utils_json.dumps(form_data)
-                                self.form_data = form_data
-                                self.uuid = None
-
-                        chart = TransientChart(form_data)
-                except Exception as e:
-                    # Form data key not found or invalid
-                    logger.debug(
-                        "Failed to get form data for key %s: %s", request.identifier, e
+                await ctx.debug(
+                    "Performing ID-based chart lookup: chart_id=%s" % (chart_id,)
+                )
+                chart = ChartDAO.find_by_id(chart_id)
+            else:
+                await ctx.debug(
+                    "Performing UUID-based chart lookup: uuid=%s"
+                    % (request.identifier,)
+                )
+                # Try UUID lookup using DAO flexible method
+                chart = ChartDAO.find_by_id(request.identifier, id_column="uuid")
+
+                # If not found and looks like a form_data_key, try transient
+                if (
+                    not chart
+                    and isinstance(request.identifier, str)
+                    and len(request.identifier) > 8
+                ):
+                    # This might be a form_data_key
+                    from superset.commands.explore.form_data.get import (
+                        GetFormDataCommand,
+                    )
+                    from superset.commands.explore.form_data.parameters import (
+                        CommandParameters,
                     )
 
+                    try:
+                        cmd_params = CommandParameters(key=request.identifier)
+                        cmd = GetFormDataCommand(cmd_params)
+                        form_data_json = cmd.run()
+                        if form_data_json:
+                            from superset.utils import json as utils_json
+
+                            form_data = utils_json.loads(form_data_json)
+
+                            # Create a transient chart object from form data
+                            class TransientChart:
+                                def __init__(self, form_data: Dict[str, Any]):
+                                    self.id = None
+                                    self.slice_name = "Unsaved Chart Preview"
+                                    self.viz_type = form_data.get("viz_type", "table")
+                                    self.datasource_id = None
+                                    self.datasource_type = "table"
+                                    self.params = utils_json.dumps(form_data)
+                                    self.form_data = form_data
+                                    self.uuid = None
+
+                            chart = TransientChart(form_data)
+                    except Exception as e:

Review Comment:
   Fixed in 4ec8ba5. Replaced blind `except Exception` with `except (ValueError, KeyError, AttributeError, TypeError)` to catch only the specific exceptions that `GetFormDataCommand.run()`, JSON parsing, and dict/attribute access can throw.



##########
superset/mcp_service/middleware.py:
##########
@@ -115,16 +117,76 @@ async def on_message(
             user_id = get_user_id()
         except Exception:
             user_id = None

Review Comment:
   Fixed in 4ec8ba5. Replaced `except Exception` with `except (RuntimeError, AttributeError)` — these are the specific exceptions `get_user_id()` can throw (RuntimeError when no Flask request context, AttributeError when `g.user` is missing).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): add event_logger instrumentation to MCP tools [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #37859:
URL: https://github.com/apache/superset/pull/37859#discussion_r2790162093


##########
superset/mcp_service/chart/tool/get_chart_preview.py:
##########
@@ -1807,66 +1808,72 @@ async def _get_chart_preview_internal(  # noqa: C901
         from superset.daos.chart import ChartDAO
 
         # Find the chart
-        chart: Any = None
-        if isinstance(request.identifier, int) or (
-            isinstance(request.identifier, str) and request.identifier.isdigit()
-        ):
-            chart_id = (
-                int(request.identifier)
-                if isinstance(request.identifier, str)
-                else request.identifier
-            )
-            await ctx.debug(
-                "Performing ID-based chart lookup: chart_id=%s" % (chart_id,)
-            )
-            chart = ChartDAO.find_by_id(chart_id)
-        else:
-            await ctx.debug(
-                "Performing UUID-based chart lookup: uuid=%s" % (request.identifier,)
-            )
-            # Try UUID lookup using DAO flexible method
-            chart = ChartDAO.find_by_id(request.identifier, id_column="uuid")
-
-            # If not found and looks like a form_data_key, try to create transient chart
-            if (
-                not chart
-                and isinstance(request.identifier, str)
-                and len(request.identifier) > 8
+        with event_logger.log_context(action="mcp.get_chart_preview.chart_lookup"):
+            chart: Any = None
+            if isinstance(request.identifier, int) or (
+                isinstance(request.identifier, str) and request.identifier.isdigit()
             ):
-                # This might be a form_data_key, try to get form data from cache
-                from superset.commands.explore.form_data.get import GetFormDataCommand
-                from superset.commands.explore.form_data.parameters import (
-                    CommandParameters,
+                chart_id = (
+                    int(request.identifier)
+                    if isinstance(request.identifier, str)
+                    else request.identifier
                 )
-
-                try:
-                    cmd_params = CommandParameters(key=request.identifier)
-                    cmd = GetFormDataCommand(cmd_params)
-                    form_data_json = cmd.run()
-                    if form_data_json:
-                        from superset.utils import json as utils_json
-
-                        form_data = utils_json.loads(form_data_json)
-
-                        # Create a transient chart object from form data
-                        class TransientChart:
-                            def __init__(self, form_data: Dict[str, Any]):
-                                self.id = None
-                                self.slice_name = "Unsaved Chart Preview"
-                                self.viz_type = form_data.get("viz_type", "table")
-                                self.datasource_id = None
-                                self.datasource_type = "table"
-                                self.params = utils_json.dumps(form_data)
-                                self.form_data = form_data
-                                self.uuid = None
-
-                        chart = TransientChart(form_data)
-                except Exception as e:
-                    # Form data key not found or invalid
-                    logger.debug(
-                        "Failed to get form data for key %s: %s", request.identifier, e
+                await ctx.debug(
+                    "Performing ID-based chart lookup: chart_id=%s" % (chart_id,)
+                )
+                chart = ChartDAO.find_by_id(chart_id)
+            else:
+                await ctx.debug(
+                    "Performing UUID-based chart lookup: uuid=%s"
+                    % (request.identifier,)
+                )
+                # Try UUID lookup using DAO flexible method
+                chart = ChartDAO.find_by_id(request.identifier, id_column="uuid")
+
+                # If not found and looks like a form_data_key, try transient
+                if (
+                    not chart
+                    and isinstance(request.identifier, str)
+                    and len(request.identifier) > 8
+                ):
+                    # This might be a form_data_key
+                    from superset.commands.explore.form_data.get import (
+                        GetFormDataCommand,
+                    )
+                    from superset.commands.explore.form_data.parameters import (
+                        CommandParameters,
                     )
 
+                    try:
+                        cmd_params = CommandParameters(key=request.identifier)
+                        cmd = GetFormDataCommand(cmd_params)
+                        form_data_json = cmd.run()
+                        if form_data_json:
+                            from superset.utils import json as utils_json
+
+                            form_data = utils_json.loads(form_data_json)
+
+                            # Create a transient chart object from form data
+                            class TransientChart:
+                                def __init__(self, form_data: Dict[str, Any]):
+                                    self.id = None
+                                    self.slice_name = "Unsaved Chart Preview"
+                                    self.viz_type = form_data.get("viz_type", "table")
+                                    self.datasource_id = None
+                                    self.datasource_type = "table"
+                                    self.params = utils_json.dumps(form_data)
+                                    self.form_data = form_data
+                                    self.uuid = None
+
+                            chart = TransientChart(form_data)
+                    except Exception as e:

Review Comment:
   <!-- Bito Reply -->
   The suggestion replaces the broad 'except Exception' with specific exceptions (ValueError, KeyError, AttributeError, TypeError) that match the operations in the try block—GetFormDataCommand.run(), JSON parsing via utils_json.loads(), and dictionary/attribute access—improving error handling by avoiding unintended exception catches and making debugging easier.
   
   **superset/mcp_service/chart/tool/get_chart_preview.py**
   ```
   except (ValueError, KeyError, AttributeError, TypeError) as e:
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org