# Claude Viewer
**Multi-User Conversation History Viewer for Claude Code**



---
## ๐ฏ Overview
Claude Viewer is an admin tool web application for visualizing Claude Code conversation history from all Windows/macOS users on a single machine. It provides rich analytics, full conversation details, token usage tracking, and model/tool insights.
MCP Server integration allows Claude Desktop and Claude Code to query conversation data directly!
### Demo
https://github.com/user-attachments/assets/1426b08d-6086-439f-9f4b-d95d7cfdac1e
---
## โจ Key Features
### v0.1 Features
- โ
**MCP Server Integration** - Query conversation data directly from Claude Desktop/Code
- โ
**5 MCP Tools** - get_claude_users, get_conversations, get_stats, get_conversation_details, open_dashboard
- โ
**Open Dashboard via MCP** - Start server and open browser with a single command
- โ
**Shared Library** - Refactored codebase with `lib/data-access.js` for reuse
- โ
**Configurable Port** - Default 2204, configurable via `CLAUDE_VIEWER_PORT` env
- โ
**Full Conversation Viewer** - View complete user/assistant message threads in modal
- โ
**Token Usage Analytics** - Track input/output/cache tokens per conversation
- โ
**Model Tracking** - See which Claude models are used (Sonnet 4.5, Opus, Haiku)
- โ
**Tool Analytics** - Top 10 most-used tools (WebSearch, Bash, Edit, etc.)
- โ
**Enhanced Dashboard** - 8 statistical cards
- โ
**Enriched Data Table** - 9 columns with messages, tokens, model, tools
- โ
**Dual-Source Architecture** - Combines `history.jsonl` + `projects/*.jsonl` for rich metadata
### Core Features
- ๐ Real-time statistics dashboard
- ๐ Advanced search and filtering (user, project, date range, text)
- ๐ Daily activity chart (last 30 days)
- โ๏ธ Keyword cloud (top 20 keywords)
- ๐ฅ CSV export with enriched data
- ๐ฅ๏ธ Multi-user support (scans all system users)
- ๐ XSS protection with HTML escaping
---
## ๐ Quick Start
### Installation
```bash
# Clone or download this repository
cd claude-viewer
# Install dependencies
npm install
# Start the server
npm start
# Open in browser
open http://localhost:2204
```
---
## โก Quick Start Integration Options
Choose your preferred method to launch Claude Viewer with a single command:
### 1๏ธโฃ Automated Launcher Script (Recommended)
A convenient bash script that starts the server and opens your browser automatically.
**Location:** `start-claude-viewer.sh`
**What it does:**
- Starts the Node.js server in the background
- Waits for server initialization (3 seconds)
- Automatically opens your default browser at `http://localhost:2204`
- Displays helpful status messages during startup
**Usage:**
```bash
./start-claude-viewer.sh
```
**To stop the server:**
```bash
# Press Ctrl+C in the terminal, or:
pkill -f 'node.*server.js'
```
**Setup (first time only):**
```bash
chmod +x start-claude-viewer.sh
```
---
### 2๏ธโฃ Global Shell Alias
For terminal power users, create a global alias to launch from anywhere.
**Add to your `~/.zshrc` (or `~/.bashrc`):**
```bash
alias claude-viewer='~/path/to/claude-viewer/start-claude-viewer.sh'
```
**Replace** `~/path/to/claude-viewer/` with your actual project path, for example:
```bash
alias claude-viewer='~/Library/Mobile\ Documents/com~apple~CloudDocs/Sviluppo\ AI/MaxTurazzini/claude-viewer/start-claude-viewer.sh'
```
**Usage from anywhere:**
```bash
claude-viewer
```
**Apply changes:**
```bash
source ~/.zshrc
```
---
### ๐ Summary of Launch Methods
| Method | Command | Requires |
|--------|---------|----------|
| **Direct Script** | `./start-claude-viewer.sh` | None (project directory) |
| **Shell Alias** | `claude-viewer` | `.zshrc` configuration |
| **Manual** | `npm start` | None |
All launch methods provide the same seamless experience:
**One command โ Server starts โ Browser opens โ View conversations**
> **Tip:** The script runs the server in the background, allowing you to continue using your terminal. To view server logs, check `server.log` or monitor the console output.
---
## ๐ MCP Server Integration (v0.1)
Claude Viewer includes an MCP (Model Context Protocol) server that exposes conversation data directly to Claude Desktop and Claude Code.
### Running the MCP Server
```bash
# Run MCP server (stdio transport)
npm run mcp
# Or directly
node mcp-server.js
```
### Available MCP Tools
| Tool | Description | Parameters |
|------|-------------|------------|
| `get_claude_users` | List users with Claude history | - |
| `get_conversations` | Get conversations with filters | `username?`, `search?`, `project?`, `dateFrom?`, `dateTo?`, `limit?`, `offset?` |
| `get_stats` | Aggregated usage statistics | - |
| `get_conversation_details` | Full transcript of a session | `sessionId`, `username` |
| `open_dashboard` | Start server and open browser | `port?` (default: 2204) |
### Configuration
#### Claude Desktop
Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
```json
{
"mcpServers": {
"claude-viewer": {
"command": "node",
"args": ["/path/to/claude-viewer/mcp-server.js"]
}
}
}
```
#### Claude Code
**Option 1: Via CLI (recommended)**
```bash
# Global (available in all projects)
claude mcp add claude-viewer -s user -- node "/path/to/claude-viewer/mcp-server.js"
# Per project (current project only)
claude mcp add claude-viewer -s project -- node "/path/to/claude-viewer/mcp-server.js"
```
**Option 2: Configuration file**
- **Global** (`~/.claude.json`):
```json
{
"mcpServers": {
"claude-viewer": {
"command": "node",
"args": ["/path/to/claude-viewer/mcp-server.js"]
}
}
}
```
- **Per project** (`.mcp.json` in project root):
```json
{
"mcpServers": {
"claude-viewer": {
"command": "node",
"args": ["/path/to/claude-viewer/mcp-server.js"]
}
}
}
```
**Verify configuration:**
```bash
# List configured MCP servers
claude mcp list
# Remove server
claude mcp remove claude-viewer -s user
```
### Example Requests to Claude
Once configured, you can ask Claude to query your conversation history. Here are some practical examples:
#### Dashboard & Overview
- "Open the Claude Viewer dashboard"
- "Show me my Claude usage statistics"
- "How many conversations do I have in total?"
#### User Analysis
- "Which users have Claude conversation history on this machine?"
- "Who is the most active Claude user?"
- "Compare token usage between users"
#### Conversation Search
- "Show me conversations about MCP from the last week"
- "Find all conversations related to React development"
- "Search for conversations where I discussed database optimization"
- "List conversations from the project /Users/max/myapp"
#### Token & Cost Analysis
- "What's my total token usage this month?"
- "Which conversations consumed the most tokens?"
- "Show daily token usage for the past 30 days"
- "Calculate my estimated API costs based on token usage"
#### Model & Tool Insights
- "Which Claude model do I use most frequently?"
- "What tools are most commonly used in my conversations?"
- "Show conversations where I used WebSearch"
- "List all conversations that used the Bash tool"
#### Conversation Details
- "Get the full transcript of session abc123..."
- "Show me the last conversation I had about authentication"
- "What did Claude suggest for the caching implementation?"
---
## ๐ Dashboard & Features
### 8-Card Statistics Dashboard
1. **Total Conversations** - Count of all conversations
2. **Active Users** - Number of unique users
3. **Most Active User** - User with most conversations
4. **Most Used Project** - Top project by conversation count
5. **Total Tokens** - Sum of all input/output/cache tokens
6. **Total Messages** - Count of all user + assistant messages
7. **Top Model** - Most-used Claude model (e.g., "sonnet-4-5")
8. **Top Tool** - Most-used tool (e.g., "WebSearch")
### 9-Column Conversation Table
- Timestamp
- User
- Project
- Prompt (user's first message)
- **Msgs** - Number of messages in conversation
- **Tokens** - Formatted token usage (e.g., "12,345")
- **Model** - Model used (e.g., "sonnet-4-5")
- **Tools** - Tool count with hover tooltip for names
- Actions (Details button)
### Additional Features
- **Conversation Modal** - Click "๐ฌ Dettagli" to view full user/assistant thread
- **Daily Activity Chart** - Canvas-based visualization of last 30 days
- **Keyword Cloud** - Frequency-based sizing (4+ character words only)
- **Advanced Filters** - Text search, user, project, date range
- **CSV Export** - Download filtered data with 8 columns
---
## ๐๏ธ Architecture
### Tech Stack
- **Backend:** Node.js + Express.js (v4.18.2)
- **Frontend:** Vanilla JavaScript, HTML5, CSS3 (no frameworks)
- **Data Format:** JSONL (JSON Lines) from Claude Code history
- **Platform:** Cross-platform (Windows/macOS/Linux)
### Dual-Source Data Architecture
Claude Viewer now combines data from two sources for enriched insights:
#### Source 1: Quick Conversation List
**Path:** `~/.claude/history.jsonl` (Windows: `C:\Users\{USERNAME}\.claude\history.jsonl`)
**Contains:**
- User prompts (display text)
- Timestamps
- Project paths
- Basic metadata
**Purpose:** Fast scanning for conversation list
#### Source 2: Full Session Transcripts
**Path:** `~/.claude/projects/{project}/{session-uuid}.jsonl`
**Contains:**
- Complete message threads (user + assistant)
- Token usage (input/output/cache_creation/cache_read)
- Model information (e.g., "claude-sonnet-4-5-20250929")
- Tool usage (WebSearch, Bash, Edit, Read, etc.)
- Thinking blocks and tool_use content
**Purpose:** Rich metadata extraction
### Data Flow
```
1. Scan ~/.claude/history.jsonl (all users)
โ
2. Parse conversation list with basic metadata
โ
3. Match conversations to projects/*.jsonl by timestamp (ยฑ5 min tolerance)
โ
4. Extract metadata: tokens, model, tools, message count
โ
5. Enrich conversation objects with full data
โ
6. Serve via REST API endpoints
โ
7. Frontend renders dashboard, table, and modal
```
### REST API Endpoints
- **`GET /api/users`** - List of users with Claude history
- **`GET /api/conversations`** - All conversations with enriched metadata
- Includes: messageCount, totalTokens, model, toolsUsed[], hasDetails
- Sorted by timestamp descending (most recent first)
- **`GET /api/stats`** - Aggregated statistics
- Original: totalConversations, totalUsers, userStats, projectStats, dailyStats, topKeywords
- New: totalTokens, totalMessages, tokensByUser, modelStats, toolStats, dailyTokenStats
- **`GET /api/conversation/:sessionId/:username`** - Full conversation transcript
- Returns complete thread with all messages
- Used by modal for detailed view
---
## ๐ ๏ธ Configuration
### Change Port (Optional)
Default port is `2204`. You can change it via environment variable:
```bash
# Set custom port
CLAUDE_VIEWER_PORT=3000 npm start
# Or export it
export CLAUDE_VIEWER_PORT=3000
npm start
```
### Data Locations
**macOS/Linux:**
- History: `~/.claude/history.jsonl`
- Sessions: `~/.claude/projects/{project}/{session-uuid}.jsonl`
**Windows:**
- History: `C:\Users\{USERNAME}\.claude\history.jsonl`
- Sessions: `C:\Users\{USERNAME}\.claude\projects\{project}\{session-uuid}.jsonl`
---
## โ ๏ธ Troubleshooting
### No Data Displayed
**Symptoms:** Empty conversation list, 0 total conversations
**Solutions:**
1. Verify Claude history files exist:
```bash
# macOS/Linux
ls ~/.claude/history.jsonl
# Windows
dir C:\Users\*\.claude\history.jsonl
```
2. Check permissions (may require admin on enterprise PCs):
```bash
# macOS/Linux
sudo npm start
# Windows (run terminal as Administrator)
npm start
```
3. Check server logs for errors:
```bash
tail -f server.log
```
---
### Dashboard Shows "0" for Tokens/Messages
**Cause:** `~/.claude/projects` directory not accessible or empty
**Solutions:**
1. Verify session files exist:
```bash
# macOS/Linux
find ~/.claude/projects -name "*.jsonl"
# Windows
dir C:\Users\%USERNAME%\.claude\projects /s /b | findstr .jsonl
```
2. Check server console for "Error enriching conversation" messages
3. **Graceful Degradation:** App still works, showing 0 values but conversation list remains visible
---
### Table Missing New Columns (Msgs, Tokens, Model, Tools)
**Cause:** Browser cached old `app.js`
**Solutions:**
1. Hard refresh: `Ctrl+Shift+R` (Windows/Linux) or `Cmd+Shift+R` (macOS)
2. Clear browser cache for `localhost:2204`
3. Try incognito/private browsing mode
---
### Port 2204 Already in Use
**Symptoms:** `Error: listen EADDRINUSE: address already in use :::2204`
**Solutions:**
1. **Option 1:** Kill existing process
```bash
# macOS/Linux
lsof -ti:2204 | xargs kill
# Windows
netstat -ano | findstr :2204
taskkill /F /PID [PID from above]
```
2. **Option 2:** Use different port via environment variable
```bash
CLAUDE_VIEWER_PORT=3000 npm start
```
---
### "Cannot find module 'express'" Error
**Cause:** Dependencies not installed
**Solution:**
```bash
npm install
```
---
### Modal Shows "Session not found"
**Cause:** Session file deleted, moved, or corrupted
**Solutions:**
1. Session may have been cleaned up by Claude Code
2. Conversation still visible in list but full transcript unavailable
3. Check if `projects/` directory exists and contains `.jsonl` files
---
### Permission Errors on Enterprise PCs
**Cause:** Corporate policies restrict access to user directories
**Solutions:**
1. Run terminal/command prompt as Administrator
2. Contact IT to grant read access to `C:\Users\*\.claude\` directories
3. Alternative: Copy history files to accessible location and modify paths in `server.js`
---
### Slow Loading (>10 seconds)
**Cause:** Too many conversations to enrich (>500)
**Performance Notes:**
- Enrichment reads `projects/*.jsonl` for each conversation (~100-700KB per file)
- Typical load time: 2-5 seconds for 200-500 conversations
- Memory usage: ~50-100MB for typical workload
**Optimization Opportunities:**
- Add in-memory cache for session metadata
- Implement lazy loading (only load on modal open)
- Consider SQLite database for >1000 conversations
---
## ๐งโ๐ป Development
### Project Structure
```
claude-viewer/
โโโ server.js # Express backend (~114 lines, uses lib/)
โโโ mcp-server.js # MCP server (~280 lines)
โโโ lib/
โ โโโ data-access.js # Shared data functions (~700 lines)
โโโ public/
โ โโโ index.html # Main UI (165 lines)
โ โโโ app.js # Client logic (525 lines)
โ โโโ styles.css # Styling (380 lines)
โโโ start-claude-viewer.sh # Launcher script
โโโ package.json # Dependencies
โโโ CLAUDE.md # Project documentation
โโโ README.md # This file
```
### Key Backend Functions
**File:** `server.js`
1. `getClaudeUsers()` - Scans for users with `.claude` directories
2. `parseHistoryFile(filePath, username)` - Parses `history.jsonl`
3. `getUserSessions(username)` - Finds all session UUID files
4. `parseSessionTranscript(filePath)` - Parses full session JSONL
5. `extractSessionMetadata(messages)` - Extracts tokens, model, tools, message count
6. `mapConversationsToSessions(conversations, users)` - Matches history to sessions
7. `buildConversationThread(messages)` - Builds threaded conversation view
### Key Frontend Functions
**File:** `public/app.js`
1. `updateDashboard(stats)` - Populates 8-card dashboard
2. `renderConversations()` - Renders 9-column table with enriched data
3. `exportToCSV()` - Exports 8 columns
4. `showConversationDetails(sessionId, username)` - Opens modal with full transcript
5. `renderConversationThread(thread, container)` - Renders user/assistant messages
6. `renderAssistantContent(content)` - Handles text/thinking/tool_use blocks
---
## ๐ Version History
### v0.1.0 (2025-12-08) - Initial Public Release
**Major Features:**
- โ
**MCP Server** - Exposes conversation data via Model Context Protocol
- โ
**5 MCP Tools** - get_claude_users, get_conversations, get_stats, get_conversation_details, open_dashboard
- โ
**Open Dashboard Tool** - Start server and open browser directly from Claude
- โ
**Shared Library** - Refactored code into `lib/data-access.js` for reuse
- โ
**ES Modules** - Migrated from CommonJS to ES modules
- โ
**Configurable Port** - Default 2204, set via `CLAUDE_VIEWER_PORT` env
**Architecture Changes:**
- `server.js`: Reduced from ~920 to ~114 lines (uses lib/)
- `lib/data-access.js`: New shared module (~700 lines)
- `mcp-server.js`: New MCP server entry point (~350 lines)
- `package.json`: Added `"type": "module"`, MCP SDK dependencies
**Dependencies Added:**
- `@modelcontextprotocol/sdk`: ^1.12.0
- `zod`: ^3.25.0
---
## ๐งช Test Checklist
After installation or upgrade, verify:
- [ ] Dashboard displays 8 cards
- [ ] "Total Tokens" and "Total Messages" cards show numbers > 0
- [ ] "Top Model" card shows model name (e.g., "sonnet-4-5")
- [ ] "Top Tool" card shows tool name (e.g., "WebSearch")
- [ ] Conversation table has 9 columns
- [ ] "Msgs" column shows message count
- [ ] "Tokens" column shows formatted numbers (with commas)
- [ ] "Model" column shows abbreviated model names
- [ ] "Tools" column shows "X tools" with hover tooltip
- [ ] "๐ฌ Dettagli" button opens modal with full conversation
- [ ] Modal displays user and assistant messages correctly
- [ ] CSV export includes 8 columns
- [ ] Search and filters work correctly
- [ ] Daily activity chart renders
- [ ] Keyword cloud displays
---
## ๐ Technical Notes
### Performance Characteristics
- **No database:** All data loaded from files on each API request
- **No backend pagination:** All conversations loaded into memory at once
- **Frontend filtering:** O(n) filtering on every filter change
- **Keyword extraction:** Simple regex word matching (`\b\w{4,}\b`)
### Security
- โ
XSS protection with `escapeHtml()` function
- โ
Session ID validation in backend
- โ
No SQL injection risk (no database)
- โ ๏ธ File system access required (ensure proper permissions)
### Browser Compatibility
- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
- Requires ES6+ support
---
## โ๏ธ Claude Code Configuration
### Session Retention
Claude Code automatically deletes conversation sessions older than **30 days** by default. To preserve history for Claude Viewer, configure the retention period in `~/.claude/settings.json`:
```json
{
"cleanupPeriodDays": 365
}
```
**Common values:**
- `30` - Default (1 month)
- `90` - 3 months
- `365` - 1 year
- `730` - 2 years
- `999999` - Virtually unlimited
**File locations:**
| OS | Path |
|----|------|
| **macOS/Linux** | `~/.claude/settings.json` |
| **Windows** | `C:\Users\{USERNAME}\.claude\settings.json` |
> **Important:** Longer retention means more historical data available in Claude Viewer!
---
## ๐ค Contributing
For issues or feature requests:
1. Check `CLAUDE.md` for architectural details
2. Review `server.log` for runtime errors
3. Open an issue on GitHub
---
## ๐ License
MIT License
Copyright (c) 2025 Max Turazzini
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
**Built with:** Node.js, Express.js, Vanilla JavaScript
**Powered by:** Claude Code conversation history data
**Author:** [Max Turazzini](https://aimax.it/en)
**Version:** 0.1.0
**Last Updated:** 2025-12-08