# Agent guide: pitfalls and learnings

> Best practice for AI agents working in a Konstrukt tenant — working rules, and known pitfalls in Kex, writes, the data model, calculations, app configuration, actions and history, with links back to the platform pages they concern.

This page collects what agents most often get wrong when they work in a Konstrukt tenant through the MCP server, the REST API or the Kex console. The platform pages describe how things work. This page describes the traps.

Each section has a stable anchor, and the platform pages link here from the part they concern. Read the whole page once before making changes in a tenant. Then return to the relevant section before each kind of task.

!!! agent "Where authoritative guidance lives"
    The MCP server serves its own guidance as resources: `KexGuidelines.md` (rules for generated scripts), `KexKnowledge.md` (known pitfalls) and `GeneralInstructions.md`. Tenant-specific conventions are in `konstrukt://TenantInstructions.md`. When these resources and this page disagree, the server's resources win for that tenant and version.

## Working rules {#working-rules}

These rules come from the server's own guidance and apply to any agent, including the in-product assistant Kai.

1. **Read `konstrukt://TenantInstructions.md` first** when you start work on a tenant, then the tenant documents it links to.
2. **Load knowledge on demand.** Start with `KexOverview.md`. Open the full reference only when you need it.
3. **Validate before returning or running a script.** Use `validate_script`. On errors, fix and retry a limited number of times (about five), using the error messages.
4. **Never validate or run write scripts in an automated retry loop.** A write is a destructive operation and needs explicit confirmation from the user.
5. **Resolve names from the model and ask only when it is ambiguous.** Syntax questions get a generic example without a model lookup. For data questions, fuzzy-match names against the model. Ask only when two candidates are equally plausible or the data exists in several plans. Never ask the same question twice.
6. **Read the app-config schema before writing configuration.** See [App configuration](#app-configuration).
7. **A calculation must write.** A saved calculation needs a valid `write to`. Create and update both validate on the server.
8. **Respect destructive semantics.** See [Destructive operations](#destructive-operations).

A safe opening sequence on an unknown tenant:

1. `resources/read konstrukt://TenantInstructions.md`
2. The `konstrukt://tenant/…` documents it links to
3. `list_plans` (note `isDefault`)
4. `get_data_model(planId, include="*")`
5. `KexOverview.md`

For any change, show the user the validated script or payload and wait for confirmation before calling a write tool.

## Identifiers {#identifiers}

- Value type and dimension IDs are **strings** (`"Amount"`, `"Department"`).
- Plan, calculation, property and reference IDs are **integers**.
- App IDs are **GUIDs**.
- Display names and IDs often differ. A value type named *Other forecast.Account* may have the ID `OtherForecastAccount`. Always resolve IDs with `get_data_model` or `list_value_types` rather than deriving them from names.
- Dimension codes are strings, even when they look numeric: `Month in {"202601"}`.

## Kex {#kex}

Pitfalls in queries. The language itself is described on the [Kex](kex.html) page.

- **Aggregate before windowing.** A value type often has more dimensions than a query shows, so a window applied to it directly partitions over all of them. Aggregate into a `var` with only the dimensions you need, then apply the window.

    ```kex
    var A = sum(Amount), Account, Month
    Cumulative = sum(A) over all previous rows ordered by (Month) partitioned by (Account)
    ```

- **Custom grouping can duplicate rows.** Group by dimensions, not by free-text properties, and aggregate variable queries.
- **Variables need a value column and unique rows.** `var x = Month` is invalid; `var x = Month, 1` is valid.
- **Cross-plan reads use the other plan's dimensions.** Custom `dim` variables are ignored inside `from plan`. The current plan must have every dimension the foreign data uses.
- **`from` clauses come after grouping.** `from plan`, `from reference` and `from history` must follow `group by`, `having` and `order by`.
- **`apply dim formatting`** works in evaluation results only, not in variables.
- **Clause order is strict.** It runs select → include options → `where` → grouping → `from …` → `limit`/`check`/`apply`. See [Clause order](kex.html#clause-order).
- **Do not invent syntax.** Some valid constructs are missing from the generated reference; they are described under [Control flow and messages](kex.html#control-flow-and-messages). Use a construct only when `validate_script` accepts it.
- **No queries or writes inside `if` blocks.** Blocks hold `var`, `scalar`, `dim`, `set`, nested `if` and `fatal`. Write after the block. Never assume that a keyword from SQL or DAX exists.
- **Each variable needs its own `from plan N`.** A `from plan` clause applies to one query, not to the whole script. Without it, a variable reading another plan fails with *Unknown identifier*.
- **`dimset` works only in table-valued variables** (`var X = …`), not directly in a `write` query.
- **Keep scripts short.** Separate select expressions with commas, leave out redundant `group by`, and add comments sparingly. This makes scripts easier for users to review.

## Writes {#writes}

The semantics are on the [Kex](kex.html#write-variants) page. These are the consequences that surprise agents:

- **The write target resolves in the default plan** for scripts run through MCP, the REST API or the console. `from plan N` in the query changes where data is *read* from, not where it is *written*. Start the script with `use plan N` to make plan N the context for everything after it, including write targets and `makecode … within`. See [`use plan`](kex.html#use-plan).
- **With no keyword, a write is an upsert** outside a calculation, and nothing is deleted. Use `replacement` to remove rows that are not in the result.
- **`replacement` outside a calculation does not delete calculated rows**, and `update` does not modify them. Calculated data is owned by its calculation.
- **Inside a calculation, the first write to a target clears that calculation's earlier rows.** Later writes to the same target in the same run upsert. A calculation never touches other calculations' rows or user-entered rows.
- **`suggestion` is valid only in calculations.** The last suggesting calculation to a target deletes earlier suggestions, unless `insert` or `upsert` is used. Let only one calculation suggest into a given value type.
- **A user value does not replace a calculated value.** Upserting data into a cell a calculation writes creates a separate, non-calculated row, and reads sum the two. To override a calculated number, change its inputs, or write the calculation with `suggestion`.
- **`exclude calculated` still returns suggestions.** Suggested rows carry no calculation ID.
- **Keep write blocks disjoint.** Several `write` blocks to the same target in one calculation should have mutually exclusive conditions, for example on period flags. If they overlap, the result depends on statement order, and the overlapping cells are rewritten on every run, which adds history versions even when the final value is unchanged. See Disjoint writes.
- **Data written through MCP or import tools gets line state 0** (suggested/imported), not 10 (edited in the interface).
- **There is no `write upsert to`.** A plain `write to` already upserts outside calculations; `upsert` is only valid as `write upsert suggestion to`.
- **Every dimension of the target must be assigned**, either implicitly or with `Dim = …`, and the value column is `$result`.
- **Writing an identical value creates no history row.** This is fine, but do not use history to detect whether a script *ran*.

## Data model {#data-model}

- **Changing a value type's dimensions requires emptying it**, and emptying also deletes its history, which removes the basis for point-in-time references. Propose a new value type instead, unless the user explicitly accepts losing history. See [Data model](data-model.html#changing-a-value-types-dimensions).
- **Property bindings must not be circular.**
- **Creating dimension values on import** (*Skapa nya dimensionsvärden*) turns every unknown code into a new member. Check codes against the dimension first, or misspelled codes become new members.
- **Sensitive value types** hide values, not rows, from users without the permission (for example the Limited Builder role). Rows without values can be an access effect rather than missing data. The SQL views do not hide sensitive values.
- **Descriptions are read by other agents.** Put the grain, sign convention, currency and writing calculation in value-type and calculation descriptions.

## Calculations {#calculations}

- **Guided to script is one-way.** Removing the `@@model` annotation and saving permanently turns a guided calculation into a script calculation. Do not strip annotations from guided calculations you edit.
- **Check the graph before changing a calculation.** Call `get_calculation_graph` with `referencedEntityIds` or `outputEntityIds` to see what depends on the value types you touch.
- **Cycles are detected when a calculation is activated**, not when it is saved. A valid script can still be rejected by the graph.
- **An invalid calculation does not run.** Check `isValid` and `validationMessages` in `list_calculations` before trusting numbers downstream of it.
- **Recalculation propagates.** A write to a widely read input value type re-runs every dependent calculation. Batch changes instead of writing row by row, and check `get_running_calculations` before reading results that depend on the change.
- **Write sparsely.** Use `having $result != 0` where zeros carry no meaning.
- **Do not promote precalculations** (`Calc<id>`) in new work. Use variables inside the calculation, or a value type.

## App configuration {#app-configuration}

- **Read the schema first.** Use `get_app_config_schema` with the types you will write. Several fields are polymorphic, discriminated by `$type`. Component filter items and presentation-rule value conditions use `Type` instead. A guessed payload can parse but silently omit data.
- **Do not guess property names one at a time.** Read the types with `get_app_config_schema` before writing, for example `["WorkspacePage", "MatrixLayout", "BarChartComponent"]`. When a write is rejected, use the shape the error shows instead of trying another name. A workspace page holds one `MainComponent`, so a chart beside a table needs a `MatrixLayout`.
- **Patch, do not rewrite.**
    1. Find the position with `search_app_config` (JSONPath such as `$..MainComponent`); note the pointer and the etag.
    2. Build a JSON Patch that changes only what the task needs. Start with a `test` op on a value you expect, so a stale pointer fails instead of editing the wrong node.
    3. Run `patch_app_config` with `dryRun: true` and check the reported changes.
    4. Run it for real with `ifMatch` set to the etag.
    5. Read the changed part back with `search_app_config`.
- **Use `overwrite_complete_app_config` only for wholesale rewrites**, based on `load_complete_app_config` and with `ifMatch`. Validate with `validate_complete_app_config` first.
- **Dataset IDs are integers.** `"DatasetId": 1`, not `"1"`; component IDs stay strings.
- **Writing works in v2 plans only.**
- **Never guess enum codes.**
    - Spread is `0`, `1`, `3` or `4`; there is no `2`.
    - Format codes are `1`–`4` or `6`; there is no `5`.
    - Take line states, line access and display-format IDs from the schema or from these docs.
- **Colours are written without `#`** (`"1F9AAD"`), although the schema text says otherwise. Follow what `load_complete_app_config` returns.
- **References in metrics use the bare ID.** `Metric.DataType` and `Compare.DataType` take `"12"`, not `"Reference_12"`; the latter silently compares against nothing.
- **External-link placeholders are `{DimensionId}`**, not `{d_DimensionId}` as the schema text says.
- **`create_app_with_config` needs an `Id`** in the JSON (any GUID). Check `list_apps` after an error; earlier versions could leave an empty app behind when validation failed.
- **A grid without a value-type axis sums across value types.** Put value types on a pivot or grouping axis when a dataset has more than one.
- **Unknown metric icons are silently removed.** Use names from the fixed server list.
- **Name and description are not part of the configuration.** They are parameters of `create_app_with_config`. MCP has no tool to rename or copy an app.
- **Saving through the admin editor is not round-trip.** Comments, unknown attributes and legacy attributes are dropped. See [App configuration](app-config.html#saving-is-not-round-trip).
- **Component errors surface late** and without line numbers. Change one component at a time.
- **Initial values grow the client dataset.** Every placeholder row is held in the browser. Broad expansions on large dimensions cost memory and rendering time, not server load. Scope sets with properties and flags.
- **Hiding an app blocks it completely.** `Access.Enabled = false` removes the app from end-user lists, and opening it by URL gives *access denied*, also for administrators.
- **Copying an app does not copy its comments.**
- **Changes are live.** Users see a changed configuration immediately. Confirm before overwriting a production app.

## Actions {#actions}

- **Actions change data directly** when a user runs them. Treat the script as a write script: validate it and show it to the user.
- **The variable filter panel stays empty until the action is saved.** Save the action first, then configure variable filters.
- **Use `exclude calculated`** in remove-style actions (`write replacement … exclude calculated where not (…)`), so that calculated rows are never rewritten.

## Imports and destructive operations {#destructive-operations}

- **`replace_value_type_data` deletes every row missing from the payload.** Use upsert unless a full replacement is intended.
- **`delete_app` deletes the app.** `delete_plan` requires an archived plan.
- **`Replace` mode on the access imports** replaces existing entries.
- **Duplicate rows in an import** are aggregated or rejected depending on the chosen option. Aggregate the payload yourself so that the result is predictable.
- **`import_users` creates no logins.** On SSO tenants, sign-in is handled by the identity provider.

## History and deletion {#history}

- **Deleting data does not delete its history.** Earlier versions stay readable through `from history` and point-in-time references. Never tell a user that a deletion removed data from the system entirely.
- **A point-in-time reference is rewritten to `from history … values only`.** Rows referring to dimension values that have since been deleted are filtered out.
- **Copying a plan empties its point-in-time references.** The copy includes everything except the history tables, so point-in-time references return nothing. Recreate them from new timestamps, or keep reading from the original plan.
- **References cannot change type.** A data reference cannot become a point-in-time reference, or the other way round.

## Known issues {#known-issues}

- **Use as filter** (*Använd som filter*) in the cell context menu has no effect on a value cell. It works only when chosen on a dimension value. Do not instruct users to use it on value cells.

## Related

- [AI agents and MCP](ai-agents.html)
- [Kex](kex.html)
- [App configuration](app-config.html)
