Build a Token-Aware RAG Cost Monitor with AI

Learn how to build a live dashboard that tracks your vector database queries, monitors token usage across AI calls, and estimates real-time costs — all powered by Claude via MCP.

What You'll Build

By the end of this project you'll have a working browser-based dashboard that combines three ideas into one tool: a vector database query interface, a live MCP data feed showing token counts in real time, and a cost estimator that breaks down your AI bill query by query. Here's what the finished tool includes:

  • A vector database query panel that sends semantic search queries and shows the top results with similarity scores
  • A live MCP data feed that surfaces real-time token counts for every retrieval and generation call
  • A per-query cost breakdown showing input tokens, output tokens, embedding tokens, and their dollar cost separately
  • A running session total that accumulates costs across all queries so you can see spend at a glance
  • A budget alert banner that warns you when your session cost crosses a configurable threshold

What You'll Need

Claude (Recommended)

Claude is ideal here because its MCP integration lets it surface live token usage data directly. Use Claude.ai or the API with an MCP-enabled client.

A Text Editor

VS Code, Cursor, or any editor you like. You'll save the generated HTML, CSS, and JavaScript files and open them in a browser to test.

Step-by-Step Guide

1

Step 1: Build the Core Dashboard Layout

Every good tool starts with structure. In this step you're asking Claude to generate the HTML skeleton for the entire dashboard — the query panel on the left, the results feed in the center, and the cost tracker on the right. Getting the layout right now means every later step just fills in the panels without touching the structure.

The prompt below is detailed on purpose. Vague prompts produce vague layouts. You want Claude to know exactly what three-panel structure you're building before it writes a single line of code.

Prompt
Build me a single-file HTML dashboard called "RAG Cost Monitor". It should have a dark background and three main panels arranged side by side on desktop:

1. LEFT PANEL — "Query" panel with: a text input for the user to type a semantic search query, a dropdown to select a vector database (options: Chroma, Pinecone, Qdrant, pgvector), a "Run Query" button in green, and a small label showing "Connected via MCP" with a green status dot.

2. CENTER PANEL — "Results" feed that shows a scrollable list of query result cards. Each card should display: the result text snippet (truncated to 2 lines), a similarity score shown as a percentage, and an "input tokens used" badge.

3. RIGHT PANEL — "Cost Tracker" that shows: session total cost in large text at the top, a per-query breakdown list below it, and a configurable budget alert row at the bottom with an input field for the user to set a $ threshold.

Use a dark zinc color scheme, white headings, green accents for active states, and amber for cost numbers. Include Tailwind CSS via CDN. Add placeholder data so I can see how it looks. No JavaScript logic yet — just the HTML and CSS structure.

What to look for: Claude should output a complete single HTML file with Tailwind loaded via CDN link in the head. You should see three distinct side-by-side columns with placeholder cards populated in the results panel and amber-colored cost numbers in the right panel. Open the file in your browser to confirm it renders before moving on.

2

Step 2: Wire Up the Vector Database Query Simulator

Real vector database connections require a backend server, but we can simulate the full query lifecycle in the browser using realistic mock data — and that's enough to understand how the pieces connect. In this step you're asking Claude to add JavaScript that mimics what Chroma, Pinecone, Qdrant, and pgvector would each return when queried, including realistic similarity scores and document snippets.

Pay attention to the per-database differences in the mock responses. Each vector DB returns data in a slightly different shape — this mirrors what you'd deal with in a real integration and teaches you to think about schema normalization.

Prompt
Add JavaScript to the dashboard that simulates vector database query responses when the user clicks "Run Query". Here's what I need:

1. A `mockVectorQuery(query, database)` function that accepts the user's query text and the selected database name, waits 600ms to simulate network latency, then returns an array of 5 mock result objects.

