Skip to main content
Glama
README.md
# LiteLLM Lens

A read-only MCP server and a self-contained HTML dashboard for [LiteLLM](https://github.com/BerriAI/litellm) proxy spend: cost, tokens and prompt caching by user, team, API key and model.

It reads LiteLLM's daily spend tables in Postgres. It never writes to the database, never reads prompts or responses, and offers no tool that runs arbitrary SQL.

This project is not affiliated with or endorsed by BerriAI (LiteLLM) or Anthropic.

## What the dashboard shows

![The dashboard with invented sample data](docs/images/dashboard.png)

One page, top to bottom (numbers invented):

```text
LLM spend                                   Data as of 2026-11-29 06:00 UTC
This month: 1 Nov – 30 Nov 2026 (UTC)

[!] 1 of 4 checks need attention: caching off for 1 person

Summary                                         [This month | Last month]
  $1,234.56 spent so far in November, on pace for $1,320.00, 8% above ...
  Top insights: Trend · Drivers · Savings · Caching · Models
  Suggestions:  Turn on prompt caching for sam · Use Opus less · ...

Ask about this data          (works when the page is opened on claude.ai)

Spend so far | Month-end projection | Requests | Total tokens | Cache-read share | Cost per request

Daily spend by model         stacked bars, last month to today   [USD | Tokens] [Chart | Table]

Breakdown                    Users | Teams | Models | Keys | Providers   (sortable table)

Prompt caching by model      cache read / cache write / fresh input, per model
```

See [the dashboard](docs/dashboard.md) for what every section means and the rules behind each flag.

## Features

- **MCP tools** for Claude Code and other MCP clients: spend by user, team, key, model or provider; daily spend by model; models that used tokens but logged $0.
- **One-file dashboard** that works offline, or a site folder (`index.html` + `data.json`) where a refresh replaces only the data.
- **Health checks** for stale data, missing usage, unpriced models and people whose prompt caching is not working.
- **Fair month comparisons**: a partial month is projected before it is compared with last month.
- **Read-only by design**: a role with column-level grants, read-only transactions with a statement timeout, and no free-form SQL.
- **Standard Postgres connection settings**: a URL, `PG*` variables, `~/.pgpass` or a service file.
- **Scheduling files** for launchd, systemd, cron and Docker. Hourly by default.

## Requirements

- Python 3.10 or later.
- For your own data: a LiteLLM proxy that logs spend to Postgres, in a version whose schema has the `LiteLLM_DailyUserSpend` and `LiteLLM_DailyTeamSpend` tables with the columns the queries use. [Database access](docs/database-access.md#check-your-litellm-version) lists them and gives a query to check.

## Quick start (5 minutes, no database)

Check your Python first. It must be 3.10 or later:

```sh
python3 --version
```

The `python3` that comes with macOS is 3.9. With it, `pip install -e .` fails with a misleading "setup.py not found" error. Install a newer Python (for example `brew install python@3.12`) and use it by name, as below.

```sh
git clone https://github.com/ykataria/litellm-lens.git
cd litellm-lens
python3.12 -m venv .venv          # or python3, if it is 3.10 or later
. .venv/bin/activate
pip install -U pip
pip install -e .
litellm-lens export --sample
```

Open the dashboard in your browser:

```sh
open out/dashboard.html        # macOS
xdg-open out/dashboard.html    # Linux
```

Every name and number in it is invented.

## Connect to your LiteLLM database

1. Create a read-only login with [`sql/readonly_role.sql`](sql/readonly_role.sql). It can read the two daily spend tables and the ID and name columns of the user, team and key tables, and nothing else.
2. Configure the connection:

   ```sh
   cp .env.example .env
   chmod 600 .env
   ```

   Fill in `PGHOST`, `PGDATABASE` and `PGUSER`. Keep `PGSSLMODE=require` (or `verify-full`) for a remote database. Keep the password in `~/.pgpass`. `PG*` variables already set in your shell win over `.env`. The generic `DATABASE_URL` is ignored, because it usually belongs to another application; use `LITELLM_LENS_DATABASE_URL` for a URL.
3. Check the connection and every tool:

   ```sh
   litellm-lens verify
   ```

4. Build your dashboard:

   ```sh
   litellm-lens export
   ```

   `out/dashboard.html` now holds your real data, including staff emails. `out/` is git-ignored.

More detail: [getting started](docs/getting-started.md) and [database access](docs/database-access.md).

## Use it from Claude Code

The repository's [`.mcp.json`](.mcp.json) registers the server. It expects the virtual environment at `.venv`, as in the quick start:

```json
{
  "mcpServers": {
    "litellm-lens": {
      "command": ".venv/bin/litellm-lens",
      "args": ["serve"]
    }
  }
}
```

Start `claude` in the repository folder and approve the `litellm-lens` project server. Run `/mcp` to check it is connected, then ask things like "What did we spend on Claude last month, by team?" or "Which models are missing a price?".

`claude mcp list` may still show the server as "Pending approval" after you approve it in a session; `/mcp` inside Claude shows the real status.

To use it from any folder, add it at user scope with absolute paths (the server reads `.env` from the working folder, so point it at the file):

```bash
claude mcp add -s user litellm-lens \
  -e LITELLM_LENS_ENV_FILE=/ABSOLUTE/PATH/TO/litellm-lens/.env \
  -- /ABSOLUTE/PATH/TO/litellm-lens/.venv/bin/litellm-lens serve
```

The tools, their arguments and their output: [MCP tools](docs/mcp-tools.md).

## Choose how to run it

| | Local only | Server or static hosting | claude.ai artifact (optional) |
|---|---|---|---|
| You get | `out/dashboard.html` on your machine | A dashboard URL for your team; optionally an MCP server over HTTP | A private claude.ai page with an Ask box |
| Command | `litellm-lens export` | `litellm-lens export --site DIR`; `litellm-lens serve --transport http` | The prompts in [`deploy/claude/`](deploy/claude/), run in Claude Code |
| Data leaves your machine | No | To your web server | To claude.ai |
| Access control | Whoever has the file | Your SSO or reverse proxy. The HTTP MCP server has **no authentication of its own** | The artifact's Share menu |
| Needs | Python | A web server or bucket | Claude Code signed in with a claude.ai account |

Start with local only. The local file and the server folder refresh on a schedule with [`scripts/refresh.sh`](scripts/refresh.sh) (launchd on a Mac, a systemd timer or cron on Linux) or with the Docker Compose loop. The claude.ai artifact refreshes from a Claude Code `/loop`, a scheduled task in the Claude desktop app, or (experimental, macOS) a launchd job that opens a Claude session in Terminal, because only a Claude session can publish it. You can try the artifact without a database: add `--sample` to the export command in the prompt. See [refresh and scheduling](docs/refresh-and-scheduling.md) and [deployment](docs/deployment.md).

### Publish the artifact every hour on a Mac (experimental)

After the artifact exists (`.artifact-url` is in the repository root), run the refresh once by hand and accept Claude's folder-trust prompt in the Terminal window it opens:

```bash
scripts/claude-refresh.sh
tail -1 logs/claude-refresh.log   # ... published (litellm-lens-refresh-...)
```

If the artifact belongs to another Claude profile than your default, name its config folder: `LITELLM_LENS_CLAUDE_CONFIG_DIR=~/.claude-other scripts/claude-refresh.sh`.

Then install the hourly job from the repository root. Set `CLAUDE_DIR` to the Claude config folder of the account that owns the artifact (`~/.claude` unless you use another profile):

```bash
CLAUDE_DIR=~/.claude
dst=~/Library/LaunchAgents/io.github.ykataria.litellm-lens.claude-refresh.plist
sed -e "s#/ABSOLUTE/PATH/TO/litellm-lens#$PWD#g" -e "s#/Users/USERNAME#$HOME#g" \
  deploy/launchd/io.github.ykataria.litellm-lens.claude-refresh.plist > "$dst"
/usr/libexec/PlistBuddy -c "Add :EnvironmentVariables:LITELLM_LENS_CLAUDE_CONFIG_DIR string $CLAUDE_DIR" "$dst"
mkdir -p logs
launchctl bootstrap gui/$(id -u) "$dst"
```

| To | Run |
|---|---|
| Check it is scheduled | `launchctl print gui/$(id -u)/io.github.ykataria.litellm-lens.claude-refresh \| grep -E 'state\|run interval\|runs\|last exit'` (`runs` counts scheduled runs since it was loaded) |
| Run it now | `launchctl kickstart -k gui/$(id -u)/io.github.ykataria.litellm-lens.claude-refresh` |
| Change how often (seconds; 1800 = 30 min) | `/usr/libexec/PlistBuddy -c "Set :StartInterval 1800" "$dst"`, then `launchctl bootout gui/$(id -u)/io.github.ykataria.litellm-lens.claude-refresh` and the `bootstrap` line again |
| Stop and remove it | `launchctl bootout gui/$(id -u)/io.github.ykataria.litellm-lens.claude-refresh && rm "$dst"` |
| See results | `tail logs/claude-refresh.log` |

The job keeps running after you close the terminal you installed it from, and after a restart: launchd starts it, not your shell. It needs you logged in and the Mac awake; a run missed while the Mac sleeps runs once when it wakes.

## Configuration

The CLI and the MCP server read environment variables, plus a `.env` file: `LITELLM_LENS_ENV_FILE` if set, otherwise `.env` in the current folder (parent folders are not searched). Real environment variables win over the file. The main ones:

| Variable | Default | Purpose |
|---|---|---|
| `LITELLM_LENS_DATABASE_URL` | not set | Connection URL. Without it, the libpq `PG*` variables, `PGSERVICE` and `~/.pgpass` apply. The generic `DATABASE_URL` is ignored. |
| `LITELLM_LENS_SCHEMA` | `public` | Schema of the LiteLLM tables. |
| `LITELLM_LENS_EXCLUDE_API_KEYS` | `litellm-internal-health-check` | Keys left out of every number. |
| `LITELLM_LENS_CONNECT_TIMEOUT` | `10` | Seconds to wait for a connection. |
| `LITELLM_LENS_STATEMENT_TIMEOUT` | `30` | Seconds per query. Set `0` behind PgBouncer in transaction mode. |
| `LITELLM_LENS_PREMIUM_MODELS`, `LITELLM_LENS_FLAGSHIP_MODELS`, `LITELLM_LENS_SAVINGS_MODELS` | `Claude=claude`, `Opus=opus`, `open models=deepseek\|glm\|...` | Dashboard model groups. |
| `LITELLM_LENS_REFERENCE_PRICES` | `Claude Sonnet 5.5=2,2.5,0.1,10` | Prices (USD per million tokens) for the savings estimate. |
| `LITELLM_LENS_ALLOWED_HOSTS`, `LITELLM_LENS_ALLOWED_ORIGINS` | localhost only | HTTP transport only: the `Host` and `Origin` headers it accepts. Set them behind a reverse proxy. |

`scripts/refresh.sh` has three variables of its own (`LITELLM_LENS_BIN`, `LITELLM_LENS_LOG_DIR`, `LITELLM_LENS_SITE_DIR`). The script reads them from its process environment only, not from `.env`, so set them in the scheduler.

The full list, with formats and examples: [configuration](docs/configuration.md).

## Security

- Use the dedicated read-only role. Every query also runs in a read-only transaction with a statement timeout, and there is no free-form SQL tool.
- Use `PGSSLMODE=require` or `verify-full` for any remote database.
- The HTTP MCP transport has **no authentication**. Keep it on localhost or a VPN, or behind an authenticating reverse proxy. It always checks the `Host` and `Origin` headers against DNS rebinding, and by default accepts only localhost.
- Dashboards contain staff emails and spend. Share them only with people who should see them.

Reporting vulnerabilities and the threat model: [SECURITY.md](SECURITY.md).

## Documentation

| Page | What it covers |
|---|---|
| [Getting started](docs/getting-started.md) | Install, sample data, connect, verify, Claude Code. |
| [Configuration](docs/configuration.md) | Every environment variable. |
| [Database access](docs/database-access.md) | The read-only role, connection options, TLS, passwords, servers, PgBouncer. |
| [MCP tools](docs/mcp-tools.md) | Each tool's arguments, output and errors. |
| [The dashboard](docs/dashboard.md) | Every section, check and threshold. |
| [Data contract](docs/data-contract.md) | The JSON behind the dashboard. |
| [Refresh and scheduling](docs/refresh-and-scheduling.md) | `refresh.sh`, launchd, systemd, cron, Docker. |
| [Deployment](docs/deployment.md) | Static hosting, HTTP MCP behind a proxy, Docker, claude.ai artifact. |
| [Architecture](docs/architecture.md) | How the parts fit together, and the module map. |
| [Troubleshooting](docs/troubleshooting.md) | Error messages and fixes. |
| [LiteLLM notes](docs/litellm-notes.md) | Health checks, prompt caching, unpriced models, how the tables count. |

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup, linting, tests and how to change the dashboard template. Changes are listed in [CHANGELOG.md](CHANGELOG.md). Everyone taking part is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).

## Licence

[MIT](LICENSE)