Skip to content

API

One FastAPI app (services/app.py), three surfaces on one port: the data plane (/v1, caller keys: asking questions), the control plane (/mgmt, admin auth: managing the install), and the governed MCP door (/mcp). A running server serves its own interactive OpenAPI at /docs.

Authentication

Bearer tokens in the Authorization: Bearer <token> header. The local dashboard rides a dst_session cookie instead; a header always wins over the cookie (services/auth/deps.py).

Prefix What Where it works
dstadm_ admin token (dst bootstrap) /mgmt; also /v1 as a superuser identity. Rejected at /mcp with a 403 naming the fix
dst_ caller API key (dst keys create) /v1 and /mcp: the governed identity, one per person
dsto_ OAuth access token same plane as caller keys, differs only by expiry
dstsess_ local dashboard session cookie-carried

Local sessions: POST /auth/login (email + password → dstsess_, in the body and as an httpOnly cookie), POST /auth/logout, GET /auth/me; accounts are managed via POST/GET /mgmt/users. Token sanity: GET /mgmt/ping (does this admin token resolve?) and GET /mgmt/whoami (to which org?).

Prefixes: services/auth/tokens.py. MCP authentication happens at the ASGI edge, before routing (services/app.py): no bearer → 401 with a WWW-Authenticate challenge pointing at the OAuth protected-resource metadata (the hook a client's native OAuth flow hangs on); a bad key fails at connect time rather than yielding a working-looking session that fails on every tool call.

Access to lenses is deny-by-default per lens; every tenant table sits behind Postgres row-level security whose failure mode is no rows, never cross-tenant (services/db/session.py).

Meta

Route Description
GET /health Liveness: the process is up
GET /ready Readiness. Five checks gate status: DB, MCP session manager, schema state, whether trace writes are landing, and typed_decisions (ok, off, or degraded (…) while the typed-decision provider is failing, until a typed decision succeeds again). Reported but never gating: embeddings, certified_matching, certified_bands (calibrated, uncalibrated (…) or n/a), ai_pricing (ok, or UNPRICED (…) naming each model your providers can call that has no price, and each anthropic provider model with no prompt-cache price), plugins, cube (the configured Cube: reachable, version, model_version, member counts, or not configured), serving (per published lens its lane, typed or cube, and why; for a Cube lane whether Cube is configured, when the monitor ran and whether a chat tier serves the HTTP question door), data_quality (the latest dst monitor run per org), and models: what this install actually resolves (fast=/smart= provider/model + embedder). A lens that names no model runs on the smart= entry, so this is where "which model does my lens run on?" is answered
GET /SKILL.md The file an agent reads to connect itself: the instance name, the MCP URL, the setup for Claude, Claude Code, Codex, ChatGPT and Cursor with the key as a placeholder, which of them sign in through OAuth instead, and in demo mode the topics and the limits. Public, text/markdown, cached for five minutes. Outside demo mode it needs DST_PUBLIC_BASE_URL and answers 404 with the reason without it

/SKILL.md is how a person connects their AI with one line: they paste Connect me to <name>: <base>/SKILL.md — my key: <key> into the AI they use, and it fetches the file and follows the steps for its own client. The file holds no key. Clients that sign in through OAuth (Claude on the web and Desktop, ChatGPT) need none; the others take the key from the line, which the demo page fills in after sign-in and an operator hands out otherwise.

Data plane (/v1)

Caller keys (or an admin token). Routes in services/api/query.py, services/api/route.py, services/api/reviews.py, services/api/openai_compat.py.

Route Description
GET /v1/lenses The lenses this key may query
GET /v1/lenses/{name} One lens's schema, definitions, certified count, and metric catalog (metrics, dimensions)
GET /v1/lenses/{name}?view= A lens served through Cube: its views (the named one in full), members with their meta.dst facts and observed values, refusals, ambiguous terms, freshness and certified pairs (CubeLensDescription)
POST /v1/lenses/{name}/cube Run the caller's own Cube query: body {"query": {…}, "ledger": [{"word", "to", "ref"}], "question": "…"}; every check, no model call; a stopped query carries retry
GET /v1/lenses/{name}/values?member=&prefix= Observed values of view.member (the probe's dictionary) or of an exposed table.column (the stored profile)
GET /v1/lenses/{name}/data_end?member= Where a time dimension, measure, cube, exposed table or column ends, with the lens clock and a partly loaded period
GET /v1/grain?table=&lens= An exposed table's blueprint, check verdicts, probe facts and rows against distinct key
GET /v1/lenses/{name}/catalog The metric catalog alone: metrics, dimensions, and tree, the metrics arranged by what each is computed from
POST /v1/lenses/{name}/query Ask: body {"q": "..."} → a governed answer. A question that asks for no number (a meaning, a yes/no over the model, the SQL, a report, the caller's log) is answered first, running nothing, under its own mode (Question types)
POST /v1/lenses/{name}/metrics Ask with a structured intent (metrics/dimensions/filters) instead of prose; same governance and receipts; compare adds a comparison window
POST /v1/lenses/{name}/metrics/batch Up to 50 structured intents in one request, read at one data_as_of (and one warehouse snapshot where the connector can hold one); results keyed by each intent's id, failures isolated
GET /v1/definitions Look a governed term up across every lens this key may use: the approved meaning verbatim, no SQL, no warehouse (dst define)
POST /v1/sql Guarded read-only SQL, against a connection (admin token) or within a lens's boundary (caller key) where the lens's hide and not_computable refusals apply; row-capped (limit, default 20, max 500) and logged; takes an optional purpose like the asking doors, kept on the lens-scoped row only when the lens sets logging.log_purpose, and an optional question, the question the read answers, kept on the row and certified with the SQL on approval. A lens-scoped read over an exposed table is logged as lane: explore
GET /v1/lenses/{name}/certified The lens's certified library; with ?q= results are similarity-ranked (top 5, scored)
POST /v1/lenses/{name}/certified/{cert_id}/run Run an approved question→SQL pair exactly as certified; zero AI SQL generation
POST /v1/query Routed ask: dst picks the lens, or declines with an uncovered envelope; when the question names a table a lens exposes, exposed_in lists that lens and the reason says to ask it by name. For a driver with Cube-backed lenses in its catalogue: those lenses by coverage and why (DriverRouteAnswer)
POST /v1/verify-receipt Check an answer's signed receipt: signature + field-by-field cross-check against the logged trace
POST /v1/reviews Open a review ticket on a traced request (optionally with a correction delta); 201, and only against a request served to this caller (admins excepted). On an outside-lens answer the ticket carries explore: the question, the SQL, the exposed tables read, every check and the answer's lines
GET /v1/reviews The tickets raised on this caller's own requests: the reporter's half of the queue
GET /v1/reviews/{ticket_id} Ticket status + tracking URL
POST /v1/chat/completions OpenAI-compatible: model: "dst/<lens>" selects the lens; stream: true returns a valid SSE stream, though composition is synchronous so it is one content delta then [DONE]; unknown fields ignored
GET /v1/models This key's lenses as OpenAI model objects

Every ask route takes "format": both, structured (data is an accepted alias), or prose. The default is both, except POST /v1/lenses/{name}/metrics, whose door defaults to structured. structured returns the rows without the written answer, and skips the LLM call that writes it, which is most of the wait: on a certified serve the difference is roughly two orders of magnitude. Everything else is unchanged (same SQL, citations, confidence, trace, receipt), so it is the right shape whenever the caller phrases the reply itself. A prose caller still receives the envelope-level truncated block: dropping the data payload cannot drop the fact that it was incomplete.

The query response (services/contracts/response.py) carries the answer plus its receipts: the sql, citations, a graded confidence (verified / partial / unverified; derived from named checks, never asserted), certification (certified / assisted / none, plus certified_failed on an error status: the approved answer's SQL no longer runs, so the badge never stands beside the fault as plain certified), source (certified: an approved answer's SQL served, its id in certified_answer_id; compiled: the compiler built the SQL from a typed intent; generated: a model wrote the SQL; null on a non-answer; the same on the direct and the routed envelope), data_as_of, a request_id that ties it to the audit trail, and a signed receipt, a portable block anyone in the org can POST back to /v1/verify-receipt later to confirm these exact claims were really served. A clarification field set means it is not a data answer; its kind says why. ambiguous_term: a governed term needs the caller to pick a meaning first. unknown_value: a filter value the question used was proven absent from the column it filters (checked against the committed value dictionary, or by a governed probe of the warehouse): term names the column, options are the values it actually holds; re-ask with the stored value you mean, or read the absence as the answer (Clarify & refusal).

Driver mode

A request whose caller is an agent runs in driver mode: the request carries X-DST-Driver: 1 (the MCP server sends it on every call), or an admin marked the caller a driver (PUT /mgmt/callers/{name}/driver, dst keys create --driver). Driver mode applies to lenses served through Cube only. On those dst resolves no model provider, and a provider call that completed anyway raises instead of being recorded (services/observability/usage.py). Lenses on the typed core answer every route exactly as without driver mode. What changes:

  • POST /v1/query, when the caller may use a lens served through Cube, returns a DriverRouteAnswer (services/api/route.py, services/serve/driver.py): candidates (lens, serving, no_model, why, matched words with their targets, uncovered), choose when several cover the question, refusal when a Cube-backed lens declares it, and no_model, per lens, true where dst calls no model. Cube-backed lenses are routed on deterministic coverage, with no embedder and no decider. When none of them covers the question, the typed lenses route it as without driver mode and their RoutedAnswer or uncovered envelope is under routed; with no typed lens, nearest and explore_kit say what is left. With no Cube-backed lens the response is unchanged.
  • POST /v1/lenses/{name}/query on a lens served through Cube answers 400: send the query with POST /v1/lenses/{name}/cube.
  • POST /v1/lenses/{name}/cube, values, data_end and grain call no model for any caller, and POST /v1/sql never did.

The /v1/lenses/{name}/cube response is the query response plus retry (check, mode, detail, change) on a non-answer. The /v1/sql response adds sql (the statement as it ran), grain and data_end (one line per exposed table read), clock (one line per time column read: what it records per the table's blueprint), checks, mode and a signed receipt graded unverified. Beside grain, data_end and empty_result, checks carries join (rows after the statement's joins against its base table's rows; a join that multiplies rows is join:disclose (wrong_grain)), clock (clock:pass with the meaning, or that no clock is declared) and reconcile (the leading number beside a certified answer of the lens over the same tables and window, pass or disclose (unverifiable) with the delta). A check that could not run reads exposed, could not verify … or <name>:skip (unverifiable): could not close: …, and mode is the first disclosure's. The same three checks run on a query answer that reads an exposed table, as JOIN:, CLOCK: and RECONCILE: lines in degraded and as checks on its verification report.

The metric catalog

GET /v1/lenses/{name} carries two catalog lists beside entities, and GET /v1/lenses/{name}/catalog returns them alone with a tree. Both go through the same authorization as every other caller door, read the lens's own scope, and make no model call and no warehouse call (services/lenses/describe.py).

Each entry in metrics has name, entity, label, aliases, description, type (simple, ratio or derived), agg, additivity (flow unless the metric declares level), unit (the declared currency, or percent, or null), currency, format, time_field, grains (the grains that time field supports: hour to year on a timestamp, day to year on a date, none otherwise), dimensions (every member the metrics door accepts beside it: its own entity's by bare name, a joined entity's as entity.member when the declared relationship does not fan the rows out), depends_on (the sibling metrics a ratio or derived metric references, numerator first), filters_summary, and certified_answer_ids (the active certified answers whose stored terms name the metric).

Each entry in dimensions has name, entity, label, type, description and values: the complete value list from the stored profile when the column is enum-sized and the profile is within probe.max_age, otherwise null. A sampled list is never served as a complete one. Declared dimensions: come first, then every field of type string, integer, boolean, date or timestamp; label is null today, since neither carries an authored label.

tree holds the metrics no other metric depends on as roots; each node's children are its depends_on, so a metric two parents share appears under both. Exposed tables stay out of all three lists.

Batches

POST /v1/lenses/{name}/metrics/batch takes {"intents": [{"id": "...", ...intent}], "format": "structured"}. Each intent is the body POST /v1/lenses/{name}/metrics takes, plus an id unique in the batch. More than 50 intents, an empty list, or a repeated id is a 422.

The batch reads the profile once, so every answer carries the same data_as_of. On a connector that can hold one snapshot across connections (Postgres, through an exported snapshot), every query reads that snapshot and the response says "snapshot": "shared"; elsewhere each query reads the warehouse at its own moment and the response says "per_query", with a snapshot_note in words. Queries run concurrently, four at a time.

results maps each id to {ok, request_id, status, error, answer}. A served intent has its own request_id, trace and receipt, exactly as if it had come alone. A failing intent has ok: false, the HTTP status the single door would have answered (400 for a compile error, 504 for a warehouse timeout) and the error detail, and the other intents are unaffected. An intent the door answered without serving it (answer.status error or rejected) is ok: false as well, with status 200, error set to the answer's sentence, and the answer itself. ok: true means a served answer, a clarification or a refusal; answer.status says which. Each intent counts against the caller's per-minute limit and daily quota like a single ask; intents past either are answered 429 one by one.

Period comparison

An intent with compare: {"to": ...} runs every metric over its own date window and over a comparison window. to is previous_period (the window of equal length just before; calendar months when the window starts and ends on month boundaries and the grain is not hour, day or week), previous_year (the same window a year earlier; 52 weeks earlier under a week grain), or an explicit range: YYYY, YYYY-MM or YYYY-MM-DD/YYYY-MM-DD with both days inclusive.

The window is read from the intent's own filters on the metrics' time field, and it must be bounded on both ends in whole days. An intent without one is refused with a 400 naming the fields to bound. Each window compiles on its own, so a level metric reads each window's latest snapshot and a flow metric sums each window's rows. Every metric gains <metric>_compare, <metric>_delta (value minus compare value) and <metric>_delta_pct (the delta over the absolute compare value, null when that is zero). Rows are joined on the intent's dimensions and, under a grain, on each bucket's counterpart in the other window; a group only the comparison window has appears with a null current value. A grain the shift cannot line up with (a month grain over a window that is not month-aligned, a week grain shifted by days that are not whole weeks) is refused rather than matched approximately. order_by may name any selected column, including the compare columns. The resolution ledger records the second window as a window slot (compared with 2026-08-01 to 2026-08-31 (previous_period)).

Row caps and truncation

Three caps, deliberately separate:

Cap Default What it bounds
max_rows_to_compose (per lens) 200 rows the composer's prompt sees (a prompt budget)
max_rows_to_return (per lens) 1000 the data payload the caller gets back
fetch cap (fixed) 5000 rows dst fetches from the warehouse at all; past it row_count is a floor

Either cap biting is stated, never inferred: truncated is a block on the response envelope, not only inside data, so a format: "prose" caller (whose data block is dropped) still holds the fact deterministically. It carries returned and total, and total is null when the engine-side fetch cap bit: the true count is then unknown and must never be stated as a number (services/contracts/response.py, services/runtime/pipeline.py).

Verifying a receipt

POST /v1/verify-receipt runs two independent checks, both deterministic, no LLM (services/api/receipts.py, services/runtime/receipt.py):

  1. Signature: recompute the HMAC-SHA256 over the receipt's canonical JSON, keyed by DST_SECRET_KEY, the same key list and rotation contract as stored-secret encryption: the first key signs, every key verifies.
  2. Trace cross-check: read the request_log row serving already wrote and compare the receipt's claims (lens, confidence, certification, sql_sha256) field by field; every disagreement is listed.

Verification is stateless: nothing new is persisted. ok means both held: valid signature, trace found, zero mismatches.

The request body is the receipt object itself, not wrapped in a {"receipt": …} envelope. A wrapped body returns 422 naming request_id, lens and served_at as missing, which is the first thing everyone gets wrong.

$ curl -sX POST $DST_URL/v1/verify-receipt -H "Authorization: Bearer $TOKEN" \
    -H 'content-type: application/json' -d "$RECEIPT_JSON"

{"ok": true, "signature": "valid", "trace_found": true, "mismatches": [],
 "question": "How many customers are repeat customers?",
 "lens": "customer_value", "caller": "admin"}

Edit any field and resubmit, and the failure is two-part: the signature and the specific field that no longer matches the logged trace:

{"ok": false, "signature": "invalid", "trace_found": true,
 "mismatches": ["confidence"], "question": "…", "caller": "admin"}

It returns the original question and caller too, which is what makes it useful to a skeptic holding only a pasted number: they learn what was actually asked, by whom, and whether anything was tampered with. signature is one of valid / invalid / unsigned (the receipt carries no digest: the serving server had no signing key, and says so rather than faking one) / unkeyed (the receipt is signed but this server holds no key to check with: a config gap named as itself, never reported as forgery). The receipt carries the SQL's hash, not the SQL: receipts travel further than SQL should, and the hash still pins the receipt to the exact query. Refusals and clarifications carry no receipt: they make no data claim to attest.

MCP (/mcp)

A remote, stateless streamable-HTTP MCP server (services/mcp/server.py); connect with a URL and a dst_ key, or via the built-in OAuth flow. Every request runs in driver mode, which changes only lenses served through Cube. Eighteen tools:

Tool Description
list_lenses What this key can query
describe_lens Fields, definitions, certified count and metric catalog for one lens; a lens served through Cube describes its views, members, refusals, freshness and certified pairs (view picks the one in full)
query_cube Run your own Cube query and word ledger through every check; rows, mode, receipt, and retry on a stopped query
values Observed values of a member or exposed column
data_end Where a member's or exposed table's data ends
grain An exposed table's blueprint and rows against distinct key
metric_catalog The metric catalog alone, with the metric tree
lookup_definition A governed term's approved meaning verbatim; no SQL, no warehouse
search_certified Similarity-search the certified library
run_certified Deterministic run; a bare question auto-resolves only at or above the configured embedder's exact band (exact_band on the certified-library response — 0.95 by default, and embedder-relative), otherwise returns no_exact_match + near misses
query Ask a named lens
query_metrics Ask with a structured intent (metrics/dimensions/filters) instead of prose; compare adds a comparison window
query_metrics_batch Up to 50 structured intents in one call, read at one moment, results keyed by id
sql Run your own read-only SQL inside a named lens's scope; guarded, row-capped, logged; the lens's hide and not_computable refusals apply
route_query The default door: dst picks the lens or declines; a decline a lens would refuse by declaration returns that lens's refusal; Cube-backed lenses are routed by coverage in driver mode
send_for_review Flag an answer into the human review queue
review_status Poll a ticket
verify_receipt Check a receipted number before repeating it: signature + trace cross-check

plus a getting_started prompt. Every tool returns a uniform envelope, {"ok": true, …} or {"ok": false, "code": auth | forbidden | not_found | rate_limited | refused | invalid | no_exact_match | upstream | unreachable, "error": …}, so an agent can branch on code instead of parsing prose (refused and invalid are the caller's to fix; upstream is a server fault). See Agents over MCP.

OAuth

A self-contained authorization-server facade for MCP clients (services/api/oauth.py): PKCE S256 only, dynamic client registration, a server-rendered consent page.

Route Description
GET /.well-known/oauth-protected-resource/mcp Protected-resource metadata (RFC 9728); also served bare at /.well-known/oauth-protected-resource
GET /.well-known/oauth-authorization-server AS metadata
POST /oauth/register Dynamic client registration
GET /oauth/authorize → POST /oauth/authorize/complete Consent flow, authorized with a caller key or admin token
POST /oauth/authorize/idp → GET /oauth/callback Consent flow through the configured OIDC issuer (Security)
POST /oauth/token Code + PKCE → dsto_ access token

Public demo mode

Only when DST_DEMO_ORG_ID is set (services/api/demo.py, services/auth/demo.py); 404 otherwise. In demo mode every verified Clerk session is a non-admin caller in that org, in group demo, named by the sign-in email, on the data plane and the MCP grant alike, and sign-in never reaches /mgmt (403, admin is a dstadm_ token).

Route Description
GET /demo Server-rendered sign-in page. It opens with the one line for the visitor's AI (Connect me to <name>: <base>/SKILL.md, the key added after sign-in), boots Clerk, mints the visitor's key, then shows how to connect Claude, Claude Code, Codex, ChatGPT and Cursor by hand, the key, and curl and OpenAI-compatible snippets. Its tagline, example conversation and privacy link come from dst.yaml's demo: section
POST /auth/demo-key Bearer = the Clerk session token → {caller, key, expires_in_days, lenses, examples, base_url, agent_line, connect, other}, where agent_line is the one line with the key in it and connect and other are the page's setup snippets ({id, label, auth, code, …}); one live dst_ key per person (a re-mint revokes the last), budgeted per source address

Sign-in on both /demo and the MCP consent page returns to the page it started on, query string included, after an OAuth provider's redirect.

Control plane (/mgmt)

Admin auth. One router per concern under services/api/; the surface is large (~100 endpoints under /mgmt), so this lists the groups and the endpoints worth knowing by name; the rest is on /docs, and the CLI wraps the ones you'd call by hand.

Prefix Concern
/mgmt/project export / plan / apply: the file-first deployment door
/mgmt/lenses drafts, publish, versions, repo + diffs, context, drift, sample queries
/mgmt/lenses/{lens}/certified · /evals the certified corpus and eval cases per lens; POST …/certified/from-request/{request_id} certifies a traced answer (an outside-lens one with a question is pinned to its tables' blueprints; with cube_query on a lens served through Cube it returns a kind: cube pair verified by row equality, 409 when the rows differ, 409 when the read carried no question)
/mgmt/lenses/{lens}/join-candidates · /profile · /profile-drift profiling
/mgmt/semantic shared entities/definitions + GET /mgmt/semantic/introspect
/mgmt/connections warehouse connections, catalog, per-connection profile, and the drift-audit endpoints
/mgmt/reviews queue and rulings; GET /mgmt/reviews/{ticket_id}/seed is the slot map dst seed-lens scaffolds from (the exposed tables an outside-lens answer read, with fields and blueprint facts)
/mgmt/callers · /mgmt/users identities and keys; PUT /mgmt/callers/{name}/driver marks a caller a driver; POST /mgmt/callers/sync-idp revokes the callers the identity provider no longer lists
/mgmt/observe KPIs, requests, callers, evals, every lens's recent runs (/mgmt/observe/runs?last=N)
/mgmt/requests the request ledger export
/mgmt/standards · /mgmt/activation · /mgmt/surface · /mgmt/gap-map the rest of the cockpit

Notable:

  • POST /mgmt/project/apply: the single deployment door (dst apply): blue/green, one transaction under a per-org advisory lock; a concurrent apply gets a 409 (services/project/apply.py).
  • POST /mgmt/project/plan: the dry run behind dst plan. Both take the body {"files": {path: content}, "lineage": …}; lineage is optional, the dbt or SQLMesh model DAG the CLI reads for table/X+ selectors (services/project/lineage.py).
  • GET /mgmt/observe/requests/{request_id}: the full trace drill-down for one request: question, SQL, cost, outcome.
  • GET /mgmt/requests?since=&until=&lens=&caller=&format=csv|json: the request ledger, one row per request in the window (since inclusive, until exclusive), uncapped: ts, caller, agent, question, lens, covered, answer_kind, certification, request_id. answer_kind is certified, generated, clarify, refuse or error; covered is false only for a refusal. dst observe export wraps it.
  • Test traffic: requests whose agent (X-Dst-Agent) is dst-test or benchmark stay in the ledger but are left out of /mgmt/observe/kpis, /audit and /callers, the basis block included; ?include_test=true counts them, and test_requests says how many were left out.
  • GET /mgmt/lenses/{name}/repo and GET /mgmt/lenses/{name}/diff?from=&to=: the lens-as-repo file tree and version diffs (services/api/mgmt_lenses.py).

(Routes verified against services/app.py and the routers under services/api/.)