Skip to main content
Glama
README.md
# llm-cost-ledger-mcp

An [MCP](https://modelcontextprotocol.io) server that answers one question for AI products: **what did this session cost?**

Your app (or an AI assistant connected to it) reports the token usage of each LLM call. The server prices it, keeps a ledger, and answers cost questions per session, per model or per day. Built for products that sell a fixed-price AI session and need to know the real cost behind it, including prompt-cache reads and writes.

## Tools

| Tool | What it does |
|---|---|
| `record_usage` | Records one call: session, model, input, output, cache-read and cache-write tokens. Returns the cost of that call. Rejects unknown models. |
| `session_cost` | Total cost of a session in US dollars, split by token type, with the number of calls. |
| `cost_report` | Spend grouped by `session`, `model` or `day`, biggest first, optionally only since a date. |
| `list_models` | Models the ledger can price, with prices per million tokens. |

There is also a resource, `pricing://table`, with the price table in use.

## Install and run

```bash
npm install
npm run build
npm start          # stdio server
```

Environment variables:

- `LEDGER_FILE`: where events are appended as JSON lines. Default `data/ledger.jsonl`. Data survives restarts.
- `PRICING_FILE`: path to a JSON price table (see `pricing.example.json`). Prices are US dollars per million tokens.

**The built-in prices are placeholders** (`example-small`, `example-large`). Point `PRICING_FILE` at your provider's real, current prices before you trust any number.

## Connect to a client

Claude Code:

```bash
claude mcp add llm-cost-ledger -e PRICING_FILE=/path/to/pricing.json -- node /path/to/llm-cost-ledger-mcp/dist/index.js
```

Any MCP client with a JSON config:

```json
{
  "mcpServers": {
    "llm-cost-ledger": {
      "command": "node",
      "args": ["/path/to/llm-cost-ledger-mcp/dist/index.js"],
      "env": { "PRICING_FILE": "/path/to/pricing.json" }
    }
  }
}
```

## Example

`record_usage` with `session_id: "run-42"`, `model: "example-small"`, `input_tokens: 12000`, `output_tokens: 800`, `cache_read_tokens: 30000` costs `$0.019` with the placeholder prices. `session_cost` for `run-42` then returns the running total split into input, output, cache read and cache write.

## Tests

```bash
npm test
```

Eleven tests run the real server and a real client over an in-memory transport. They cover cost math with cache tokens, rejection of unknown models, per-session totals, report ordering and the `since` filter, tool and resource listing, and how the ledger behaves when things go wrong: restart persistence, a half-written last line, malformed lines, a model removed from the price table, a failed disk write, and invalid token counts.

## Design notes

- Costs are computed when you ask, from the stored token counts, so fixing a price table corrects past reports.
- The ledger is an append-only file on purpose: no database to run, easy to inspect and back up. For high volume, replace the `Ledger` class with a database-backed one; the tools do not change.
- Nothing is logged to stdout except protocol messages, as required for stdio servers.
- A ledger line that cannot be read (for example after a crash mid-write) is skipped with a warning on stderr; the file is never rewritten.
- Calls whose model is no longer in the price table are counted as `unpriced_calls` in reports instead of being silently priced at zero, so a changed price table cannot hide spend.
- Events are written to disk before they are kept in memory, so a failed write leaves no phantom event.

## Limits

- Single user, local stdio server with no authentication. Do not expose it over a network as is.
- The whole ledger is held in memory at startup. That is fine for hundreds of thousands of events; beyond that, use a database-backed `Ledger`.
- Costs are rounded to six decimals, so very large sums of tiny calls can differ from your provider's invoice in the last digits.

## License

MIT

TDQS

A3.6/5.0

Scored across 4 tools

Disambiguation4/5

record_usage and list_models are clearly distinct actions, and session_cost vs cost_report are separated by scope (single session, token-type breakdown) versus multi-group reporting with date filtering. The two reporting tools still overlap enough that an agent may occasionally pick the wrong one for a simple spend question.

Naming Consistency4/5

All names use consistent snake_case and are readable. There is a minor deviation in verb ordering (record_usage/list_models are verb-first, session_cost/cost_report are noun-first), but the pattern remains predictable within each pair.

Tool Count5/5

Four tools is a tight, well-scoped surface for a cost ledger: one write path, two query paths, and one reference lookup. Each tool earns its place with no redundant entries.

Completeness4/5

The core lifecycle of recording usage and reporting cost is covered, including price reference via list_models. However, there is no way to correct or delete a mis-recorded call, and no explicit session enumeration outside of cost_report grouping.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues