AI and MCP

AI proposals

How write-shaped LLM emissions become reviewable Proposals - state machine, preview contract, apply/reject endpoints, RBAC parity.

What proposals are

Every write-shaped emission from an LLM - a create_pipeline / create_metric / create_model MCP tool call, or a data-analyst handoff that routes to the data-engineer persona - becomes a stored Proposal instead of applying directly. A human reviewer inspects the rendered preview, then posts apply or reject. The proposal record survives forever (a 30-day TTL sweeps only stale pending) so compliance and postmortem can trace exactly what the AI suggested versus what a human accepted.

Endpoints on this page

  • GET /api/ai/proposals - inbox, tenant-scoped, ?status=&kind=&origin=
  • GET /api/ai/proposals/{id} - single proposal detail
  • POST /api/ai/proposals/{id}/apply - commit a pending proposal
  • POST /api/ai/proposals/{id}/reject - mark a pending proposal rejected

State machine

Six statuses, enforced by a single transition validator.

StatusMeaning
pendingLLM emitted the payload, preview rendered, awaiting human review
approvedHuman reviewer said yes; apply is queued or in progress (transient)
appliedApply succeeded; the mutation landed in the target system
rejectedHuman reviewer said no; will not apply
expired30-day TTL swept the proposal before any human reviewed it
failedApply attempted but the underlying write path errored (RBAC / validation / ClickHouse)

Allowed transitions:

pending  -> approved | rejected | expired | failed
approved -> applied | failed

Terminal statuses (applied, rejected, expired, failed) refuse every further transition. The audit trail treats a rejected or expired proposal as historical fact, not a mutable draft.

Proposal shape

Each proposal is stored server-side, one record per proposal. Wire shape returned by the REST surface:

id: p_1734307200_a1b2c3
tenant_id: acme
kind: propose_pipeline
origin: ai:data-engineer         # matches audit_log.origin
author: analyst@example.com      # authenticated user who triggered the LLM
payload: |                       # LLM-emitted JSON, verbatim
  {
    "connection_id": "warehouse-src",
    "source": "public.orders",
    "target": "raw_orders",
    "mode": "incremental",
    "inc_column": "updated_at",
    "schedule": "*/15 * * * *"
  }
preview: |                       # rendered dry-run, JSON-encoded
  {
    "pipeline": { ... },
    "source_columns": [ ... ],
    "warnings": [ ... ],
    "target_ddl_hint": "CREATE TABLE ..."
  }
status: pending
created_at: 2026-08-18T09:14:07Z
decided_at:                      # populated on apply / reject
decided_by:                      # user id of the reviewer
target_id:                       # populated on apply success
apply_error:                     # populated on failure or reject reason

The raw payload is preserved so a future change to the preview logic can re-derive the dry-run without asking the LLM again. Cross-tenant reads return 404, matching the same id-oracle guard the connections and pipelines surfaces use.

Kinds and preview contracts

propose_pipeline

The preview:

  1. Loads the connection and confirms it belongs to the caller’s tenant.
  2. Introspects source columns, honouring the connection’s SSRF guard.
  3. If mode: incremental, asserts inc_column is a real column on the source relation.
  4. Validates the schedule grammar with the same parser the human pipeline UI uses.
  5. Renders the canonical pipeline record, the introspected source columns, structured warnings, and a best-effort target DDL hint.

Apply re-runs the preview at commit time (schema-drift defense: a model dropped between preview and apply must not slip through) then invokes the same pipeline write path, RBAC included, that REST callers hit.

propose_metric

The preview:

  1. Enforces per-type required fields. simple and cumulative need measure; ratio needs numerator and denominator; derived needs expression; cumulative additionally needs window and time.grain plus time.column.
  2. Enum-restricts cumulative.window against the values the semantic-layer parser accepts (7d, 28d, mtd, qtd, ytd, etc.), so a proposal that passes preview is guaranteed to load in the semantic layer.
  3. Refuses duplicate names against both the live compiled semantic project AND prior tenant overrides.
  4. Renders the metric definition block that will be appended to the tenant’s semantic project.

Apply writes the definition, then stamps target_id with the metric name.

propose_model (wired)

The preview:

  1. Validates materialization against view | table | materialized_view. dictionary is refused at preview time.
  2. Accepts primary_entity as either a scalar string OR a JSON array (composite keys).
  3. Extracts every {{ ref('...') }} and {{ source('...', '...') }} from the SQL body. Unknown refs refuse the proposal.

