# Tool reference

> Every tool of the Layerz MCP server, with its annotations, its description and its parameters, generated from the server itself.

The 29 tools exactly as a client lists them, for a full-access key. A read-only key or a key limited to one model sees fewer. Annotations: **read-only** tools never write; **destructive** tools can overwrite or delete; **idempotent** tools can be retried safely.

## layerz_build_from_blueprint

**Build from blueprint** · destructive

Builds or extends a model from a strict Blueprint (whole sections with their hierarchy, items referenced by name), or applies a stored template as a module through `template_id` (mutually exclusive with `blueprint`, loaded server-side). `mode: 'merge'` (default) adds to the model, reusing items by name and keeping the presentation fields a re-declared item omits; `mode: 'replace'` rebuilds the whole model (structure, timelines, values, branches), keeping style colours, custom formats, locale, glyph, subtitle and FINANCE.md. `dry_run: true` validates and returns errors with their path without writing; `apply_if_clean: true` validates and writes only when there is no error (one call instead of a dry run then the same blueprint again). A large blueprint can come as `file_id` (a JSON file uploaded through `layerz_create_upload_url`) instead of `blueprint`. UIDs are stable for a given model, so a dry run's `name_to_uid` holds for the apply. The result is concise: `name_to_uid`, counters, warnings / errors, `version_number` and `revision_id`, `health` when the model has checks; `include_items: true` adds every item of the model. Persists one version labelled with `summary`. The result carries `conventions` (workspace conventions + model FINANCE.md, as in `layerz_get_conventions`) when either is set. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `blueprint` | `object \| string` |  | Strict Blueprint object: { project?, timelines?: { monthly? \| quarterly? \| yearly?: { start, end } }, lists?: [{ display_name, items: [{ label, mapped_to?: Record<listName, labels[]> }] }], sections: [{ name, collapsed?, sections?: [sub-sections, same shape], items: [{ role, name, timeline_ref?, value?, values?, formula?, item_style?, opening_balance?, liste_ref?, timeline_values?: Record<elementLabel, (number\|null)[]>, children?, … }] }], dashboards?: [{ name, items: [{ role: chart \| kpi \| mini_table, … }] }] } (`charts` / `kpis` / `tables` arrays are accepted in place of `items`). At least one section is required. Items reference each other by name (formula inputs, callup source, chart series); a callup omits `name` and inherits its source's. A list-mode item binds a declared list through `liste_ref` and carries `timeline_values` keyed by element label; a `balance` with `liste_ref` requires every list-typed child to share it. Accepted as a JSON object or a JSON-encoded string. |
| `template_id` | `string` |  | Stored template to apply as a module (mutually exclusive with `blueprint`). |
| `file_id` | `string` |  | Uploaded JSON file holding the blueprint (`layerz_create_upload_url`), instead of `blueprint`. |
| `mode` | `"merge" \| "replace"` |  | 'merge' (default): adds to the existing model, reusing items by name. 'replace': rebuilds the whole model from the blueprint. |
| `dry_run` | `boolean` |  | Validates the blueprint and reports errors without writing. |
| `apply_if_clean` | `boolean` |  | Validates, then writes only when there is no error (else answers as a dry run). |
| `include_items` | `boolean` |  | Also return every item of the resulting model (large). |

## layerz_create_model

**Create model**

Creates a model and returns its detail with its UUID, in `workspace_id` (a workspace the caller belongs to; default the personal one) where every member of that workspace edits it. `template_id` copies a template (official, or from the library of a workspace the caller belongs to) into the new model with its sources, staged transactions and mapping rules under fresh ids (connector credentials excluded); the template itself is unchanged. `timelines` sets the grains and bounds (only the grains given: `{ monthly }` alone gives a monthly-only model; on a template, the bounds), `glyph` its emblem (a kebab-case Lucide icon name, e.g. `trending-up`, `landmark`, `house`, `coffee`, `wallet`). `file_id` imports an uploaded workbook instead (deterministic compiler, no AI) and returns `{ model_id, name, status: "importing" }` with `guidance` (the rebuild method) at once: the import runs after the response (about a minute for a large workbook), then its report (fidelity by scenario, residue, constructions map) lands in the model FINANCE.md (`has_finance_md`); a failed import deletes the model. The workbook stays with the model for `layerz_diff { source }`. Undated period headers return `IMPORT_DECISION_REQUIRED` with the axes to anchor (`anchors`). `conventions` carries the conventions of the workspace it lands in and its FINANCE.md (as in `layerz_get_conventions`) when either is set. Rejected past the plan model cap. Not advertised to model-scoped or read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | `string` |  | Model name. Required without `file_id`; an imported workbook names the model after its file. |
| `subtitle` | `string` |  |  |
| `glyph` | `string` |  | Emblem icon: a kebab-case Lucide icon name (https://lucide.dev/icons), e.g. "trending-up", "coffee", "landmark". Shown in-app and on the social/OG card. Emojis/free text are rejected with suggestions. Aliases: cash/money→banknote, bank→landmark, cart→shopping-cart, chart/graph→chart-line. |
| `template_id` | `string` |  |  |
| `file_id` | `string` |  | An uploaded workbook (`layerz_create_upload_url`) the model is imported from by the deterministic compiler: live formulas, values where a formula has no equivalent, and the import report (`import`: fidelity, residue, recalculation coverage, constructions map). Exclusive with `template_id`. |
| `anchors` | `object[]` |  | With `file_id`: the first period (`2026`, `2026-01`, `2026-Q1`) of each sheet whose period headers carry no date, as listed by an `IMPORT_DECISION_REQUIRED` error; `[]` leaves those sheets out. |
| `workspace_id` | `string` |  | Workspace the model is created in (one the caller belongs to; `layerz_list_models` lists them). Default: the personal workspace. |
| `timelines` | `object` |  |  |

## layerz_create_upload_url

**Create file upload URL**

Issues a signed Storage URL for an Excel/CSV file and returns `file_id`, `signed_url`, `upload_expires_at`, `expires_at`. `signed_url` accepts one HTTP PUT of the file body with the declared content type within 2 h of issue (`upload_expires_at`): create the URL right before the PUT (a shell `curl -X PUT --data-binary @file`; the binary stays out of the conversation); after that a new call issues a fresh URL and `file_id`. The uploaded `file_id` is the identifier the file-consuming tools take, readable for 24 h (`expires_at`). Limits: 25 MB, MIME whitelist (xlsx, xls, csv, json, txt). Mints no model data, so it stays available to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `filename` | `string` | yes | Original filename, e.g. "actuals_q1.csv". |
| `size` | `integer` | yes | File size in bytes (max 25 MB). |
| `content_type` | `string` | yes | MIME type, e.g. "text/csv" or the xlsx content type. |

## layerz_delete_branch

**Delete branch** · destructive · idempotent

Deletes a branch, every input row tagged with its `dataset_id`, and the data sources that fed only that branch (their staged transactions with them); a source shared with another branch is detached instead. The default branch is rejected. Returns `deleted_dataset_id`, `inputs_removed`, `sources_removed`. Persists one version labelled with `summary`. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `dataset_id` | `string` | yes |  |

## layerz_dependencies

**Trace dependencies** · read-only · idempotent

Returns an item's dependency graph, like Excel trace precedents / dependents: `precedents` (items its formula references) and `dependents` (items referencing it). `depth` (1–5) walks transitively, `direction` restricts to one side.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `uid` | `string` | yes | Item UID to trace (role-prefixed forms accepted) |
| `depth` | `integer` |  | Transitive depth to walk (1 = direct only). Default: 1. |
| `direction` | `"precedents" \| "dependents" \| "both"` |  | 'precedents' = what feeds the item, 'dependents' = what references it, 'both' (default). |

## layerz_diff

**Diff two versions** · read-only · idempotent

Returns the semantic diff between two revisions of a model: `{ from, to, diff: { items: [{ uid, displayName, status, fields? }], branches: [{ id, display_name, status?, items }], metadata: [...], summary: { added, removed, modified, branches } } }`. `items` compares the base plan; `branches` lists, per branch, the overlay cells it records over the base (`null` where the base shows through): a write under `branch_id` or an import on a branch appears there, not as a base change. `from` and `to` each take exactly one of `revision_id`, `version_number` or `id`; without `to`, the diff runs against the live model. `sources` carries the delta of the source settings and bindings (`sources[] { id, display_name, status, fields[] }`) and of the mapping rules (`rules { added, removed, changed }`), present when both endpoints carry that state. `values: true` adds `values`, the computed-values diff: `{ granularity, scope, tolerance, computable, items: [{ uid, display_name, status?, changed, cells: [{ period, before, after, delta }] }], summary: { items_compared, items_changed, cells_changed, max_abs_delta, truncated } }`: the periods whose value moved beyond `tolerance`, on the lines `uids` names, else the key lines (checks, totals), else every value line; computed on the base plan or under `branch_id`, at `granularity`. `computable: false` with `errors` per endpoint when a revision cannot be computed. `source` (in place of `from`): the live model against its source workbook recalculated.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `from` | `object` |  | Older endpoint: exactly one of revision_id / version_number / id. Required unless `source`. |
| `source` | `object` |  | Compares the live model (base plan or `branch_id`) with the workbook it was imported from, recalculated by the Excel engine with the cells of `set` overridden (a scenario; none = as saved). Lines: the ones the import linked to their cells, `uids` restricts them, `refs` links rebuilt ones. Each listed line (gaps only, 50 at most, largest first) carries `cells`, `compared`, `off` and `first_gaps: [{ period, source, model, delta }]`; `summary` counts every line (`score`: the share of cells reproduced, `lines_compared`, `lines_matching`, `cells_compared`, `cells_off`, `max_abs_delta`); `unlinked` names the asked uids with no source cells. |
| `to` | `object` |  | Newer endpoint; omitted = the current live model. |
| `values` | `boolean` |  | Adds the computed-values diff of the two revisions under `values` (the numbers, not the formulas). |
| `uids` | `string[]` |  | With `values`: the lines compared (default: checks and totals). With `source`: the lines compared (default: every linked line). |
| `branch_id` | `string` |  | With `values`: the branch whose `[base, branch]` checkout both revisions are computed under; with `source`: the branch the model is computed on. Absent = the base plan. |
| `granularity` | `"monthly" \| "quarterly" \| "yearly" \| "native"` |  | With `values`: the dated grain of the comparison; `native` (default) = the finest active grain. |
| `tolerance` | `number` |  | With `values` or `source`: absolute difference above which a cell counts as changed (default 0.01). |

## layerz_export

**Export to file**

Generates a file from a model and returns `{ download_url, filename, size, file_id, expires_at }`. `target: 'model'` (default) is the Excel workbook (the same export as the web app: Intro + per-section sheets, native charts and dashboards, live formulas), plus `structure_hash` / `values_hash`; when the model has branches, the statements and single-value widgets follow `branch_id` (default: the base branch) while dashboards keep every branch they break down by. `target: 'transactions'` is the full staged import of the data source `source_id` as a CSV file (no filters, no routing annotations), plus `row_count`. Each call persists a new private file in Storage, where the file and its signed `download_url` expire after 24h; the model itself is not modified, so the tool stays available to read-only keys, off quota.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `target` | `"model" \| "transactions"` |  | model (default): the Excel workbook of the model. transactions: the staged import of `source_id` as a CSV file. |
| `branch_id` | `string` |  | target model only. Branch the statements and single-value widgets follow (default: the base branch). Dashboards keep every branch. |
| `source_id` | `string` |  | target transactions only (required there). Data source id as returned by layerz_list_integrations. |

## layerz_external_ref

**Link, refresh or unlink external reference** · destructive

Manages the links from this model to items of other Layerz models (an external ref, like an Excel linked workbook), by `op`. `link`: creates (or retargets, with `uid`) a non-list assumption whose `values` hold a snapshot of the source item's computed series projected to this model's grain (`null` outside the source's coverage); requires read access to the source model; the line is referenceable in formulas like any assumption; up to 200 links in `links` (one form per call) load each source once, are validated whole (one failure writes nothing) and return `results`. `refresh`: re-reads every linked source (or `uids`) and rewrites the snapshots, the only way the values move; a per-link failure (source or item gone) leaves the stored values intact; when values change, the pre-refresh state is snapshotted first (`Auto-backup before refresh`). `unlink`: detaches the line `uid`, keeping its values as an ordinary assumption. A self-link is rejected; a cross-model cycle resolves one hop per refresh. Link status and staleness: `layerz_list_integrations { include_external_refs: true }`. Persists one version labelled with `summary`. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `op` | `"link" \| "refresh" \| "unlink"` | yes | link \| refresh \| unlink. |
| `source_model_id` | `string` |  | `link`: the model read from. |
| `source_uid` | `string` |  | `link`: uid of the source item in that model. |
| `uid` | `string` |  | `link`: existing non-list assumption to retarget. `unlink`: the linked line to detach. |
| `parent` | `string` |  | `link` (create): parent container uid (section / formula / balance / dashboard). |
| `name` | `string` |  | `link`: display name (default: the source item's name). |
| `timeline_ref` | `"constant" \| "monthly" \| "quarterly" \| "yearly"` |  | `link`: grain of the linked line (default: the source's grain when active here, else the finest active grain). |
| `links` | `object[]` |  | `link`: up to 200 links written as one batch, in place of the flat fields. |
| `uids` | `string[]` |  | `refresh`: restricts the refresh to these linked items (default: all). |

## layerz_get_conventions

**Get conventions** · read-only · idempotent

Returns the conventions the tools' values are expressed in: `custom_instructions` (the conventions of a workspace, the standing instructions for AI agents its members share, ≤ 3000 chars, empty string when unset; also carried as `conventions` by the entry tools on a model), `workspace` (`{ id, name, kind }`: the targeted model's workspace when the caller is a member of it, else `workspace_id`, else the personal workspace) and, when a model is targeted, `finance_md` (the model's FINANCE.md: `raw` Markdown, `source`, `spec_version`, parsed `front_matter` with currency / units / sign convention / glossary, `validation_errors`; `null` when the model has none). `include_guide: true` adds `guide`, the modeling guide (session workflow, structure, stock-flow, lists, branches, sources, templates, checks, versions; also the resource `modeling-guide://reference`); `include_formula_spec: true` adds `formula_spec`, the formula language (functions, lags, list subscripts; also the resource `formula-spec://reference`), for a client that cannot read resources.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `workspace_id` | `string` |  | A workspace the caller belongs to (`layerz_list_models` lists them); default: personal. |
| `include_guide` | `boolean` |  | Also return the modeling guide (Markdown). |
| `include_formula_spec` | `boolean` |  | Also return the formula language reference (Markdown). |

## layerz_get_model

**Get model detail** · read-only · idempotent

Returns the full detail of a model: items, lists, timelines, custom `formats`, `number_locale`, `glyph`, `revision_id` (sha256 fingerprint) and `version_number`, plus `branches[]` (id, display_name, priority, actuals_through, actuals_through_locked) and `sharing` with the roster (`members[]`: owner, collaborators and pending invites with their roles and ids, `is_owner`, `link_visibility`: `invite` = sign-in required, `public` = anyone with the link reads it). Item values are the base plan; read a branch with `layerz_read` `branch_id`. Larger payload than `layerz_read`, which returns a filtered snapshot. `conventions` carries the workspace conventions and the model FINANCE.md (as in `layerz_get_conventions`) when either is set.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |

## layerz_history

**List version history** · read-only · idempotent

Returns the version history of a model, newest first: `{ current_revision_id, current_version_number, history_days, hidden_count, oldest_hidden_at, pinned_count, max_pinned_versions, versions: [{ revision_id, version_number, created_at, trigger_type, actor_user_id, label, conversation_id, pinned }] }`. Each version is a full snapshot persisted at one mutation boundary; `revision_id` (sha256 of the snapshot) is stable while the model is unchanged. Versions older than the plan window are counted in `hidden_count` but not listed; pinned versions stay listed whatever their age. `limit` and `since` scope the list. With `uid`, returns instead that item's change events across the history: `{ uid, events: [{ revision_id, version_number, created_at, actor_user_id, trigger_type, status: added | removed | modified, fields?: [{ field, oldValue, newValue }], branches?: [{ id, display_name, status, fields? }] }] }`: `fields` describes the base plan, `branches` the overlay cells a branch records over it (a write under `branch_id` or an import on a branch lands there, not in `fields`).

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `uid` | `string` |  | Item UID: returns that item's change events instead of the version list. |
| `limit` | `integer` |  | Max versions returned (default 100; with `uid`, max versions scanned, default 50). |
| `since` | `string` |  | ISO timestamp lower bound on the version list (ignored with `uid`). |

## layerz_import_branch

**Import data into branch** · destructive

Writes values onto a branch of the model, creating the branch when `branch.id` names none (`branch.display_name` required then). Two sources, mutually exclusive: `entries[]` (one value per item and period, items resolved by `item_uid` or `item_label`, created as assumptions when absent; `entry_uid` / `entry_label` target one entry of a list-mode item) or `file_id` (an uploaded spreadsheet parsed server-side, rows classified with the source's mapping rules). A new version of a file already imported: `file_id` + `replace_source_id`, nothing else (refreshed in place on the branch it feeds, default included). A first file onto the base: `file_id` + `branch.id: "default"` (a new source, own rows only). A new file of a kind the model already has: `file_id` + `rules_from_source_id` (classified with that sibling's rules, copied onto the new source). An entry's `timeline_ref` equals the target item's grain or `constant`; on a `formula` / `balance` it is a per-period override; on a `callup` it lands on the source. `replace: true` (with `branch.id`) wipes the branch's rows before writing; `replace_scope: 'import'` wipes only this source's own rows; `merge: true` upserts cell by cell; `dry_run: true` returns the impact without persisting (`purged_periods`, `overridden_items`, `validation_errors_new`, `suggested_replace_source`). Returns counts, `warnings` and, on the file path, `skipped`, `opening_entries`, `rules_copied`, `file_structure`. Persists one version labelled with `summary`.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `branch` | `object` | yes |  |
| `replace` | `boolean` |  |  |
| `replace_scope` | `"branch" \| "import"` |  |  |
| `merge` | `boolean` |  |  |
| `dry_run` | `boolean` |  |  |
| `confirm_replace` | `boolean` |  | Replaces a source whose new version would empty its lines (refused otherwise with IMPORT_CONFIRMATION_REQUIRED and a replace_preview). |
| `record_import` | `object` |  |  |
| `entries` | `object[]` |  |  |
| `file_id` | `string` |  | Upload id from layerz_create_upload_url ('f_' + 16 hex chars). Alternative to entries[]. |
| `sheet_name` | `string` |  |  |
| `structure_override` | `object` |  | Override auto-detected columns for a long-format/ledger file (e.g. value_column chose "Débit" and dropped credit rows, or an account-code column won the label). Omitted fields stay auto-detected. |
| `replace_source_id` | `string` |  | file_id path only: refresh this existing file source in place (id from layerz_list_integrations) instead of creating a second one. The rows are classified with that source's own rules and replace its rows on the branch it feeds (the default branch included): `replace`, `replace_scope: 'import'` and `branch.id` are implied. |
| `rules_from_source_id` | `string` |  | file_id path, new source only: classify this upload with the rules of that source of the model (id from layerz_list_integrations) and copy them onto the new source, existing rules kept: a second file of the same kind starts mapped. |

## layerz_list_integrations

**List data sources** · read-only · idempotent

Lists every data source feeding a model: API connectors (Qonto, Pennylane, Stripe, Airtable, Metabase) and file imports (kind csv | fec), each with kind, display_name, `branch_ids` (the branches it feeds), sync status, last_synced_at and `source_fields` (the payload fields an API connector's `field_map` can re-point its description / category / account_number to; null when there is nothing to choose). A row with `legacy_import_id` is a materialized pre-staging import that owns input rows but staged no transactions. `include_external_refs: true` adds `external_refs`: the links to items of other Layerz models, each with a value-aware `stale` flag (the source moved in a way that changes the snapshot) and its source health. Stored credentials are not returned.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `include_external_refs` | `boolean` |  | Also return the external references (links to other models) with their staleness. |

## layerz_list_mappings

**List mapping rules** · read-only · idempotent

Lists the import classification rules in scope for a model: `sets` (each with a `scope`: `model` = the model's own rules, `system_template` = the curated country catalogs (PCG, US GAAP, UK, SKR03/04), `user_template` = the reusable catalogs of the caller's workspaces), `mappings` (every effective rule: pattern → target item, sign, source scope; `total` counts them) and `templates` (the catalogs importable through `layerz_manage_mapping { op: "import_template" }`). A model classifies with its own `model` rules only; a catalog applies once imported. A `pattern` is a case-insensitive glob where `*` matches anywhere. `include_user_mappings: true` adds the catalogs of the caller's workspaces to `sets` / `mappings`; `include_coverage: true` adds per-rule `match_count` and a `coverage` block (auto-created count, ignored count, the top keys routing nowhere).

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `include_user_mappings` | `boolean` |  | Also list the user catalogs of the caller's workspaces in `sets` / `mappings` (default: only what the model classifies with). |
| `include_coverage` | `boolean` |  | Also compute `match_count` per rule and a `coverage` block (classifies every source: heavier read). |

## layerz_list_models

**List models** · read-only · idempotent

A user's Layerz models are where their financial models, budgets, forecasts, closes and imported Excel models persist from one session to the next. Lists the models the authenticated user can access, most recently edited first, and the workspaces they belong to (`workspaces[]`: id, name, kind personal | team, role admin | member, plan, `has_conventions`). Each model carries `id`, `name`, `workspace_id`, `can_write` (owner, workspace member or editor guest) and `updated_at`; `layerz_get_model` returns its detail. `limit` caps the list (default 20, at most 200) and `total` counts every match. `q` filters by name (case- and accent-insensitive substring, `*` wildcard), `writable: true` keeps owner/editor models only. A model-scoped key gets its bound model only.

| Field | Type | Required | Description |
|---|---|---|---|
| `q` | `string` |  | Name filter: case- and accent-insensitive substring ("swoop" matches "SWOOP - BP 2026", "homelior" matches "Homélior"); `*` is a wildcard, `%`, `_` and `&` are literal. |
| `writable` | `boolean` |  | When true, only models the caller can edit (owner or editor). |
| `limit` | `integer` |  | Most recently edited models returned (default 20, at most 200). |

## layerz_list_templates

**List templates** · read-only · idempotent

Lists the model templates the caller can start from: the `official` templates curated by Layerz and the `workspace` templates of the caller's workspaces (each workspace's library, read by its members and not by its guests; `workspace_id` names it). A template is a read-only copy published from a model in the web app; this tool reads it and changes nothing. Each entry carries name, subtitle, glyph, `description` (the template's FINANCE.md, its usage guide), scope and a structure summary (section names + item count). With `template_id`, returns that single template in full, `blueprint` included. A template forks into a new model through `layerz_create_model { template_id }` and applies as a module through `layerz_build_from_blueprint { template_id }`.

| Field | Type | Required | Description |
|---|---|---|---|
| `scope` | `"official" \| "workspace"` |  | Scope filter: "official" (curated by Layerz) or "workspace" (the libraries of the caller's workspaces). |
| `template_id` | `string` |  | One template in full (blueprint + usage guide) instead of the list. |

## layerz_list_transactions

**List staged transactions** · read-only · idempotent

Returns a data source's staged transactions (API connector or csv/fec file import) annotated with their routing: the target item and whether a `rule` or an `auto`-created item matched, the skip reason otherwise (mapping is the only routing path, no fuzzy match), or `ignored` for a row an `__ignore__` rule routes nowhere on purpose. `period` (YYYY-MM) and `q` (substring on description/category) filter the rows; the rows come one page at a time (`limit`, default 200, at most 1000; `offset`), with the matching `total` on the first page. The full staged import as a CSV file is `layerz_export { target: 'transactions' }`. A materialized legacy import derives one row per owned cell from the model's input rows.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `connection_id` | `string` | yes | Source id as returned by layerz_list_integrations. |
| `period` | `string` |  | Keeps only this YYYY-MM period. |
| `q` | `string` |  | Keeps rows whose description/category contains this text. |
| `limit` | `integer` |  | Rows per page (default 200, at most 1000). |
| `offset` | `integer` |  | Rows to skip (default 0). |

## layerz_manage_integration

**Sync, configure or delete data source** · destructive

Runs one operation on a data source (API connector Qonto, Pennylane, Stripe, Airtable, Metabase, or a csv/fec file import) by `op`. `sync`: pulls the provider's rows into the bound branch as a replace of this source's own rows (the baseline is untouched); on a file source, replays the projection over the staged rows; `target_branch_id` lands a still-unbound connection on an existing branch; `dry_run: true` reports the impact without persisting. `rebind`: re-points the source at `branch_ids`, wiping its rows from detached branches and reprojecting into the new ones. `update`: renames the source (`display_name`) and/or applies `config` then replays the projection; a change of `import_level` or of a tabular mapping (`field_map`, `measures`, `sign_rule`) re-fetches and re-stages, and is rejected on a csv/fec file source. `delete`: disconnects the source, drops its staged transactions and purges everything it projected into the model (input rows, provenance, import entry); items and the branch are kept, emptied; when the purge would destroy values the source cannot re-project, the call is refused with `PURGE_CONFIRMATION_REQUIRED` and a `purge_preview`, and a retry with `confirm_purge: true` performs it. Every projecting op returns `unmapped`, `proposed_window`, `deletable_items` (reported, not removed), `cutover_changes`, `shadowed`, `warnings`. Credentials stay in the web app. Persists one version labelled with `summary`. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `op` | `"sync" \| "update" \| "rebind" \| "delete"` | yes | Operation to run on the source. |
| `connection_id` | `string` | yes | Source id as returned by layerz_list_integrations. |
| `dry_run` | `boolean` |  | `sync` only: reports the impact without persisting. |
| `target_branch_id` | `string` |  | `sync` only: existing branch a still-unbound connection feeds (e.g. `default`). Ignored once bound. |
| `branch_ids` | `string[]` |  | `rebind` only: the existing branches the source feeds afterwards (e.g. ["default"]). |
| `display_name` | `string` |  | `update` only: new label of the source (metadata, no reprojection). |
| `config` | `object` |  | `update` only: non-secret import config to apply. |
| `confirm_purge` | `boolean` |  | `delete` only: confirms the purge after a `PURGE_CONFIRMATION_REQUIRED` refusal. |
| `confirm_replace` | `boolean` |  | `sync` only: stages a fetch that would empty the lines the source fills (refused otherwise with `IMPORT_CONFIRMATION_REQUIRED` and a `replace_preview`). |

## layerz_manage_mapping

**Set, delete or import mapping rules** · destructive · idempotent

Writes the model's classification rules by `op`, in its single mapping set. `set`: creates or updates rules identified by (`source_id`, `pattern`, `secondary_pattern`), one rule from the flat fields or up to 500 in `rules`. `pattern` is a case-insensitive glob (`*` anywhere: `Apport*`, `*641`) tested against the source's primary key, `secondary_pattern` (default `*`) against its secondary key; `source_id` is the data source the rules classify, or `source_ids` writes the same rules on several sources at once (one file per exercise: one correction, every year; a `rules` item may name its own `source_id`); `target` is an item name or uid, `uid::entryUid` for one list entry, or `__ignore__`; `sign` (natural | negate | absolute) adjusts the amount. The batch is validated whole: one failure writes nothing; each rule reports `created`, `updated` or `unchanged`, a replay writes nothing. `delete`: removes `mapping_id` or every id of `mapping_ids` (up to 500). `import_template`: copies the catalog `template_id` onto `source_id` (targets by item name; a conflict overwrites, reported in `overwritten`). `copy`: gives `source_id` the rules of `rules_from_source_id` (another source of the model) by rule key, `on_conflict` `keep` (default) or `replace`; reports `copied`, `replaced`, `kept`, `unchanged`. A rule change applies on the next `layerz_manage_integration { op: "sync" }`. Rules are versioned under `summary`; a restore puts them back. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `op` | `"set" \| "delete" \| "import_template" \| "copy"` | yes | Operation to run on the rules. |
| `pattern` | `string` |  | Primary key glob (`*` anywhere) or exact value. |
| `secondary_pattern` | `string` |  | Secondary key glob tested against the source's `dimension_by` field (default `*` = any). |
| `source_id` | `string` |  | The data source of the model the rules classify (id from layerz_list_integrations); a `rules` item may name its own. |
| `source_ids` | `string[]` |  | `set`: write the same rules on each of these sources (in place of `source_id`; a `rules` item naming its own `source_id` is not fanned out). |
| `rules_from_source_id` | `string` |  | `copy`: the source of the model whose rules are copied onto `source_id`. |
| `on_conflict` | `"keep" \| "replace"` |  | `copy`: when `source_id` already has a rule with the same key, keep it (default) or replace it. |
| `target` | `string` |  | Target item name or uid; `uid::entryUid` pins one list entry; `__ignore__` routes nowhere on purpose. |
| `sign` | `"natural" \| "negate" \| "absolute"` |  | Sign convention applied to the matched amount (default natural). |
| `rules` | `object[]` |  | `set`: up to 500 rules written as one batch, in place of the flat fields. |
| `mapping_id` | `string` |  | `delete`: rule id from layerz_list_mappings. |
| `mapping_ids` | `string[]` |  | `delete`: up to 500 rule ids removed as one batch. |
| `template_id` | `string` |  | `import_template`: catalog set id from layerz_list_mappings `templates`. |

## layerz_manage_version

**Pin, unpin or restore version** · destructive · idempotent

Acts on one version of a model (`version`: exactly one of `revision_id`, `version_number`, `id`) by `op`. `pin`: keeps the version listed, diffable and restorable beyond the plan history window; capped per plan (`max_pinned_versions`, 403 past the cap); a no-op on a pinned version. `unpin`: frees the slot; a version past the window then stops being listed. `restore`: replaces the live items, schema and inputs with that snapshot, and puts back the source settings (window, keys, bindings) and the mapping rules as they stood at that version, after saving the current state as a `restore` backup version (`backup_version_id`, `null` when the live state already matched the latest snapshot); requires `summary`, the label of the restored state. Returns `{ ok, version_id, version_number, revision_id, pinned, pinned_count, max_pinned_versions }` for pin / unpin, `{ ok, restored_version_id, restored_version_number, restored_revision_id, backup_version_id, sources?: { sources_restored, rules_written, rules_removed }, warnings[] }` for restore: `warnings` names what could not come back (a source deleted since, a rule whose target is gone, a version written before source versioning). The target is inside the plan window or pinned. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` |  | Required with `restore`: label of the restored state in the history. |
| `op` | `"pin" \| "unpin" \| "restore"` | yes | pin \| unpin \| restore. |
| `version` | `object` | yes | Target version: exactly one of revision_id / version_number / id. |

## layerz_match_items

**Match labels to items** · read-only · idempotent

Resolves free-text labels (e.g. row labels of a parsed file) to existing item UIDs of a model: the top 3 candidates per label across exact_uid, exact_name, slug and fuzzy (Levenshtein) methods, each with a score. An empty candidate list means no existing item matched. Deterministic, no LLM call.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `labels` | `string[]` | yes | Free-text labels to resolve. |

## layerz_parse_file

**Parse uploaded file** · read-only · idempotent

Parses an uploaded Excel/CSV (`file_id`) deterministically and returns a token-optimized structure: sheet summaries (without `sheet_name`) or, for one sheet, the detected timeline, `suggested_structure` (layout, header row, columns), row labels and column headers with samples. A wide sheet is recognised by its period header: a run of at least three consecutive periods (bare years such as `2026`, `YYYY-MM`, `Jan 2026`, `Q1 2026`, date cells) in any column, reported as `detected_periods` and `period_range`. A raw DATEV EXTF export and a French FEC (compact `YYYYMMDD` dates) are detected natively; on any columnar ledger a journal column of short codes is mapped as `category_column`, and its opening journal (`AN`, `RAN`, `ANO`, `AD`, or a journal labelled "à nouveau") is read as opening entries (`opening_rows`; prior-year rows moved into the first month): remap or ignore that column to change it. `structure_override` re-parses with corrected columns when a ledger is misdetected (a Débit column taken as the value, an account-code column taken as the label) or when a wide sheet has fewer than three period columns (`layout: "wide"`). Without `sheet_name`, a model workbook (formulas under period headers) also returns `workbook` (how far the Excel engine recalculates it, its scenario selectors with their scenarios, its data tables) and `guidance`. The raw binary is not returned.

| Field | Type | Required | Description |
|---|---|---|---|
| `file_id` | `string` | yes | Upload id as returned by layerz_create_upload_url ('f_' + 16 hex chars). |
| `sheet_name` | `string` |  | Sheet of a multi-sheet workbook. Omitted: sheet summaries only. |
| `structure_override` | `object` |  | Override auto-detected columns for a long-format/ledger file (e.g. value_column chose "Débit" and dropped credit rows, or an account-code column won the label). Omitted fields stay auto-detected. |

## layerz_patch

**Apply model patch** · destructive

Applies a batch of mutations to a model: `create`, `replace`, `update`, `delete`, `move`, `list_create`, `list_update`, `list_delete` and `meta` (name, subtitle, finance_md, timelines, formats, number_locale, default_branch, glyph). The batch is all-or-nothing: a validation failure persists nothing and returns every error at once (`MODEL_VALIDATION_ERROR`, `details[]`). A `create` may carry a temp `id` later ops reference (`parent`, `source`, `target`, `series`, `liste_ref`, `after`, `before`, `$_id` in a formula); `map` gives each temp id its UID. `replace` keeps the item's UID and presentation fields; `update` is a strict partial merge of the named fields. `after` / `before` (`create`, `move`, list ops) order siblings and tabs; `unchanged: true`: nothing written. Root accepts `section` and `dashboard`; `dashboard` accepts widgets only; a `formula` with both an expression and children is rejected (`FORMULA_EXPR_AND_CHILDREN`); a list-mode item takes `timeline_values`, a non-list item `value` / `values`. `branch_id` routes the value writes onto that branch as an overlay of the cells differing from the base; `compute` returns the computed series of the given UIDs (under `compute_branch`, default `branch_id`); `dry_run` validates and computes without persisting; `compare_values` adds `value_diff` (as in `layerz_diff`). Persists one version labelled with `summary`. Not advertised to read-only keys. Modeling patterns and examples: resource `modeling-guide://reference`.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `ops` | `object[]` | yes | Mutation operations. Each op is a discriminated object on a string `op` field (e.g. {op:'create', role:'assumption', name:'Revenue'}; {op:'replace', from_uid:'abc', new_item:{role:'formula', name:'Revenue', formula:'xyz * 12'}}; {op:'update', uid:'abc', value:42}). |
| `compute` | `string[]` |  | UIDs to compute after mutations |
| `compute_branch` | `string` |  | Branch whose `[base, branch]` checkout the `compute` values are returned under (mirror of `layerz_read` `branch_id`). Defaults to `branch_id` when that is set, else the base plan. Requires `compute`. |
| `branch_id` | `string` |  | Branch that receives the value writes of this batch (`update` / `replace` `value`, `values`, `timeline_values` on assumptions): only the cells that differ from the base are stored as that branch's overlay, the same record a value edit makes in the web editor with the branch checked out; no data source is created. Absent or `default`: the base plan. Structural ops and non-value fields apply to the model as a whole; a `create` carrying values under a branch is rejected. An unknown id is rejected. |
| `dry_run` | `boolean` |  | Validates and computes the batch without persisting it. |
| `compare_values` | `boolean` |  | Adds `value_diff`: the computed-values diff between the model before and after the batch: the `compute` UIDs, else the key lines (checks and totals): at the finest grain under `compute_branch`, with before / after / delta per changed period and a summary. With `dry_run`, a preview of what the batch changes in the numbers. |

## layerz_read

**Read model snapshot** · read-only · idempotent

Returns a UID-native snapshot of a model: `model` (name, timelines, lists, branches), `items` (flat, `parent_uid` carries the hierarchy, each with role, formula, check, note; values are the base plan) and `revision_id` / `version_number`. Filters: `uids`, `roles`, `include_children`. `with_values: true` adds the computed series `v` aligned with the periods `p` (`periods` for explicit labels of mixed grains, else `granularity`), `variance` adds `vv`, `per_element` adds `ve` for list-mode items, `health` adds the check report, `branch_id` computes `v` and `health` under one branch's `[base, branch]` checkout, else they are the base plan. The check report is judged on a branch checkout: without `branch_id`, a multi-branch model reports the branch it opens on (`health.branch_id`) and every branch under `health.by_branch`. When the response leads with `computable: false`, `errors[]` names the broken dependencies (e.g. `CIRCULAR_DEPENDENCY`) and every series is a zero-filled placeholder. A read without `uids` or `roles` also carries `conventions` (workspace conventions + model FINANCE.md, as in `layerz_get_conventions`) when either is set, and `guidance` (the rebuild method of the modeling guide § 12) on a model of 1000 items or more.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `uids` | `string[]` |  | Filter by items: UIDs or names |
| `roles` | `("assumption" \| "formula" \| "callup" \| "balance" \| "section" \| "chart" \| "dashboard" \| "kpi" \| "mini_table")[]` |  | Filter by role |
| `include_children` | `boolean` |  | Include descendants of filtered containers |
| `with_values` | `boolean` |  | Compute and return values for matched items |
| `periods` | `string[]` |  | Period labels to scope values to |
| `granularity` | `"monthly" \| "quarterly" \| "yearly" \| "native"` |  | Grain for `v`/`p` when no explicit `periods` are given, among the active timelines (another one: `GRANULARITY_UNAVAILABLE`). 'native' = finest active dated grain (monthly>quarterly>yearly). Default: 'yearly' when the model has it, else 'native'. Ignored when `periods` are provided (each label resolves its own grain). |
| `include_lists` | `"referenced" \| "all" \| "none"` |  | Which named lists to embed in `model.lists`: 'referenced' (default: only lists used by the returned items via liste_ref), 'all', or 'none'. |
| `variance` | `boolean` |  | Also return the variance series `vv` (the `branch_id` checkout − the base plan), aligned with `v`. Requires with_values and branch_id. |
| `health` | `boolean` |  | Also returns the `health` block: non-blocking check violations (lines flagged `check`), evaluated at the finest active grain under a branch checkout: the `branch_id` requested, else on a multi-branch model the branch the model opens on (`health.branch_id`) with every branch's verdict under `health.by_branch`. `with_values: true` already includes `health` when the model has checks; this flag returns `health` without the full value series. |
| `per_element` | `boolean` |  | Also return `ve`: per-element series for list-mode items, keyed `ve[itemUid][elementLabel]` and aligned with `p` (e.g. payroll split by Business Unit). Without it, `v` only carries the aggregate. Requires with_values. |
| `branch_id` | `string` |  | Branch whose `[base, branch]` checkout the values `v` and the check report `health` are computed under. Absent: the base plan. An unknown id is rejected. Requires with_values or health. |

## layerz_set_custom_instructions

**Set custom instructions** · destructive · idempotent

Replaces the conventions of a workspace (the personal one by default, or `workspace_id`): the standing instructions for AI agents its members share (plain Markdown/text, ≤ 3000 chars; an empty string clears them). They apply across every model of the workspace, on top of each model's FINANCE.md, and come back as `conventions` in the results of the tools that open a model of the workspace. Any member may write them. No version is persisted. Not advertised to model-scoped or read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `content` | `string` | yes | Workspace conventions, max 3000 chars. Empty string clears them. |
| `workspace_id` | `string` |  | A workspace the caller belongs to (`layerz_list_models` lists them); default: personal. |

## layerz_set_finance_md

**Set FINANCE.md** · destructive · idempotent

Replaces the FINANCE.md attached to a model with the given Markdown (YAML front matter + body, ≤ 5,000 chars). `source: 'imported'` marks content synced from a project-root file, `'user'` (default) content authored in place. The content parses as a YAML front-matter document; schema warnings are returned without blocking. A template is a read-only published copy and is out of this tool's reach; a model's FINANCE.md becomes a template's usage guide when the model is published from the web app. Persists one version labelled with `summary`. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `content` | `string` | yes | Full FINANCE.md Markdown (YAML front matter + body), max 5,000 chars. |
| `source` | `"user" \| "imported"` |  | Provenance: 'imported' (synced from a project-root FINANCE.md) or 'user' (default). |

## layerz_share_model

**Invite or revoke model access** · destructive · open world

Changes who can access a model, by `op`. `invite` (default): grants `email` the role `viewer` (read-only, default) or `editor`; a registered user gets an active share, an unregistered one a pending invite; both receive an email. `revoke`: removes the collaborator or pending invite `principal_id` (an id from the `sharing.members` of `layerz_get_model`). Anyone who edits the model may invite a new person; only the owner or a workspace admin changes an existing access, adds an editor seat or uses `revoke`. The link visibility (`invite` / `public`) is changed by the owner in the web app only. No version is persisted. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `op` | `"invite" \| "revoke"` |  | invite (default) \| revoke. |
| `email` | `string` |  | `invite`: the email address to invite. |
| `role` | `"viewer" \| "editor"` |  | `invite`: viewer (read-only, default) or editor. |
| `principal_id` | `string` |  | `revoke`: collaborator user id or pending-invite id from `sharing.members`. |

## layerz_update_branch

**Create or update branch** · destructive · idempotent

Creates or updates a branch. With `dataset_id`, patches that branch's metadata (`display_name`, `priority`, `source_hint`, `file_name`, `actuals_through`). Without it, the branch named `patch.display_name` is updated when it exists and created otherwise, with no data source and no input rows. `ops` (the `layerz_patch` operations) are applied on the branch in the same call, as `layerz_patch { branch_id }` would: a scenario that changes a value is one call; the result then carries `patch`. `priority` is rejected on the default branch. An explicit `actuals_through` pins the real/forecast cutover (`actuals_through_locked: true`: source syncs stop rewriting it); `null` resets it to auto. Returns `{ branch, created }`. Persists one version labelled with `summary`. Not advertised to read-only keys.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
| `summary` | `string` | yes | Short note (3–100 chars) describing the change, stored as the label of the resulting version. Examples: "Renamed Revenue to Net Revenue", "Imported 2024 OPEX from Excel". |
| `dataset_id` | `string` |  | Branch to update. Absent: the branch named `patch.display_name` is updated when it exists, created otherwise. |
| `patch` | `object` | yes |  |
| `ops` | `object[]` |  | Operations applied on this branch in the same call, in the `layerz_patch` `ops` format (value writes land as the branch overlay). |

## layerz_validate_model

**Validate model** · read-only · idempotent

Runs the core model validator (structural / formula / timeline checks) without writing and returns `{ ok, error_count, warning_count, errors[], warnings[] }`; each issue carries a `code` (e.g. `UNKNOWN_UID`, `CIRCULAR_DEPENDENCY`, `INVALID_ROLE_CHILD`, `TIMELINE_MISMATCH`), a `message` and `item_uids`. The write path auto-repairs some of these issues and enforces a few invariants this audit skips, so `ok: true` is a sanity signal rather than a write guarantee.

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | `string` |  | Target model UUID. Required for user-scoped API keys; validated against the bound model for model-scoped keys. |
