mcp-lettrage
# mcp-lettrage
**An MCP server for bank reconciliation, and an eval suite that measures whether its tools actually help an agent.**
*Lettrage* is the French accounting term for matching each incoming bank payment to the customer invoices it settles. It sounds trivial until you read a real bank statement:
```
VIR SEPA RECU /FRM SARL IMPRIMERIE MARECH F429 F522 F489 18 158,79 €
VIR RECU COUVERTURE MICHE 151,01 €
VIR INST GF SERVICES N FACT 0510 331,65 €
VIREMENT DE LACROIX OPTIQUE REF F2026-0431 12 256,37 €
```
The labels are truncated by the bank, references come in half a dozen formats or with typos, the payer is sometimes a holding company instead of the customer, one transfer can settle three invoices, and the amount rarely matches the invoice: partial payments, early-payment discounts, credit notes deducted, double payments. (The four lines above: three invoices in one transfer, an unapplied credit note deducted, a parent company paying, a reference with two digits swapped that points to *another* customer's invoice.)
This repository is a public, fully synthetic re-implementation of a problem I solved in production for an ERP (in PHP/Laravel, not shown here). It contains:
1. **A synthetic ledger in Postgres**, generated from a fixed seed: 80 customers, 573 invoices, 45 credit notes, 461 bank lines, and 54 ground-truth bank lines covering 13 reconciliation scenarios. No real data.
2. **An MCP server in TypeScript** (official SDK, stdio) exposing the reconciliation tools in two versions: **v1**, the naive version you would ship first, and **v2**, the version the evals pushed towards.
3. **An eval suite** that runs Claude on the 54 cases in three configurations (**no tools**, **tools v1**, **tools v2**) and grades the answers **in code**, measuring pass rate, tool usage, tokens, cost, latency and variance across runs.
## Architecture
```mermaid
flowchart LR
subgraph data["Synthetic data (fixed seed)"]
gen["src/seed/generate.ts"] --> pg[("Postgres 18<br>pg_trgm + unaccent")]
gen --> truth["schema verite<br>(ground truth)"]
gen --> cases["evals/cases.jsonl<br>54 cases"]
end
subgraph tools["Tools (shared definitions)"]
v1["v1: exact match"]
v2["v2: fuzzy payer, typo refs,<br>subset sum, discount,<br>credit notes, double payment"]
end
pg --> v1 & v2
v1 & v2 --> mcp["MCP server (stdio)<br>src/server.ts --tools v1|v2"]
mcp --> desktop["Claude Desktop"]
v1 & v2 --> runner["Eval runner<br>evals/run.ts"]
cases --> runner
pg -- "ledger export<br>(no-tools baseline)" --> runner
runner <--> api["Claude API<br>claude-opus-5-5"]
runner --> grade["Code grader<br>evals/grade.ts"] --> results["evals/results/*<br>summary.md / runs.jsonl"]
```
The same `ToolDef` objects (name, description, zod schema, handler) are registered on the MCP server **and** handed to the Claude API by the eval runner, so the evals measure exactly what Claude Desktop sees. The tools never read the ground-truth schema (a test enforces it).
### Tools
| Tool | v1 | v2 |
|---|---|---|
| `rapprocher_paiement` (match a payment) | full `F2026-XXXX` reference or exact amount, one invoice | parses 6 reference formats, fuzzy payer to customer (aliases included), typo-tolerant references, 2-4 invoice combinations (subset sum), discount / credit note / double payment / partial / overpayment; scored and explained candidates |
| `chercher_factures` (search invoices) | `ILIKE` on name, exact number or amount | partial numbers, fuzzy names, amount with tolerance, status and date filters |
| `solde_client` (customer balance) | total due | open invoices with days overdue, unapplied credit notes, last payments; resolves bank aliases |
| `expliquer_ecart` (explain the gap) | partial or overpayment only | 7 gap types with amount, explanation and suggested accounting entry |
| `lister_releves_a_lettrer` (list unmatched lines) | – | entry point for an interactive session (not used by the evals) |
All tools are read-only: the agent proposes, a human posts.
## Results
### 1. Tools alone, no LLM (free, deterministic)
Is the **top candidate** of `rapprocher_paiement` exactly right (invoices, gap type and gap amount)? `npm run tools:accuracy`
| Category | n | v1 | v2 |
|---|---:|---:|---:|
| reference_exacte | 6 | 6 | 6 |
| reference_courte | 5 | 5 | 5 |
| sans_reference (no reference) | 6 | 6 | 6 |
| payeur_alias (holding / acronym pays) | 5 | 5 | 5 |
| montant_seul (cheque, amount only) | 3 | 3 | 3 |
| reference_erronee (typo in reference) | 4 | 0 | 4 |
| trop_percu (overpayment) | 2 | 0 | 2 |
| paiement_partiel (instalment) | 4 | 0 | 4 |
| multi_factures (one transfer, 2-3 invoices) | 6 | 0 | 6 |
| double_paiement | 3 | 0 | 3 |
| escompte (2 % discount) | 3 | 0 | 3 |
| avoir_deduit (credit note deducted) | 4 | 0 | 4 |
| montant_ambigu (two customers owe the same amount) | 3 | 1 | 3 |
| **Total** | **54** | **26** | **54** |
On five other seeds the tools never saw (`npm run db:seed -- 1` … `5`), v1 scores 25-29 / 54 and v2 54 / 54. One held-out failure ("SARL TRANSPORTS", a name too generic to identify the customer, plus a typo in the reference) led to a general fix rather than a special case. **Caveat:** the generator and v2 have the same author, so 54/54 mainly shows that v2 covers the scenarios the generator produces. The agent evals below are the real test.
### 2. Agent evals: trial run only
`claude-opus-5-5`, effort `medium`, **5 cases** spread across levels (2 easy, 2 medium, 1 trap) × 3 configs × **1 pass**, 15 conversations, $0.88 in total. Raw data: [`evals/results/2026-12-03T08-16-49/`](evals/results/2026-12-03T08-16-49/).
| Metric | no tools | tools v1 | tools v2 |
|---|---:|---:|---:|
| Pass rate | 5 / 5 | 5 / 5 | 5 / 5 |
| Input tokens / case | 23,058 | 5,614 | 9,857 |
| Output tokens / case | 388 | 456 | 397 |
| Cost / case | $0.123 | $0.022 | $0.031 |
| Latency p50 / p95 | 6.1 s / 6.8 s | 6.7 s / 7.4 s | 5.0 s / 6.9 s |
| Tool calls / case | 0 | 3.0 | 1.8 |
What this trial does and does not show:
- **Opus 5.5 does not need tools to be accurate on these 5 cases** when the whole ledger (≈ 570 invoices) is pasted into its prompt. That baseline costs **4-6× more per case**, and it would not scale to a real ledger.
- **v1 gets there by brute force**: it calls `chercher_factures` on every case (4 calls on the typo case), working around the tool's weaknesses. v2 needs fewer calls and uses `solde_client` / `expliquer_ecart` to confirm.
- **It does not cover the hardest traps**: none of the 5 sampled cases is a multi-invoice payment, discount, credit note, double payment or instalment, exactly where the tool-only numbers diverge. Five cases and one pass say nothing about variance either.
The full run (54 cases × 3 configs × 3 passes = 486 conversations) is one command away. Based on the trial, I estimate it at **$30-40** and about 15 minutes. I have not run it.
```bash
npm run evals # full run, writes evals/results/<timestamp>/summary.md
npm run evals -- --limit 5 --runs 1 # the trial above
```
## How it is graded
Each case is one bank line. The agent sees only the line (id, date, label, amount) and must end by calling `reponse_finale` with `{factures, avoirs, type_ecart, montant_ecart, confiance, justification}`. Grading is pure code ([`evals/grade.ts`](evals/grade.ts)), with no LLM judge:
- **pass** = same invoice set **and** same gap type **and** gap amount within €0.01 **and** same credit notes
- **partial score** = 0.5 × F1 on invoices + 0.2 type + 0.2 amount + 0.1 credit notes
- the runner records, per run: tools called in order, model turns, input / output / cache tokens, cost, wall-clock and API latency, stop reasons, errors (refusals count as failures; no fallback model, so every result is from the model under test)
- the summary reports pass rate per level and per category, the standard deviation of the pass rate across passes, and cases that pass in every pass vs only some
Case format, categories and gap conventions: [`evals/README.md`](evals/README.md).
## Run it
Requirements: Node 20+, PostgreSQL with the `pg_trgm`, `unaccent` and `fuzzystrmatch` extensions (bundled with the standard Postgres installers).
```bash
npm install
psql -U postgres -h localhost -f db/bootstrap.sql # creates role + database + extensions (prompts for a password)
cp .env.example .env # set DATABASE_URL (and ANTHROPIC_API_KEY for the evals)
npm run db:seed # schema + synthetic data, deterministic
npm test # 49 tests (DB tests skip without DATABASE_URL)
npm run tools:accuracy # tool-level results above, no API calls
npm run build && npm run smoke -- dist # MCP server over real stdio
```
| Script | What it does |
|---|---|
| `db:seed [-- seed]` | recreate the schema and load the dataset (default seed 20261130) |
| `evals:cases` | regenerate `evals/cases.jsonl` from the seed (a test fails if it drifts) |
| `tools:accuracy [-- -v]` | top-1 accuracy of v1 / v2 without an LLM |
| `evals [-- options]` | agent evals: `--configs sans_outil,v1,v2 --runs 3 --limit N --cases id,id --concurrency 4 --model ID --effort medium` |
| `build`, `start` | compile to `dist/`, start the MCP server (`--tools v1\|v2`, default v2) |
| `smoke [-- dist]` | spawn the server over stdio, list tools, match one line |
| `dev:http`, `start:http` | remote MCP server over Streamable HTTP (`/mcp`, `/v1/mcp`, `/health`) |
| `desktop-config [-- --both]` | print the Claude Desktop config block for this checkout |
| `demo [-- v1]` | replay the Claude Desktop demo against the real MCP server over stdio, no LLM call |
## Demo in Claude Desktop
```bash
npm run build
npm run desktop-config -- --both # v1 and v2 side by side
```
Paste the printed block into `claude_desktop_config.json` (Windows: `%APPDATA%\Claude\claude_desktop_config.json`, macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`) and restart Claude Desktop. Then try:
1. *"Quels paiements reçus ne sont pas encore lettrés ?"* ("Which incoming payments are still unmatched?") → `lister_releves_a_lettrer`
2. *"Lettre la ligne `VIR SEPA MARTIN & FILS F549 F505 F469`."* ("Match this line.") → 3 invoices found by subset sum, score 0.99
3. *"Et `VIR RECU COUVERTURE MICHE` ?"* ("And this one?") → invoice minus an unapplied credit note, score 0.58, confirmed with `expliquer_ecart`
4. *"`VIR INST GF SERVICES N FACT 0510` : qui est GF SERVICES ?"* ("Who is GF SERVICES?") → `solde_client` resolves the bank alias
Full script: [`docs/claude-desktop.md`](docs/claude-desktop.md). To see what each tool returns for these lines without Claude Desktop or an API key: `npm run demo` (and `npm run demo -- v1` for comparison: v1 finds nothing for the first two).
## Connect your Claude to a hosted server
**Live instance:** `https://mcp-lettrage-production.up.railway.app/mcp` (tools v2) · `…/v1/mcp` (tools v1). In claude.ai: **Settings → Connectors → Add custom connector**, paste the URL, enable it in a conversation and ask *"Lettre la ligne VIR SEPA MARTIN & FILS F549 F505 F469"*.
`src/http.ts` serves the same tools over **Streamable HTTP** (stateless, read-only, rate-limited): `POST /mcp` (v2) and `POST /v1/mcp` (v1). Once deployed, anyone can test it with nothing installed: in claude.ai, **Settings → Connectors → Add custom connector**, paste `https://<host>/mcp`, and ask *"Lettre la ligne VIR SEPA MARTIN & FILS F549 F505 F469"*. Deployment (hosted Postgres with a read-only role, Dockerfile, env vars) and a tunnel option for a one-off session: [`docs/remote.md`](docs/remote.md).
## Repository layout
```
db/ schema.sql (tables, balance view, trigram indexes, ground-truth schema), bootstrap.sql
src/seed/ deterministic generator (PRNG, name lists, 13 scenarios) and loader
src/tools/ shared ToolDef, label parser, v1, v2
src/server.ts MCP server (stdio)
src/http.ts remote MCP server (Streamable HTTP, stateless)
evals/ cases.jsonl, grader, agent loop, no-tools ledger export, stats, runner, results/
scripts/ seed, migrate, build-cases, tool-accuracy, smoke-stdio, desktop-config
tests/ 49 tests: generator invariants, parser, tools on the DB, MCP protocol (stdio and HTTP), agent loop with a fake client
```
## Design notes
- **Why a no-tools baseline with the whole ledger in the prompt?** Without tools the model cannot see the data at all, so comparing against an empty prompt would be meaningless. Pasting the ledger is the honest alternative to tools, and it shows the real trade-off: accuracy may hold on a small ledger, cost and context do not.
- **Why code grading?** Every case has a single correct answer (a set of invoice numbers, a gap type, an amount), so an LLM judge would only add noise and cost.
- **Why cases from a generator instead of hand-written ones?** Every case is reproducible from the seed, and the trap cases are checked by tests to be solvable *and* actually hard (the amount-only cheque points to exactly one open invoice; the ambiguous amount is owed by exactly two customers; no single invoice matches a multi-invoice transfer).
- **Read-only tools.** Posting a match is an accounting entry; in production this goes through a human validation step.
## License
MIT. All company names, amounts and labels are generated; any resemblance to a real company is coincidental.
TDQS
Scored across 5 tools
Each tool has a reasonably distinct role, but rapprocher_paiement, chercher_factures, and solde_client all involve locating invoices/client data and could be confused at the edges. The descriptions do a good job of stating when to prefer each (e.g. fall back to chercher_factures when rapprochement finds nothing), which keeps ambiguity low.
Nearly all names follow a French verb_noun snake_case pattern (lister_releves_a_lettrer, rapprocher_paiement, chercher_factures, expliquer_ecart). 'solde_client' breaks the verb-first convention as a noun phrase, but the style and casing remain uniform and readable.
Five tools map cleanly onto a single reconciliation workflow: list lines, match, search, check client balance, explain discrepancy. Each earns its place with no redundancy and no filler.
The read/analysis side of lettrage is well covered, but there is no tool to actually commit or record a matching (validate/lettrer a line), leaving the workflow ending at a recommendation. Also no way to list or filter already-lettered items or pending matchings, which are notable gaps for a reconciliation domain.