Apply writes the model body and its YAML entry atomically: if the YAML append fails, the body write is rolled back so an operator never sees a half-written model.

REST surface

MethodPathAuthPermissionResponse
GET/api/ai/proposalsJWT or PATallow_save{proposals: [...], count}
GET/api/ai/proposals/{id}JWT or PATallow_saveProposal
POST/api/ai/proposals/{id}/applyJWT or PATallow_save + target RBAC{proposal, target} or 422 {error, proposal}
POST/api/ai/proposals/{id}/rejectJWT or PATallow_saveProposal (updated)

Notes:

  • Reject accepts an optional JSON body { "reason": "wrong target schema" }; the reason is persisted in apply_error so a future audit trace explains why a proposal did not ship. Body cap is 4 KiB.
  • List filters (?status=, ?kind=, ?origin=) are ANDed. An empty filter passes everything.
  • Apply is two-phase: pending -> approved first (so a concurrent apply on the same id sees approved and refuses) then per-kind dispatch. On the mutation error path, apply stamps status: failed with the error preserved in apply_error, and returns HTTP 422 with the updated proposal in the body.
  • All four endpoints record to the audit log under actions ai.proposal.list, ai.proposal.apply, ai.proposal.reject. Apply and reject stamp origin from the proposal so the audit row is attributed to the persona that produced the proposal, not the reviewer who clicked apply.

Attribution

Every proposal carries an origin string that matches the audit_log.origin column (see Audit and lineage). Values:

originSet when
ai:data-analystHandoff or auto-save from the data-analyst playbook
ai:data-engineerPipeline proposal from the data-engineer playbook
ai:data-architectMetric or model proposal from the data-architect playbook
ai:diagnosticDiagnostic playbook produced the write (rare - diagnostics are usually read-only)
system:mcpAn MCP tool call reached the create endpoint without a _persona argument
userA human posted a REST mutation directly (never appears on AI proposals)

A single origin-builder helper is the sole path that turns a playbook id into an origin string. A playbook id present but not in the switch statement becomes ai:<id> verbatim, so a new playbook gains provenance without a code change. MCP calls default to system:mcp when the client omits _persona.

RBAC parity

Apply is not a privilege-escalation surface. The endpoint gates on allow_save, and the per-kind dispatcher re-invokes the underlying mutation’s own RBAC:

  • The pipeline apply path invokes the same tenant-scoped pipeline write helper the REST surface uses, which enforces the per-pipeline allow-list.
  • The metric apply path writes to the tenant’s semantic project; a reviewer without write access to that path gets a failure surfaced as apply_error.
  • The model apply path follows the same tenant-scoped semantic path.

A user who can list-and-review proposals but cannot create the target resource cannot sneak a write through the AI surface. The audit row records both the persona that produced the proposal (origin) and the reviewer who clicked apply (user_id), so an operator can always distinguish “the AI suggested this” from “a human accepted it”.

End-to-end flow

Concrete walkthrough from an MCP client (Claude Desktop, Cursor, or a custom agent):

  1. Agent calls tools/call { name: "create_pipeline", arguments: { connection_id, source, target, mode, ... } } on the MCP server.
  2. Server runs the pipeline preview, validates end-to-end without touching the pipeline store, and persists a proposal { status: pending, kind: propose_pipeline, origin: ai:data-engineer, payload, preview }. The MCP response returns the proposal id.
  3. A reviewer opens /ai-proposals in the Goni web app or fetches GET /api/ai/proposals?status=pending&kind=propose_pipeline.
  4. Reviewer inspects the rendered preview (source columns, warnings, target DDL hint) and posts POST /api/ai/proposals/{id}/apply.
  5. Server flips pending -> approved, re-runs the preview against live state (schema-drift check), invokes the same pipeline write path REST uses (RBAC enforced), stamps status: applied with target_id, and returns 200 { proposal, target }.
  6. Audit log records ai.proposal.apply with origin: ai:data-engineer and user_id: <reviewer>, so both the proposer and the approver are traceable forever.

If the reviewer rejects instead: POST /api/ai/proposals/{id}/reject { "reason": "..." } flips pending -> rejected, the reason lands in apply_error, no mutation runs.

Web app inbox

The Goni web app ships a first-class inbox at /ai-proposals. It polls GET /api/ai/proposals every 30 seconds, filters by status / kind / origin, opens each proposal in a drawer with apply and reject actions, and paints a badge on the nav tray showing the pending count. The route is available to any user with allow_save; users without it are 403’d at the API and see an empty inbox in the app.

Last updated