2. Each result object should have: `text` (a realistic document snippet relevant to the query), `score` (a float between 0.72 and 0.99 representing cosine similarity), `tokens` (an integer between 40 and 180 representing the token count of that chunk), and `source` (a fake filename like "docs/chapter-3.md").

3. Make the mock responses slightly different per database to reflect real-world differences:
   - Chroma: returns results in a `documents` array format
   - Pinecone: returns results in a `matches` array format  
   - Qdrant: returns results in a `points` array format
   - pgvector: returns results as SQL-style rows with a `distance` field (convert to similarity: 1 - distance)

4. After the query resolves, populate the center results panel with the 5 result cards. Clear previous results first. Show a subtle loading spinner in the panel during the 600ms delay.

5. Display the selected database name and query text in a small breadcrumb at the top of the results panel.

Keep all existing HTML structure intact — only add JavaScript.

What to look for: When you type a query and click "Run Query", the results panel should clear, show a brief spinner, then populate with five cards showing text snippets, percentage similarity scores, and token badges. Try switching between databases in the dropdown — the internal data format should differ even if the displayed cards look the same, confirming normalization is working.

3

Step 3: Add the MCP Live Token Feed

MCP Resources let Claude expose live data — like token usage stats — that your dashboard can read in real time. In a production setup you'd point this at a real MCP server endpoint. Here you're building the client-side receiver that would consume that feed, plus a realistic simulation so you can see exactly how it would work. This step teaches you how the MCP data flow maps onto your UI.

The key insight is that an MCP resource is just a structured data endpoint. Your dashboard reads it on a polling interval — just like it would read a REST API — and updates the token display whenever new data arrives. Build that pattern here and you can swap in a real MCP endpoint later with almost no changes.

Prompt
Add an MCP Live Token Feed to the dashboard. Here's exactly what I need:

1. Create a `mcpTokenFeed` module in the JavaScript that simulates reading from an MCP Resource endpoint. The module should expose a `poll()` method that, when called, returns a structured object mimicking what an MCP resource named `rag://token-usage/live` would return:

```json
{
  "resource": "rag://token-usage/live",
  "timestamp": "",
  "data": {
    "embedding_tokens": ,
    "retrieval_input_tokens": ,
    "generation_input_tokens": ,
    "generation_output_tokens": ,
    "model": "claude-3-5-sonnet-20241022"
  }
}
```

2. When the user runs a query, call `mcpTokenFeed.poll()` to get the token breakdown for that query. The embedding tokens should be proportional to the query length (roughly 1 token per 4 characters). The retrieval input tokens should equal the sum of `tokens` across all 5 returned results. The generation input and output tokens should be realistic random values (input: 400-900, output: 150-400).

3. Add a small "MCP Feed" status panel beneath the left query panel. It should show: the resource URI, the last-polled timestamp, and a live log of the last 3 polls as collapsible JSON (use a `
` element). Show a green pulsing dot when polling is active. 4. After each query, update this feed panel with the new poll result so the user can see the raw MCP data that feeds into the cost calculation. Do not break any existing functionality.

What to look for: After running a query, the MCP Feed panel beneath the left column should update showing the resource URI, a fresh timestamp, and a collapsible JSON block with the four token categories. Click the details element to expand it and verify the numbers look proportional — embedding tokens should be small (tied to your query length), retrieval tokens should be larger (five chunks worth), and generation tokens should be in the hundreds.

4

Step 4: Wire in Real Token Pricing and Cost Calculations

Token counts are only useful when you can convert them to dollars. This step adds the pricing layer that ties everything together — the numbers from the MCP feed get multiplied against real per-token rates and displayed as actual cost. This is exactly how your AI bill works: input tokens and output tokens are priced differently, embedding calls are priced separately, and it all adds up per request.

You'll hardcode a pricing table for a few common models so users can switch models and instantly see how the cost changes. This makes the tool genuinely educational — you can run the same query twice with different model selections and see the price difference side by side.

Prompt
Add a real token pricing engine to the dashboard. Here's what I need:

