Skip to main content
Glama
Bluecoins MCP Server

Bluecoins MCP Server

README.md
# Bluecoins MCP Server

> [!NOTE]
> **Disclaimer:** This is an independent, unofficial project. It is not affiliated with, endorsed by, sponsored by, or otherwise associated with Bluecoins or its developers. All product names and trademarks are the property of their respective owners.
>
> This software is provided **"as is"**, without warranty, guarantee, or support of any kind. Use it at your own risk — the authors assume no responsibility or liability for any loss of data, database corruption, inaccuracies, or other damages resulting from its use. Always maintain backups of your Bluecoins database.

Strictly read-only [FastMCP](https://gofastmcp.com/) server for querying and analyzing personal finance data from a synced **Bluecoins** SQLite database (`bluecoins.fydb`), designed to run in Docker on a local NAS behind an internet-facing reverse proxy.

## Features

- **Strictly read-only**: Never modifies or locks your Bluecoins database. Snapshots are opened with SQLite `mode=ro&immutable=1` and `PRAGMA query_only = ON`, and the Docker volume is mounted `:ro`.
- **Live NAS sync without restarts**: Monitors `(st_mtime_ns, st_size, st_ino)` on the read-only mounted NAS folder. When `rclone` or Synology Cloud Sync updates `bluecoins.fydb`, the server copies it to container `/tmp`, verifies integrity via `PRAGMA quick_check`, and atomically swaps snapshots. If a file is caught mid-write, it safely keeps serving the last valid snapshot and marks `/health` as `degraded`.
- **Accurate Bluecoins accounting**: Automatically handles micros scaling (`1_000_000`), active posted transaction filtering (`deletedTransaction = 6 AND reminderTransaction IS NULL`), FX-accurate foreign-currency account balances, split resolution, transfer exclusion in analytics, and placeholder account exclusion.
- **Fail-closed authentication**: Constant-time Bearer token auth by default (supporting comma-separated tokens for zero-downtime key rotation), or optional OAuth 2.1 (`google`, `github`, `oidc`) with a mandatory single-owner allowlist.
- **Hardened container**: Multi-stage `uv` → `python:3.13-slim` build, non-root `appuser` (`uid 1000`), `read_only: true` root filesystem, `cap_drop: ALL`, `no-new-privileges`, and `/tmp` on `tmpfs`.

## How It Works

```text
Bluecoins (Android) ──► Google Drive ──► NAS sync folder (mounted /data:ro)
                                                │
                                 stat check + copy + PRAGMA quick_check
                                                ▼
                                  Verified snapshot in /tmp (ro, immutable)
                                                │
                                  Semantic TEMP VIEWs + Repositories + SQL Guard
                                                ▼
                               FastMCP Streamable HTTP (/mcp) + /health
```

## Quick Start (Docker on NAS)

1. Copy `.env.example` to `.env`:
   ```bash
   cp .env.example .env
   chmod 600 .env
   ```
2. Edit `.env` and set:
   - `HOST_BLUECOINS_DATA_DIR=/path/on/nas/to/bluecoins-folder` — point to the **parent directory** containing `bluecoins.fydb`, not the file itself, so atomic renames from `rclone` or Synology Cloud Sync are detected cleanly.
   - `MCP_AUTH_TOKENS` — generate a strong token (≥ 32 characters):
     ```bash
     python3 -c "import secrets; print(secrets.token_urlsafe(48))"
     ```
3. Set `PUID` and `PGID` in `.env` to match a NAS user with read access to `bluecoins.fydb` (run `id` on your NAS to check; defaults to `1000:1000`). `docker-compose.yml` passes these directly via `user: "${PUID:-1000}:${PGID:-1000}"` while keeping `read_only: true`, `cap_drop: ALL`, and `no-new-privileges`.
4. Build and start:
   ```bash
   docker compose up -d --build
   ```
5. Verify health (unauthenticated, returns zero financial data):
   ```bash
   curl http://127.0.0.1:8000/health
   ```

## Reverse Proxy Notes

`docker-compose.yml` binds `127.0.0.1:8000:8000` so TLS termination stays at your reverse proxy or tunnel:

- **Caddy / Cloudflare Tunnel**: Streamable HTTP works out of the box; proxy `/mcp` (and optionally `/health`) to `http://127.0.0.1:8000`.
- **Nginx**: Disable response buffering so Streamable HTTP SSE streams flush immediately:
  ```nginx
  location /mcp {
      proxy_pass http://127.0.0.1:8000;
      proxy_http_version 1.1;
      proxy_buffering off;
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  ```

## Connecting MCP Clients

### Claude Code CLI (`claude`)

Streamable HTTP (remote NAS or local HTTP server):
```bash
claude mcp add --transport http bluecoins https://bluecoins-mcp.example.com/mcp \
  --header "Authorization: Bearer <YOUR_TOKEN>"
```

Local stdio (no HTTP server required):
```bash
claude mcp add bluecoins \
  -e MCP_TRANSPORT=stdio \
  -e AUTH_MODE=none \
  -e ALLOW_UNAUTHENTICATED=true \
  -e BLUECOINS_DATA_DIR="/path/to/bluecoins-folder" \
  -e DB_STAGING_DIR="/tmp/bluecoins-mcp" \
  -- uv run --directory "/path/to/bluecoins-mcp" bluecoins-mcp
```

### Antigravity (`agy` CLI / App)

Add to `~/.gemini/config/mcp_config.json`:

```json
{
  "mcpServers": {
    "bluecoins": {
      "url": "https://bluecoins-mcp.example.com/mcp",
      "headers": {
        "Authorization": "Bearer <YOUR_TOKEN>"
      }
    }
  }
}
```

### Generic Streamable HTTP Clients & MCP Inspector

- **Endpoint**: `https://bluecoins-mcp.example.com/mcp` (or `http://127.0.0.1:8000/mcp` locally)
- **Header**: `Authorization: Bearer <YOUR_TOKEN>`
- Test interactively with `npx @modelcontextprotocol/inspector`.

## Tools & Resources Reference

All 13 tools carry read-only MCP annotations (`read_only_hint=True`, `destructive_hint=False`, `idempotent_hint=True`, `open_world_hint=False`).

### Tools

| Category | Tool | Description |
| --- | --- | --- |
| **Context** | `get_database_overview` | Default currency, schema version, date range, active/hidden counts, and NAS sync status |
| **Context** | `list_categories` | Parent and child category hierarchy (filterable by `expense`, `income`, `transfer`) |
| **Context** | `list_labels` | Distinct labels with active posted transaction counts |
| **Transactions** | `search_transactions` | Filter by dates, type, account, category, payee/item, label, free-text query, amount range, currency; returns paginated rows plus exact `sum_base` across all matches |
| **Transactions** | `get_transaction_details` | Full details for one transaction, including sibling split legs or paired transfer leg |
| **Analytics** | `get_cash_flow` | Total income, expenses, net cash flow, and savings rate for an inclusive date range (excludes transfers) |
| **Analytics** | `get_spending_breakdown` | Ranked breakdown by `parent_category`, `child_category`, `item`, `account`, or `label` (with multi-label support) |
| **Analytics** | `get_monthly_trends` | Chronological `YYYY-MM` income, expense, and net cash flow series with summary averages and min/max months |
| **Analytics** | `compare_periods` | Side-by-side comparison of two date ranges with overall and per-group deltas |
| **Accounts** | `get_accounts` | Account list with FX-accurate native and base-currency balances and optional credit card fields |
| **Accounts** | `get_net_worth` | Total assets, total liabilities (positive debt magnitude), net worth, and breakdowns by account type & currency (supports historical `as_of_date`) |
| **Accounts** | `get_credit_card_summary` | Per-card balance owed, credit limit, available credit, utilization %, cutoff/due days, and current-cycle spend |
| **Ad-Hoc SQL** | `run_sql_query` | Single read-only `SELECT`/`WITH` query over semantic views (`v_transactions`, `v_accounts`, `v_categories`, `v_transfers`) or raw tables, enforced via SQLite `set_authorizer`, row cap, and timeout |

### Resources

| URI | MIME Type | Description |
| --- | --- | --- |
| `bluecoins://info` | `application/json` | Database overview and sync metadata |
| `bluecoins://schema` | `text/markdown` | Semantic SQL view schemas, sign conventions, and example queries |

### Example Prompts
- *"Give me an overview of my Bluecoins database and my current net worth."*
- *"Compare my spending by category this month vs last month."*
- *"What is my current credit card utilization and spending since my last cutoff date?"*
- *"Run a read-only SQL query to find my top 10 payees this year."*

## Configuration Reference

| Variable | Default | Description |
| --- | --- | --- |
| `HOST_BLUECOINS_DATA_DIR` | *(required in Compose)* | Host NAS directory containing `bluecoins.fydb` |
| `PUID` / `PGID` | `1000` / `1000` | UID and GID used by Docker Compose (`user:`) to read the NAS bind mount without root |
| `BLUECOINS_DATA_DIR` | `/data` | Directory path inside the app/container |
| `BLUECOINS_DB_FILENAME` | `bluecoins.fydb` | SQLite database filename |
| `DB_SYNC_CHECK_INTERVAL_SECONDS` | `5.0` | Minimum interval between NAS file stat checks |
| `DB_STAGING_DIR` | `/tmp/bluecoins-mcp` | Local directory for verified read-only snapshots |
| `SQL_QUERY_TIMEOUT_SECONDS` | `5.0` | Max runtime for `run_sql_query` (0–30s) |
| `SQL_MAX_ROWS_LIMIT` | `500` | Upper bound for `run_sql_query(max_rows=...)` |
| `MCP_TRANSPORT` | `http` | `http` (Streamable HTTP) or `stdio` |
| `HOST` / `PORT` | `0.0.0.0` / `8000` | HTTP server bind address and port |
| `LOG_LEVEL` | `INFO` | Structured JSON log level |
| `AUTH_MODE` | `bearer` | `bearer` (default), `oauth`, or `none` |
| `MCP_AUTH_TOKENS` | `""` | Comma-separated Bearer tokens (each ≥ 32 chars; supports zero-downtime rotation) |
| `ALLOW_UNAUTHENTICATED` | `false` | Must be `true` to allow `AUTH_MODE=none` (local dev only) |
| `OAUTH_PROVIDER` | *(none)* | `google`, `github`, or `oidc` (when `AUTH_MODE=oauth`) |
| `OAUTH_CLIENT_ID` | *(none)* | OAuth client ID |
| `OAUTH_CLIENT_SECRET` | *(none)* | OAuth client secret |
| `OAUTH_BASE_URL` | *(none)* | Public HTTPS base URL (register `<base_url>/auth/callback` with provider) |
| `OAUTH_ALLOWED_IDENTITIES` | `""` | **Required** comma-separated allowlist of permitted emails/subjects/logins for OAuth |
| `OAUTH_AUTHORIZE_URL`, `OAUTH_TOKEN_URL`, `OAUTH_JWKS_URI`, `OAUTH_ISSUER` | *(none)* | Required only when `OAUTH_PROVIDER=oidc` |

## Compatibility

Tested against Bluecoins SQLite schema `PRAGMA user_version = 47`.

## Local Development

```bash
uv sync
uv run pytest -v
uv run ruff check src tests
uv run ruff format --check src tests
uv run mypy src tests
```

## License

MIT — see [LICENSE](LICENSE).