Skip to main content
Glama
ledgerlens

ledgerlens

by vovaddk
README.md
# ledgerlens

[![CI](https://github.com/vovaddk/ledgerlens/actions/workflows/ci.yml/badge.svg)](https://github.com/vovaddk/ledgerlens/actions/workflows/ci.yml)

**Ask Claude about your bank statements. An MCP server for CSV exports, with an eval suite that catches regressions.**

ledgerlens imports bank-statement CSV files into a local SQLite database and gives Claude
13 tools to work with them: search transactions, categorize them, summarise a month, check
budgets, find subscriptions and flag unusual spending, across UAH, USD and EUR accounts. The
second half of the project is the part most MCP demos skip: an evaluation harness that drives
Claude against the server, grades its answers and diffs every run against a stored baseline,
so a prompt tweak or a model upgrade cannot quietly make the agent worse.

Python 3.12+ · official MCP Python SDK 2 · Anthropic SDK · SQLite · uv · ruff · pyright (strict) · pytest

> All data in this repository is synthetic. Every merchant, employer and amount comes
> from a seeded generator; no real statement was used to build or test it.

## What it looks like

Ask *"Which of my subscriptions are still running, and what do they cost me a month?"* and
Claude calls `detect_recurring`. On the demo data the tool reports (real output, condensed):

| Merchant | Cadence | Charge | Per month, UAH | Status |
| --- | --- | --- | --- | --- |
| Rent Apartment Lypova St | monthly | 18,000.00 UAH | 18,000.00 | active |
| Misto Utilities | monthly | 2,012.26 UAH, varies | 2,012.26 | active |
| CodeForge Pro | monthly | 12.00 USD | 508.77 | active |
| Mobilink | monthly | 350.00 UAH | 350.00 | active |
| Streamly | monthly | 199.00 UAH | 199.00 | active |
| CloudVault | monthly | 2.99 USD | 126.77 | active |
| FitPulse Gym Membership | monthly | 900.00 UAH | 900.00 | inactive since 2026-07-02 |

The tools return structured JSON, which is what the model reads. Real output from
`detect_anomalies` on the same data:

```text
category_month  restaurants spending in 2026-08 was 20,050.70 UAH, 3.2x the median month
                (6,211.47), not counting individually flagged purchases.
transaction     Tekhnoland charge of 48,999.00 UAH on 2026-06-14 is 67.5x a typical
                electronics merchant's charge (725.50).
transaction     Varenyk House charge of 9,800.00 UAH on 2026-08-16 is 15.3x Varenyk House's
                usual charge (639.32).
transaction     Shvydko Taxi charge of 2,450.00 UAH on 2026-03-28 is 10.6x Shvydko Taxi's
                usual charge (230.83).
```

Those are exactly the four anomalies the generator planted, and nothing else.

## Features

- **Two import paths.** An adapter for the column layout of monobank-style exports
  (Ukrainian headers, card currency in the header, FX rate per row), and a generic importer
  driven by a small TOML mapping (delimiter, date format, signed amount *or* debit/credit
  columns, decimal comma, thousands separator, fixed or per-row currency). UTF-8 and
  Windows-1251 files are both read.
- **Idempotent imports.** Every row gets a fingerprint. Re-importing a file, or an
  overlapping one, adds nothing twice. Two identical coffees in the same second are still
  both kept.
- **Categorization that respects you.** The order is fixed: a transaction you pinned, then a
  merchant you corrected, then rules (merchant patterns and MCC codes), then a cached LLM
  answer, and only then a call to Claude for merchants nothing else recognises. Each unknown
  merchant is sent at most once. Your corrections survive re-imports and re-runs.
- **Money done carefully.** Amounts are stored as signed integers in minor units. Parsing
  goes through `Decimal` with banker's rounding. Foreign-currency charges keep both the card
  amount and the original amount, so a 2.99 USD subscription stays 2.99 USD even when its
  UAH price moves.
- **Multi-currency reporting.** Monthly UAH reference rates are learned from statements or
  set by hand (`set_fx_rate`, never overwritten by imports). Any total can be reported in
  UAH, USD or EUR. When a month has no rate, the nearest month is used and the output says so.
- **Analysis tools.** Monthly summary with savings rate and month-over-month change,
  breakdowns by category, merchant, month or account, budgets with ok / warning / over and a
  month-end projection, subscription detection, and anomaly detection.
- **Clear errors.** Bad input comes back as a message the model can act on:
  `Unknown category 'food'. Valid categories: groceries, restaurants, ...`,
  `Unknown account 'Savings'. Known accounts: [...]`, or, for a typo in a merchant name,
  `No transactions for merchant 'Zerno Cafe'. Similar merchants: ['Zerno Coffee']`.
- **Resources and prompts.** `ledgerlens://overview`, `ledgerlens://categories`,
  `ledgerlens://budgets`, `ledgerlens://formats` and a `ledgerlens://summary/{month}`
  template. Prompts: `monthly_review`, `subscription_audit`, `budget_plan`.
- **An eval suite.** 26 questions with answers computed from the generator's ground truth,
  four graders (exact, numeric tolerance, set match, LLM-as-judge), cost and latency
  accounting, and a baseline diff that fails CI on regressions.

## Architecture

```mermaid
flowchart LR
  subgraph Clients
    CD["Claude Desktop / Claude Code"]
    EV["Eval runner<br/>(Claude API, tool use)"]
  end
  subgraph "ledgerlens MCP server (stdio)"
    T["13 tools · 5 resources · 3 prompts<br/>server.py"]
    IMP["importers/<br/>monobank-style · generic mapping"]
    CAT["categorize.py<br/>pins → corrections → rules → LLM"]
    AN["analytics.py<br/>summary · budgets · recurring · anomalies"]
    FX["fx.py<br/>monthly UAH rates"]
  end
  DB[("SQLite<br/>~/.ledgerlens/ledgerlens.db")]
  API["Claude API<br/>(categorization fallback)"]

  CD -->|MCP| T
  EV -->|MCP over stdio| T
  T --> IMP & CAT & AN
  AN --> FX
  IMP & CAT & AN & FX --> DB
  CAT -.->|unknown merchants only| API
```

## Tools

| Tool | What it does |
| --- | --- |
| `import_statement` | Import a CSV (auto-detects the monobank-style layout; `generic` takes a TOML mapping). Runs rule categorization on new rows. |
| `list_accounts` | Accounts with currency, row count, date range and uncategorized count. |
| `query_transactions` | Filter by dates or month, account, category, merchant text, amount range and direction. Totals cover all matching rows even when the page is cut. |
| `spending_breakdown` | Spending or income grouped by category, merchant, month or account, in one reporting currency. |
| `monthly_summary` | Income, expenses, net, savings rate, category split, top merchants, largest expense, change vs the previous month. |
| `categorize_transactions` | Run the categorization pipeline, optionally with the LLM fallback. |
| `set_category` | Correct one transaction, or a merchant for all past and future rows. |
| `budget_status` / `set_budget` | Monthly limits per category, with status and month-end projection. |
| `detect_recurring` | Subscriptions and recurring bills: cadence, typical amount, monthly cost, next expected date, active or cancelled. |
| `detect_anomalies` | Unusually large purchases and category spikes, with robust z-scores and a plain-language explanation. |
| `convert_currency` / `set_fx_rate` | Convert with the stored monthly rate, or store a manual one. |

Read-only tools carry `readOnlyHint`, so clients can run them without asking.

## How the analysis works

**Merchant keys.** `"KOLOS MARKET #12"`, `"Kolos Market 07"` and `"KOLOS MARKET #31"` all
become `kolos market`. Store numbers, payment-processor suffixes (`*Storage`), domains and
legal-form words are stripped first. Rules, corrections, the LLM cache and recurring
detection all group by this key.

**Recurring charges.** Expenses are grouped by merchant, account and the *original*
currency. A group is recurring when the median gap between charges matches a cadence
(weekly, biweekly, monthly, quarterly, yearly) and at least 80% of the gaps fall inside that
cadence's tolerance. Amounts that vary by more than about 10% turn a subscription into a
`variable_bill` (utilities). A charge is `inactive` when nothing arrived within one interval
plus tolerance before the last date in the data. Comparing in the original currency is what
keeps the 2.99 USD CloudVault charge recognisable while its UAH amount drifts.

**Anomalies.** Two kinds, both using median and MAD instead of mean and standard deviation,
so one outlier cannot hide itself:

- *Single purchases.* With five or more earlier charges at the same merchant, a charge is
  flagged when it is at least 3x the usual one and its robust z-score on the log scale passes
  the threshold. For rarely seen merchants it is compared with the category instead, using the
  median of each merchant's median, so that many small coffees do not make every restaurant
  dinner look unusual. That comparison needs a 10x gap.
- *Category spikes.* A category month is flagged when it is 1.8x its median month, at least
  2,000 UAH above it, and past the z threshold. Purchases already flagged on their own are
  left out first, so a month shows up only when spending was broadly higher.

Rent, cash withdrawals and transfers between own accounts are excluded. On the canonical
seed the detectors report exactly the planted anomalies and subscriptions. On other seeds
they still find every planted one, plus occasional real spikes such as a holiday month.

## Getting started

Requirements: [uv](https://docs.astral.sh/uv/). It installs Python 3.13 for you.

```bash
git clone https://github.com/vovaddk/ledgerlens
cd ledgerlens
uv sync
uv run ledgerlens demo          # synthetic statements -> ~/.ledgerlens/ledgerlens.db
uv run pytest                   # deterministic suite, no API key needed
```

`ledgerlens demo` writes three fictional statements (a UAH and a USD card in the
monobank-style layout, and an EUR account from the made-up "Hryvnia Trust" bank in a
semicolon/decimal-comma layout), imports them through the real importers and applies the
rules. Two merchants are deliberately unknown to the rules, so you can watch the LLM fallback
handle them with `categorize_transactions`. The same CSVs are in `examples/statements/`.

### Connect to Claude Desktop

Add this to `claude_desktop_config.json` (Settings → Developer → Edit Config; on Windows the
file is in `%APPDATA%\Claude\`, on macOS in `~/Library/Application Support/Claude/`):

```json
{
  "mcpServers": {
    "ledgerlens": {
      "command": "uv",
      "args": ["--directory", "/absolute/path/to/ledgerlens", "run", "ledgerlens", "serve"],
      "env": {
        "LEDGERLENS_DB": "/absolute/path/to/.ledgerlens/ledgerlens.db",
        "ANTHROPIC_API_KEY": ""
      }
    }
  }
}
```

Restart Claude Desktop and ask *"Give me a review of August 2026"*. The API key is optional;
without it everything works except the LLM categorization fallback, which then tells you
what is missing. A Windows version is in
[`examples/claude_desktop_config.json`](examples/claude_desktop_config.json).

### Connect to Claude Code

```bash
claude mcp add ledgerlens -e LEDGERLENS_DB=$HOME/.ledgerlens/ledgerlens.db \
  -- uv --directory /absolute/path/to/ledgerlens run ledgerlens serve
```

Or copy [`examples/mcp.json`](examples/mcp.json) to `.mcp.json` in the repository root to
share it as a project-scoped server. Then `/mcp` in Claude Code shows the server and its tools.

### Your own statements

```bash
uv run ledgerlens import ~/Downloads/statement.csv --account "My card"
uv run ledgerlens import export.csv --account "Savings EUR" --format generic \
  --mapping examples/mappings/hryvnia_trust.toml
uv run ledgerlens categorize           # rules first, then Claude for unknown merchants
```

Or just ask Claude to import a file: the `import_statement` tool does the same. Mapping keys
are listed in the `ledgerlens://formats` resource. Personal rules go in a TOML file pointed to
by `LEDGERLENS_RULES`; they are tried before the built-in ones in
[`src/ledgerlens/data/rules.toml`](src/ledgerlens/data/rules.toml).

## Evals

The agent is only as good as what Claude does with the tools, so the repository tests that
too.

```mermaid
flowchart LR
  G["synth.generate(42)<br/>ground truth"] --> D["evals/dataset.json<br/>26 questions + expected answers"]
  G --> S["seeded SQLite<br/>(real importers)"]
  D --> R["runner: Claude + tool use"]
  S --> M["MCP server<br/>(one stdio process per case)"]
  R <-->|tools/call| M
  R --> GR["graders<br/>exact · numeric · set · judge"]
  GR --> RUN["run JSON<br/>pass rate · cost · latency"]
  RUN --> DIFF["diff vs baseline<br/>regressions fail CI"]
```

- **Dataset.** `ledgerlens-eval build-dataset` turns the generator's ground truth into 26
  questions: 13 numeric (*"How much did I spend on groceries in March 2026?"*), 6 exact
  (*"Which subscription looks cancelled?"*), 4 set (*"In which months did I go over my
  groceries budget?"*) and 3 free-text ones for the judge (*"I want to spend 5,000 UAH less
  per month. What should I cut?"*). Expected answers are computed with small, independent
  arithmetic over the generated transactions. They never call the analytics code, so a bug
  there shows up as a failed eval instead of moving the expected answer with it.
- **Graders.** *Exact* compares normalized text against aliases (`2026-06`, `June 2026`, ...);
  a short wrapper such as "the restaurants category" is fine, a sentence that names several
  candidates is not. *Numeric* uses per-question absolute and relative tolerance, and only
  spending questions accept the signed ledger amount (`-1234.50`). Numbers written in prose
  are read with decimal commas and thousands separators (`12 450,50`). *Set* matches items to
  expected entries one-to-one and needs both precision and recall; partial credit is reported
  as F1. *Judge* sends the question, reference facts and a rubric to Claude and passes only if
  it graded every criterion and all of them are met.
- **Runner.** Each case gets its own copy of the database and its own MCP server process
  over stdio, so a case that changes data cannot leak into another. The agent loop sends the
  full assistant content back each turn, returns tool errors as `is_error` results, and asks
  for a JSON-schema answer (`answer`, `number`, `items`) so grading never parses prose. Only a
  turn that ends normally is graded: a `max_tokens` cut or a refusal counts as no answer, and
  a failing judge call fails that one case instead of the run. It
  uses adaptive thinking with a configurable effort, prompt caching on the stable prefix, and
  server-side refusal fallbacks. Every run records pass rate (overall and per kind), mean
  score, cost from token usage (cache reads and writes included), p50/p95 latency, tool calls
  per case, the prompt version hash and the dataset fingerprint.
- **Baseline diff.** `ledgerlens-eval compare` lists regressions (pass → fail), fixes, new
  and removed cases, and the change in pass rate, cost and latency. It warns when the model,
  effort, prompt or dataset changed between the two runs, and `--fail-on-regression` makes it
  exit with code 1.

```bash
uv run ledgerlens-eval run                       # needs ANTHROPIC_API_KEY
uv run ledgerlens-eval run --effort high --case top-category-jan-2026
uv run ledgerlens-eval promote evals/runs/<run-id>.json   # make it the baseline
uv run ledgerlens-eval compare evals/runs/<run-id>.json --fail-on-regression
```

**What CI checks without a key.** `uv run pytest` runs 125 tests with no network. Among them:

- an *oracle* test plays a perfect agent for each of the 23 deterministic questions. It calls
  the MCP tools a careful agent would call and passes the result through the same graders,
  which proves every question can be answered from the tools;
- a scripted stand-in for Claude drives real MCP server subprocesses through the full runner,
  grading, cost accounting, report and baseline diff, including a deliberately regressed run
  that must be flagged;
- the committed dataset must match what the generator produces.

The live eval is opt-in: the **Live eval** workflow runs only when started by hand and needs
an `ANTHROPIC_API_KEY` repository secret.

### Live eval results

No live run has been recorded yet: this repository was built without an Anthropic API key, so
`evals/baselines/` is empty and the table below has no numbers. The first
`ledgerlens-eval run` prints a report in this shape and saves the run JSON; promote it to
create the baseline.

| Metric | Value |
| --- | --- |
| Model / effort / judge | `claude-opus-5-5` / `medium` / `claude-sonnet-5-5` |
| Pass rate | not run yet |
| Cost (agent + judge) | not run yet |
| Latency p50 / p95 | not run yet |

## Privacy

- The database is a local SQLite file. Nothing leaves your machine unless you use the LLM
  fallback or a Claude client.
- The categorization fallback sends only the unknown merchants' statement text, MCC and
  direction, never amounts, dates or balances, and caches each answer.
- When you chat through Claude Desktop or Claude Code, the tool results you ask for are sent
  to Claude as part of the conversation, as with any MCP server.
- `import_statement` reads only `.csv`, `.tsv` or `.txt` files up to 20 MB, and mappings must
  be `.toml`. Set `LEDGERLENS_IMPORT_DIR` to confine both to one folder.
- `.gitignore` excludes `*.db`, `data/` and every `.env*` file except `.env.example`.

## Configuration

| Variable | Default | Purpose |
| --- | --- | --- |
| `LEDGERLENS_DB` | `~/.ledgerlens/ledgerlens.db` | SQLite database path. |
| `ANTHROPIC_API_KEY` | empty | Categorization fallback and the live eval. `ant auth login` profiles work too. |
| `LEDGERLENS_CATEGORIZER_MODEL` | `claude-haiku-5-5` | Model for the categorization fallback. |
| `LEDGERLENS_LLM` | `on` | `off` never calls the LLM from the server. |
| `LEDGERLENS_RULES` | empty | Extra rules file, tried before the built-in rules. |
| `LEDGERLENS_IMPORT_DIR` | empty | If set, `import_statement` only reads files inside this folder. |
| `LEDGERLENS_EVAL_MODEL` | `claude-opus-5-5` | Agent model for the live eval. |
| `LEDGERLENS_JUDGE_MODEL` | `claude-sonnet-5-5` | Judge model for free-text answers. |

## Commands

| Command | What it does |
| --- | --- |
| `uv run ledgerlens serve` | Run the MCP server over stdio. |
| `uv run ledgerlens demo [--force] [--llm]` | Create a database from synthetic statements. With `--force` an existing one is moved to `<name>.<timestamp>.bak`, never deleted or overwritten. |
| `uv run ledgerlens generate --out DIR --seed N` | Write synthetic statements, a mapping file and the ground truth. |
| `uv run ledgerlens import FILE --account NAME` | Import a statement. |
| `uv run ledgerlens categorize [--no-llm] [--all]` | Categorize transactions. |
| `uv run ledgerlens-eval build-dataset` | Rebuild `evals/dataset.json`. |
| `uv run ledgerlens-eval run / compare / report / promote` | Live eval and baseline handling. |
| `uv run pytest` | Deterministic test suite. |
| `uv run ruff check . && uv run ruff format --check .` | Lint and formatting. |
| `uv run pyright` | Type-check (strict). |

## Project layout

```
src/ledgerlens/
  server.py          MCP server: tools, resources, prompts
  importers/         monobank-style adapter, generic mapping importer, idempotent storage
  categorize.py      rules, corrections, LLM fallback with cache
  analytics.py       queries, summaries, budgets, recurring and anomaly detection
  fx.py, money.py    currency conversion and integer money parsing
  synth.py           seeded generator of fictional statements + ground truth
  demo.py, cli.py    demo database and command line
  evals/             dataset builder, graders, runner, pricing, reports, CLI
evals/               dataset.json, baselines/, runs/
examples/            sample statements, mapping, Claude Desktop and Claude Code configs
tests/               pytest suite (no network)
```

## License

[MIT](LICENSE)

TDQS

A3.7/5.0

Scored across 13 tools

Disambiguation4/5

Most tools have clearly distinct purposes: querying raw transactions, importing statements, categorizing, budgeting, recurring detection, anomalies, and FX rates are separable. The main overlap is between spending_breakdown and monthly_summary, which both aggregate spending by category/month, though their descriptions distinguish report scope and depth.

Naming Consistency4/5

All names use consistent snake_case, and most are action-oriented verb_noun names such as query_transactions, set_budget, and convert_currency. A few report-style names like spending_breakdown, monthly_summary, and budget_status break the verb_noun pattern, but the overall convention remains readable and predictable.

Tool Count5/5

The 13 tools are well-scoped for a personal-finance ledger server. Each tool covers a meaningful operation across imports, reporting, categorization, budgets, recurring charges, anomalies, and currency handling.

Completeness4/5

The surface covers the core finance lifecycle well: import, query, categorize, summarize, budget, detect recurring/anomalous activity, and handle currency. Minor gaps remain around editing or deleting individual transactions and managing accounts beyond listing imported ones.