Best practice
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.
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#
These rules come from the server's own guidance and apply to any agent, including the in-product assistant Kai.
- Read
konstrukt://TenantInstructions.mdfirst when you start work on a tenant, then the tenant documents it links to. - Load knowledge on demand. Start with
KexOverview.md. Open the full reference only when you need it. - 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. - Never validate or run write scripts in an automated retry loop. A write is a destructive operation and needs explicit confirmation from the user.
- 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.
- Read the app-config schema before writing configuration. See App configuration.
- A calculation must write. A saved calculation needs a valid
write to. Create and update both validate on the server. - Respect destructive semantics. See Destructive operations.
A safe opening sequence on an unknown tenant:
resources/read konstrukt://TenantInstructions.md- The
konstrukt://tenant/…documents it links to list_plans(noteisDefault)get_data_model(planId, include="*")KexOverview.md
For any change, show the user the validated script or payload and wait for confirmation before calling a write tool.
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 withget_data_modelorlist_value_typesrather than deriving them from names. - Dimension codes are strings, even when they look numeric:
Month in {"202601"}.
Kex#
Pitfalls in queries. The language itself is described on the Kex 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
varwith only the dimensions you need, then apply the window.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 = Monthis invalid;var x = Month, 1is valid. - Cross-plan reads use the other plan's dimensions. Custom
dimvariables are ignored insidefrom plan. The current plan must have every dimension the foreign data uses. fromclauses come after grouping.from plan,from referenceandfrom historymust followgroup by,havingandorder by.apply dim formattingworks 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. - Do not invent syntax. Some valid constructs are missing from the generated reference; they are described under Control flow and messages. Use a construct only when
validate_scriptaccepts it. - No queries or writes inside
ifblocks. Blocks holdvar,scalar,dim,set, nestedifandfatal. Write after the block. Never assume that a keyword from SQL or DAX exists. - Each variable needs its own
from plan N. Afrom planclause applies to one query, not to the whole script. Without it, a variable reading another plan fails with Unknown identifier. dimsetworks only in table-valued variables (var X = …), not directly in awritequery.- 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#
The semantics are on the Kex 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 Nin the query changes where data is read from, not where it is written. Start the script withuse plan Nto make plan N the context for everything after it, including write targets andmakecode … within. Seeuse plan. - With no keyword, a write is an upsert outside a calculation, and nothing is deleted. Use
replacementto remove rows that are not in the result. replacementoutside a calculation does not delete calculated rows, andupdatedoes 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.
suggestionis valid only in calculations. The last suggesting calculation to a target deletes earlier suggestions, unlessinsertorupsertis 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 calculatedstill returns suggestions. Suggested rows carry no calculation ID.- Keep write blocks disjoint. Several
writeblocks 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 plainwrite toalready upserts outside calculations;upsertis only valid aswrite 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#
- 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.
- 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#
- Guided to script is one-way. Removing the
@@modelannotation 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_graphwithreferencedEntityIdsoroutputEntityIdsto 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
isValidandvalidationMessagesinlist_calculationsbefore 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_calculationsbefore reading results that depend on the change. - Write sparsely. Use
having $result != 0where zeros carry no meaning. - Do not promote precalculations (
Calc<id>) in new work. Use variables inside the calculation, or a value type.
App configuration#
- Read the schema first. Use
get_app_config_schemawith the types you will write. Several fields are polymorphic, discriminated by$type. Component filter items and presentation-rule value conditions useTypeinstead. 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_schemabefore 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 oneMainComponent, so a chart beside a table needs aMatrixLayout. - Patch, do not rewrite.
- Find the position with
search_app_config(JSONPath such as$..MainComponent); note the pointer and the etag. - Build a JSON Patch that changes only what the task needs. Start with a
testop on a value you expect, so a stale pointer fails instead of editing the wrong node. - Run
patch_app_configwithdryRun: trueand check the reported changes. - Run it for real with
ifMatchset to the etag. - Read the changed part back with
search_app_config.
- Find the position with
- Use
overwrite_complete_app_configonly for wholesale rewrites, based onload_complete_app_configand withifMatch. Validate withvalidate_complete_app_configfirst. - 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,3or4; there is no2. - Format codes are
1–4or6; there is no5. - Take line states, line access and display-format IDs from the schema or from these docs.
- Spread is
- Colours are written without
#("1F9AAD"), although the schema text says otherwise. Follow whatload_complete_app_configreturns. - References in metrics use the bare ID.
Metric.DataTypeandCompare.DataTypetake"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_configneeds anIdin the JSON (any GUID). Checklist_appsafter 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.
- 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 = falseremoves 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 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 calculatedin remove-style actions (write replacement … exclude calculated where not (…)), so that calculated rows are never rewritten.
Imports and destructive operations#
replace_value_type_datadeletes every row missing from the payload. Use upsert unless a full replacement is intended.delete_appdeletes the app.delete_planrequires an archived plan.Replacemode 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_userscreates no logins. On SSO tenants, sign-in is handled by the identity provider.
History and deletion#
- Deleting data does not delete its history. Earlier versions stay readable through
from historyand 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#
- 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.