1. Add a `PRICING` constant object at the top of the script containing per-token rates (in dollars per 1,000 tokens) for these models:
   - claude-3-5-sonnet: input $0.003, output $0.015, embedding $0.0001
   - claude-3-haiku: input $0.00025, output $0.00125, embedding $0.0001
   - gpt-4o: input $0.005, output $0.015, embedding $0.00013
   - gpt-4o-mini: input $0.00015, output $0.0006, embedding $0.00002
   - text-embedding-3-small: input $0.00002, output $0, embedding $0.00002

2. Add a model selector dropdown to the left query panel (above the Run Query button) that lets the user pick one of the above models. Default to claude-3-5-sonnet.

3. Create a `calculateCost(tokenData, model)` function that takes the MCP feed token object and the selected model, and returns:
   - `embeddingCost`: embedding_tokens × embedding rate
   - `inputCost`: (retrieval_input_tokens + generation_input_tokens) × input rate
   - `outputCost`: generation_output_tokens × output rate
   - `totalQueryCost`: sum of all three
   Each value formatted to 6 decimal places.

4. After each query, call `calculateCost()` and:
   - Add a new row to the per-query breakdown list in the right Cost Tracker panel showing: query number, truncated query text, model used, and total query cost in amber
   - Update the session total at the top of the right panel
   - If session total exceeds the user's budget threshold, show a rose/red alert banner at the top of the page with the message "⚠️ Budget threshold exceeded — session cost: $X.XXXXXX"

5. Add a "Reset Session" button at the bottom of the right panel that clears the cost history and resets the session total to $0.000000.

Do not break existing functionality.

What to look for: Run three or four queries with different models selected. The right panel should accumulate a row per query showing the cost to 6 decimal places — you'll notice claude-3-5-sonnet costs noticeably more per query than gpt-4o-mini. Set a budget threshold of $0.01 and run enough queries to trigger the rose alert banner at the top of the page. Confirm the Reset Session button zeros everything out.

5

Step 5: Add a Token Efficiency Score and Export

The final step pulls all three concepts together into one insight layer. A token efficiency score tells you how much useful retrieval you got per dollar spent — high similarity results that used fewer tokens are more efficient than low-similarity results that burned tokens on irrelevant chunks. This is the kind of metric that makes the tool genuinely actionable rather than just decorative.

You'll also add a JSON export so users can download their session log and analyze it elsewhere — in a spreadsheet, a notebook, or fed back into another AI prompt for analysis. It's a small feature but it closes the loop on the whole tool.

Prompt
Add two final features to complete the RAG Cost Monitor:

FEATURE 1 — Token Efficiency Score:
1. After each query, calculate a "Token Efficiency Score" using this formula:
   score = (average similarity score of top 5 results × 100) / (totalQueryCost × 10000)
   Cap the score at 100. Round to 1 decimal place.

2. Display this score on each per-query row in the right panel as a small badge:
   - Score ≥ 70: green badge labeled "Efficient"
   - Score 40-69: amber badge labeled "Moderate"
   - Score < 40: rose badge labeled "Costly"

3. Add a "Session Avg Efficiency" line just below the session total in the right panel that averages the efficiency scores across all queries in the session.

FEATURE 2 — Session Export:
1. Add an "Export Session JSON" button in the right panel (above Reset Session).

2. When clicked, generate a JSON file and trigger a browser download. The JSON should contain:
   - `exported_at`: ISO timestamp
   - `session_total_cost`: number
   - `session_avg_efficiency`: number
   - `queries`: array of objects, one per query, each containing: query text, database, model, token breakdown (from MCP feed), cost breakdown, similarity scores of all 5 results, and efficiency score

3. Name the file `rag-cost-session-.json`.

Do not break any existing functionality. Make sure the efficiency badges appear cleanly inside the existing per-query row layout.

