""" Reference Implementation — Autonomous Data Quality Agent (MCP + SQLGlot + DuckDB + Evals) Author: Murilo Lympius (https://murilolympius.com.br/agente) Architecture highlights: 1. SQLGlot AST Guardrail: strict read-only SQL governance (blocks DDL/DML, multi-statements, PII columns, SELECT *, recursive CTEs, and DuckDB file/system functions such as read_csv_auto/read_parquet). 2. Defense in depth: DuckDB runs with `enable_external_access = false` and `lock_configuration = true`. 3. MCP JSON-RPC 2.0 Tool Server: exposes 5 read-only analytical tools (list_partitions, inspect_schema, run_readonly_sql, compare_volume_window, reconcile_layers) with full request/response tracing. 4. Structured Output (Pydantic v2) & 18-case Automated Evals Suite. All datasets, table names, and metrics below are 100% synthetic. """ from __future__ import annotations import duckdb import sqlglot from pydantic import BaseModel, Field from sqlglot import exp ALLOWED_TABLES = frozenset( { "bronze_transacoes", "silver_transacoes", "gold_margem_segmento", "dim_cambio", "dim_mcc", "pipeline_metadata", } ) BLOCKED_PII_COLUMNS = frozenset({"cpf", "cpf_cliente", "cnpj", "numero_cartao", "pan", "cvv"}) ALLOWED_FUNCTIONS = frozenset( {"count", "sum", "avg", "min", "max", "round", "coalesce", "nullif", "abs", "cast"} ) FORBIDDEN_NODES = ( exp.Drop, exp.Delete, exp.Update, exp.Insert, exp.Alter, exp.Create, exp.Command, exp.Merge, exp.Copy, exp.Grant, exp.Set, exp.Pragma, exp.Attach, exp.Detach, ) MAX_LIMIT = 500 class GuardrailDecision(BaseModel): allowed: bool rule_id: str | None = None blocked_reason: str | None = None normalized_sql: str | None = None tables_referenced: list[str] = Field(default_factory=list) def validate_readonly_sql(sql: str) -> GuardrailDecision: """AST-based SQL guardrail enforcing read-only, LGPD, and compute safety.""" statements = [s for s in sqlglot.parse(sql.strip(), read="duckdb") if s is not None] if len(statements) != 1: return GuardrailDecision(allowed=False, rule_id="GR-003", blocked_reason="Multi-statement SQL blocked.") stmt = statements[0] if not isinstance(stmt, (exp.Select, exp.Union)): return GuardrailDecision(allowed=False, rule_id="GR-004", blocked_reason="Only read-only SELECT is allowed.") for node in FORBIDDEN_NODES: if stmt.find(node) is not None: return GuardrailDecision(allowed=False, rule_id="GR-004", blocked_reason=f"Forbidden {node.__name__} node.") for with_clause in stmt.find_all(exp.With): if with_clause.args.get("recursive"): return GuardrailDecision(allowed=False, rule_id="GR-010", blocked_reason="WITH RECURSIVE CTE blocked.") for fn in stmt.find_all(exp.Anonymous): if fn.name.lower() not in ALLOWED_FUNCTIONS: return GuardrailDecision( allowed=False, rule_id="GR-011", blocked_reason=f"Function {fn.name}() blocked (prevents file/system access).", ) for col in stmt.find_all(exp.Column): if col.name.lower() in BLOCKED_PII_COLUMNS: return GuardrailDecision(allowed=False, rule_id="GR-005", blocked_reason=f"PII column '{col.name}' blocked.") cte_names = {c.alias_or_name.lower() for c in stmt.find_all(exp.CTE)} tables = [t.name.lower() for t in stmt.find_all(exp.Table) if t.name.lower() not in cte_names] if not tables or any(t not in ALLOWED_TABLES for t in tables): return GuardrailDecision(allowed=False, rule_id="GR-006", blocked_reason="Table outside read-only allowlist.") if any(isinstance(s, exp.Star) for s in stmt.find_all(exp.Star)) and stmt.find(exp.Count) is None: return GuardrailDecision(allowed=False, rule_id="GR-007", blocked_reason="Wildcard SELECT * blocked.") is_scalar_agg = any(stmt.find(a) for a in (exp.Count, exp.Sum, exp.Avg)) and stmt.find(exp.Group) is None limit_node = stmt.args.get("limit") limit_val = int(limit_node.expression.this) if (limit_node and isinstance(limit_node.expression, exp.Literal)) else None if not is_scalar_agg and (limit_val is None or limit_val > MAX_LIMIT): return GuardrailDecision(allowed=False, rule_id="GR-008", blocked_reason=f"Explicit LIMIT <= {MAX_LIMIT} required.") return GuardrailDecision( allowed=True, normalized_sql=stmt.sql(dialect="duckdb"), tables_referenced=sorted(set(tables)), ) def create_hardened_connection() -> duckdb.DuckDBPyConnection: """Create an in-memory DuckDB connection locked against external file/HTTP access.""" con = duckdb.connect(":memory:") con.execute("SET threads = 2; SET memory_limit = '256MB';") # ... populate synthetic Bronze/Silver/Gold tables ... con.execute("SET enable_external_access = false; SET lock_configuration = true;") return con