mcp-lettrage
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-lettrage match this payment to invoices: SARL IMPRIMERIE MAREC F429 F522 18 158,79 €"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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:
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.
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.
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
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 |
| full | 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 |
|
| partial numbers, fuzzy names, amount with tolerance, status and date filters |
| total due | open invoices with days overdue, unapplied credit notes, last payments; resolves bank aliases |
| partial or overpayment only | 7 gap types with amount, explanation and suggested accounting entry |
| – | entry point for an interactive session (not used by the evals) |
All tools are read-only: the agent proposes, a human posts.
Related MCP server: supplier-statement-check
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/.
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_factureson every case (4 calls on the typo case), working around the tool's weaknesses. v2 needs fewer calls and usessolde_client/expliquer_ecartto 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.
npm run evals # full run, writes evals/results/<timestamp>/summary.md
npm run evals -- --limit 5 --runs 1 # the trial aboveHow 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), 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.
Run it
Requirements: Node 20+, PostgreSQL with the pg_trgm, unaccent and fuzzystrmatch extensions (bundled with the standard Postgres installers).
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 stdioScript | What it does |
| recreate the schema and load the dataset (default seed 20261130) |
| regenerate |
| top-1 accuracy of v1 / v2 without an LLM |
| agent evals: |
| compile to |
| spawn the server over stdio, list tools, match one line |
| remote MCP server over Streamable HTTP ( |
| print the Claude Desktop config block for this checkout |
| replay the Claude Desktop demo against the real MCP server over stdio, no LLM call |
Demo in Claude Desktop
npm run build
npm run desktop-config -- --both # v1 and v2 side by sidePaste 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:
"Quels paiements reçus ne sont pas encore lettrés ?" ("Which incoming payments are still unmatched?") →
lister_releves_a_lettrer"Lettre la ligne
VIR SEPA MARTIN & FILS F549 F505 F469." ("Match this line.") → 3 invoices found by subset sum, score 0.99"Et
VIR RECU COUVERTURE MICHE?" ("And this one?") → invoice minus an unapplied credit note, score 0.58, confirmed withexpliquer_ecart"
VIR INST GF SERVICES N FACT 0510: qui est GF SERVICES ?" ("Who is GF SERVICES?") →solde_clientresolves the bank alias
Full script: 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.
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 clientDesign 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.
Available Tools
5 toolschercher_facturesARead-only
Recherche de factures avec filtres combinables. texte accepte un numéro complet ou partiel (F2026-0418, 418) ou un nom de client approximatif (recherche floue, alias compris). montant + tolerance pour chercher un montant proche. Renvoie numéro, client, dates, TTC, reste dû, taux d'escompte et statut. Utile quand rapprocher_paiement ne trouve rien ou pour vérifier une hypothèse.
Inputs: texte, limite, statut, montant, +4 more.
expliquer_ecartARead-only
Qualifie l'écart entre un paiement et une ou plusieurs factures : aucun, paiement_partiel, trop_percu, escompte (taux prévu sur la facture), avoir (avoir non imputé du client qui couvre exactement l'écart), double_paiement (factures déjà soldées). Renvoie le type, le montant de l'écart (|reste dû − montant reçu|), une explication et l'écriture à passer. À appeler pour confirmer un candidat dont l'écart n'est pas nul.
Inputs: factures (required), avoirs, montant, releve_id.
lister_releves_a_lettrerARead-only
Liste les lignes de relevé bancaire reçues et pas encore lettrées (id, date, libellé, montant), des plus anciennes aux plus récentes. Point de départ d'une session de lettrage : enchaîner ensuite rapprocher_paiement sur chaque releve_id.
Inputs: limite, date_max, date_min.
rapprocher_paiementARead-only
Point d'entrée pour lettrer une ligne de relevé bancaire. Analyse le libellé (références de facture même tronquées ou mal tapées, nom du payeur même abrégé ou via un alias/holding) et le montant, puis renvoie les meilleures hypothèses classées : une facture, plusieurs factures payées en un virement, ou une facture avec un écart (escompte, avoir déduit, paiement partiel, trop-perçu, double paiement). Chaque candidat porte un score 0-1, le type et le montant de l'écart, et les raisons du score. Score ≥ 0,8 : rapprochement fiable. Entre 0,5 et 0,8 : vérifier avec solde_client ou expliquer_ecart. Fournir releve_id si la ligne est en base, sinon libelle + montant.
Inputs: date, libelle, montant, releve_id.
solde_clientARead-only
Situation d'un client : encours, factures ouvertes (avec retard et escompte), avoirs non imputés, derniers paiements reçus. client accepte le code (C0042), la raison sociale, un nom abrégé ou un alias vu sur un relevé (ex. « GROUPE MARTIN »). Utile pour départager des candidats ou repérer un avoir à déduire.
Inputs: client (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
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.
Maintenance
Related MCP Connectors
Match bank receipts and payments to invoices with confidence, deductions and exceptions.
Reconcile business documents, inspect exact differences and evidence, and export reports.
Parse Spanish Norma 43 bank statements, reconcile against invoices, validate IBAN/NIF/SEPA ids.
Mechanically reconcile supplied purchase-order lines, invoice lines and goods receipts under expl...
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI IDEs to perform financial reconciliation through five native tools for matching invoices, detecting bundled payments, and handling bank fee variances.MIT
- AlicenseAqualityBmaintenanceEnables comparison of supplied supplier or vendor statement open items against an accounts payable ledger, identifying missing items, amount and date discrepancies, and ambiguous repeated references with exact reference evidence.8MIT
- AlicenseNot gradedqualityBmaintenanceEnables users and AI agents to reconcile CSV bank statements against invoices or bills by matching amounts and references, then sorting each line into matched, likely, review, or unmatched groups with reasons. It exposes read-only tools for matching files and inspecting detected CSV columns and row counts.72 npmMIT
- AlicenseNot gradedqualityBmaintenanceEnables finance teams to reconcile gateway settlements, bank statements, and ledgers through deterministic matching, batch decomposition, exception investigation, draft journals, and audited human approvals, with AI restricted to read-only evidence.MIT