# MCP interface spec — `ledger-mcp` ## Goal The primary interface to the books is an AI agent driving MCP tools. The engine (`ledger-core`) stays pure, `ledger-store` persists, and `ledger-mcp` exposes both over the Model Context Protocol — the open standard, so the books are drivable by any MCP client (Muse, Claude Code, IDE agents), not locked to one assistant. ## Crates in this phase | Crate | Role | Spec | |---|---|---| | `ledger-store` | SQLite persistence, blob metadata, event log | `docs/receipt-store.md` | | `ledger-mcp` | MCP server wrapping store + core | this document | Rust, `rmcp` SDK (the Rust MCP SDK). The MCP crate holds no accounting logic: it translates tool calls into `Ledger` commands and formats results. If a behavior can't be expressed through `ledger-core`'s public API, the core is missing something — fix the core, don't work around it in the MCP layer. ## Company settings The books keep their own settings (journal format 2, plan/served.md P1): each change is a `settings.set` line with who decided it and when, replayed into `ledger_core::settings::Settings` by the server and the viewer alike (rules.md B-29). Every key is in `ledger_core::settings::KEYS`, with what it takes and means: the company's facts (`company.name`, `.entity_type`, `.tax_classification`, `.tax_form`, `.fiscal_year_start` ("MM-01"; the year's end is derived, never stored), `.timezone` (what "today" means for the books), `.formation_state`, `.formed`, `.state_entity_number`, `.ein` (the one identity number a setting keeps, shown masked: "**-***5893"), `.irs_name_control`, `.duns`, `.address`, `.registered_agent`, `.partnership_representative`, `.cpa`, `.members` (name, share as "50%" or "0.5", capital account, optional distributions account and `files_jointly_with`; shares sum to exactly 1)); the books' (`books.accounting_basis`, `.cash_accounts`, `.financing_accounts` (loans, and money the owners advanced: ASC 230-10-45-14(b)), `.investing_accounts` (ASC 230-10-20), `.close_into` (single owner only), `.close_sweep`, `.asset_tag_prefix`); and policy (`policy.evidence.threshold` (receipts strictly above it; "0.00": every entry), `.required_accounts`, `.exempt_accounts`, `policy.parties` (off, suggest, require), `policy.approval_rules` (off, the default, or enforce)). A value is checked by its key and kept in one spelling (a time zone as the database spells it, an amount without leading zeros, a return as `schedule_c`, `1065`, `1120s` or `1120`); a change is all or nothing, and the settings after it must hold together (members and `close_into` never both, a classification that names one return, a fiscal year that doesn't move under a closed period). No setting holds nine digits that read as an SSN or EIN (bare, or printed 3-2-4 or 2-7) except `company.ein` and `company.duns`. Books from before P1 hold no `settings.set` and still read the books dir's `wanderbooks.toml` (default: next to `--data-dir`; `--books-toml PATH`) and `config.json`'s `receipt_policy`, reloaded whenever either changes, as before. `books.import_settings` moves them in once; from then on no file is read, not even at start (a broken file beside the books can't stop the server). A vault key file is never a books setting: `--vault-key-file PATH` names it to the server and the viewer (it wins over a file's `[vault] key_file`). - `books.settings {}` → `{ source ("books" or "file"), timezone, today, approval_rules, keys: [{ key, doc, identity, value, set_by, seq }], books_toml, books_toml_exists, config_json_present, reload_error, loads, company, fiscal_year_start, tax_form, basis, receipt_rule, receipt_required_accounts, receipt_exempt_accounts, parties, members, cash_accounts, financing_accounts, investing_accounts, close_into, close_sweep, problems }`: the settings in force, every key the books know with its value (null: unset, its default applies) and who set it, and `problems`, settings that disagree with the chart, each saying what to change (conventions naming an account no longer in the chart among them); `books.digest` repeats them as `settings_problems`. Settings are named by key for books that keep their own, as the file spells them for books that still read one; for those, `keys` shows the file's values, with no journal line. - `books.set_setting { changes: [{ key, value }], decided_by, decided_on?, citation?, note? }` → `{ changed: [{ key, was, value }], problems }`: one or more changes, together or not at all (`value` null clears a key back to its default; a value already set changes nothing, idempotent; destructive, since it can clear or switch off a setting). Refused while the books still read a settings file (or `config.json`): import it first, so no setting is lost. - `books.import_settings { toml_text, config_json_text?, confirmed?, skip_unknown?, decided_by, decided_on?, citation?, note? }` → `{ status ("preview" or "imported"), changes, notes, unknown, comments }`: exactly the changes that make the books' settings what the file (and `config.json`'s `receipt_policy`, which wins as it does for the server) says. `notes` are what isn't a books setting and where it goes (`[books] data_dir`, `[vault] key_file`, `[viewer]`, `base_currency`); `unknown` are entries the books don't know, not imported (confirm with `skip_unknown`); `comments` are the file's comments, in order, which are not settings and are not imported (record what matters in them as a decision, open item, convention or a setting's note). The text must be the file the server reads, whole (its import is compared with the server's own reading of its files, key by key), and the server must read every setting afterwards as it does now; the vault key must then come from `--vault-key-file` (on the viewer too). A file never turns approval rules on. Books that keep their own settings take no import that changes them (an identical one is no change). Without `confirmed`, a preview that records nothing. An identity value exported masked imports as "unchanged". - `books.export_settings {}` → `{ toml_text }`: the settings as a settings file, each with who decided it as a comment, the EIN masked; a copy, and importing it back changes nothing (`ledger_config::codec`). The accounts invoices, bills, payroll, and closes post to are not settings: they are control roles in the journal (rules.md B-23). - `books.roles {}` → `{ roles: [{ role, purpose, account_type, default_code, assigned, account_code?, account_name? }] }`: every control role and the account filling it. - `books.assign_role { role, account? }` → `{ roles }`: assign a role one of the chart's accounts (`account` null: back to the default code). Refuses the wrong type, a placeholder, an account already filling another role, and moving a balance sheet role while its account holds a balance. Journaled as `role.assigned`. ## Tools — how the books are kept Conventions, decisions, open items and approvals live in the books too (`ledger_core::conventions`, rules.md B-29), each with who decided it and when; `books.start` lists them, and the handbook's settings-and-conventions section says how to use them. - `books.start { focus? }` (read-only, at most 8 KB) → `{ book: { name, timezone, today, fiscal_year, base_currency, basis }, head: { seq, hash }, state ("needs_onboarding" or "active"), settings_source, rules: { evidence, parties, approval_rules }, settings_summary: [{ key, value, set_by, seq }], conventions: [{ id, kind, title, summary }], open_items: [{ id, title, due }], truncated, handbook_sections, next_steps: [{ tool, args?, why }], isolation }`. The connect text names it as the first call. `isolation` is `same_user (advisory)` (D-32): the books are hidden from agents in the owner's own account, not locked against them. Lists cut to fit say so in `truncated` ("conventions: 4 more (books.conventions)"). `focus` adds steps: `onboarding` the onboarding step, `close` the company's close steps, `audit` `books.verify`. Not built yet (P5): `book.id`, `book.url`, `head.last_handoff`, the `agent` input, and loading it up front under tool search. Also `books://start`. - `books.conventions { kind?, include_retired? }` → every convention with its full text, structure, revision and source (`books://conventions`). `books.set_convention { id, kind, title, body_md, structured?, decided_by, ... }` sets or revises one (kinds: `posting_template`, structured `{ description?, lines: [{ account, side, share }] }`, each side's shares summing to 1, on accounts in the chart that take postings or on slots (`"{expense}"`) each draft names; `approval_rule`, structured `{ approver, accounts?, amount_over? }`; and `policy`, `close_step`, `calendar`, `mapping`, `note`, in words). An id is a slug, revised in place (same kind), never reused once retired: `books.retire_convention { id, reason, decided_by, ... }` (destructive). - `books.draft_from_template { template_id, date, amount, accounts?, description?, party?, no_party_reason? }` → `{ entry_id, description, lines }`: a draft whose lines split the amount (at most a line's) by the template's shares, each side summing to it exactly, odd cents by largest remainder; `accounts` names each slot's account (`{"expense": "6300"}`), every slot and nothing else. A refused draft journals nothing (a disk failing midway could leave a partial draft, as for any draft built line by line). - `books.record_decision { subject, decision_md, decided_by: [..], decided_on, evidence_attachment?, supersedes?, citation? }` → `{ id }`; `books.decisions { include_superseded? }`. A decision supersedes at most one live decision; its evidence is a document still in the books. - `books.raise_item { title, detail_md?, due?, decided_by, ... }` → `{ id }`, `books.resolve_item { id, resolution, decided_by, ... }`, `books.open_items { include_resolved? }`. - `books.approve_entry { entry_id, approver, note?, approved_on? }`: the approver approved the draft as it stands (its fingerprint: date, description, every line and class; a line added or a class changed afterwards voids it). Under `policy.approval_rules = enforce`, `books.post_entry`'s preview lists `approvals_missing` and a confirmed post is refused with `approval_required` until each covering rule's approver approved (the store refuses it too), and a tool that posts at once (an invoice, a bill, a payment, payroll, a remittance, a disposal) is refused when a rule covers the entry it would post: draft it instead. Reversals, closes, depreciation and amortization are exempt. A rule names accounts that take postings; an account a rule names can't be renumbered until the rule is revised, and `books.renumber_account` lists the conventions that name the old code. Under `off` (the default) rules block nothing. ## Transports - **stdio** (default): `ledger-mcp --data-dir PATH`. For Claude Code, Claude Desktop and other local agents. No auth: the OS user boundary is the only boundary. - **Streamable HTTP**: `ledger-mcp --data-dir PATH --http 127.0.0.1:8080`. Serves MCP at `http://127.0.0.1:8080/mcp` via rmcp's tower integration. **There is no authentication on this transport today**: no token and no Origin check. The only guard is rmcp's default `Host` check, which accepts `localhost`, `127.0.0.1` and `::1`. Any local process that can reach the port can read and change the books. Bind it to loopback only; binding a LAN, tailnet or public interface is an explicit human decision, never a default. Auth, scopes and Origin validation arrive with the served books (`plan/served.md`, P2). - **Served books** (`wanderbooks server`, started by the host; an agent connects with `wanderbooks mcp --book ID`, a stdio bridge): every book in the data root, on a socket in the root's private `run/` folder that only this account can connect to. Every request carries a bearer token live for that book (refused 401 without one, 403 with another book's). Refusals at the door, tool calls, uploads, downloads and exports are recorded in the book's access log; when a record can't be written the book stops taking requests (an upload, download or export is then refused, 503). - `/b/{book}/mcp`: the book's MCP service. A request is at most 1 MiB. - `PUT /b/{book}/u/{upload}`: an upload's bytes (`books.begin_upload`), from the token that began it; what `wanderbooks upload --book B [--token NAME] UPLOAD FILE` sends. Streamed to the disk, kept only if exactly the size and SHA-256 declared (so at most 25 MiB), once. The receive and its access record are one blocking task: bytes are never kept without their record (if it can't be written they are thrown away, 503 `not-recorded`, and the books stop). 200 with `{ received, size, sha256 }`; else, with nothing kept and the code in `x-wanderbooks-refused`: 404 `no_such_upload` (unknown or lapsed, also if it lapsed while being sent), 403 `not_yours`, 409 `already_sent` (its bytes came, or a call holds them), 409 `in_use` (another request is sending them), 400 `not_as_declared` (short, more than declared, or the wrong hash), 503 `stopped` (the books stopped after an internal error), 500 `failed`. A refused request's body is read and dropped (up to 25 MiB), so the client gets the answer, not a cut connection. Logged as action `upload` with the upload's id, a refusal at the door (no token, another book's) too. An upload's id is `up_` and 32 letters `a`-`p`: no digits, so the access log's TIN masking never hides it. - `GET /b/{book}/a/{attachment}`: a stored file's bytes, for a token with `books:read` (403 `insufficient_scope` without it; 404 `no_such_attachment`); the read and its access record are one blocking task. Sent with `Content-Type` (the stored MIME type, or `application/octet-stream` if it can't be a header), `Content-Disposition: attachment; filename="…"; filename*=UTF-8''…` (the plain name: anything but visible ASCII and spaces, and `"` and `\`, made `_`; then the whole name, RFC 8187 percent-encoded), `X-Content-Type-Options: nosniff`, and `Repr-Digest: sha-256=::` (RFC 9530). A stored file that can't be read whole is 500 `failed`; books that stopped, 503 `stopped`. GET only (a HEAD is 405, unrecorded). Logged as action `download` with the attachment's id, a refusal at the door too. - `GET /b/{book}/x/{export}`: a file the books made for an agent (the CPA package, a 1099 worksheet, a W-9: a `HandedFile`, "Tools — the TIN vault"), as `/a/` (the same door, the same headers, `Repr-Digest` included, GET only), but only for the token it was made for (403 `not_yours`), with no scope of its own to check (the tool that made it checked its scope); 404 `no_such_export` (unknown or lapsed), 503 `stopped`. An export's id is `ex_` and 32 letters `a`-`p`; it is kept 15 minutes, fetched as often as wanted until then, at most 16 per token, and swept like uploads. Logged as action `export` with the export's id. - `wanderbooks download --book B [--token NAME] ID --to DIR` takes an attachment's id (a number, `/a/`) or an export's (`ex_…`, `/x/`), checks the digest before saving, and saves it under the server's name (`filename*` first) made plain: separators and control characters made `_`, invisible (Unicode format) characters and leading dots and spaces dropped, at most 200 bytes with the extension kept. Beside a file of that name it is `name (1).ext`, and so on; `attachment-` or `export-` if the folder takes no such name. It is written to a hidden file and hard-linked in: never a partial file under the real name, never over another file. ## Server instructions The MCP `initialize` response carries an `instructions` string, the **connect text** (`ledger-mcp/src/handbook.rs`), composed in `get_info` from the settings in force when the client connects (the settings are re-read first, so a client connecting after an edit is told the new rule). It is short on purpose: clients cut long instructions (one cut the old text at 4,096 characters), so it is at most **1,400 characters**, and its first paragraph, at most **512**, stands alone: the entry point (`books.start` first each session, and `books.handbook` for every procedure), the rule that these tools are the only way to the books (never local files), decimal-string amounts, and the draft → lines → preview → confirmed post flow. The second paragraph adds that every entry balances and uses real accounts from `books.chart`; the parties rule in force (`[books] parties`: under "require" every entry the agent posts names its party or a no-party reason, since closes, depreciation and amortization post with none; under "suggest" name it where there is one; under "off" nothing); corrections by reversal; the receipt rule in force (`ReceiptPolicy::rule`: the exact threshold in the books' base currency, never rounded, the accounts that always need a receipt and those exempt, and that reversals need none); the exemptions (depreciation and amortization, whose schedules are the evidence, and closes, derived from the books); that `books.create_invoice`, `books.create_bill`, `books.receive_payment`, `books.pay_bill`, `books.run_payroll` and `books.remit_payroll_taxes` post at once without a receipt check; TINs only into the vault; show the numbers, and after posting check `books.digest` and offer it to the human; and where settings live: in the books, changed only through the tools, or, for books that still read a settings file, that file, the one local file the agent may edit until `books.import_settings` moves it in. When a long rule (many accounts, a huge threshold, a long name) would push it past 1,400 characters, it drops the tracing hint first (the handbook's tracing-figures section has it), then the reasons in parentheses, then the tracing hint for good and lists fewer account codes (at last only how many there are; `books.settings` lists every one, uncut, in `receipt_required_accounts` and `receipt_exempt_accounts`), then words that only help; never the rule itself. A company with no name yet (the settings' default) is "a new company". The company name in it is one line of plain text (control characters and line breaks become spaces, Unicode format characters such as bidi overrides and zero-width spaces are dropped), cut to 56 characters. `instructions_budget` (the longest rule, every parties setting) and `the_company_name_is_one_plain_line` check it. The long guidance is the **handbook**, compiled in from `ledger-mcp/handbook/*.md`, with the receipt rule in force rendered in: - `books.handbook { section? }` (read-only) → `{ read_first, sections: [{ id, title, uri, chars }], section: { id, title, text } | null }`. Without `section`, the index (`read_first` says to read `contract` first); with a section id, that section's Markdown; with `"all"`, the whole handbook in reading order. The input schema lists the ids: contract, entries, drafts-and-reversals, evidence-and-receipts, attachments, files-in-out, reconciliation, fixed-assets, prepaid-and-recurring, revenue-and-payouts, parties-and-tins, 1099, cpa-handoff, settings-and-conventions, viewer, rules-that-change, control-roles, tracing-figures. - The same as resources: `books://handbook` (the index, JSON) and `books://handbook/{section}` (Markdown, `text/markdown`), one listed per section. No text the agent is given (tool JSON with its schemas, resources, connect text, handbook, and every refusal fixed in code: each error variant's template in the crates under the server, scanned from source, built error texts, and the server's refusal constants) names a helper command, a home path, the data dir or its flag, the old import-root flag, a file of the books (`.jsonl`, the database, `vault.key`, `.gitignore`), git, GitHub, a pull request, a repo doc (`docs/`, `.md`), or tells the agent to read the books' files; no tool title or description, connect text or handbook section names `wanderbooks.toml` (the input and output schemas name it by design, for `books.settings`' `books_toml`) (`tool_text_lint`). A rule set by law that the books don't know for a year names its official source (the statute or publication, with its address) and says to tell the human. Tool descriptions are at most 700 characters; eight longer ones are listed in `tool_descriptions_fit_700_characters`, to be shortened in P5. **Annotations.** Every tool has a `title` and a `readOnlyHint`; every tool that changes anything also has a `destructiveHint`, true for these 29: `books.post_entry`, `books.reverse_entry`, `books.import_settings`, `books.set_setting`, `books.retire_convention`, `books.unlink_receipt`, `books.unlink_attachment`, `books.withdraw_attachment`, `books.correct_asset`, `books.dispose_asset`, `books.run_depreciation`, `books.run_schedules`, `books.run_recurring`, `books.renumber_account`, `books.rename_account` (the label every past report prints), `books.assign_role`, `books.close_period`, `books.reconcile`, `books.void_statement`, `books.void_reconciliation`, `books.set_w9`, `books.set_tin` (both overwrite a vault record), `books.purge_tin`, `books.create_invoice`, `books.create_bill`, `books.receive_payment`, `books.pay_bill`, `books.run_payroll`, `books.remit_payroll_taxes`; and an `idempotentHint` on the seven that a repeat with the same arguments leaves the journal and the vault as they were: `books.verify`, `books.run_depreciation`, `books.run_schedules`, `books.run_recurring`, `books.set_party_roles`, `books.set_setting` and `books.import_settings` (a setter such as `books.update_party`, `books.set_fx_rate` or `books.set_tin` journals a line, and `books.set_tin` seals a new vault record, every time, so none carries it; `idempotent_tools_change_nothing_when_repeated` calls each candidate twice to check). Every tool's `openWorldHint` is false: the books are a closed world, and no tool reaches beyond them, but `books.back_up_now`, which pushes the books to the owner's backups (true). `books.export_cpa_package`, `books.vendor_1099` and `books.get_w9` keep a file for the agent (an export) and record the ones with TINs, so they are not read-only. No tool carries `requiresUserInteraction` (owner decision 2026-10-16: no added prompts). `annotations_complete` pins all of this. The read-only hint is true in behaviour: `spec_mcp` checks, on every call, that a read-only tool leaves the journal, the contents of every file under the data dir (the database by every row of every table; SQLite's -wal and -shm files, which move pages and hold read marks on their own, aside), the vault and the settings file as they were (`read_only_tools_change_nothing`). `books.show` is read-only though it writes the viewer's request into the books' `ops/` folder: that folder is a side channel, never journaled, and moves only the view. **Failing closed.** Tool bodies run on blocking threads, one at a time on the store. If a request panics (an internal error), the journal may hold a line the memory doesn't, so the server stops taking requests: every later call, on every session sharing the store, is refused with "the books server stopped taking requests after an internal error, to protect the books: ask the human to restart the books server", never the panic's own text. A restart re-verifies the journal (`a_request_that_panics_stops_the_server`). So a panic an input can reach would be a denial of service, and none can be: the dates a tool takes are four-digit years and real days, its amounts at most a journal line's, and a recurring run bounded; books an earlier version wrote past those bounds still open (replay accepts what that version accepted), so every figure the server derives from them (a draft's total, a schedule's plan, aging, a party's totals, the asset register) is computed or refused ("too large to compute exactly", or a date outside the calendar the books keep), never a panic (rules.md B-28). `tests/hostile_args.rs` drives every tool with generated hostile arguments and every resource with generated URIs, checks after each call that the server still serves, restarts it after them to check the books reopen, and drives every tool over every book in ledger-store's `tests/fixtures/old-books`. ## Tool design principles - **Narrow tools, explicit arguments.** No "do what I mean" tools. The agent supplies dates, accounts, sides, amounts; the server validates. - **Amounts are decimal strings** in requests and responses. Never floats, never locale-formatted numbers. - **Every mutating tool echoes the exact resulting state.** The "show the numbers" rule from AGENTS.md applies over the wire too. - **Preview-before-post.** `post_entry` and `reverse_entry` take `confirmed: bool`. Without confirmation they return a preview (full lines + resulting account balances) and post nothing. The agent must present the preview to the human before confirming. This encodes the standing fact-check rule in the protocol itself. - **Errors are typed strings** mirroring `LedgerError` variants, with the offending values included (e.g. unbalanced totals). ## Tools — books - `books.handbook { section? }`: the guide (see "Server instructions"). - `books.chart` → `{ accounts: [{ id, code, name, type, parent, placeholder, balance }] }`. Balances included: one call answers "what do we have." - `books.add_account { code, name, account_type, parent?, placeholder?, tax_category?, deductible_percent? }` → `{ account_id, warnings? }`. Codes are unique; a name another account under the same parent has (top-level accounts are siblings too; ignoring capitals and surrounding space), one holding a run of nine digits, or one that isn't one line of at most 200 characters, is refused (rules.md B-31); the name is kept trimmed. A revenue or expense account (not a header) without `tax_category` is created with a warning ("6150 Software has no tax category: the tax summary will list it as uncategorized. Propose one from books.tax_categories and set it with books.set_tax_category once the human agrees."), or, under `policy.require_tax_category = refuse`, refused (rules.md B-32). The category is checked against the account's type and the return, as `books.set_tax_category` checks it; journaled as `account.added` then `account.tax_set`. - `books.draft_entry { date: "2026-10-10", description: "...", vendor?, party?, parties?, no_party_reason? }` → `{ entry_id, status: "draft" }`. `party` tags the counterparty (see "Tools — parties"); given with `vendor`, both must name the same vendor record, else nothing is drafted. `parties` names several, each with a share (as `books.set_entry_party`), in place of `party` and `vendor`. - `books.add_line { entry_id, account: "1000" | , side: "debit" | "credit", amount: "123.45" }` → `{ ok: true }`. A refused line (unknown account or class, bad amount) adds nothing. - `books.post_entry { entry_id, confirmed }` → `{ status, entry_id, date, description, total, lines (with resulting balances), receipts, receipt_required, receipt_missing, split_detected, party_policy, party_id?, party?, parties, parties_error?, no_party_reason?, party_missing, party_suggestions }`. Without `confirmed: true`, `status` is `"preview"` and nothing changes; with it, the receipt policy is enforced and `status` is `"posted"`. `parties` lists every party the entry names with its share resolved to the cent (`{ party_id, party, share: "amount" | "percent" | "derived", amount?, percent?, resolved }`); when the shares don't add up to what the entry moved, `parties_error` says why and confirming fails with code `party_shares`. - `books.reverse_entry { entry_id, date, description, confirmed }` → same preview/confirm pattern as post. - `books.get_entry { entry_id }` → full entry with lines, receipts, and its `vendor`, `party_id`, and `party` (the party's label, when it names exactly one) tags, `parties` / `parties_error` as in the `post_entry` preview, and `no_party_reason` when it is marked as having no counterparty. `total` (its debits) is null, with `total_error` saying why, for a draft an earlier version journaled whose lines exact arithmetic can't sum; a draft line on an account the chart doesn't have (older books hold such drafts) shows an empty code and "(no account N)". - `books.search_entries { account?, date_from?, date_to?, text?, limit?, offset? }` → entries with lines, newest first. `limit` caps at 100. - **Omitted dates (rules.md B-30).** One rule everywhere (`ledger_core::calendar::PeriodDefaults`), stated in every report tool's description and date parameters in the same words: a period report with no dates covers the fiscal year to date (`company.fiscal_year_start`): `end` defaults to today (the company's time zone), `start` to the first day of the fiscal year that holds `end`; a `start` after the `end`, given or derived (`start` after today with no `end`), is refused, never swapped. An `as_of` defaults to today; a party's `year` to this calendar year. Every result names the dates it covers. - `books.trial_balance { as_of? }` → `as_of`, lines, totals, `balanced` (the trial balance as of the date, default today). - `books.balance_sheet { as_of? }` → totals (`assets`, `liabilities`, `equity`, `current_earnings`, `balanced`) plus `asset_accounts`, `liability_accounts`, `equity_accounts` (`{code, name, amount}`), as of the date (default today). - `books.profit_and_loss { start?, end?, class? }` → totals plus `revenue_accounts` and `expense_accounts` for the range (omitted dates: the fiscal year to date). Closing entries are excluded, so a closed period still shows what it earned. - `books.cash_flow { start?, end?, cash_accounts?, financing_accounts?, investing_accounts? }` (each defaults to the books' settings, `books.cash_accounts` and so on; cash is required one way or the other) → the statement of cash flows, direct method (rules.md B-14, P3 defect 1; omitted dates: the fiscal year to date): `{ method: "direct", start, end, operating_by_class, operating, cash_from_operations, investing_by_kind, investing, cash_from_investing, financing_by_kind, financing, cash_from_financing, net_change_in_cash, cash_beginning, cash_ending, noncash_disclosures, operating_reconciliation, reconciles, warnings }`. - Lines (`operating`, `investing`, `financing`) are one per entry, section and kind: `{ entry, date, label, kind, amount, on_behalf?, accounts, reverses?, class? }`; every transaction is listed (D-35), each under its kind. An entry's interest is its own operating class, (b) or (e), apart from the rest of its operating cash. What a member or a lender paid or received for the company with no cash account moving is cash borrowed (or contributed) and spent, on the entry's date (D-42, rules.md B-14 rule 11): an expense a member paid personally through Due to Members is a "Proceeds from borrowing — " line and an operating line, each with `on_behalf`, the part of its amount so handled (absent when none; an entry's `on_behalf` parts net to zero). Labels never come from a reversal's sign: "Reversal of #N — …", "Reinstatement of #A (reverses #B)". An entry and its reversal in the same period drop out together. - `operating_by_class`, `investing_by_kind`, `financing_by_kind`: `{ kind, class?, amount, entries }`, how the printed statement shows the sections: operating by ASC 230-10-45-25 class (`from_customers`, `interest_and_dividends_received`, `other_receipts`, `to_suppliers_and_employees`, `interest_paid`, `income_taxes_paid`, `other_payments`), investing and financing by kind ("Contributions from members — ", "Repayments of borrowing — ", "Purchases of property and equipment", …). - `noncash_disclosures`: `{ entry, date, label, amount, operating, investing, financing, exchanged, reverses? }`, the investing and financing activities no cash settled (ASC 230-10-50-3): property contributed, debt converted to equity, a purchase on the seller's credit, interest charged into a loan, the noncash part of a part-cash purchase. - `operating_reconciliation`: `{ net_income, lines: [{ kind, label, amount, account?, entries }], net_cash_from_operating }`, net income reconciled to operating cash (ASC 230-10-45-30), kinds `depreciation`, `investing_gain_loss`, `noncash_through`, `other_noncash`, `operating_balance_change`. - `reconciles`: `{ sections_sum, net_change, difference }`; `difference` is always `"0.00"`: a statement that wouldn't foot is an engine error, never output. - `warnings`: `{ entry, kind, message }` for an entry whose later payment or collection the books can't classify (`asset_on_operating_payable`, `asset_sold_on_operating_receivable`), with the fix. - Refused, naming the setting, when the roles contradict the chart or each other (cash and investing accounts must be assets, financing accounts liabilities or equity; no account in two lists or twice in one; no registered asset's account as cash). - Changed in P3 (breaking): `net_income`, `depreciation` and `working_capital` are gone (net income is in `operating_reconciliation`). - `books.digest { since: "2026-10-01" }` → `{ entries_posted: [...], totals_by_account: [...], stale_rules: [...] }`. The human review surface: "what did the AI do with my books lately." The digest is the answer to "trust, but verify." `stale_rules` lists legal amounts wanderbooks may no longer know as of today (`{ name, known_through, catalog, source, why }`): research the current value or ask the human, then update it upstream (pull request or issue at github.com/swaits/wanderbooks). `unreconciled_accounts` lists the cash and card accounts due for reconciliation (`{ code, name, reconciled_through?, due_through, next_step }`): the cash accounts (`[books] cash_accounts`, else asset accounts named for cash: cash, bank, checking, savings, money market), the card accounts (the business-card payment methods' liabilities, else liabilities named "card", not "gift", before their first statement: `ledger_core::parties::card_accounts`), and every other liability with a recorded statement, that have posted activity through the end of last month but no reconciliation (not voided) through it. The viewer's Needs attention uses the same rule (`ledger_store::reconcilable`). `uncategorized_accounts` lists every revenue and expense account (not a header) with no tax category, active or not, `"CODE Name"`: the list Needs attention shows (rules.md B-32). ## Tools — fixed assets Straight-line **book** depreciation only; tax depreciation stays with the CPA. Partial first/final months prorated by days; the final month trues up so the lifetime total is exactly (cost − salvage). - `books.register_asset { description, purchase_date, cost, salvage_value?, useful_life_months, cost_account, accum_depr_account, expense_account, tag?, serial? }` → `{ asset_id, tag }`. Accounts resolved by id or code. Without `tag`, the next free `PREFIX-0001` (`[books] asset_tag_prefix`, else the company name's initials without LLC/Inc; "FA" when none). - `books.label_asset { asset, tag?, serial?, clear_serial? }` → `{ asset_id, tag, serial }`: set or change the tag (unique ignoring case, never reused by another asset even after a retag or disposal) or the manufacturer's serial. `asset` is the id or current tag. Journaled as `asset.tagged`, `asset.serial_set`. - `books.asset_labels { assets?, skip? }` → `{ file_name, content_base64, tags }`: an Avery 5160/8160 label sheet (PDF): company, tag, QR code of the tag, description, serial. Default: every active tagged asset; `skip` reuses a partly used sheet. - `books.asset_schedule { asset_id | tag }` → `{ status, schedule: [{ period, amount, accumulated, book_value }] }`. - `books.list_assets {}` → assets with status and current book values. - `books.run_depreciation { period: "YYYY-MM", asset_id? }` → per-asset `{ entry_id, amount, already_posted }`, plus `skipped` for assets outside their useful life. Idempotent per asset and period. - `books.dispose_asset { asset_id | tag, date, proceeds, proceeds_account, gain_loss_account, buyer?, confirmed?, receipt_attachment_ids? }` → without confirmation: `{ status: "preview", ... }` and posts nothing; with `confirmed: true`: auto-posts missing final-period depreciation, then posts the balanced disposal entry. Subject to receipt policy (bill of sale); monthly depreciation is exempt as an allocation. `buyer` (a party) is the disposal entry's party; under `[books] parties = "require"` a sale with proceeds without one is refused before anything posts (`party_required`); a retirement with no proceeds and no buyer is marked as having no counterparty. - `books.export { report: "fixed_asset_register", format: json | csv, as_of? }`: every asset registered by the date (tag, serial, cost, depreciation by schedule, book value, disposal), totals, and the general ledger's balances of the assets' cost and accumulated depreciation accounts, with `unposted_depreciation` and `unregistered_cost` (zero when register and books agree; `ledger_core::fixed_asset_register`). - `books.show { asset }` opens an asset in the viewer; `page: "assets"` and `report: "fixed_asset_register"` open the register. ## Tools — schedules and recurring entries Amortization spreads a prepaid expense (asset → expense) or deferred revenue (liability → revenue) evenly over the months it covers, posting on each month end, to the cent (the last month absorbs rounding). Like depreciation, the schedule is the evidence: its postings are exempt from the receipt policy (the original payment carries the receipt). Recurring entries never post: they generate drafts, so every real receipt still goes through the policy. - `books.create_schedule { kind: "prepaid_expense" | "deferred_revenue", description, total, start, months, balance_account, pl_account }` → `{ schedule_id, ..., total, remaining, months: [{ date, amount, posted }], plan_error }`. Prepaid needs an asset and an expense account; deferred revenue a liability and a revenue account. `plan_error` is null, except for a schedule an earlier version accepted whose months run past the last date the books can compute: then it says why, `remaining` is null and `months` empty, and `books.run_schedules` refuses until it is dealt with. - `books.list_schedules {}` → `{ schedules: [...] }`, same shape. - `books.run_schedules { through?, confirmed? }` → `{ status: "preview" | "posted", postings: [{ schedule_id, date, description, amount, entry_id? }] }`: every unposted month ending on or before `through` (default today). Idempotent; closed periods are refused. - `books.create_recurring { description, frequency: "weekly" | "monthly" | "quarterly" | "yearly", start, end?, lines: [{ account, side, amount }] }` → `{ recurring_id, ..., generated: [] }`. Lines must balance. Monthly and longer occurrences are computed from the start date each time, so a month-end start stays on month ends (Jan 31, Feb 28, Mar 31). - `books.list_recurring {}` → `{ recurring: [...] }`. - `books.run_recurring { through? }` → `{ drafts: [{ recurring_id, date, entry_id }] }`: one draft per occurrence on or before `through`, once. ## Tools — the viewer - `books.show { entry_id | account | report | attachment_id | asset | party | reconciliation | search | page, start?, end?, columns?, compare? }` → `{ shown, viewer_open, note }`. Asks the human's viewer (`ledger-gui`) to open an entry, an account register or a report (for start/end dates if given), a stored file, an asset, a party (by id or name, resolved as in "Tools — parties"), a reconciliation (by id: its account's page, with its statements and reconciliations; viewer target `{show: "reconciliation", id}`), a transactions search, or a page (`parties` among them). Exactly one target; entries, accounts, attachments, assets, parties, and reconciliations are checked to exist. Never journaled: the request is a line `{seq, at, target}` of the books' own `ops/show.jsonl` (at most 32 lines, replaced whole, so a reader sees each line whole), which the viewer reads and never writes. The server makes `ops/` and `ops/viewer.lock` when it opens the books (and on a request); the viewer holds a shared lock on `ops/viewer.lock`, through a read-only descriptor, while it has the books open, and `viewer_open` says whether one does. The note says "The viewer shows …", or "No viewer has these books open: ask the human to open it (opened within a couple of minutes, it shows …)". - **Dates (rules.md B-30).** For an account or a report, the dates are resolved by the one default (omitted: the fiscal year to date; only `end`: its fiscal year to it) and sent to the viewer resolved, so `shown` and the screen can't differ: "the register of 1000 Business Checking, 2026-01-01 to 2026-10-20", "the profit and loss report, 2026-01-01 to 2026-10-20", "the trial balance report, as of 2026-10-20" (trial balance, aging, fixed asset register, a balance sheet in one total column), "the vendor 1099 report, for 2026". A start after the end, given or derived, is refused and nothing is sent. - **Options a target ignores are refused**, naming what takes them: `start`, `end`, `columns` and `compare` for any target but an account or a report; `columns` and `compare` for an account; `columns` but for `profit_and_loss`, `balance_sheet` and `cash_flow`; `compare` but for those and `tax_summary`, and never with a split; `start` for a report as of a day (the trial balance, the agings, the fixed asset register, a balance sheet in one total column unless compared with the prior period) or for `vendor_1099` (its year is `end`'s); and a split into more columns than the viewer shows (`ops::MAX_REPORT_COLUMNS`, 240: past it the viewer shows the total). - The viewer takes a target's dates as sent; one it can't honour (text that isn't a date, a start after the end from an earlier writer or a hand-edited `ops/show.jsonl`, an unknown split) is ignored whole, as an unknown page is. ## Tools — integrity - `books.verify { blobs? }` → `{ status: "ok" | "healed", events, head, healed?, blobs_verified?, checked }`. Verifies the journal's hash chain, replays it against the live ledger, and compares every table of the SQLite database row for row against a fresh projection of the journal. A drifted database is rebuilt from the journal (the old file kept as `wanderbooks.mismatch.