saga-mcp
# saga-mcp
[](https://www.npmjs.com/package/saga-c-mcp) [](https://github.com/klove-app/saga-mcp/releases/latest) [](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.klove-app/saga-mcp) [](LICENSE)
An unofficial, free and open-source [MCP](https://modelcontextprotocol.io) server that lets an AI assistant
(Claude Desktop, or any MCP client) **read** the accounting data of a **SAGA C.** firm database:
trial balance, general ledger, journal, suppliers and customers with open invoices, purchase and sales
documents, stock, cash and bank registers, VAT and a basic SAF-T (D406) readiness check.
It is **read-only by default**. A set of **experimental** write tools (suppliers and customers, analytic
accounts, articles, warehouses, purchase and sales invoices, cash/bank payments) exists behind an explicit
switch, with a dry run by default and a backup before every save.
> **Not affiliated with SAGA Software S.R.L.** "SAGA" and "SAGA C." are names of SAGA Software S.R.L., used
> here only to say which program's databases this tool reads. This project contains no SAGA code, binaries
> or database files. Use it only on databases you are entitled to access, under your own SAGA licence.
**🇷🇴 Documentația completă în limba română: [README.ro.md](README.ro.md).**
**Pe scurt (RO):** server MCP neoficial, gratuit, pentru bazele de date SAGA C. (Firebird 3). Permite unui
asistent AI să citească balanța, fișele de cont, jurnalul, furnizorii și clienții cu facturile neachitate,
documentele de intrare/ieșire, stocurile, casa și banca, TVA. Implicit doar citire. Scrierea (parteneri,
conturi analitice, articole, gestiuni, facturi, plăți) este experimentală, dezactivată implicit, cu backup înainte de fiecare salvare. Fără nicio garanție.
---
<a href="docs/media/saga-mcp-demo.mp4"><img src="docs/media/saga-mcp-demo.gif" width="260" align="right" alt="Demo: a chat with an AI assistant using saga-mcp (click for the full video)"></a>
**Using it day to day:** the step-by-step [user guide](docs/GUIDE.md) ([în română](docs/GHID.md)) — install in
Claude Desktop with one double-click, what to ask, how writing works, common problems.
**Demo video** (73 s, [MP4](docs/media/saga-mcp-demo.mp4), Romanian with English subtitles): three user stories in a chat
with an assistant using saga-mcp — *what state is the February VAT return in*, *create a purchase invoice with VAT on
collection* (preview, confirm, save, read back) and *a EUR invoice and its payment at a different rate*. Every number
in it is a real tool result on the synthetic test database ([transcript](docs/media/demo-transcript.json)). Rebuild it
with `SAGA_TEST_FB_PASSWORD=… SAGA_DEMO_DB=/path/demo.fdb npx tsx scripts/demo/record.ts`, then
`python3 scripts/demo/render.py` (Pillow and ffmpeg).
<br clear="right">
## Contents
- [What it can do](#what-it-can-do)
- [Who uses it and how](#who-uses-it-and-how)
- [Safety model](#safety-model)
- [Data protection (GDPR)](#data-protection-gdpr)
- [Setup on Windows with SAGA](#setup-on-windows-with-saga)
- [Configuration reference](#configuration-reference)
- [Experimental write tools](#experimental-write-tools)
- [How SAGA stores things (notes)](#how-saga-stores-things-notes)
- [Development and tests](#development-and-tests)
- [Licence and warranty](#licence-and-warranty)
## What it can do
Read tools (always available; every one runs in a Firebird `READ ONLY` transaction that is rolled back):
| Tool | What it returns |
|---|---|
| `saga_list_firms` | Firm databases this server can open |
| `saga_firm_info` | Last closed period, VAT settings, ledger date range, record counts |
| `saga_list_accounts` | Chart of accounts (planul de conturi), by prefix or name |
| `saga_trial_balance` | Balanța de verificare: opening at 1 January, previous and period turnover, closing; synthetic, analytic or 3-digit level; a `balanced` flag |
| `saga_account_ledger` | Fișa contului: opening balance, entries with running balance, closing balance |
| `saga_journal` | Registru jurnal: entries of a period, filterable by account, kind and text |
| `saga_journal_sources` | Which kinds of entries exist (invoices, cash, bank, closing…) |
| `saga_partners` | Suppliers / customers search (personal codes masked) |
| `saga_open_invoices` | Unpaid invoices at a date with days overdue, foreign-currency invoices included (amount in the currency and in lei) |
| `saga_partner_balances` | Per partner: open invoices vs. the partner's ledger balance, with the difference |
| `saga_documents` / `saga_document` | Purchase (intrări) and sales (ieșiri) documents, in lei or (`currency: true`) in foreign currency; one document with lines, ledger entries and payments |
| `saga_stock` / `saga_stock_movements` | Stock per warehouse and article at a date (with an estimated value); movements of one article |
| `saga_cash_bank_balances` / `saga_cash_bank_register` | Balances of 531x/512x accounts; register of one account |
| `saga_vat_summary` | Turnover of 4423/4424/4426/4427/4428 and net/VAT by rate (not a D300) |
| `saga_saft_check` | SAF-T (D406) readiness: accounts without a SAF-T mapping, partners without a fiscal code, unposted documents |
| `saga_list_tables` / `saga_describe_table` | Database structure, no data |
| `saga_query` | One `SELECT` of your own, read-only, row-capped |
Example questions that work well:
- "Show the trial balance for March 2026 at synthetic level. Is it balanced?"
- "Which customers owe us money more than 60 days overdue?"
- "Why does supplier F012 show a different balance in 401 than in its open invoices?"
- "What is in stock in warehouse G1 at 30 June, and what did article ART01 move this year?"
- "Before I generate the D406: which accounts have no SAF-T mapping?"
## Who uses it and how
The server runs on a Windows computer that can reach SAGA's Firebird server (usually the same computer where
SAGA runs, or any computer in the office network). The person asks questions in plain language in their AI
assistant; the assistant calls the tools and answers with figures taken from the SAGA database. Nothing is
installed inside SAGA and nothing changes in the way SAGA is used.
### 1. Accounting firm with many clients in one SAGA
The usual case: one SAGA installation, one folder per client firm (`0001`, `0002`, …).
- **Setup.** List the clients you want to expose with readable codes, so you can say "ALFA" instead of "0007"
(SAGA keeps the firm name outside the firm database, so the server only knows the codes you give it):
```json
"SAGA_FIRMS": "ALFA=C:\\SAGA C.3.0\\0007\\cont_baza.fdb;BETA=C:\\SAGA C.3.0\\0012\\cont_baza.fdb"
```
`SAGA_ROOT` instead exposes every firm folder found. Use the [read-only user](scripts/readonly-user.sql).
- **Typical work.**
- Month-end review per client: "For ALFA, is the trial balance for May balanced? Which 4xx accounts have
a balance on the wrong side?"
- Receivables follow-up: "List BETA's customers with invoices overdue more than 30 days, with amounts and a
reminder text I can send."
- Reconciliation: "Why is supplier F012's balance in 401 different from its open invoices?" (the answer
usually lists unlinked payments or compensations).
- Before filing: "Run the SAF-T check for ALFA for Q2" or "Show the VAT accounts for June next to sales and
purchases by rate" before you prepare the D300 in SAGA.
- **Data protection.** Your clients' data goes to the AI provider you use: cover this in your engagement
letters and in your data-processing agreement with the provider (see [Data protection](#data-protection-gdpr)).
### 2. A company that keeps its own books in SAGA
An in-house accountant, or a manager who does not use SAGA but wants answers from it.
- **Setup.** Install on the accountant's computer, or on the manager's computer if it can reach SAGA's
Firebird server (see scenario 3). Give a manager only the read-only user, never `SYSDBA`, and never enable writes.
- **Typical questions.** "How much do customers owe us today, and who is late?", "What do we owe suppliers this
month?", "How much cash is in the cash desk and in each bank account?", "What is in stock in warehouse G1 and
which articles did not move this year?", "Show me invoice 1234 with its lines and payments."
- **Remember.** Figures are as recorded in SAGA up to the last entry; unposted documents and the month-end
closing (for example cost of goods sold) are not in the ledger yet. The assistant says so when it matters.
### 3. SAGA on a server in the office network
SAGA's Firebird server runs on one computer (the server); SAGA and this tool run on others.
- On the computer with this tool set `SAGA_FB_HOST` to the server's name or IP, and give each database path
**as the server sees it** with `SAGA_DB` or `SAGA_FIRMS` (`SAGA_ROOT` only works when that folder is
readable from this computer, e.g. a shared folder).
- The server's firewall must allow the Firebird port (usually 3050) from the office network only. Never expose
the Firebird port to the internet. Wire encryption is on by default.
- Run `node dist\index.js --check` on the client computer to confirm it can reach every firm.
### 4. A monthly checklist with the assistant
Ask these in order, firm by firm, after the month's documents are entered:
1. "Firm info for ALFA: what is the last closed month?"
2. "Trial balance for this month at synthetic level: balanced? Any class 6/7 balances left after closing?"
3. "Customers and suppliers whose open invoices do not match their ledger balance."
4. "Cash and bank balances at month end; any cash account below zero on any day?"
5. "VAT summary for the month."
6. "SAF-T check for the month: accounts without mapping, partners without a fiscal code, unposted documents."
The assistant only reads. You fix what it finds in SAGA.
### 5. Entering documents (experimental, accountants only)
With writes enabled (see [Experimental write tools](#experimental-write-tools)) an accountant can ask the
assistant to enter, for example, the purchase invoices from a list or from documents shown to the assistant:
it prepares each invoice as a dry run, shows the ledger entries SAGA would make, and saves only after you confirm,
with SAGA closed and after a backup. Recommended:
- create missing suppliers, customers, articles or bank accounts first with the `saga_create_*` tools (the
assistant checks for duplicates by name and fiscal code);
- try it first on a **copy** of the firm (restore a SAGA backup into a separate folder and point `SAGA_DB` at it);
- enable writes in a separate MCP server entry (e.g. `saga-write`) that you turn on only when needed;
- check every saved document in SAGA.
### Which AI clients
Any MCP client that can start a local stdio server works: Claude Desktop (setup below), Claude Code and other
MCP-capable assistants and IDEs. The setup is the same: command `node`, argument the path to `dist/index.js`,
and the environment variables below.
## Safety model
- **Read-only by default.** Without the write switch the server does not even register write tools.
Every read runs in a `READ ONLY` Firebird transaction; Firebird itself rejects any change made in one.
- **`saga_query` is checked twice:** only a single `SELECT`/`WITH` statement is accepted (no `EXECUTE`,
`INSERT`, `UPDATE`, generators, `EXECUTE BLOCK`…), and it still runs in a read-only transaction.
- **Row caps.** Results are capped (500 rows by default, `SAGA_MAX_ROWS`, at most 5000) and paged.
- **SAGA can stay open while you read.** Firebird gives each reader a consistent snapshot without locking
SAGA's users. (Writes are different, see below.)
- **Optional read-only database user.** For extra safety you can connect with a Firebird user that has
only `SELECT` rights and no access to payroll tables: see [`scripts/readonly-user.sql`](scripts/readonly-user.sql).
With that user even a bug in this program cannot change data.
- **Secrets.** The password is read from the environment only. It is never written to logs or tool output;
error messages mask it.
## Data protection (GDPR)
**Whatever a tool returns is sent to the AI model your MCP client uses** (for Claude Desktop: Anthropic's
API, under your account's terms). Accounting data contains personal data: names of individual customers and
suppliers (PFA, natural persons), sometimes personal numeric codes (CNP), and in SAGA's payroll module salaries
and employee data. Before connecting a firm's database:
- make sure you are allowed to process that firm's data this way (you are typically the controller or a
processor for your clients; check your contracts and the AI provider's data-processing terms);
- prefer an AI provider and plan whose terms fit professional use (no training on your data, a DPA);
- tell your clients if your engagement terms require it.
What this server does to limit exposure:
- **CNP masking.** Values that pass the CNP checksum are masked (`1**********06`) in every tool result,
including `saga_query`. Turn this off only if you really need it: `SAGA_SHOW_PERSONAL_IDS=1`.
- **Payroll is blocked.** Payroll tables (`SALARIATI`, `CALCULE`, `CONCEDII`, `REVISAL_IST`, …) cannot be
read through `saga_query` unless you set `SAGA_ALLOW_PAYROLL=1`. No dedicated tool reads them.
- **Local only.** The server talks to your Firebird server and to the MCP client on the same computer
(stdio). It makes no other network connections and sends no telemetry.
## Setup on Windows with SAGA
**Easiest: the Claude Desktop extension.** Download `saga-mcp-<version>.mcpb` from [Releases](https://github.com/klove-app/saga-mcp/releases/latest) and double-click it, fill in the SAGA folder and the
Firebird password, done; Claude Desktop brings its own Node.js. See the [user guide](docs/GUIDE.md). Build the file
yourself with `npm install && npm run build:mcpb` (→ `build/saga-mcp-<version>.mcpb`).
The manual setup below is for other MCP clients, or if you prefer to run it yourself.
You need: SAGA C. 3.0 (with its Firebird 3 server, Windows service `Firebird30_Saga` or similar),
[Node.js](https://nodejs.org) 20 or newer (the LTS installer is fine), and an MCP client such as
[Claude Desktop](https://claude.ai/download).
### 1. Install
Open **Command Prompt** (or PowerShell) and run:
```bat
cd %USERPROFILE%
git clone https://github.com/klove-app/saga-mcp.git
cd saga-mcp
npm install
npm run build
```
(Without git: download the repository as a ZIP, unpack it to `C:\Users\<you>\saga-mcp`, then run the last
three commands in that folder.)
**Or from npm, without git or a build:** the package is [`saga-c-mcp`](https://www.npmjs.com/package/saga-c-mcp).
Wherever this guide says `node dist\index.js`, use `npx -y saga-c-mcp` instead (e.g. `npx -y saga-c-mcp --check`),
and in the Claude Desktop config below put `"command": "npx", "args": ["-y", "saga-c-mcp"]`.
### 2. Find your firm's database and the Firebird password
- **Database:** every firm is a folder in the SAGA folder, e.g. `C:\SAGA C.3.0\0001\`, containing
`cont_baza.fdb`. The folder number is the firm number shown in SAGA.
- **Password:** the password of the Firebird user `SYSDBA` set when SAGA's Firebird was installed. Firebird's
factory default is `masterkey`; if it was changed, ask whoever installed SAGA. Never post it anywhere.
- **Port:** usually `3050`. If the computer has more than one Firebird, check `RemoteServicePort` in
`firebird.conf` of the Firebird folder that SAGA uses.
- **Network installs:** if SAGA's database lives on another computer, set `SAGA_FB_HOST` to that computer and
give the path **as that computer sees it** (e.g. `D:\SAGA C.3.0\0001\cont_baza.fdb`), not a mapped drive.
### 3. Check the connection
In the same Command Prompt:
```bat
set SAGA_FB_PASSWORD=your-password
set SAGA_ROOT=C:\SAGA C.3.0
node dist\index.js --check
```
You should see one `OK` line per firm, e.g. `OK 0001 C:\SAGA C.3.0\0001\cont_baza.fdb (Firebird 3.0.x, 12345 ledger rows)`.
A `FAIL` line says what is wrong (service not running, wrong password, wrong path…).
### 4. Add it to Claude Desktop
Open Claude Desktop → Settings → Developer → *Edit Config*, which opens
`%APPDATA%\Claude\claude_desktop_config.json`, and add (note the doubled backslashes in JSON):
```json
{
"mcpServers": {
"saga": {
"command": "node",
"args": ["C:\\Users\\you\\saga-mcp\\dist\\index.js"],
"env": {
"SAGA_FB_PASSWORD": "your-password",
"SAGA_ROOT": "C:\\SAGA C.3.0"
}
}
}
}
```
Restart Claude Desktop. The SAGA tools appear in the tools menu; ask "Which SAGA firms can you see?".
To expose only one firm, use `"SAGA_DB": "C:\\SAGA C.3.0\\0001\\cont_baza.fdb"` instead of `SAGA_ROOT`.
To expose a chosen list: `"SAGA_FIRMS": "0001=C:\\SAGA C.3.0\\0001\\cont_baza.fdb;0007=C:\\SAGA C.3.0\\0007\\cont_baza.fdb"`.
The configuration file holds the password in plain text: keep it on a computer only you use, or use the
read-only user from [`scripts/readonly-user.sql`](scripts/readonly-user.sql) with its own password.
## Configuration reference
| Variable | Default | Meaning |
|---|---|---|
| `SAGA_FB_PASSWORD` (or `ISC_PASSWORD`) | — | Firebird password (required) |
| `SAGA_FB_USER` | `SYSDBA` | Firebird user |
| `SAGA_FB_HOST` / `SAGA_FB_PORT` | `127.0.0.1` / `3050` | Firebird server |
| `SAGA_DB` | — | One firm database (path as the server sees it) |
| `SAGA_FIRMS` | — | Several firms: `CODE=PATH;CODE=PATH` |
| `SAGA_ROOT` | — | SAGA folder to scan for `*/cont_baza.fdb` (must be readable from this computer) |
| `SAGA_DEFAULT_FIRM` | first firm | Firm used when a tool call names none |
| `SAGA_MAX_ROWS` | `500` | Row cap per call (max 5000) |
| `SAGA_SHOW_PERSONAL_IDS` | off | `1` = do not mask CNP |
| `SAGA_ALLOW_PAYROLL` | off | `1` = allow payroll tables in `saga_query` |
| `SAGA_FB_WIRECRYPT` | on | `0` = disable Firebird wire encryption |
| `SAGA_FB_CONNECT_TIMEOUT_MS` | `10000` | Connection timeout |
| `SAGA_MCP_ENABLE_WRITES` or `--enable-writes` | off | Enable the experimental write tools |
| `SAGA_BACKUP_DIR` | firm folder | Where backups before writes go (a folder on the database server) |
`node dist/index.js --help` prints the same list.
## Experimental write tools
> **EXPERIMENTAL — read this whole section before enabling.** Writing into another program's database is
> risky. SAGA Software does not document or support third-party writes; a future SAGA update may change the
> database in ways this tool does not know about. You are responsible for every document saved and for
> checking it in SAGA. Keep your normal backups.
Enabled only with `SAGA_MCP_ENABLE_WRITES=1` (or the `--enable-writes` argument). Then these tools appear:
| Tool | What it does |
|---|---|
| `saga_create_partner` | Creates a supplier or customer with **SAGA's own** `INSERTFC` procedure: SAGA picks the next code and creates the analytic account (`401.00123`, `4111.00123`). Refused if the same name or fiscal code exists |
| `saga_create_account` | Creates an analytic account under an existing synthetic one (e.g. `5121.2` for a new bank account) with **SAGA's own** `INSSIN` procedure |
| `saga_create_article` | Adds an article (product or service) with name, unit, VAT rate and type; the code comes from SAGA's `MAXCOD` |
| `saga_create_warehouse` | Adds a warehouse (gestiune); code from SAGA's `MAXCOD`, valuation method from the firm settings |
| `saga_create_purchase_invoice` | Inserts a supplier invoice (header + lines) and posts it with **SAGA's own** procedure (`INTRARI_VALID`, or `INTRARI_V_VALID` for an invoice in a foreign currency); supports reverse charge and suppliers with VAT on collection (TVA la încasare) |
| `saga_create_sales_invoice` | Inserts a customer invoice and posts it with **SAGA's own** procedure (`IESIRI_VALID`, or `IESIRI_V_VALID` in a foreign currency); supports reverse charge (taxare inversă, lines with 0% VAT) |
| `saga_record_payment` | Records a supplier payment or customer receipt (cash 531x or bank 512x, including the currency accounts 5124 / 5314) against posted invoices of one partner; for purchases with VAT on collection it also moves the paid share of the VAT from 4428 to 4426, as SAGA does; for invoices in a foreign currency the amount is in that currency |
| `saga_backup` | Takes a full Firebird backup (`.fbk`) of the firm database |
**Foreign currency.** Give `currency` (e.g. `EUR`) and `exchange_rate` (lei for one unit, e.g. the BNR rate
`4.9871`) and enter prices in the currency. SAGA keeps these invoices in their own tables (purchases in `INTRD`,
sales in `EXPORT`); the tool fills them the way the SAGA program does (lei value per line =
quantity × `ROUND(price × rate, 4)` for purchases, `ROUND(value × rate, 2)` for sales; purchase VAT =
`ROUND(value in currency × VAT% × rate, 2)`) and posts them with SAGA's own procedure. The rate is **passed in**
(SAGA keeps no daily rate table, only yearly rates in `CURSURI_T`); take the BNR rate of the document date.
A payment of such an invoice is entered in the currency and pays the invoice off **at the invoice's own rate**,
so the supplier or customer closes at zero in the currency and in lei. Give `payment_rate` (the rate of the payment
day) and the difference is booked the way the SAGA program books it: a separate entry on the same document number,
treasury account against `6651` (loss) or `7651` (gain), the accounts set in SAGA's `C_CONF`. Example: 81.50 EUR
invoiced at 5.10 and received at 5.20 → `5124 = 4111` 415.65 and `5124 = 7651` 8.15. All invoices in one payment
must share the currency and the rate. **Not in scope:** revaluing open balances at month end (unpaid invoices,
currency bank accounts, loans); SAGA's month-end closing does that.
How a save works:
1. **Dry run by default.** Every write tool runs the whole operation, including SAGA's posting procedure,
in a transaction that is rolled back, and returns what would be saved: the document, the ledger
entries SAGA would create and any message from SAGA. Nothing is stored. The assistant is instructed to show
you this preview and to save only after you confirm.
2. **SAGA's own checks decide.** Closed periods, negative stock and other rules are checked by SAGA's procedures.
If SAGA refuses (e.g. *"Data documentului este precedenta ultimei inchideri contabile."*), nothing is saved.
If SAGA accepts with a **warning** (e.g. stock becomes negative), the result is `needs_confirmation` and a
save requires `accept_saga_warnings: true`.
3. **Not while SAGA is open.** If any other program is connected to the firm database, a save is refused
(`refused`) unless `allow_while_saga_open: true` is given. Close SAGA on all computers first.
4. **Backup first.** Before the real save a full backup is written next to the database
(`cont_baza-saga-mcp-YYYYMMDD-HHMMSS.fbk`, or into `SAGA_BACKUP_DIR`). If the backup fails, nothing is saved.
The result names the backup file. Restore with `gbak -c` (or SAGA's own restore) if needed.
5. **One transaction.** The document, its lines and its posting are committed together or not at all.
6. **SAGA's own logic wherever SAGA has it.** Partners, analytic accounts and posting go through SAGA's stored
procedures. Articles and warehouses (no procedure in SAGA) get one row with the fields the SAGA program
fills; the rest stays at SAGA's defaults, so check and complete them in SAGA.
What these tools will not do:
- create synthetic accounts (they come from the official chart of accounts that SAGA ships);
- write raw ledger rows for anything other than the payment recipe above (which reproduces exactly the rows
SAGA itself creates for a cash/bank payment: one entry, the invoice links, the reduced unpaid amount, and
for VAT on collection one `4426 = 4428` entry per invoice);
- foreign-currency imports with **customs, commission, excise or transport** added to the cost (enter those in
SAGA), month-end revaluation of currency balances (SAGA's closing does it) and VAT on collection on a currency
invoice;
- **firms that themselves apply VAT on collection** (TVA la încasare at the firm level; refused), and customer
invoices with VAT on collection;
- numbering series, e-Factura upload;
- post cost of goods sold for sales: like SAGA, `607 = 371` is posted at month-end closing in SAGA.
Known side effect: SAGA uses one shared id generator (`GEN_DB`). A dry run advances it, so ids may have gaps.
This is harmless (SAGA itself leaves gaps) but you will notice it.
## How SAGA stores things (notes)
Useful if you write your own `saga_query` queries. Learned from SAGA C. 3.0 databases (Firebird 3, `WIN1252`):
- **Ledger:** table `REGISTRU` (`DATA`, `CONT_D`, `CONT_C`, `SUMA`, `EXPLICATIE`, `NDP`, `FEL_D` = kind).
**Compound entries** ("% = 401" or "401 = %") are stored as one header row whose other side is the
placeholder account `%`, plus detail rows with one side blank. To total debit or credit turnover, count a
side only if it is neither blank nor `%`; that way every entry and every period balances.
- **Chart of accounts:** `CONTURI`, with opening balances (`DEB_INIT`/`CRED_INIT`) and balances brought
forward from earlier years (`DEB_PREC`/`CRED_PREC`). Analytic accounts are written with a dot: `401.00012`.
- **Partners:** `FURNIZORI` / `CLIENTI`; the partner's analytic account is in `ANALITIC`.
- **Documents:** `INTRARI`/`INTR_DET` (purchases), `IESIRI`/`IES_DET` (sales); `NEACHITAT` is the unpaid
amount; `VALIDAT` = posted. Payments link to invoices through `NOTE_FACTURI`. `NR_NIR` (goods-received note) is
a running number from SAGA's `MAXCOD`; `TIP_O` is `001` on purchase invoices and `007` on sales invoices.
- **Foreign currency:** `INTRD`/`INTRD_DET` (purchases; unpaid in the currency in `NEACHITAT_VAL`) and
`EXPORT`/`EXPORT_DET` (sales; `NEACHITAT` is in the currency). Payment links are in `NOTE_FACTURI_VAL`
(amounts in the currency); SAGA's function `REACTNEACHITATVAL` recomputes the unpaid amount. Ledger rows carry
`COD_VALUTA`, `CURS` and `SUMA_VAL`. `CONTURI.COD_VALUTA` stays empty even for 5124, so currency treasury
accounts are recognised by number (5124, 5314). A payment is booked at the invoice rate; the exchange difference
is a separate one-row note (`Dif. curs …`, same `NDP`) between the treasury account and `C_CONF.CHELTDC` / `VENDC`.
- **Stock:** `MISCARI` (+ entries, − exits). Exits carry no price (`PRET = 0`); cost is set at month-end, so
this server values stock at the weighted average entry price and labels it an *estimate*.
- **Closing:** `SOCIET.DATA_INCH` is the last closed date.
- **Default accounts:** `C_CONF` (suppliers `FUR`, customers `CLI`, VAT accounts `TVADE` = 4426, `TVACO` = 4427,
`TVANEP` = 4428 for purchases with VAT on collection, …).
- **VAT on collection:** an invoice with `TVAI = 1` posts its VAT to 4428; every payment adds a `4426 = 4428`
entry for the paid share of the VAT (`NOTE_FACTURI.TVAINC`).
- Text columns are padded with trailing spaces; `=` ignores them, `LIKE` does not (use `TRIM`).
## Development and tests
```sh
npm install
npm run build # TypeScript → dist/
npm run test:unit # no database needed
```
Integration tests run against a **synthetic** SAGA-shaped database (a fictional firm, invented partners,
fake personal codes) that the tests build afresh from [`fixtures/synthetic-schema.sql`](fixtures/synthetic-schema.sql).
The schema is a hand-written subset of the tables and columns this server uses; its procedures
(`INTRARI_VALID`, `IESIRI_VALID`, `INTRARI_V_VALID`, `IESIRI_V_VALID`, `REACTNEACHITATVAL`, `INSERTFC`, `INSSIN`,
`MAXCOD`) are simplified stand-ins written for the tests,
not SAGA's procedures. You need a Firebird 3
server you can create databases on:
```sh
export SAGA_TEST_FB_PASSWORD=... # SYSDBA password of the test server
export SAGA_TEST_DB=/path/on/server/synthetic.fdb # will be DROPPED and recreated
npm test # unit + integration (integration is skipped without these variables)
npm run fixture:create # optional: build the synthetic firm to explore it with --check or an MCP client
```
Optional: `SAGA_TEST_FB_HOST`, `SAGA_TEST_FB_PORT`, `SAGA_TEST_FB_USER`. Never point `SAGA_TEST_DB` at a real
firm database.
Contributions: issues and pull requests are welcome. Please never attach real SAGA databases, backups or
screenshots with real data to an issue; reproduce problems on the synthetic database.
## Licence and warranty
Licensed under the [Apache License 2.0](LICENSE). See [NOTICE](NOTICE).
This software is provided **"AS IS", without warranties or conditions of any kind**. It is not accounting,
tax or legal advice. The authors are not liable for any loss of data, wrong postings, penalties or other
damage arising from its use, in particular from the experimental write tools. Always check the results in
SAGA and keep backups.
TDQS
Scored across 21 tools
Each tool targets a fairly distinct accounting artifact (trial balance, account ledger, journal, documents, stock, cash/bank, VAT, SAF-T checks), and descriptions explicitly clarify boundary cases like match=account vs match=prefix and balances vs register. Some genuine overlap remains between saga_journal and saga_account_ledger, and between saga_open_invoices and saga_partner_balances, which could cause occasional misselection.
All names are snake_case with a consistent 'saga_' prefix, and most are resource-oriented nouns (saga_partner_balances, saga_cash_bank_register). There are minor deviations in verb usage: some resources use explicit verbs (saga_list_firms, saga_list_accounts, saga_describe_table, saga_query) while comparable ones do not (saga_partners, saga_documents).
21 tools is on the heavy side, but the domain is a full accounting ERP and nearly every tool maps to a distinct report or artifact (trial balance, ledger, journal, invoices, stock, cash/bank, VAT, SAF-T, raw SQL access). It is slightly over-scoped rather than padded with redundant tools.
As a read-only reporting/inspection server it covers the main workflows well: firm discovery, chart of accounts, trial balance, ledgers, documents, partners, stock, cash/bank, VAT and SAF-T pre-checks, plus a generic SELECT escape hatch. Gaps are minor: no master lists for articles/warehouses (only date-based stock views), no payroll coverage beyond flagging, and no write operations by design.