Skip to content

Tools & Toolkits Governed semantic layer

github-actions[bot] edited this page Dec 2, 2026 · 2 revisions

Governed semantic layer

Installation and clean-room format

Install the optional ai-parrot-semantic distribution and use its native, sqlglot-based compiler. It has no third-party semantic-engine dependency or adapter: the model format is clean-room work informed only by public format documentation. Model files declare a physical schema, dimensions, metrics, and relationships; an adjacent <model>.policy.yaml supplies governance.

# orders.yml
models:
  - name: orders
    table: sales.orders
    columns: {id: INTEGER, region: VARCHAR, order_date: TIMESTAMP, amount: DECIMAL}
    primary_key: [id]
    dimensions:
      - {name: region, kind: categorical, column: region}
      - {name: ordered_at, kind: time, column: order_date, grain: day}
    metrics:
      - {name: revenue, agg: sum, column: amount}
      - {name: orders, agg: count_distinct, column: id}
    relationships: []

A file may declare several models under models:. A relationship joins the one side to the many side with paired key columns, for example {from_model: customers, to_model: orders, cardinality: one_to_many, from_columns: [id], to_columns: [customer_id]}; every model it references must be declared and have its own policy side-file.

Aggregates accept declared input columns and can be filtered; derived metrics may reference declared metrics. Joins require paired keys from the one side to the many side. The supported time grains are second, minute, hour, day, week, month, quarter, and year. The compiler rejects ambiguous or fan-out-prone paths rather than applying symmetric aggregates. It emits native SQL for DuckDB, Postgres, and BigQuery; compilation is CPU work and runs off the event loop.

Authorization and identity

Models are governed by default. A governed model requires both a trusted PermissionContext and an available PBAC evaluator; missing context, evaluator, manifest authorization, lineage, or RLS validation denies the request. Only a policy with governed: false opts out explicitly.

# orders.policy.yaml
governed: true
connection: warehouse
limits: {default: 100, max: 1000}
roles:
  analyst: {metrics: [revenue, orders], dimensions: [region, ordered_at], usage: []}
rls:
  - {driver: duckdb, table: sales.orders,
     predicate_template: "region IN (:subject.programs)", subject_attribute: programs}

The HTTP and agent surfaces receive a host-authenticated context. The local MCP surface is different: it accepts only a host-configured static_subject, agent_id, and guard_factory. Tool callers cannot supply credentials or override this identity. Each local instance uses a fresh session id and the fixed mcp-local channel; every call is logged and audited. Invalid factories, missing evaluator modules, malformed subjects, and policy-load errors fail startup closed.

Tools and audit

SemanticLayerToolkit exposes these sl_* tools (the prefix is added by the toolkit):

Tool Signature
sl_list_models list_models()
sl_list_metrics list_metrics(model: str)
sl_get_dimensions `get_dimensions(model: str, metrics: list[str]
sl_get_dimension_values `get_dimension_values(model: str, dimension: str, metrics: list[str]
sl_search_data_model `search_data_model(text: str, model: str
sl_list_saved_queries list_saved_queries(model: str)
sl_compile_query compile_query(query: SemanticQuery)
sl_query_metrics query_metrics(query: SemanticQuery)
sl_run_sql run_sql(model: str, sql: str) — host opt-in only
sl_save_result_as_dataset `save_result_as_dataset(result_id: str, name: str, description: str

Saved queries are policy-owned and receive the same governance as an explicit query. Raw SQL is absent unless the trusted constructor setting allow_raw_sql: true enables it; it still uses model-manifest authorization, lineage, RLS, limits, and audit. The audit ledger signs each entry and records the structured query, subject digest, model/policy digests, native engine, compiled and governed SQL, exact member provenance (including dependencies), dialect, row count, duration, PBAC decision, and outcome.

The default audit_required: null resolves to whether a durable audit sink is configured. A required missing or failed sink fails the operation. Use postgres_audit_storage(dsn_or_pool, table="semantic_audit_events") to write the signed payload to Postgres; the target table is parrot/semantic/sql/semantic_audit_events.sql.

Guarded dataset hand-off

Result retention is disabled as a public capability until a host supplies a conforming GovernedDatasetSink. Handles are opaque, bounded by TTL, and bound to agent, user, tenant, session, model/policy versions, and subject digest. sl_save_result_as_dataset rechecks ownership, expiry, current policy, and PBAC before publishing. Every downstream read invokes the registered read authorizer, so policy changes and revocation take effect immediately.

A bare DatasetManager, dataframe, or plain manager factory is rejected. The host adapter must declare guarded reads, immutable owner scope, async publish, and pass the sink conformance tests; without it the hand-off tool is not exposed.

Semantic datasets in DatasetManager

The hand-off above pushes a retained result into a sink. The pull direction is a SemanticDataSource: a DatasetManager dataset whose rows come from one semantic model. Every fetch runs the full governed path of SemanticLayerToolkit.query_metrics (PBAC, member rights, compile, RLS, masks, limit cap, execution, audit). The semantic executor runs the SQL; the source only turns the governed rows into a DataFrame, and no SQL leaves the layer.

Register it in either form. add_semantic imports ai-parrot-semantic lazily and raises ImportError when it is missing; pass exactly one of toolkit or models_dir with dialect (otherwise ValueError). A toolkit built from models_dir receives the manager's dataplane guard unless dataplane_guard is given in the extra keyword arguments.

from parrot.semantic import SemanticDataSource

dm.add_semantic("sales", model="orders", toolkit=semantic_toolkit)
dm.add_semantic("sales", model="orders", models_dir=Path("models"), dialect="duckdb",
                default_query={"metrics": ["revenue"]})
dm.add_source(SemanticDataSource(name="sales", toolkit=semantic_toolkit, model="orders"))

An unknown model raises SemanticPolicyError("model_not_found"). A default_query with keys outside the query fields raises invalid_default_query.

Query shape. The agent passes the query as fetch_dataset conditions; sql is ignored. Accepted keys are the SemanticQuery fields except model: metrics, dimensions, time_dimensions, filters, order_by, limit, offset, saved_query.

fetch_dataset(name="sales", conditions={
    "metrics": ["revenue"], "time_dimensions": [{"name": "ordered_at", "grain": "month"}],
    "filters": {"op": "and", "items": [{"member": "region", "op": "equals", "values": ["EU"]}]},
    "limit": 500})

Empty conditions fall back to default_query; with neither the fetch raises SemanticValidationError("query_required"). Passing model or an unknown key raises invalid_params; a value the query model rejects raises invalid_query.

Identity. The source fails closed. It reads the semantic context bound by the host (bind_semantic_context) and the core permission context of the tool call. Both present and different → SemanticAccessError("context_required"). Only the semantic one → it is used. Only the core one → the source bridges it: it must be a PermissionContext, and it is bound as the semantic context for the duration of the governed call. A bridged call has no host-bound identity, so the toolkit retains no result handle for it. Neither present → context_required.

Per-subject frames. The source is self_governed, so the manager never wraps it in AuthorizingDataSource. The entry keeps each loaded DataFrame in a slot keyed by current_owner(), the subject digest of the resolved context. loaded, df and the column types read the calling subject's slot only; for any other subject the dataset is not loaded. With no resolvable subject nothing is stored. Slots are bounded per entry (least-recently-used eviction). A denied fetch returns a correctable error and never marks the dataset unavailable for other subjects.

Session isolation. Server sessions never share governed rows. _clone_agent_dm does not copy the frame or column types of a self-governed entry, and UserObjectsHandler.configure_dataset_manager builds a fresh, unloaded DatasetEntry with a request-scoped copy of the source instead of sharing the agent's entry.

Row cap and response fields. The policy limit (limits.default / limits.max) applies unchanged; raise it in the model's policy file. The DataFrame carries attrs["semantic"], and the fetch_dataset response returns the same four fields under semantic: model, audit_id, truncated, row_count (rows materialized, not an uncapped estimate). Two more fields are added for semantic responses only:

  • inline_complete — every materialized row fits in the inline response.
  • complete — inline_complete and not semantic.truncated.

A truncated result always carries a warning, even when all its rows fit inline. Preview notes say "materialized result", never "FULL dataset". Non-semantic responses are unchanged.

Never cached. Rows are never read from or written to the Redis Parquet cache; every fetch_dataset re-fetches, and force_refresh is not passed to the source. Frames are never copied to another manager or subject.

When to re-fetch. A loaded semantic dataset is the result of one query. Call fetch_dataset again with new conditions whenever metrics, dimensions, grain, filters, ordering, limit, offset or saved query change, even if the dataset is loaded. Do not re-aggregate a previous result in pandas or with raw SQL. Reusing the same fetched result for further analysis in the same session is fine. The DatasetManager usage rules and the fetch_dataset description tell agents this.

When to prefer sl_query_metrics. Use the dataset when the agent needs the governed rows as a DataFrame in the pandas workspace (joins with other datasets, charts, Python analysis). Use sl_query_metrics directly for a one-off answer, or when the result must be retained as a handle for sl_save_result_as_dataset; a bridged dataset fetch never retains one.

MCP-local configuration

Operator configuration is intentionally local. Copy this section into the operator's ignored .parrot/mcp-toolkits.yaml; substitute only host-owned paths and factory names, and do not commit private settings or secrets.

toolkits:
  semantic-layer:
    class: parrot.semantic.bootstrap.LocalSemanticLayerToolkit
    kwargs:
      models_dir: /path/to/models
      dialect: duckdb
      agent_id: local-semantic
      static_subject: {user_id: operator, tenant_id: local, roles: [admin]}
      guard_factory: myapp.semantic_auth.build_guard
      guard_factory_kwargs: {policy_dir: /path/to/policies}
    env: {}
# Host must supply the factory; missing configuration fails closed.

Add the matching operator-local .mcp.json entry:

{
  "mcpServers": {
    "parrot-semantic-layer": {
      "command": "parrot",
      "args": ["mcp-local", "semantic-layer"]
    }
  }
}

For a deterministic local check, write those blocks to a temporary directory, replace the placeholder model and policy paths with fixture paths, and run:

parrot mcp-local semantic-layer --config /tmp/semantic-mcp/toolkits.yaml

Exercise both an explicit allow and an explicit deny policy against the real server factory. Parsing or listing configuration alone is not evidence that the configured PBAC guard binds the static identity around tool execution.

Accounting metrics

Chart-of-accounts rollups (revenue, EBITDA, …) are served by the finance_* tools of parrot.semantic.accounting — see accounting-metrics-layer. Their visibility is per metric through DatasetPolicyGuard and allows every metric when no guard or no permission context is configured; the sl_* tools on this page fail closed instead.

Example agents

Runnable examples live in examples/agents/semantic/, over one committed model fixture and a DuckDB warehouse built at run time. Each has a --smoke mode that runs offline: no LLM call, no network, nothing written outside a temporary directory. A pin test in packages/ai-parrot-semantic/tests/ keeps each one honest, and CI already runs them.

The llm_metrics_agent.py example demonstrates an LLM driving the sl_* tools through ask(permission_context=...). It proves that omitting either the permission context or the identity binding fails closed — the agent cannot access any semantic tool without both.

The mcp_local_agent.py example exercises the MCP-local path with a real guard factory, showing both an explicit allow and an explicit deny decision through create_toolkit_mcp_server. It validates that the static subject identity is bound around every tool call.

The masked_policy_agent.py example shows column-level redaction through the masks: directive. Roles that are not exempt have the column redacted in query results. It also demonstrates saved_queries: — running a reviewed query by name, which receives the same governance as an explicit query.

The governed_joins_agent.py example proves that time grains (second, minute, hour, day, week, month, quarter, year) work correctly. It also demonstrates that a governed cross-model query is DENIED — the governed path refuses to compile a join across models. The same join compiles successfully only under the explicitly ungoverned model in models_ungoverned/, which serves as the compiler surface for ad-hoc analysis.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally