Skip to content

Developer guide ​

GetMy Books is an MCP server and web app (Node 22, TypeScript, Hono, the MCP SDK, Postgres with row-level security) that finds what's wrong in a UK company's Xero books. The owner uses it from their own Claude account; every figure comes from code, and every write to Xero needs the owner's Approve in an approval card.

For developers working in this repo. Owners should read the Owner's guide. How a change is governed (specs, ADRs, trailers) is a separate document: the SGE governance guide. The rules every contributor follows are in CLAUDE.md.

Set up ​

You need Node 22 or later, Docker, and the Doppler CLI signed in with access to the getmy-books project.

bash
corepack enable
pnpm install
git config core.hooksPath .githooks   # once per clone
pnpm test          # also: lint, typecheck, build, docs:build
pnpm dev           # web app on :3000

Use pnpm rather than corepack pnpm where the SGE tdd-guard needs to see a test run (CLAUDE.md). Settings come from Doppler (getmy-books, dev): .mcp.json starts the local MCP server over stdio with doppler run.

Local Postgres. The row-level security, audit-log, migration and store tests need a real Postgres, always a throwaway one, never the NAS database. pnpm db:setup builds the schema as production does (the app role, every migration, policies.sql, bootstrap.sql). It has a guard: the host must be local or CI's postgres service, and the database must be getmy_books_dev or end _test or _dev, never prd or prod. It resets an existing app role's password only if APP_DB_PASSWORD is set. The full recipe is in Running the Postgres tests locally.

Architecture ​

FolderRole
src/rules/Pure business rules (matching, deadlines, periods, outstanding balances). No I/O.
src/vat/Pure VAT derivation, verification, corrections and readiness. No I/O.
src/shared/Pure helpers: money in integer pence, dates, names.
src/present/Turns results into the summaries the owner reads (markdown tables, text). Pure formatting of figures code already worked out.
src/mcp/MCP tools, prompts, the approval card, server instructions. An entry point.
src/web/The web app (sign-in, connect, approval pages). An entry point.
src/xero/Xero client, OAuth, reads and guarded writes.
src/banks/Bank accounts, statement reading (CSV presets, saved mappings, OFX, QIF, Amex; no live bank connection, ADR 0035), preview and write log, activity log.
src/platform/Database, migrations, row-level security policies, logging, crypto, settings.
src/deadlines/, src/companies-house/Deadline sources and the Companies House client.

Module rules:

  • src/vat/ and src/rules/ are pure: no I/O.
  • src/mcp/ and src/web/ are the only entry points.
  • src/xero/ and src/hmrc/ never import each other.
  • Money is integer pence; every number comes from code in src/rules/ or src/vat/, never from a language model.
  • The entity comes only from the authenticated session. Tools take the entity's name, resolved from the session, never an id from input.

