Appearance
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 :3000Use 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
| Folder | Role |
|---|---|
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/andsrc/rules/are pure: no I/O.src/mcp/andsrc/web/are the only entry points.src/xero/andsrc/hmrc/never import each other.- Money is integer pence; every number comes from code in
src/rules/orsrc/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
- 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 withcheckPeriodOrder. - 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. - Handler. Register the tool with
server.registerTool, with atitlein plain words (a host's permission dialog shows it in place of the name), and wrap the handler insafeHandler(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. - Logic. Fetch with
src/xero/orsrc/banks/, decide insrc/rules/orsrc/vat/. - 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). - 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_statusreports what became of a preview and never writes. Seesrc/mcp/approval-card.tsandwrite-and-log.ts. - Register. Add it to
tool-list.tsand cover it intests/mcp/.
Testing
- Unit tests in
tests/<module>/mirrorsrc/. Rules and VAT tests use synthetic data. Scenarios are tagged by spec in the test name, for exampleSPEC-006 S1: .... Never put real secrets in fixtures (useFAKEfakevalues). - Golden snapshots for presenters:
tests/present/golden.tsrecords every string a presenter returns while a file runs, and snapshots it byte for byte withgoldenTest(...)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_URLandAPP_DATABASE_URL. They skip when unset, but CI setsREQUIRE_DATABASE_TESTS=trueso a missing URL fails the build. Run them locally withREQUIRE_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 linthas zero warnings allowed.pnpm lint:migrationschecks 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 thesecurityjob beside gitleaks,pnpm audit, trivy and an SBOM. - Row-level security. Every table has
entity_idunder row-level security. Policies live insrc/platform/policies.sql; the app connects as theapprole. - 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. SeeAUDIT.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). Useghfor issues and pull requests. - One pipeline:
.github/workflows/ci.yml. A pull request runsverify(lint, typecheck, migration rules, tests against a Postgres service, build, docs build),securityand, 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
productionenvironment, 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.tsholds the rule). The jobs that need the NAS LAN (migrate-nas,deploy-nas) run on the self-hosted runner labelledgetmy-books-deploy. - On main, after
verify:migrate-nasapplies migrations, thendeploy-nasdeploys to the NAS, anddeploy-docspublishes this site to Cloudflare Pages./healthshows 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 pushagainst it. A migration is a numbered SQL file insrc/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.tsreads every stored credential and prints how many decrypt withXERO_TOKEN_ENCRYPTION_KEYand how many do not. Counts only, read only; it exits 1 when any row fails.reencrypt-credentials.tsdecrypts every credential withOLD_KEYand writes it back encrypted withNEW_KEY, in one transaction. Eachxero_connectionrow is written only over thetoken_versionit read, and its version goes up by one: if a token refresh lands mid-run the whole run is refused and nothing changes. A rowOLD_KEYdoes 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:
- Generate the new key (
openssl rand -hex 32) and keep it in Dopplerprdbeside the current one under a temporary name. Do not replaceXERO_TOKEN_ENCRYPTION_KEYyet. - Check the current key opens everything:
XERO_TOKEN_ENCRYPTION_KEY=<old> node --import tsx scripts/check-encryption-key.ts --allow-production getmy_booksmust report 0 failing rows. If any row fails, stop: find out why first. - Start the window: stop the app container on the NAS so nothing refreshes a token during the run.
- Re-encrypt:
OLD_KEY=<old> NEW_KEY=<new> node --import tsx scripts/reencrypt-credentials.ts --allow-production getmy_books. If it saystoken_versionchanged, the app was still running: nothing was changed; stop it and run again. - Check the new key opens every row (0 failing) and the old key opens none (every row failing, exit 1), with
check-encryption-key.tsas in step 2. - Set
XERO_TOKEN_ENCRYPTION_KEYin Dopplerprdto the new key and redeploy from main. Confirm/healthshows the commit andconnection_checkreaches 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. - 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
- SECURITY.md: reporting, and what we do.
- Threat model and quality evidence.
- Asset register: every account the service depends on, and its owner.
- Running the Postgres tests locally.
- Runbooks: break-glass Xero reconnect.