Repository navigation
fix(mcp): relax column name regex, improve generate_chart validation errors and examples - #39915
aminghadersohi wants to merge 15 commits into
Conversation
…errors and examples - Remove overly strict regex pattern from ColumnRef.name, FilterConfig.column, and BigNumberChartConfig.temporal_column — sanitize_name/sanitize_column already handle XSS/SQL injection; the pattern rejected valid column names like "1Q_revenue" (digit-prefixed) or "order-date" (hyphenated) - Extend generate_chart docstring with usage examples for all supported chart types: pie, big_number (with/without trendline), pivot_table, mixed_timeseries, handlebars - Improve _enhance_validation_error fallback in SchemaValidator to produce type-specific, actionable messages instead of raw pydantic error strings (extract _format_single_error helper to reduce cyclomatic complexity) - Add tests verifying digit-prefixed/hyphenated column names now pass, and that XSS/SQL injection is still blocked by sanitize_name()
- FilterConfig.column: add check_sql_keywords=True to sanitize_column (Copilot review: sanitize_column was missing SQL keyword checking) - BigNumberChartConfig.temporal_column: add sanitize_temporal_column field_validator using sanitize_user_input with check_sql_keywords=True (Copilot review: no validator after regex removal left field unprotected) - generate_chart docstring IMPORTANT: list all chart types, not just xy/table (Copilot review: IMPORTANT section was misleading after adding more examples) - Fix test_xss_attempt_blocked: nh3 strips HTML tags instead of rejecting, so rename to test_xss_tags_are_stripped (asserts tag is removed) and add test_event_handler_injection_blocked (on...= patterns ARE rejected) - Fix _format_single_error literal_error: preserve pydantic 'Input should be' message instead of replacing with custom format (broke existing test test_non_value_error_pydantic_body_is_surfaced) - Add test_sql_injection_in_filter_column_blocked to verify FilterConfig now rejects SQL injection column names
- Remove unused 'type: ignore[return-value]' from sanitize_temporal_column (mypy correctly infers the return type; comment was unnecessary) - Fix test_xss_tags_are_stripped → test_script_tag_blocked: nh3 strips the entire script element including its content, leaving an empty string that the allow_empty=False guard then rejects with ValidationError
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
…ner text nh3.clean() removes HTML tag delimiters but preserves the text content between them, so '<script>alert(1)</script>' becomes 'alert(1)' rather than an empty string. Update the test to assert the tag is stripped (not that a ValidationError is raised).
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #39915 +/- ##
==========================================
- Coverage 64.37% 63.91% -0.46%
==========================================
Files 2569 2584 +15
Lines 134745 136897 +2152
Branches 31278 31560 +282
==========================================
+ Hits 86739 87504 +765
- Misses 46508 47868 +1360
- Partials 1498 1525 +27
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
nh3 behavior for '<script>alert(1)</script>' varies by version: - some versions strip entire element (empty → ValidationError) - others strip only tag delimiters (preserving 'alert(1)') Accept both outcomes: no ValidationError means no <script> tag stored.
There was a problem hiding this comment.
Pull request overview
This PR improves the MCP generate_chart tool’s usability by loosening overly-restrictive column-name validation while keeping (and in some places strengthening) sanitization-based security checks. It also expands tool documentation examples and makes schema validation errors more actionable.
Changes:
- Removed strict regex constraints on several column-name fields and added/strengthened sanitization validators (
check_sql_keywords=True), including a new validator forBigNumberChartConfig.temporal_column. - Improved schema validation error formatting by extracting
_format_single_errorand surfacing more actionable messages/suggestions. - Added unit tests covering relaxed column-name acceptance plus XSS/event-handler/SQL-injection blocking; expanded
generate_chartdocstring examples to cover all supported chart types.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
superset/mcp_service/chart/schemas.py |
Removes regex patterns from column-related fields; strengthens sanitization for filter and temporal columns. |
superset/mcp_service/chart/validation/schema_validator.py |
Refactors validation error enhancement to format per-error messages and suggestions. |
superset/mcp_service/chart/tool/generate_chart.py |
Updates generate_chart tool docstring to list supported chart types and provide examples. |
tests/unit_tests/mcp_service/chart/test_chart_schemas.py |
Adds tests verifying relaxed column-name handling and continued XSS/SQLi protections. |
…n comment - schema_validator.py: _format_single_error string_pattern_mismatch branch used column-name-specific wording; generalize to apply to any pattern- constrained field - schemas.py: FilterConfig.column comment referenced sanitize_name() but that field is validated by sanitize_column(); correct the name
…ttern Instead of hardcoding the error message for string_pattern_mismatch errors, extract the actual regex pattern from Pydantic's error context (err["ctx"]["pattern"]) and include it in the message dynamically. This gives callers the exact pattern they need to satisfy rather than a generic hint.
Code Review Agent Run #6e566aActionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
fitzee
left a comment
There was a problem hiding this comment.
Griffen Review — LGTM with nits
Note: Codex review unavailable — Griffen-only verdict below. (Known infrastructure gap.)
Context
Sources consulted: PR description, diff, sanitize_user_input implementation (superset/mcp_service/utils/sanitization.py, master), ColumnRef.sanitize_name on master (schemas.py:721).
No linked Shortcut story or GitHub issue. Reviewed on PR description alone.
Intent: Remove over-restrictive column name regex from ColumnRef.name, FilterConfig.column, and BigNumberChartConfig.temporal_column — the regex broke real-world column names (digit-prefixed, hyphenated) — and replace it with check_sql_keywords=True sanitization that provides equivalent or stronger protection. (PR description)
Door Classification
Two-way door.
Rollback complexity: Simple — restore three pattern= field arguments.
Blast radius: MCP generate_chart tool only.
Deployment reversible: Yes, unconditionally.
Security Baseline — What Actually Changed
The load-bearing question is whether the sanitizer covers what the regex covered. Before and after for each field:
| Field | Before | After |
|---|---|---|
ColumnRef.name |
regex + sanitize_name(check_sql_keywords=True) |
sanitize_name(check_sql_keywords=True) — regex dropped, no other change |
FilterConfig.column |
regex + sanitize_column(no check_sql_keywords) |
sanitize_column(check_sql_keywords=True) — regex dropped, SQL check added |
BigNumberChartConfig.temporal_column |
regex only, no sanitizer at all | new sanitize_temporal_column(check_sql_keywords=True) — regex dropped, sanitizer added |
ColumnRef.name is security-neutral (already had the SQL check on master). FilterConfig.column and temporal_column are strictly better: the regex was the only protection on those fields, and it was wrong — it allows SQL keywords (SELECT name FROM users is alphanumeric + spaces, passes the regex) while blocking valid column names (order-date, 1Q_revenue).
sanitize_user_input with check_sql_keywords=True enforces: nh3 HTML stripping (XSS), URL scheme blocking, event handler patterns (on\w+=), SQL DDL/DML keywords, shell metacharacters, and SQL comments. Stronger guarantees than the regex provided.
The PR description's claim that sanitization "already blocks XSS and SQL injection" is accurate for ColumnRef.name (which had it). For the other two — this PR is what adds the protection.
Medium / Low Findings
LOW — string_pattern_mismatch branch in _format_single_error is now unreachable for the three affected fields
The branch exists for other fields in the schema that still carry regex patterns, so it's not dead code. But with the three main column-name fields now pattern-free, it won't be hit through the primary user path. No correctness issue.
Mitigation: Verify other pattern-bearing fields still exist, or document the branch serves them explicitly.
NIT — test_script_tag_neutralized has a bare except: pass (test_chart_schemas.py:814)
The comment correctly explains the nh3 version variance. But pass also silently swallows ValidationErrors raised for unexpected reasons, making the test vacuously passing in failure modes.
Mitigation: In the except block, assert the specific error message — e.g. assert "cannot be empty" in str(exc_info.value) — so the test fails explicitly if the error comes from somewhere other than the empty-value guard.
NIT — literal_error and missing branches in _format_single_error not covered by tests
Pure formatting branches, no security implications. Coverage gap only.
Architectural Read
The PR makes the right structural move. A regex on a column name field was doing two jobs poorly: format enforcement (rejecting valid names) and security (allowing SQL keywords that happen to be alphanumeric). Replacing it with a purpose-built sanitizer separates those concerns correctly.
The three column-name fields now share a consistent security contract — nh3 + SQL keyword check. Previously they were inconsistent: one had it, one had a weaker version, one had only a regex.
_format_single_error is a clean extraction. The cyclomatic complexity reduction is real; the dict.fromkeys() deduplication in suggestions is the right pattern. Docstring examples are load-bearing in MCP tool descriptions — including them for all seven chart types is the right call.
Trajectory note: as chart types expand, the inline examples will grow proportionally. At some point a schema inspection tool (get_chart_schema?) will be preferable to embedding all examples in the docstring. Not a current problem.
Verdict: LGTM with nits. The security model is correct and actually stronger than what's being replaced. The nits are all in test quality and coverage — none are blockers.
Griffen + Codex Synthesis — LGTM with nitsDual Review SynthesisGriffen verdict: LGTM with nits Where they agreed
Where they divergedCodex MEDIUM: relaxed punctuation acceptance (Hypothesis) Griffen's read: this is a pre-existing architectural property, not a regression introduced here. The correct invariant is quoting at SQL generation, not format restriction at schema validation. A regex that blocks Standout findings (caught by one, missed by the other)LOW — Test suite doesn't cover the actual regression (Codex caught, Griffen missed) LOW — Griffen's final callLGTM with nits. The security model is sound and net-positive. The two LOWs above are real but not blockers — they're documentation and test coverage gaps, not correctness failures. The MEDIUM hypothesis about downstream quoting is worth tracking architecturally but doesn't change anything in this PR. Nits to address before or after merge (none are blockers):
|
…rage - test_script_tag_neutralized: replace bare except/pass with assertion that the ValidationError message contains "cannot be empty", making the test version-agnostic while still failing if neither expected outcome occurs - TestFormatSingleError: cover the 'missing' and 'literal_error' branches of SchemaValidator._format_single_error which had no direct unit tests
…ertion - Add docstrings to test_name_with_hyphen_accepted, test_name_with_dot_accepted, test_name_with_spaces_accepted, test_xy_chart_with_hyphenated_column - In test_script_tag_neutralized success path, assert col.name is non-empty so a future nh3 regression that returns "" without raising cannot mask the validation bug
…_user_input nh3 can strip entire elements (e.g. <script>alert(1)</script> → ""), leaving an empty string that bypassed the pre-strip emptiness check. Add a post-strip guard so sanitize_user_input raises ValueError when the result is empty after HTML sanitization, regardless of nh3 version behavior. Also shorten test docstring to satisfy E501 (88-char line limit).
… locale tests - sanitize_user_input: add final emptiness check after _remove_dangerous_unicode so zero-width-only inputs raise ValueError instead of silently returning "" - test_sanitize_user_input_xss_entity_encoded: make version-agnostic (try/except) because nh3 may strip to "" (new guard raises) or preserve inner text - add test_sanitize_user_input_zero_width_only_raises and _allow_empty_returns_none - test_chart_schemas: add TestBigNumberTemporalColumnRelaxedPattern (3 tests) covering digit-prefixed, hyphenated, and SQL-injection temporal_column inputs - test_chart_schemas: add TestLocaleColumnNamesAccepted (café_revenue, 订单日期)
Merge the None-guard and the empty-after-strip guard into a single check via `(value or '').strip()`. Reduces McCabe complexity from 11 to 9 (ruff C901 limit is 10), with no change in observable behaviour.
fitzee
left a comment
There was a problem hiding this comment.
Griffen Review — fix(mcp): relax column name regex, improve generate_chart validation
Reviewed by Griffen (AI Distinguished Engineer), with Matt Fitzgerald. Reach out to Matt directly if anything needs clarifying.
Context
Sources consulted: PR description, diff, existing review comments (Copilot, CodeAnt)
Missing context: No linked Shortcut story or GitHub issue — reviewing based on PR description alone.
Intent: Remove an overly strict regex that rejected valid real-world column names (digit-prefixed, hyphenated, locale chars) from the MCP generate_chart validation layer, while tightening sanitization to compensate and improving error messages for LLM clients. (PR description)
Door Classification
Two-way door
| Dimension | Assessment |
|---|---|
| Rollback complexity | Simple — revert restores the regex, removes the new validators, no state to unwind |
| Blast radius | Narrow — scoped entirely to MCP generate_chart validation; no schema migrations, no data mutations, no public REST API surface affected |
| Deployment reversible | Yes — stateless validation logic, no persistence, no protocol change |
| Reversibility mechanisms | Not needed; inherently reversible |
One caveat worth noting: if any external LLM client has been prompted or fine-tuned against the old Pydantic error message text, the improved error messages could silently break that client's error-handling logic. Still a two-way door operationally, but worth keeping in mind if you have clients with hardcoded error-response parsing.
Security
The security story holds — and is improved in one spot.
ColumnRef.sanitize_name()already callssanitize_user_inputwithcheck_sql_keywords=True. Removing the regex doesn't weaken it.FilterConfig.sanitize_column()previously lackedcheck_sql_keywords=True— this PR adds it. Good catch.BigNumberChartConfig.temporal_columnhad no validator at all — this PR addssanitize_temporal_column. Also good.- The old regex provided no security value not already covered by
sanitize_user_input. Removing it is correct.
Findings
[MEDIUM] [Two-way] — test_script_tag_neutralized success branch doesn't assert content
The test's success path asserts col.name is truthy but doesn't check that the sanitized value doesn't still contain alert(1). An input where nh3 strips the tags but preserves the inner text would pass the test while storing an unsanitized payload.
Confidence: Fact (observable in test)
Mitigation: Add assert "alert" not in col.name in the try branch.
[LOW] [Two-way] — Missing XSS/event-handler test for BigNumberChartConfig.temporal_column
TestColumnRefNameRelaxedPattern and TestFilterConfigColumnRelaxedPattern both test XSS and event-handler injection. TestBigNumberTemporalColumnRelaxedPattern only tests SQL injection — the on...= pattern is untested for this field.
Confidence: Fact
Mitigation: Add a test_event_handler_injection_blocked to TestBigNumberTemporalColumnRelaxedPattern.
[NIT] — _format_single_error returns "" for "no suggestion"
Returning an empty string to signal "no suggestion" is implicit; tuple[str, str | None] with None would be self-documenting at the call sites. Minor — the if suggestion: guards handle it correctly as-is.
What's Good
The core design decision is sound: the regex was defense-in-depth theater that blocked legitimate inputs while providing no security value the sanitizers didn't already cover. Removing it and simultaneously adding check_sql_keywords=True to the two fields that were missing it is the right tradeoff — stricter where it matters, more permissive where it was arbitrary.
The sanitize_user_input emptiness check refactor is a genuine improvement. Inputs that reduce to empty after HTML stripping or Unicode normalization previously could slip through; the new post-strip checks close that gap correctly. The new tests (test_sanitize_user_input_zero_width_only_raises, _allow_empty_returns_none) verify the edge cases directly.
The docstring examples for all 7 chart types are the right call for an MCP tool consumed by LLM clients — concrete examples do more work than schema descriptions.
Architectural Read
This is a narrow, well-scoped cleanup. The pattern it follows — rely on explicit sanitizers rather than input-shaping regexes for security, and make the validation layer match the actual security invariant rather than a proxy for it — is the right model for an MCP validation layer that has to handle real-world user data.
No architectural concerns. The two test gaps above are the only things worth addressing before merge.
Verdict: LGTM with nits — the two test gaps are worth fixing but not worth a full review cycle. Core design is sound, merge when ready.
Griffen Review —
|
| Dimension | Assessment |
|---|---|
| Rollback complexity | Simple — revert restores the regex, removes the new validators, no state to unwind |
| Blast radius | Narrow — scoped entirely to MCP generate_chart validation; no schema migrations, no data mutations, no public REST API surface affected |
| Deployment reversible | Yes — stateless validation logic, no persistence, no protocol change |
| Reversibility mechanisms | Not needed; inherently reversible |
One caveat worth noting: if any external LLM client has been prompted or fine-tuned against the old Pydantic error message text, the improved error messages could silently break that client's error-handling logic. Still a two-way door operationally, but worth keeping in mind if you have clients with hardcoded error-response parsing.
Security
The security story holds — and is improved in one spot.
ColumnRef.sanitize_name()already callssanitize_user_inputwithcheck_sql_keywords=True. Removing the regex doesn't weaken it.FilterConfig.sanitize_column()previously lackedcheck_sql_keywords=True— this PR adds it. Good catch.BigNumberChartConfig.temporal_columnhad no validator at all — this PR addssanitize_temporal_column. Also good.- The old regex provided no security value not already covered by
sanitize_user_input. Removing it is correct.
Findings
[MEDIUM] [Two-way] — test_script_tag_neutralized success branch doesn't assert content
The test's success path asserts col.name is truthy but doesn't check that the sanitized value doesn't still contain alert(1). An input where nh3 strips the tags but preserves the inner text would pass the test while storing an unsanitized payload.
Confidence: Fact (observable in test)
Mitigation: Add assert "alert" not in col.name in the try branch.
[LOW] [Two-way] — Missing XSS/event-handler test for BigNumberChartConfig.temporal_column
TestColumnRefNameRelaxedPattern and TestFilterConfigColumnRelaxedPattern both test XSS and event-handler injection. TestBigNumberTemporalColumnRelaxedPattern only tests SQL injection — the on...= pattern is untested for this field.
Confidence: Fact
Mitigation: Add a test_event_handler_injection_blocked to TestBigNumberTemporalColumnRelaxedPattern.
[NIT] — _format_single_error returns "" for "no suggestion"
Returning an empty string to signal "no suggestion" is implicit; tuple[str, str | None] with None would be self-documenting at the call sites. Minor — the if suggestion: guards handle it correctly as-is.
What's Good
The core design decision is sound: the regex was defense-in-depth theater that blocked legitimate inputs while providing no security value the sanitizers didn't already cover. Removing it and simultaneously adding check_sql_keywords=True to the two fields that were missing it is the right tradeoff — stricter where it matters, more permissive where it was arbitrary.
The sanitize_user_input emptiness check refactor is a genuine improvement. Inputs that reduce to empty after HTML stripping or Unicode normalization previously could slip through; the new post-strip checks close that gap correctly.
The docstring examples for all 7 chart types are the right call for an MCP tool consumed by LLM clients — concrete examples do more work than schema descriptions.
Architectural Read
Narrow, well-scoped cleanup. The pattern it follows — rely on explicit sanitizers rather than input-shaping regexes, and make the validation layer match the actual security invariant rather than a proxy for it — is the right model for an MCP validation layer handling real-world data. No architectural concerns.
Verdict: LGTM with nits — the two test gaps are worth fixing but not worth a full review cycle. Core design is sound.
…turn type, event-handler test - test_script_tag_neutralized: add assert "alert" not in col.name in the try branch so payloads where nh3 strips tags but preserves inner text are also caught - _format_single_error: change return type from tuple[str, str] to tuple[str, str | None]; return None instead of "" for no-suggestion branches (literal_error and generic fallback) — more self-documenting at call sites - TestBigNumberTemporalColumnRelaxedPattern: add test_event_handler_injection_blocked to cover the on...= XSS pattern on temporal_column (mirrors existing coverage in TestColumnRefNameRelaxedPattern and TestFilterConfigColumnRelaxedPattern) - schemas.py: document check_sql_keywords=True as a tightening vs master for FilterConfig.column and temporal_column, and note the word-boundary safety (deleted_at/created_date are fine; exact SQL keywords are rejected)
…in _format_single_error
- TestFormatSingleError.test_missing_field_message: add assert suggestion is not None
before the `in` check — mypy correctly flags str|None as invalid right operand for `in`
- test_script_tag_neutralized: remove `assert "alert" not in col.name`; when nh3 strips
only the tags (not the inner text), col.name == "alert(1)" which is plain text and
therefore safe — the assertion was wrong and would fail on those nh3 versions
- _format_single_error: use `ctx = err.get("ctx") or {}` with isinstance guard instead of
`err.get("ctx", {}).get(...)` — Pydantic can return ctx=None explicitly, which would
cause AttributeError on the chained .get() call
Code Review Agent Run #ccf880Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…E001, add _reset_for_testing(), remove exec bits
schemas.py:
- Add @field_validator('temporal_column') on BigNumberChartConfig — the regex removal
in d883b62 left this field with only min/max_length guards; ColumnRef.name and
FilterConfig.column already used sanitize_user_input (check_sql_keywords=True) and
sanitize_user_input respectively, but BigNumberChartConfig.temporal_column was missed.
PR #39915 (relaxing the original regex) was closed; this PR covers the same intent
by relying on sanitize_user_input validators instead.
- serialize_chart_object: split the broad except Exception (BLE001) into ImportError
(for import-failure path) + Exception (for third-party plugin errors) so the scope
of each catch is explicit.
registry.py:
- Add _reset_for_testing() that resets _REGISTRY, _plugins_loaded, _plugins_load_failed,
and _filter_config — gives tests a single clean-slate function instead of four
separate monkeypatches.
- Move _RegistryProxy instantiation to module level (_PROXY); get_registry() returns
the singleton instead of allocating a new object on every call.
file modes:
- Remove executable bits (100755 → 100644) from 9 files: plugin.py, all 7 plugin
files, registry.py, and initialization/__init__.py.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Summary
Addresses validation rigidity in the
generate_chartMCP tool that caused unnecessary failures when using valid but unconventionally-named columns.Changes:
Relax column name regex — Remove the
pattern=r"^[a-zA-Z0-9_][a-zA-Z0-9_\s\-\.]*$"constraint fromColumnRef.name,FilterConfig.column, andBigNumberChartConfig.temporal_column. Many real-world column names (digit-prefixed like1Q_revenue, hyphenated likeorder-date) were silently rejected with cryptic pydantic errors. The existingsanitize_name()/sanitize_column()validators already block XSS and SQL injection — the regex added no security value and only hurt usability.Add
sanitize_temporal_columnvalidator —BigNumberChartConfig.temporal_columnnow has a field_validator usingsanitize_user_inputwithcheck_sql_keywords=True, matching the protection level ofColumnRef.sanitize_name.Add
check_sql_keywords=TruetoFilterConfig.sanitize_column— ensures SQL injection patterns are blocked for filter column names.Extend docstring examples — Add
generate_chartusage examples for all supported chart types:pie,big_number(with and without trendline),pivot_table,mixed_timeseries,handlebars. Update IMPORTANT section to list all 7 supported chart types.Improve validation error messages — Extract
_format_single_errorhelper from_enhance_validation_error(reduces cyclomatic complexity) and make the fallback produce type-specific, actionable messages forstring_pattern_mismatch,missing, andvalue_errorpydantic error types.literal_errorpreserves the original pydantic "Input should be ..." message.Tests — New
TestColumnRefNameRelaxedPatternandTestFilterConfigColumnRelaxedPatternclasses verify: digit-prefixed and hyphenated column names now pass; script-tag XSS is blocked (nh3 strips to empty, empty-value guard rejects); event-handler injection is blocked; SQL injection is blocked;FilterConfigSQL injection is blocked.Testing
pytest tests/unit_tests/mcp_service/chart/test_chart_schemas.py -xgenerate_chartwith a column named1Q_revenueororder-datesucceeds