Skip to main content
Glama
ledger-mcp

ledger-mcp

README.md
# ledger-mcp

[![CI](https://github.com/saikiran-manne/ledger-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/saikiran-manne/ledger-mcp/actions/workflows/ci.yml)
![Python 3.12](https://img.shields.io/badge/python-3.12-blue)
![License: MIT](https://img.shields.io/badge/license-MIT-green)

An [MCP](https://modelcontextprotocol.io) server that lets an AI assistant such as Claude
track **personal expenses and client invoices**. It exposes five typed tools with
schema-validated inputs and outputs, stores data in SQLite through SQLAlchemy (Postgres is
a config change), and turns every bad input into a short, readable error. The model never
sees a stack trace.

```
 Claude / any MCP client
          │  stdio (default)  or  streamable HTTP + bearer token
          ▼
 ┌──────────────────────────────────────────────────────────┐
 │ server.py    FastMCP tools (thin wrappers, typed schemas) │
 │ errors.py    middleware: ValidationError / LedgerError →  │
 │              clean message, everything else → masked      │
 │ auth.py      bearer-token ASGI middleware (HTTP only)     │
 ├──────────────────────────────────────────────────────────┤
 │ services.py  business rules, framework-free               │
 │ schemas.py   Pydantic v2 inputs/outputs                   │
 ├──────────────────────────────────────────────────────────┤
 │ models.py    SQLAlchemy 2.0 ORM (money as integer cents)  │
 │ db.py        engine + transactional sessions              │
 └──────────────────────────────────────────────────────────┘
          ▼
   SQLite (default)  /  Postgres
```

## Design notes

- **Money is exact.** Amounts are `Decimal` end to end and stored as integer hundredths, so
  `0.10 + 0.20 == 0.30` holds on SQLite, which has no exact decimal column type.
  In JSON, amounts are strings such as `"12.50"` so no precision is lost.
- **No currency conversion.** `monthly_summary` groups totals by currency rather than
  guessing exchange rates.
- **Invoice status is derived.** An invoice is `open` through its due date and `overdue`
  after it. Nothing is stored that could drift out of date.
- **Errors are for the model.** One middleware maps validation and business-rule failures to
  messages like `Invalid input: amount: Input should be greater than 0`. Unexpected errors
  are logged server-side and returned as a generic message.
- **Testable clock.** Business rules that depend on "today" (no future expenses, overdue
  invoices) take an injectable clock, so tests are deterministic.

## Setup

Requires Python 3.12. [uv](https://docs.astral.sh/uv/) is recommended.

```bash
git clone https://github.com/saikiran-manne/ledger-mcp.git
cd ledger-mcp
uv sync                 # creates .venv with runtime + dev dependencies
uv run ledger-mcp       # starts the server on stdio
```

<details>
<summary>With pip instead</summary>

```bash
python3.12 -m venv .venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -e .
pip install pytest pytest-asyncio pytest-cov ruff mypy httpx
ledger-mcp
```
</details>

### Configuration

All settings are environment variables (a `.env` file also works; see `.env.example`).

| Variable | Default | Description |
|---|---|---|
| `LEDGER_DATABASE_URL` | `sqlite:///ledger.db` | Any SQLAlchemy URL, e.g. `postgresql+psycopg://user:pw@host/ledger` (install the driver). |
| `LEDGER_TRANSPORT` | `stdio` | `stdio` or `http`. |
| `LEDGER_HOST` / `LEDGER_PORT` | `127.0.0.1` / `8000` | Bind address for HTTP. |
| `LEDGER_AUTH_TOKEN` | *(unset)* | **Required** for HTTP. The server refuses to start without it. |
| `LEDGER_DEFAULT_CURRENCY` | `EUR` | Used by `create_invoice` when no currency is given. |

Tables are created automatically on first start.

## Tool reference

Dates are `YYYY-MM-DD`. Currencies are ISO-4217 codes (case-insensitive, normalised to
upper case). Money accepts numbers or strings with at most 2 decimal places.

| Tool | Inputs | Returns |
|---|---|---|
| `add_expense` | `amount` (> 0), `currency`, `category`, `date` (not in the future), `note?` (≤ 500 chars) | the saved expense |
| `list_expenses` | `start_date?`, `end_date?`, `category?`, `min_amount?`, `max_amount?` (all inclusive), `limit?` (1–500, default 100) | `{items, count}`, newest first |
| `monthly_summary` | `month` (`YYYY-MM`) | totals per category, per currency |
| `create_invoice` | `client`, `line_items` (1–50 × `{description, quantity > 0, unit_price ≥ 0}`), `due_date` (today or later), `currency?` | the invoice with line totals, total, number and status |
| `list_invoices` | `status?`: `open` \| `overdue` \| `all` (default) | `{items, count}`, by due date |

Categories: `food`, `transport`, `housing`, `utilities`, `software`, `travel`, `office`, `other`.

### Examples

These are real outputs, with "today" set to 2026-03-15.

**`add_expense`** `{"amount": "12.50", "currency": "eur", "category": "food", "date": "2026-03-14", "note": "Lunch"}`

```json
{
  "id": 1, "amount": "12.50", "currency": "EUR", "category": "food",
  "date": "2026-03-14", "note": "Lunch", "created_at": "2026-03-15T09:12:04.120931Z"
}
```

**`monthly_summary`** `{"month": "2026-03"}`, after also adding a USD 49.00 software expense:

```json
{
  "month": "2026-03",
  "expense_count": 2,
  "currencies": {
    "EUR": { "total": "12.50", "by_category": { "food": "12.50" } },
    "USD": { "total": "49.00", "by_category": { "software": "49.00" } }
  }
}
```

**`create_invoice`**
`{"client": "Acme Studio", "line_items": [{"description": "Logo design", "quantity": 10, "unit_price": "80.00"}, {"description": "Hosting (March)", "quantity": 1, "unit_price": "15.50"}], "due_date": "2026-04-14"}`

```json
{
  "id": 1, "number": "INV-0001", "client": "Acme Studio", "currency": "EUR",
  "line_items": [
    { "description": "Logo design",     "quantity": "10.00", "unit_price": "80.00", "line_total": "800.00" },
    { "description": "Hosting (March)", "quantity": "1.00",  "unit_price": "15.50", "line_total": "15.50" }
  ],
  "total": "815.50", "issue_date": "2026-03-15", "due_date": "2026-04-14", "status": "open"
}
```

**A bad call:** `add_expense` with `{"amount": "-3", "category": "snacks", ...}` returns an error result:

```
Invalid input: amount: Input should be greater than 0; category: Input should be 'food',
'transport', 'housing', 'utilities', 'software', 'travel', 'office' or 'other'
```

## Demo with Claude Desktop

Add this to `claude_desktop_config.json` (Settings → Developer → Edit Config), using absolute
paths:

```json
{
  "mcpServers": {
    "ledger": {
      "command": "uv",
      "args": ["--directory", "/absolute/path/to/ledger-mcp", "run", "ledger-mcp"],
      "env": { "LEDGER_DATABASE_URL": "sqlite:////absolute/path/to/ledger.db" }
    }
  }
}
```

Or run it from the Docker image:

```json
{
  "mcpServers": {
    "ledger": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "-v", "ledger-data:/data", "ledger-mcp"]
    }
  }
}
```

Restart Claude Desktop, then try:

- *"Log €12.50 for lunch today, and $49 for a software subscription on March 2nd."*
- *"What did I spend in March, by category?"*
- *"Show my food expenses over €10 since February."*
- *"Invoice Acme Studio for 10 hours of logo design at €80/hour plus €15.50 hosting, due in 30 days."*
- *"Which invoices are overdue?"*

## HTTP transport

```bash
export LEDGER_TRANSPORT=http
export LEDGER_AUTH_TOKEN="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"
uv run ledger-mcp        # serves streamable HTTP at http://127.0.0.1:8000/mcp
```

Every request must send `Authorization: Bearer $LEDGER_AUTH_TOKEN`. Anything else gets
`401` with a `WWW-Authenticate: Bearer` header. Tokens are compared in constant time. For
anything beyond localhost, put it behind TLS (a reverse proxy).

## Docker

```bash
docker build -t ledger-mcp .

# stdio (for MCP clients that launch the container)
docker run -i --rm -v ledger-data:/data ledger-mcp

# HTTP
docker run --rm -p 8000:8000 -v ledger-data:/data \
  -e LEDGER_TRANSPORT=http -e LEDGER_AUTH_TOKEN=change-me ledger-mcp
```

The image is multi-stage, runs as a non-root user, and keeps the SQLite database on the
`/data` volume.

## Development

```bash
uv run pytest --cov            # tests + coverage report (fails under 90%)
uv run ruff check . && uv run ruff format --check .
uv run mypy src                # strict
```

The tests cover every tool through the real MCP client (in memory), the business rules
directly, a parametrised suite of invalid inputs for every tool (asserting no tracebacks or
internals leak), and HTTP auth. CI runs lint, type checks and tests on every push, and also
builds the Docker image and smoke-tests it over stdio and over HTTP with bearer auth.

```
src/ledger_mcp/   __main__.py  auth.py  config.py  db.py  errors.py
                  models.py  schemas.py  server.py  services.py
tests/            test_auth.py  test_db.py  test_expenses.py  test_invoices.py
                  test_summary.py  test_validation.py
```

## License

MIT