How a tool is built ​

  1. Input. Use the shared fragments in src/mcp/schemas.ts (entityInputSchema, periodInputSchema, isoDate) so every tool describes a field in the same words. Check period order with checkPeriodOrder.
  2. Guidance. Rules shared by instructions, descriptions and prompts are written once in src/mcp/guidance.ts (for example the statement-file confirmation and the no-VAT costs). A tool description carries a short pointer to a rule, not a copy.
  3. Handler. Register the tool with server.registerTool, with a title in plain words (a host's permission dialog shows it in place of the name), and wrap the handler in safeHandler (src/mcp/context.ts). It runs the call inside a per-call memo and turns any thrown error into an error result carrying the message.
  4. Logic. Fetch with src/xero/ or src/banks/, decide in src/rules/ or src/vat/.
  5. Presenter. Format the reply in src/present/. Tool replies start with that summary, then the JSON; a reply shown in an approval card carries the summary alone, with its data as structuredContent (approvalCardResult).
  6. Writes. A write is always preview first (bank_entries_preview, vat_corrections_preview, attachments_preview). The owner's Approve in the card makes the write. write_status reports what became of a preview and never writes. See src/mcp/approval-card.ts and write-and-log.ts.
  7. Register. Add it to tool-list.ts and cover it in tests/mcp/.

Testing ​

  • Unit tests in tests/<module>/ mirror src/. Rules and VAT tests use synthetic data. Scenarios are tagged by spec in the test name, for example SPEC-006 S1: .... Never put real secrets in fixtures (use FAKEfake values).
  • Golden snapshots for presenters: tests/present/golden.ts records every string a presenter returns while a file runs, and snapshots it byte for byte with goldenTest(...) as the file's last test. A change to any owner-visible text fails until the snapshot is updated on purpose.
  • Database tests need DATABASE_URL and APP_DATABASE_URL. They skip when unset, but CI sets REQUIRE_DATABASE_TESTS=true so a missing URL fails the build. Run them locally with REQUIRE_DATABASE_TESTS=true pnpm test.
  • Call budgets in tests/performance/ (budgets.ts) fix how many Xero requests each entry point makes for a given amount of data (Xero allows 60 a minute). Budgets are exact: an increase or a saving both fail until the number changes, with the reason in the commit.
  • Gates. pnpm lint has zero warnings allowed. pnpm lint:migrations checks migration rules. Chain them: pnpm lint && pnpm typecheck && pnpm test, and commit only on success.

Security rules ​

  • Semgrep project rules in security/semgrep/ (each with a fixture): the entity must come from the session in MCP tools, no logging of credentials or statement text, no raw pence arithmetic outside the money helpers, and pure modules do no I/O. CI runs semgrep in the security job beside gitleaks, pnpm audit, trivy and an SBOM.
  • Row-level security. Every table has entity_id under row-level security. Policies live in src/platform/policies.sql; the app connects as the app role.
  • Approval path (AUDIT C5). No MCP tool submits or approves a filing, and a Xero write needs a human action the model cannot perform. Each preview shows an approval card; Approve calls an app-only tool the model cannot see, with a one-time token only the card receives. Writes also respect Xero's lock dates. Only src/approvals/ may call the HMRC submit function. See AUDIT.md.
  • Logging. First argument is the object, second the message: logger.error({ err: error, entityId }, 'VAT sync failed').

Wording in owner-visible text ​

Tool descriptions, prompts, presenter strings and docs follow ADR 0036: the software finds, checks, flags and proposes; the owner confirms, approves and files. Never describe GetMy Books as an accountant, or its results as verified, assured, audited, guaranteed or advice, and never say it prepares or files anything for the owner. Telling the owner to ask their accountant is fine. Tool names stay as they are (renaming breaks connected clients). Golden snapshots make every wording change deliberate.

Two features are out of bounds while ADR 0036 stands: any human service on customers' books, and filing with HMRC or Companies House (not doing).

Deploying ​

  • The code is on GitHub, FEAW-Serv/getmy-books (private; ADR 0046). Use gh for issues and pull requests.
  • One pipeline: .github/workflows/ci.yml. A pull request runs verify (lint, typecheck, migration rules, tests against a Postgres service, build, docs build), security and, when the schema build changes, n1-compat, on GitHub's runners. Each job is a check on the pull request.
  • Production secrets are secrets of the GitHub production environment, which only main can use. Only the main-only jobs name it, so no pull request or branch job can read them (DH-13; tests/infra/ci-workflow.test.ts holds the rule). The jobs that need the NAS LAN (migrate-nas, deploy-nas) run on the self-hosted runner labelled getmy-books-deploy.
  • On main, after verify: migrate-nas applies migrations, then deploy-nas deploys to the NAS, and deploy-docs publishes this site to Cloudflare Pages. /health shows the deployed commit. Building the image in CI and deploying it by digest is planned (ADR 0028, proposed; issue #75): today the NAS builds the image from the deployed commit.
  • Migrations go by the pipeline only. Never run migrations or seeds against the NAS database yourself, and never run drizzle-kit push against it. A migration is a numbered SQL file in src/platform/migrations/ that must work with both the current and previous release (expand, then contract; see the change protocol).
  • A red or flaky main stops feature work until the cause is fixed. No retrigger commits.

Rotate the encryption key ​

XERO_TOKEN_ENCRYPTION_KEY encrypts every stored credential: the Xero access and refresh tokens in xero_connection, and bank_account.credentials_encrypted (always empty since ADR 0035, but covered). Two tools in scripts/ move them to a new key (issue #63):

  • check-encryption-key.ts reads every stored credential and prints how many decrypt with XERO_TOKEN_ENCRYPTION_KEY and how many do not. Counts only, read only; it exits 1 when any row fails.
  • reencrypt-credentials.ts decrypts every credential with OLD_KEY and writes it back encrypted with NEW_KEY, in one transaction. Each xero_connection row is written only over the token_version it read, and its version goes up by one: if a token refresh lands mid-run the whole run is refused and nothing changes. A row OLD_KEY does not open also stops the run before anything is written.

Neither tool prints a key, a token or the database URL. Both refuse any database that is not a throwaway one, and NODE_ENV=production, unless they are given --allow-production <database> with the exact name of the database in DATABASE_URL (production's is getmy_books).

On production only the Product Owner runs them, in a maintenance window, with the owner connection. Agents never do (CLAUDE.md rule 6). Rehearse the steps on a throwaway database first. In order:

  1. Generate the new key (openssl rand -hex 32) and keep it in Doppler prd beside the current one under a temporary name. Do not replace XERO_TOKEN_ENCRYPTION_KEY yet.
  2. Check the current key opens everything: XERO_TOKEN_ENCRYPTION_KEY=<old> node --import tsx scripts/check-encryption-key.ts --allow-production getmy_books must report 0 failing rows. If any row fails, stop: find out why first.
  3. Start the window: stop the app container on the NAS so nothing refreshes a token during the run.
  4. Re-encrypt: OLD_KEY=<old> NEW_KEY=<new> node --import tsx scripts/reencrypt-credentials.ts --allow-production getmy_books. If it says token_version changed, the app was still running: nothing was changed; stop it and run again.
  5. Check the new key opens every row (0 failing) and the old key opens none (every row failing, exit 1), with check-encryption-key.ts as in step 2.
  6. Set XERO_TOKEN_ENCRYPTION_KEY in Doppler prd to the new key and redeploy from main. Confirm /health shows the commit and connection_check reaches each company's Xero. A web form left open across the change is refused once (its token's key is derived from the same key, SPEC-017); reloading the page fixes it.
  7. Only then destroy the old key: delete the temporary Doppler entry and any copy held elsewhere. Older database dumps hold tokens under the old key and become unreadable, which is intended; a restore from one needs Xero reconnected.

To undo a rotation before step 7, run step 4 again with OLD_KEY and NEW_KEY swapped and put the old key back in Doppler. If the tools cannot be used, the fallback is to reconnect each company's Xero (scripts/xero-connect.ts) after changing the key.

Further reading ​