Written for: For AI agentsUsing Astrato instead? Read the product guide
Author a semantic layer over MCP
This page is written for an AI agent, or a script, that changes a semantic layer through the Astrato MCP server. People build layers in the Semantic Layer Editor. The exact stored forms these tools accept are in the Semantic layer authoring reference.
Use the Nash MCP gateway to inspect and change semantic layers without editing the stored document directly. Describe a change in business terms and the server resolves it against the model, builds the definition, validates it, and protects the write with a revision check.
Connect your MCP client by following MCP setup. Semantic-layer reads require
sl:read, edits require sl:write, and creating versions or importing a Snowflake semantic
view also requires sl:version.
Start with live context
Section titled “Start with live context”When your authorization includes sl:read, call astrato_get_context at the start of the session.
It returns:
- your permissions and scopes;
- the configured default semantic layer, if one exists;
- the current draft revision and how revision checks work;
- the supported authoring workflows.
A data-only client holding data:query cannot call astrato_get_context. Use tools/list and the
server-provided instructions, then start the data flow with astrato_data_prepare_query.
If you already know which layer to use, pass its semanticLayerId to every subsequent tool that
accepts it. Session-scoped calls carry the selected layer through sessionId. If the layer is not
known, use the default returned by astrato_get_context. When there is no default, call
astrato_semantic_layer_list, review the available layers, and select the intended one. If it is not
clear which layer applies, stop and ask before continuing. The list is paginated: follow
pagination.nextOffset while pagination.hasMore is true when the requested layer is not in the
current page. Do not switch layers implicitly.
Inspect progressively
Section titled “Inspect progressively”Use the smallest read that answers the question:
astrato_semantic_layer_searchfor a focused question about a view, field, join, measure, dimension, or function.astrato_semantic_layer_get_summaryfor counts and current revision.astrato_semantic_layer_get_detailsfor one paginated collection. FollownextCursoronly when you need more results.astrato_semantic_layer_validatewhen you need to check correctness and before treating an edit as complete.
Do not fetch the entire model for a focused change. The prepare tools use the same ranked field
matching as astrato_semantic_layer_search_fields, so there is no need to search first when prepare already resolves
the requested fields.
To read the whole model at once, follow Read the complete V3 document.
Choose the edit workflow
Section titled “Choose the edit workflow”To create a semantic layer that does not exist yet, call astrato_data_list_sources, choose the exact
datasourceId, then call astrato_semantic_layer_create. The new layer is empty and unpublished.
Astrato may rename it to avoid a collision, so use the returned name in the response and pass the
returned semanticLayerId to every later authoring call.
| Requested change | Workflow |
|---|---|
| One measure | astrato_semantic_layer_prepare_measure_change → astrato_semantic_layer_apply_measure_change |
One dimension of any kind: field, bucket, drillthrough, mapping, periodAxis or sets |
astrato_semantic_layer_prepare_dimension_change → astrato_semantic_layer_apply_dimension_change |
| Several independent measures or dimensions | astrato_semantic_layer_plan_authoring_batch → astrato_semantic_layer_commit_authoring_batch |
| One or more view and field changes | Optional source search → astrato_semantic_layer_prepare_view_change → astrato_semantic_layer_apply_view_change |
| A supported join, function, or description edit | astrato_semantic_layer_begin_edit_session → astrato_semantic_layer_apply_edit → astrato_semantic_layer_preview_edit_session → astrato_semantic_layer_commit_edit_session |
| Upstream datatype or conservative physical-field rename | astrato_semantic_layer_check_source_schema → confirmation → astrato_semantic_layer_apply_source_schema_fix |
| Snowflake semantic-view import | astrato_semantic_layer_list_snowflake_views → astrato_semantic_layer_preview_snowflake_view_import → confirmation → astrato_semantic_layer_import_snowflake_view |
Do not use a generic edit session for structural measure, dimension, view, or field changes. The
typed tools accept structured business requests and are the supported MCP workflows. A
description-only update, including a dimension description, uses the edit session’s batched
update_descriptions operation.
One measure or dimension
Section titled “One measure or dimension”Prepare once with the complete request and every concept needed by the definition. The result contains field matches, available aggregations, an existing target when applicable, and the current revision. If several matches are plausible, resolve the ambiguity instead of choosing one by guess.
This example prepares a new aggregate measure:
{ "semanticLayerId": "11111111-1111-4111-8111-111111111111", "request": "Create Total Order Amount as the sum of Order Amount", "queries": [ { "id": "orderAmount", "text": "Order Amount", "kinds": ["field"], "dataTypes": ["numeric"] } ]}Pass that object to astrato_semantic_layer_prepare_measure_change.
Set includeSuggestions: true when you also want create-ready measure suggestions from the
semantic engine. Set includeCompiledSql: true to receive statement-only SQL for the prepared
measure; on a create request it returns and compiles the suggested measures. Dimension preparation
supports the same includeSuggestions option. These optional operations use the current draft and
never publish it.
For repeated deterministic measure preparation, set compact: true. The compact response preserves
the revision, exact field and measure references, aggregation capabilities, target definition and
relevant joins. It omits repeated locale, relative-period and authoring-rule metadata, plus candidate
descriptions and duplicate confidence fields. Omit compact when a person or model needs that
display context; the default response is unchanged.
When prepare finds an exact match and confirms that SUM is available, pass the returned names and
revision to astrato_semantic_layer_apply_measure_change in one call:
{ "semanticLayerId": "11111111-1111-4111-8111-111111111111", "preparedTarget": null, "expectedRevision": 42, "change": { "operation": "create", "name": "Total Order Amount", "definition": { "description": "Total value of orders.", "inputs": [ { "id": "orderAmount", "kind": "aggregate", "field": { "view": "Orders", "field": "Order Amount" }, "aggregation": "SUM" } ] } }}The UUID and revision above are examples. Use the selected semantic-layer ID, keep the input IDs
consistent between prepare and apply, and copy the exact view, field, aggregation, revision, and
preparedTarget returned by prepare. The apply call validates the change and commits at most one
draft revision. It never publishes the layer.
To aggregate arithmetic over each row, give an aggregate input row instead of field: an
expression over names in braces, and fields mapping each name to its view and field.
{"expression": "{price} * {quantity}", "fields": {"price": {...}, "quantity": {...}}} stores
SUM(Price * Quantity). A row cannot contain a number yet, so write SUM(Price * (1 - Discount))
as two inputs, SUM(Price) and SUM(Price * Discount), with the expression {m1} - {m2}. Use this
split only when Price and Discount are fields of the same view: SUM(Price) adds each price once
per row of its own view, so with Price on a parent view it counts a product once rather than once
per order line, and returns a wrong total without an error. For fields on different views, compute
the value in a SQL view. Even on one view, the two
agree only where Discount is never null: the original leaves out a row whose discount is null, but
SUM(Price) counts its price. Where it can be null, give the SUM(Price) input an is_set filter on
Discount as well, or compute the value in a SQL view.
A conditional measure is an IF written as the whole expression over the input IDs, for example
IF(sales > 1000000, 'Large', IF(sales > 100000, 'Medium', 'Small')) with one aggregate input
sales. The rules it follows are listed under Stored measure expression rules.
A parameter input takes dataType int or float; it is float when omitted, and an int
default must be a whole number. To change the default of a parameter a measure already declares,
patch it by name with astrato_semantic_layer_apply_measure_change, without resending the
calculation:
{ "operation": "patch", "name": "Rolling Sales", "patch": { "parameters": { "periods": 6 } } }Each parameter keeps its stored type. A name the measure does not declare is refused with the names it does.
A field dimension can group a date or time field by dateLevel (such as month) or extract a
datePart (such as quarter). Use a name from the dateLevels or dateParts that dimension
preparation lists for the datasource; the names vary by database. Names match without regard to
case. A query’s local dimension is checked against the same lists, and so is a date transform in
a query’s or business question’s filter or in the filter of a measure the query defines. A name
the datasource does not offer is refused before the query runs, with the names it does. A stored
measure’s, view’s or dataset’s filter is not checked. dayOfWeek, weekday and dayOfMonth are
not names: use dayofweekiso, which counts Monday as 1 and Sunday as 7, and day for the day of
the month.
A periodAxis dimension (a Time Axis) reads one date field, or several sources when fact
tables that do not join share one axis, such as order date and return date. Each source is
{ "field": { "view": ..., "field": ... } } or { "dimension": ... }, a field dimension over a
date or timestamp field with no date level or part. An axis takes at most one source per view.
A replace keeps what its definition leaves out: the label, synonyms, categories and import
record, and on a measure the aggregate settings the authoring fields do not carry. Send label or
categories to change them. To change one bucket bound or the Time Axis window, patch bucketing
or timeAxis instead of replacing the dimension. A delete takes references: remove deletes
the item with what depends on it, as the editor’s Delete references does, and keep, the
default, leaves those references broken and lists them under publishBlockers. Rename takes references: keep to rename only
the item. duplicate copies a measure or dimension as Copy of its name unless newName is given.
A typed expression follows the stored measure expression rules, and a filter on an input or a custom-group rule follows the filter conditions.
Dimensions use the same pattern. Prepare all field or reusable-dimension concepts together, then
apply one typed field, bucket, drillthrough, mapping, periodAxis or sets definition. The
server derives result types and can resolve omitted numeric bucket ranges from data.
Current-draft engine previews
Section titled “Current-draft engine previews”The editor’s measure SQL view and the optional prepare-tool suggestions use the current draft, so unpublished edits appear immediately, and they never publish it. A draft with blocking validation errors cannot run these operations; correct the reported document issues first.
Compiled SQL is a statement preview only. It does not execute data, perform a new authorization or datasource lookup, or return query warnings and resolved items.
Author several items as one batch
Section titled “Author several items as one batch”Plan independent measure and dimension requests together. For a proposed measure creation, include a measure query for the intended use case so planning can find an exact existing measure instead of creating a duplicate.
{ "semanticLayerId": "11111111-1111-4111-8111-111111111111", "items": [ { "id": "totalOrderAmount", "entity": "measure", "operation": "create", "request": "Create Total Order Amount as the sum of Order Amount", "queries": [ { "id": "existingTotal", "text": "Total Order Amount", "kinds": ["measure"] }, { "id": "orderAmount", "text": "Order Amount", "kinds": ["field"], "dataTypes": ["numeric"] } ] }, { "id": "orderDate", "entity": "dimension", "operation": "create", "request": "Create an Order Date field dimension", "queries": [{ "id": "orderDateField", "text": "Order Date", "kinds": ["field"], "dataTypes": ["date"] }] } ]}Call astrato_semantic_layer_plan_authoring_batch with that object and review the complete plan. Commit only when
every item is ready and the plan has not found an existing item that should be reused. Copy the
returned revision, optional planId, and each preparedTarget into
astrato_semantic_layer_commit_authoring_batch with the complete typed changes:
{ "semanticLayerId": "11111111-1111-4111-8111-111111111111", "planId": "22222222-2222-4222-8222-222222222222", "expectedRevision": 42, "items": [ { "id": "totalOrderAmount", "entity": "measure", "preparedTarget": null, "change": { "operation": "create", "name": "Total Order Amount", "definition": { "inputs": [ { "id": "orderAmount", "kind": "aggregate", "field": { "view": "Orders", "field": "Order Amount" }, "aggregation": "SUM" } ] } } }, { "id": "orderDate", "entity": "dimension", "preparedTarget": null, "change": { "operation": "create", "name": "Order Date", "definition": { "kind": "field", "field": { "view": "Orders", "field": "Order Date" } } } } ]}Copy planId, the revision, every preparedTarget, and all resolved views, fields, and
aggregations from the plan. Keep the item and input IDs consistent. If the plan finds an exact
existing use case, reuse it instead of creating a duplicate. The batch is all-or-nothing: if one
item fails compilation or validation, nothing is written. A successful commit creates at most one
draft revision and returns a receipt for every item.
Author views and fields from physical sources
Section titled “Author views and fields from physical sources”Use astrato_semantic_layer_prepare_view_change and astrato_semantic_layer_apply_view_change for table, SQL, and inline view creation;
view copy, rename, metadata/source update, and deletion; and field creation, update, rename, and
deletion. One ordered apply call can change several views and fields and commits at most one draft
revision without publishing.
When physical-source discovery is required, call astrato_semantic_layer_search_source_catalog with ordinary business
terms, or pass all source concepts to prepare so it can resolve them together. Keep the exact
schema, table, column identifiers, and casing returned by the source catalog. Never invent a source
identifier when discovery is ambiguous or empty.
Source discovery returns a progressive informationSchemaUri. Reuse that URI in later searches
and in view prepare/apply calls so previously loaded branches are not fetched again. Broad searches
are bounded; continue with nextSchemaOffset when it is returned. The resource expires after ten
minutes without use, after which omitting the URI starts a fresh context.
Call astrato_semantic_layer_refresh_source_catalog only when you need current source metadata. With no branch it
refreshes everything already loaded. A schema refreshes its table list and loaded columns; a table
refreshes that table and its columns. Refresh keeps the same URI and does not discover unrelated
branches.
Catalog-backed table creation can select all fields, an explicit subset, or all except an explicit list. Deletes that would break a join, dimension, measure, or filter are rejected instead of cascading silently. Copy every resolved source and revision from prepare into apply.
Some datasource-native values need a lossless semantic representation. View preparation returns
nativeDataTypeOptions for the active datasource. Each option declares the exact
nativeDataType, semantic dataType, and sourceType combination accepted by the engine. Use only
those returned combinations and only on physical column fields; inline columns and expression
fields cannot use datasource-native types.
For Google BigQuery, the currently supported option is:
{ "nativeDataType": "INT64", "dataType": "string", "sourceType": "column"}This keeps values larger than JavaScript’s lossless number range as strings while queries continue
to use BigQuery INT64. Setting another semantic datatype removes the native override. Source
checks compare the stored native datatype with the raw datatype currently reported by the database;
an actual upstream change is reported rather than hidden by the override.
astrato_semantic_layer_suggest_joins returns the same connected-data join suggestions as the
editor when enabled and supported, including measured join quality when available. Otherwise,
candidates use field names and data types; their confidence describes metadata evidence.
Other entity edits
Section titled “Other entity edits”Use an edit session for focused join, function, and description changes supported by
astrato_semantic_layer_apply_edit. Description-only changes use the batched update_descriptions operation.
- Begin a session. Its base revision pins the work to a known draft state.
- Apply one or more structured edits. They remain session-local.
- Preview the complete diff and validation result.
- Commit the session when the preview is valid. Roll it back only if you intend to discard every pending change.
Sessions expire after 30 minutes of inactivity by default and belong to the current tenant and identity. A commit may rebase non-overlapping concurrent changes. If the same entity changed elsewhere, re-read the layer and begin a fresh session.
Validate and repair upstream changes
Section titled “Validate and repair upstream changes”astrato_semantic_layer_validate checks the semantic document. To check for database drift, call
astrato_semantic_layer_check_source_schema with fresh: true. A fresh check requires write access and may create
one draft revision when the database confirms that a referenced object is missing or has been
restored. Datatype changes and likely renames based on casing or separators remain suggestions.
A fresh check also executes each Custom SQL table’s statement once with its parameter defaults and
reports columns it no longer returns, type changes and new columns. Automatic checks in the editor do
this at most once a day per layer. Physical tables get no new-column report, because a table may
deliberately hold only some of its columns. A column that appears in the warehouse stays out until
someone applies its fix: it could be sensitive, and a field reaches dashboards and Nash. Changing a
statement is the exception. It adds the columns the change introduces, and on a table with no column
fields it adds every column the statement returns.
Validation also refuses a Custom SQL table whose statement holds more than one statement, stops half way, or is not a read-only SELECT or WITH query (a parenthesised query is also accepted).
Review every suggested fix and apply it only after explicit confirmation. Pass the exact runId,
entityKey, and revision returned by the check to astrato_semantic_layer_apply_source_schema_fix. See
Semantic layer issues for the meaning of each issue origin.
Repair an unsupported measure calculation
Section titled “Repair an unsupported measure calculation”astrato_semantic_layer_validate returns the affected measure, operand path, and validation error.
Prepare a change with astrato_semantic_layer_prepare_measure_change, naming the affected measure.
Its target includes the original definition, ordered field bindings, and repair guidance, including
in compact responses. Use astrato_semantic_layer_apply_measure_change with operation: "patch"
and a complete supported calculation in patch.calculation, using the prepared target and revision.
This replaces the broken calculation and preserves the measure’s presentation metadata. You do not
need the Dev tab. Validate again after repair; an unsupported formula must not be copied into a
new definition or silently replaced with a guessed calculation.
Review and repair issues
Section titled “Review and repair issues”- Use
astrato_semantic_layer_validatefor semantic-document errors and warnings, including aggregation support when live capability discovery succeeds for the layer’s active data connection. - Use
astrato_semantic_layer_check_source_schemafor database drift and source-check failures. A fresh check requires write access and can record confirmed missing or restored objects in a new draft revision. - Treat datatype and conservative rename findings as suggestions. Review the old and new values,
then call
astrato_semantic_layer_apply_source_schema_fixonly after confirmation. A finding reported as an error is one that would break a consumer if applied as-is — a rename included, since applying one also writes the replacement column’s datatype; read the accompanying consumer entries before deciding whether to apply the fix or repair the consumer first. - Identify the field a source-check finding or issue is about by its
viewNameandfieldName. Do not splitentityKey: it joins the two names with a dot, and either name can contain a dot itself. A field issue withoutviewNameandfieldNamecomes from a report that did not record them, where more than one view name followed by a dot beginsentityKey. It stays unattached even when only one of those fields still exists, so do not treat that field as its target.
After applying a fix, validate the layer again and confirm that the issue is resolved.
Benchmark questions
Section titled “Benchmark questions”Over MCP, astrato_semantic_layer_benchmark_questions runs the same benchmark, without the
concurrency test, for up to 25 questions per call. filterValues sets how many filter values to
test (0 to 5, default 3). It returns the score, each question’s time, query id, link and causes,
and the recommendations with their steps and documentation links. It runs real queries; its
description tells assistants to confirm with you before calling it.
Import a Snowflake semantic view
Section titled “Import a Snowflake semantic view”The order is astrato_semantic_layer_list_snowflake_views, then
astrato_semantic_layer_preview_snowflake_view_import, then
astrato_semantic_layer_import_snowflake_view with the preview’s revision and source hash.
To create a layer for the import, call astrato_semantic_layer_create first; it can also copy an
existing layer. No MCP tool imports a YAML file.
List the views available on the datasource, then preview the selected import. Review the conversion counts and diagnostics before continuing. Import only after the preview is confirmed, and copy its revision and source hash exactly. Import creates a draft revision and a named version, but does not publish the layer.
New imports preserve case-distinct physical columns and their references. For example, Snowflake
expressions "YEAR" and "Year" import as separate fields. Unquoted column identifiers use
Snowflake’s uppercase spelling. Semantic layers imported earlier are not updated automatically.
Average metrics written as AVG(...) retain the AVG aggregation in the imported measure.
The data connection’s normal aggregation restrictions still apply.
Snowflake filters (a fact or dimension labelled FILTER, and the standalone filters of a table)
import as Boolean dimensions in the Filters category. A filter fact is never turned into a
measure. A metric that conditions on a filter, such as SUM(IFF(discounted_line, revenue, 0)),
imports as a measure with that filter. Labels other than FILTER are still not imported and are
reported in the preview diagnostics.
The imported layer records which semantic view, and which element of it, each table, field, join, dimension, and measure came from. The Semantic Layer Editor uses this to report later changes to the view; see When an imported Snowflake semantic view changes.
Imported sources
Section titled “Imported sources”To check an imported Snowflake semantic view, call astrato_semantic_layer_check_source_schema with fresh: true and read
report.importChecks: one entry per import source, with a status of checked or unverified
and its findings, each with a status of changed, removed, not-imported, added or
renamed, the five results described in
When an imported Snowflake semantic view changes.
astrato_semantic_layer_unlink_import_source unlinks an imported source, as Unlink does in the
editor; it is an ordinary draft edit, reviewed and published like any other. See
When an imported view changes.
Where Databricks metric views are enabled, import one in this order:
astrato_semantic_layer_list_databricks_metric_viewslists the metric views on the connection. Each has a catalog (database), schema and name.astrato_semantic_layer_preview_databricks_metric_view_importreads and converts one metric view without changing the layer. It returns counts, warnings, a source hash and the layer’s revision.astrato_semantic_layer_import_databricks_metric_viewapplies it. Pass back the preview’s revision and source hash, and accept its warnings.
Version, export, and publish
Section titled “Version, export, and publish”astrato_semantic_layer_create_versioncreates a named, durable version of the draft head at call time. It does not publish. The tool does not acceptexpectedRevision, and its result does not identify the revision that was captured.astrato_semantic_layer_export_ossie(sl:read) exports the exact current validated V3 draft as Apache Ossie YAML. It does not publish. Advanced measures are retained as clearly labelled comment-only engine SQL; see Apache Ossie export.astrato_semantic_layer_export_snowflake_semantic_viewwrites the SQL that creates a Snowflake-backed layer as a Snowflake semantic view, for you to run in Snowflake. It does not publish or run anything; see Create a Snowflake semantic view.astrato_semantic_layer_preview_publishshows what publishing would send, without publishing. Publishing always sends the whole draft, including changes other people made in the editor or through another conversation or agent, not only yours. The result haschangeCountandcountsby type, which cover every change, andchanges, which lists up to 60 of them: each change’s type and name, whether it wasadded,changedorremoved, the draft revisions that made it, andchangedBywith each author’s name, channel (editor,nashormcp) andyouwhen it is your own account.omittedChangessays how many changes are not listed, andunattributedChangeshow many have no author on record; each is left out when it would be zero.changesByOthersistruewhen someone else made any of them. A change listed under your own account can still come from another conversation: compare its revisions with the ones your own commits returned. Before you offer or perform a publish, tell the user everything it lists, say when the names are partial, and name the changes you did not make. Pass itsexpectedRevisionto the publish tool once the user approves that whole set.astrato_semantic_layer_publishis a separate write. Call it only when publishing was explicitly requested, and pass the exact revision that was confirmed. After publishing, it rates the joins that publish added or changed with the engine’s join-quality check and returns them underjoinQuality. Tell the user about every join listed underneedsAttention, with its recommendation. The check never blocks or fails the publish. When it cannot run,notMeasuredsays why.
To rate joins before publishing, call astrato_semantic_layer_check_join_quality. It measures the
draft’s joins. Queries keep using the published joins until you publish, so the result lists under
publishedJoinsNotInDraft the published joins that the draft removes or changes. A join on a view
that is new or changed in the draft is measured on the draft when your workspace routes draft
analysis through an exit node. Otherwise it is listed under needsAttention with the status
awaitingPublish until you publish. The same applies to every join when the draft uses another
data connection.
When you create a version and publish in the same workflow, validate revision R, create the
version, then immediately re-read the summary. Publish with expectedRevision: R only if the
summary still reports R. If the revision changed, stop: the version may have captured a different
draft. The publish call’s expected-revision check protects against another edit after the re-read.
After any write, re-read the summary before relying on the current revision. Another editor may have committed after the tool response.
astrato_semantic_layer_export_snowflake_semantic_view takes database, schema and name, so
the script arrives already targeted; name defaults to the semantic layer’s name in upper snake
case. The script comes back only on a call with finalize: true.
astrato_semantic_layer_export_databricks_metric_view attaches the .sql file and lists what was
left out.
Failure handling
Section titled “Failure handling”- Ambiguous match: review the alternatives and resolve the ambiguity before continuing. Do not guess.
- Stale revision: re-read the layer, then prepare or plan the change again.
- Validation failure: report the affected entity and diagnostics; do not publish or retry with invented data.
- Typed-workflow no-op: report that the layer was already in the requested state. Atomic and batch tools do not create a revision for a no-op.
- Missing scope or unavailable MCP endpoint: report the access needed. Do not fall back to undocumented HTTP calls or raw V3 edits.
What next
Section titled “What next”- Semantic layer authoring reference — stored measure expressions, filter conditions and the complete V3 document.
- Semantic layer issues — what each issue origin means, which tool returns it, and which findings hold a publish back.
- Business questions guide — a layer’s stored questions, listed, read and executed by ID over MCP without constructing engine JSON.
- Semantic layer entity model — what a V3 document holds and how its entities reference each other, when a typed change needs that context.