|
| 1 | +"""Loading and matching of per-endpoint style-rule exceptions (waivers). |
| 2 | +
|
| 3 | +An exceptions file lets an operator waive a specific style requirement for a |
| 4 | +specific endpoint when it legitimately cannot comply. Waived rules are passed to |
| 5 | +the scorer so they are excluded from the P0/P1/P2 counts and surfaced separately |
| 6 | +in the feedback. |
| 7 | +
|
| 8 | +File schema (see ``datasets/mcp_readability/exceptions.yaml``):: |
| 9 | +
|
| 10 | + exceptions: |
| 11 | + - product_name: "Cloud SQL" # any of product_name / endpoint_type |
| 12 | + rule_id: "tool-names" |
| 13 | + reason: "..." |
| 14 | + - endpoint_type: AUTOPUSH # "*" or omitted field = match-all |
| 15 | + rule_id: "use-enums" |
| 16 | + reason: "..." |
| 17 | +""" |
| 18 | + |
| 19 | +import logging |
| 20 | +from util.config import load_yaml_config |
| 21 | + |
| 22 | + |
| 23 | +def load_exceptions(path: str) -> list[dict]: |
| 24 | + """Load the exceptions list from a YAML file. Missing/empty -> [].""" |
| 25 | + if not path: |
| 26 | + return [] |
| 27 | + parsed = load_yaml_config(path) |
| 28 | + if not parsed: |
| 29 | + return [] |
| 30 | + exceptions = parsed.get("exceptions") or [] |
| 31 | + if not isinstance(exceptions, list): |
| 32 | + logging.warning( |
| 33 | + "mcp_readability: 'exceptions' in %s is not a list; ignoring.", path |
| 34 | + ) |
| 35 | + return [] |
| 36 | + return exceptions |
| 37 | + |
| 38 | + |
| 39 | +def _matches(field_value, exception_value) -> bool: |
| 40 | + """A matcher field matches when it is absent, '*', or equal (case-insensitive).""" |
| 41 | + if exception_value is None or exception_value == "*": |
| 42 | + return True |
| 43 | + if field_value is None: |
| 44 | + return False |
| 45 | + return str(field_value).strip().lower() == str(exception_value).strip().lower() |
| 46 | + |
| 47 | + |
| 48 | +def applicable_exceptions(endpoint: dict, all_exceptions: list[dict]) -> list[dict]: |
| 49 | + """Return exceptions whose matchers all apply to ``endpoint``. |
| 50 | +
|
| 51 | + Matchers considered: ``product_name`` and ``endpoint_type`` (the endpoint's |
| 52 | + identity in #469's ``endpoints.yaml``). Each exception keeps its ``rule_id`` |
| 53 | + and ``reason`` for the scorer prompt. |
| 54 | + """ |
| 55 | + matched = [] |
| 56 | + for exc in all_exceptions: |
| 57 | + if not isinstance(exc, dict): |
| 58 | + continue |
| 59 | + if not exc.get("rule_id"): |
| 60 | + continue |
| 61 | + if ( |
| 62 | + _matches(endpoint.get("product_name"), exc.get("product_name")) |
| 63 | + and _matches(endpoint.get("endpoint_type"), exc.get("endpoint_type")) |
| 64 | + ): |
| 65 | + matched.append( |
| 66 | + { |
| 67 | + "rule_id": exc.get("rule_id"), |
| 68 | + "reason": exc.get("reason", ""), |
| 69 | + } |
| 70 | + ) |
| 71 | + return matched |
0 commit comments