What to look for: Run several queries mixing different models and databases. Each row in the cost tracker should now show a colored efficiency badge — cheaper models on simpler queries should score green while expensive models on low-similarity results should score amber or rose. Click Export Session JSON and open the downloaded file to verify every query's full data is there, nested correctly with token breakdowns and similarity arrays.

Common Issues

The results panel doesn't clear between queries

This usually means the DOM clear step is running before the new results are injected rather than replacing them. Ask Claude: "The results from the previous query aren't clearing before new ones appear. Find the results container clearing logic and make sure it runs synchronously before the new cards are inserted, not inside the async mock delay."

Cost numbers show as NaN or undefined

This happens when the selected model key doesn't match a key in the PRICING object — often a whitespace or case mismatch from the dropdown value. Ask Claude: "My cost calculation is returning NaN. Add a console.log that prints the selected model value and the PRICING object keys immediately before calculateCost() runs, so I can see if they match."

The budget alert banner appears immediately without crossing the threshold

The threshold input might be reading as a string instead of a number, so the comparison fails. Ask Claude: "The budget alert triggers even when the session cost is below the threshold I set. Find the threshold comparison and make sure the threshold value is parsed with parseFloat() before comparing it to the session total."

The exported JSON file is empty or malformed

The session query array is probably not being populated as queries run — the export captures whatever is in the array at click time. Ask Claude: "My exported JSON has an empty queries array. Find where each query result is supposed to be pushed into the session log array and add a console.log to confirm it's firing after every query."

The MCP feed panel doesn't update after queries

The feed update function is likely not being called in the main query handler, or it's being called before the mock async response resolves. Ask Claude: "The MCP Feed panel shows stale data after I run a new query. Make sure the feed panel update call happens inside the .then() or await block that resolves the mock query, not before it."

What You Learned

Vector Database Response Shapes

You saw how Chroma, Pinecone, Qdrant, and pgvector each return query results in a different schema — and why normalization matters when you want one dashboard to handle all of them without special-casing every call.

MCP as a Live Data Channel

You built a client that reads from a structured MCP resource URI on a per-query basis — the same pattern you'd use with a real MCP server. The resource URI, polling model, and JSON payload structure are all production-realistic.

Token Pricing in Practice

You implemented a real pricing table and saw how input tokens, output tokens, and embedding tokens are billed separately at different rates. Switching models in the dropdown makes the cost difference viscerally clear in a way that reading a pricing page never does.

Efficiency as a RAG Metric

You created a composite metric that combines retrieval quality (similarity score) with cost — giving you a single number to optimize. This is the kind of product thinking that separates a tool that shows data from one that generates insight.

Tips for Going Further

  • →

    Connect a real Chroma instance

    Run Chroma locally with Docker and replace the mock query function with a real fetch call to `http://localhost:8000/api/v1/query`. Your cost calculations will then reflect actual retrieval token counts from real documents.

  • →

    Point the MCP feed at a real MCP server

    Build a minimal MCP server that exposes a `rag://token-usage/live` resource returning real usage data from your API calls. Your dashboard client code is already written — you just swap the mock poll for a real fetch.

  • →

    Add a cost-per-chunk heatmap

    Color each result card's background based on how many tokens that chunk contributed to the total cost — deeper amber means more expensive. This makes it immediately visible when long chunks are consuming a disproportionate share of your bill.

  • →

    Feed your exported session JSON back into Claude for analysis

    Download a session log after 20 queries, paste it into Claude, and ask it to identify which query patterns are most expensive and suggest prompt rewrites that would reduce token usage. The tool's output becomes another AI prompt's input.

  • →

    Add a chunking strategy selector

    Let users choose between fixed-size chunks (512 tokens), sentence-boundary chunks, and paragraph chunks. Adjust the mock token counts accordingly and show how chunking strategy directly affects retrieval token costs — connecting this tool to the chunking tutorial concepts.

More projects

One of 44 hands-on projects.

All projects Prompting & Workflows tutorials