feat(mcp): Financial intelligence layer for the MCP server
[!IMPORTANT]
This PR is no longer the one to review. Following @jjmata's suggestion, the work is being
delivered as a series of smaller PRs. This one stays open as the integrated view: it is the only
place the eight gaps are described together, with the screenshots, and it is what the individual
PRs point back to. It is deliberately not kept rebased on main, so expect it to show conflicts.
Review the PRs in the table below instead.
How this is being split
Seven independent pieces. Three are open, four are waiting on their base to land.
| # | What | Where it is described below | PR |
|---|---|---|---|
| G | Wise SCA private key refused without encryption | not below, found while reviewing this PR | #3415 |
| A | terms on get_accounts, transaction context, LabelNormalizer, get_uncategorized_transactions | §1 (first half), §5 (first half) | #3421 |
| E | Statement vault bridged to search, get_document_text | §4 | #3422 |
| B | Overdraft and loan term columns, get_liabilities | §1 (second half) | after A |
| D | Seasonal recurring detection | §3 | after A |
| C | Day-by-day cash projection, simulate_scenarios | §2 | after B |
| F | Category trends, derived loan amortization | §5 (second half), §6 | after B |
| H | insights_golden_v1 eval dataset | not below, requested in review | after F |
main
├── G Wise SCA key encryption → #3415 independent
├── E document vault → #3422 independent, 1 migration
└── A base tool context → #3421
├── D seasonal detection
└── B overdraft and loan terms 2 migrations
├── C cash projection and scenarios
└── F trends and amortization
G went first and alone because it is not part of this feature work at all. Reviewing this PR
surfaced that WiseItem wraps its encrypts declarations in if encryption_ready?, so an install
without Active Record encryption configured stored the SCA private key as plaintext. That does not
belong inside a 5,700 line feature stack.
On the ordering. I have no push access here, so the branches live on my fork, and a cross-fork
PR has to take its base from this repository. B and D cannot be based on A: opened today they would
each replay A's diff on top of their own, and C and F would replay two. So each one is opened once
its parent has merged, which keeps every PR a single-purpose diff. If you would rather have real
stacked PRs in the sense of the docs you linked, that needs the branches to exist on
we-promise/sure, which only a maintainer can do. Happy either way.
On the evals, and a correction to what I said earlier. I said the base PR would carry the
eval dataset. That turned out to be the one place it cannot go. insights_golden_v1 is a chat
eval that pins the ROUTING contract, and its 37 samples reference nine tools spread across A, B,
C, D and F. Landing it before those exist would assert routing to tools that are not in the
registry yet, so every one of those samples would fail and the dataset would measure nothing. It
goes last, as H.
Worth flagging two things I found while writing it. No CI change is needed: llm-evals.yml globs
db/eval_data/*.yml and builds its matrix from whatever it finds, so the dataset file is the
whole change. And get_document_text cannot be covered at all: ChatRunner#reference_user is
User.order(:created_at).first, the eval job runs db:schema:load without seeding, so the user
is nil and the preview gate never opens. get_holdings and update_tag are silently dropped
from the definitions for the same reason. No existing sample expects them, so nothing is failing
today, but the harness is running against 22 of 24 ungated tools rather than all of them.
What the split cost. Nothing was lost in the process: I reconstructed the seven branches into a
single tree and diffed it against this one. On the 63 files that belong only to these lots the diff
is empty, app/models/assistant.rb (whose registry lines are spread across five PRs) is identical,
and db/schema.rb differs only by check_constraint formatting from a different PostgreSQL dump
version, on tables none of this touches.
Everything below is the original description, unchanged.
Why
I manage my real household finances through an AI agent connected to Sure's MCP server. During an
actual conversation the agent told me I would be at -2 498,79 € on 1 October. The figure was
computed from outflows only, because the one forward-looking piece of code in the app,
Insight::Generators::CashFlowWarningGenerator, filters recurring_transactions.amount > 0 and
therefore never adds a salary back. A balance that can only fall is not a projection, and I acted
on it for a week before working out it was wrong.
That was one of eight failures I hit in a single session. Digging into each of them, the ceiling
turned out not to be where I expected: most of what the agent was missing is already in the
database and simply never read by the tools. get_accounts discarded the entire delegated
accountable record, so loans.interest_rate, loans.term_months, Loan#monthly_payment and
credit_cards.apr were invisible despite sitting in the schema. get_transactions loaded the
matched transfer pair into memory and then threw it away.
This PR closes the eight gaps. Four needed new columns; the rest needed the tools to return what
the app already knew.
What this changes
1. Accounts carry their terms
get_accounts gains a terms sub-object populated per accountable type, and a new
get_liabilities tool returns debt with its repayment projection. Unset keys are omitted
rather than returned as zero, so a missing rate reads as unknown.
Two things were genuinely absent from the schema and are added as nullable columns:
depositories carried nothing but subtype and locked_attributes, so a current account's
most consequential numbers, the point at which it enters unauthorised overdraft and what the bank
charges for it, existed nowhere. An assistant reading the data could only advise "never go below
zero", which is both wrong and needlessly alarming for a holder with an arranged facility.
Six columns record the arranged limit, the interest rate on the overdraft, and the per-payment fee
with its threshold and its monthly caps. Banks cap those fees either by amount or by count and some
do both, so both forms exist and Depository#capped_monthly_fees applies whichever binds first.
intervention_fee_for returns nil when the terms were never entered and 0 when they were and
the fee does not apply, so "no fee" stays distinguishable from "we do not know".
loans gains the terms that anchor the schedule in time: term_months without an origination
date is a duration with no origin, so neither an end date nor a remaining instalment count could be
derived. apr is deliberately separate from interest_rate and never reaches the amortization
formula: a French TAEG bundles fees and insurance, and feeding it in would overstate the interest
every month. insurance_monthly_amount is billed alongside the instalment but sits outside the
schedule, so Loan#total_monthly_cost states the sum rather than leaving an assistant to quote the
instalment and understate the real burden.
scheduled_payment makes variable and adjustable rates first-class. Loan#monthly_payment only
ever returns a figure for a fixed rate, so effective_payment prefers the hand-entered amount and
everything downstream derives from it. remaining_payments solves the amortization identity from
the live balance, so an overpayment is reflected, and returns nil rather than a plausible
number when the payment cannot cover the monthly interest or when the rate is unknown.
Both forms put the new fields behind a <details> disclosure, open only when the terms are already
filled: most accounts have no arranged overdraft, and the loan contract details are not needed to
record a loan.
2. A cash projection that includes income
Cashflow::Projection is a new engine, deliberately alongside CashFlowWarningGenerator rather
than replacing it. It walks the balance day by day and reports a dated low point plus, per
threshold, where the balance first crosses it and how deep it goes.
Zero and the arranged overdraft limit are distinct thresholds, because crossing into overdraft
and crossing the arranged facility are different events and only the second costs money. A
threshold that is never reached is absent from the result rather than reported at zero, so the
presence of the key is itself the signal.
Materialized occurrences are only generated 90 days out
(RecurringTransaction::OccurrenceGenerator::HORIZON_DAYS), so a six-month projection built on them
alone would silently lose every bill past that frontier and read as far more comfortable than
reality. The engine uses occurrences where they exist, since they carry partial payments, snoozes
and skips a schedule cannot know about, and falls back to RecurringTransaction::Schedule past
each series' own frontier. Splitting per series and per date is what keeps the two sources from
double counting.
Intervention fees are driven by the dated events of the day and never by the smoothed discretionary
baseline, which is not a payment and cannot trigger anything. The whole month is re-capped on each
charging day and only the increment is taken, so a cap that binds mid-month really does stop the
charges. The overdraft floor is summed across the projected accounts, because the projection runs on
a pooled balance and two accounts with a 400 facility each really can reach -800. The fee terms are
not summed: applying every account's schedule to the same payment would charge it once per
account, so one set of terms is used and warnings says so when accounts disagree.
Exposed as project_cash_balance, with simulate_scenarios layering dated movements onto the same
projection so scenarios compare like for like. It returns the low-point delta against the baseline
computed server-side, and tells the caller to compare low points rather than ending balances: a
scenario that ends comfortably can still cross the limit on the way.
3. Quarterly, semiannual and annual obligations become visible
Four quarterly tax instalments and an annual insurance premium were invisible to detection, and not
by oversight. RecurringTransaction::Identifier looks back 3 months, requires 3 occurrences, and
tests consistency on the day of the month. A quarterly charge never produces three hits inside a
three-month window, so the pattern cannot be seen at all and the money is budgeted at zero. The
failure is silent, which is the worst kind.
SeasonalIdentifier is a separate class rather than a branch inside Identifier. The monthly pass
is load-bearing and well tuned; this one answers a different question, whether the gap between
charges is consistent rather than whether the day of the month is, and gets to be wrong on its own.
Consistency is judged per gap, never on the average, mirroring the monthly pass's per-occurrence
rule: charges 3, 6 and 15 months apart average out to something plausible and are not a cadence.
Tolerances are tight relative to the period (10 days on a quarter, 25 on a year) because looser ones
start matching unrelated purchases that happen to fall a season apart. Anything under a 60-day gap
is left to the monthly pass, so the two can never claim the same series.
Two occurrences is the floor and also the ceiling for an annual charge, since 24 months of history
cannot hold three. The safety valve is not the count but the fact that everything lands as
suggested and waits for confirmation, plus a minimum amount.
Wired into the nightly sweep and the two user-triggered buttons, and left off in the debounced
post-sync pipeline: this pass reads 24 months of entries against the monthly pass's 3, and a
quarterly charge cannot appear between two syncs.
4. The document vault becomes searchable, and readable
Sure had two disjoint document stores and only one of them was searchable.
AccountStatement.create_from_prepared_upload! never touched the vector store, so a statement
uploaded through the web vault or the MCP tool existed only in account_statements and was
structurally invisible to search_family_files. A user could attach a PDF to the right account and
be told, truthfully from the code's point of view and falsely from theirs, that no document had been
uploaded.
Three separate defects, fixed separately:
- The bridge. An
after_create_commiton the one point all three producers share enqueues
indexing. The link lives in the document's own metadata rather than in a new column, so a re-run
or the/importspath having already indexed the file cannot produce a duplicate. Both paths take
the statement row lock, because the existence check alone is check-then-write across two queues. - The message. "No documents have been uploaded" was returned whenever
families.vector_store_id
was NULL, which means no store was ever created, an entirely different claim. Both unconfigured
cases now degrade to a metadata search over the vault and report the real reason, so the answer is
"here is what exists, full-text search is unavailable" rather than "you uploaded nothing". - The contents.
get_document_textreads a statement page by page throughPDF::Reader, already
a dependency and already what backsVectorStore::Embeddable. A PDF with no text layer is reported
as a scan with an explicit "there is no OCR here, ask the user" rather than as a document that says
nothing, and an unparseable file is reported distinctly from a scan. Access is narrower than the
other vault tools: full text is a bigger disclosure than metadata, so it also requires access to
the linked account.
5. Labels, categorisation and trends
Transaction::LabelNormalizer cleans French bank labels with no LLM involved. This matters beyond
readability: merchant detection and auto-categorisation run only as Rule actions and rules.active
defaults to false, so an install without such a rule keeps raw labels forever.
RecurringTransaction::Identifier then groups patterns by entries.name whenever merchant_id is
nil, making CB 02/09 CARREFOUR and CB 04/10 CARREFOUR look like two different payees and
preventing any recurring series from being detected at all.
Two signals fall out of the label because nothing else carries them. operation_date is the date
the bank printed, returned only when it differs from entries.date, which holds whatever the
provider chose. A refund rail is the only available hint that an inflow is money coming back, since
the domain has no refund model, kind, or link to the refunded transaction.
get_uncategorized_transactions groups by cleaned payee instead of listing rows, so each group is
what a single categorisation rule would cover, and its enrichment block reports whether an active
rule actually performs auto-categorisation and merchant detection. Without it an assistant sees the
symptom and cannot name the cause.
get_category_trends returns monthly spend per category over up to 24 months with the direction of
travel. Direction is reported two ways on purpose: the OLS slope is sensitive to a single outlier
month, the half-over-half comparison is not, and a label is emitted only where the two agree.
That is what stops one holiday month from being reported as a trend.
get_transactions rows now report kind, entry_id and the counterparty account, with pending
and excluded as sparse keys so a 50-row page does not pay for fifty falses. The tool description
documents two traps that silently produce wrong answers: amount is always positive with the
direction in classification, and the returned totals span the whole filtered set while excluding
tax-advantaged accounts.
6. Loan history
Balance::BaseCalculator moves a loan's non-cash balance only through entries carried by the loan
account, so without writes the balance plateaus until the next Valuation and then catches up in a
step. Loan::AmortizationSchedule derives the theoretical schedule from the contract terms and
reports the divergence against recorded history, rather than rewriting persisted balances. That is
the honest correction to measure before deciding whether to touch the calculator, and it keeps the
upstream merge tractable.
New MCP tools
| Tool | Answers |
|---|---|
get_liabilities | debt with terms, remaining instalments, payoff date, optional amortization |
project_cash_balance | day-by-day balance, dated low point, threshold crossings, simulated fees |
simulate_scenarios | up to 5 scenarios of dated movements against one baseline |
get_category_trends | monthly spend per category over N months, with direction of travel |
get_uncategorized_transactions | grouped by cleaned payee, plus why enrichment is not running |
get_document_text | the actual text of a stored statement, page by page |
Security
Two authorization defects were found by review during this branch's development and are fixed
here, plus one pre-existing gap the branch would otherwise have widened:
Cashflow::Projectionscoped the accounts it projects to the caller but read the recurring series
that drive it off the family. Series names and amounts are echoed back throughevents,
assumptionsandwarnings, so with per-account sharing off a member could read another member's
private bills and salary out of a projection built on their own accounts. All three reads now go
throughRecurringTransaction.accessible_by, the scope every other reader uses.search_family_files' metadata fallback listed the vault with no role check, while every other
vault tool opens withstatement_manager?. Full-text search being unconfigured must not become a
way around the gate.family_documentshad no account dimension at all, so the store was family-wide by construction.
That was tolerable while only/importsfed it and stopped being so once every vault upload was
indexed.account_idis now a real column with a foreign key, backfilled from metadata, and
FamilyDocument.readable_byfilters search results. Only a document that names an account can
be withheld: a tax return with no account stays family-wide, as it should.
Design notes
Absent, never zero. Throughout, a value that cannot be computed honestly makes its key disappear
from the payload rather than appear as 0 or null, with an unavailable block naming the reason
and, where it is fixable, the field to fill. A model cannot cite a figure that is not in what it
received; it will always cite a zero. This is the single rule that addresses the original failure.
No new dependencies. PDF::Reader was already in the Gemfile and already backs
VectorStore::Embeddable. No LLM is involved in label normalisation or seasonal detection.
Additive and upstream-friendly. All three migrations add nullable columns to tables the upstream
does not otherwise touch. CashFlowWarningGenerator, Identifier and Balance::BaseCalculator are
left alone; the new engines sit alongside them and callers opt in. The one exception is
IncomeStatement::Totals, which gains an optional group_by_month (default false, no behaviour
change for existing callers) so get_category_trends can aggregate a 24-month window in one query
instead of 24. Duplicating that SQL in a fork would have diverged in silence; the merge surface is
the lesser cost.
Verification
8453 runs, 33722 assertions, 0 failures, 0 errors, 30 skips
bin/rubocopcleanbin/brakeman --no-pager0 warningsbundle exec erb_lintclean on both views this branch touches (10 pre-existing errors elsewhere,
untouched)- 12 new test files, ~2 400 lines of tests
- Three full-suite runs green, including one replaying a seed that had previously produced flakes
under heavy machine load
Not in this PR
- Value date vs operation date.
entries.dateis a singledatecolumn and each provider
flattens its own pair of dates into it with a different rule; SimpleFIN even inverts its preference
by account type. The label side is handled byLabelNormalizer, which extracts the date embedded
inCB 02/09 CARREFOUR. The provider side needs anentries.value_datecolumn filled by
processors I have no way to test, so it is left for someone who can. - Rewriting persisted loan balances. The derived amortization schedule measures the divergence;
changingBalance::BaseCalculatoris the real fix and belongs in its own PR. - An account column on
family_documentsfor the/importspath's older rows. The backfill
covers what has metadata; documents indexed before the vault bridge have no account and stay
family-wide.
🤖 Generated with Claude Code
Summary by CodeRabbit
- New Features
- Added overdraft limits, interest, and intervention-fee settings for depository accounts.
- Added expanded loan details, repayment projections, payoff dates, and remaining-interest estimates.
- Added seasonal recurring-transaction detection for quarterly, semiannual, and annual charges.
- Added searchable account-statement content, text extraction, and metadata-only fallback search.
- Expanded assistant tools with liability summaries, cash projections, scenario comparisons, category trends, uncategorized spending, and document text retrieval.
- Improved transaction and account details with cleaned labels, transfer information, and financial terms.
- Bug Fixes
- Improved document access filtering and prevented duplicate indexing during concurrent uploads.