npm package: @o8n/mcp-optimizer
Description: Optimize MCP servers for Claude Code - analyze, track usage, and reduce context consumption
Author: o8n
Latest version: 0.1.0

# mcp-optimizer

Optimize MCP servers for Claude Code - analyze, track usage, and reduce context consumption.

## Problem

MCP servers consume context tokens in Claude Code sessions. As you add more servers, the context window fills up with tool descriptions, leaving less room for actual work. This tool helps you:

- **Visualize** how much context each MCP server consumes
- **Identify** duplicate, unused, or high-cost servers
- **Optimize** your configuration for better context efficiency

## Installation

```bash
npm install -g mcp-optimizer
```

Or run directly with npx:

```bash
npx mcp-optimizer analyze
```

## Usage

### Analyze MCP Servers

Analyze your configured MCP servers and see context consumption:

```bash
mcp-optimizer analyze
```

Example output (estimate mode):

```
MCP Server Analysis
Project: /Users/you/your-project
──────────────────────────────────────────────────────────────────────────────

Status    Server                        Type      Tools     Tokens
──────────────────────────────────────────────────────────────────────────────
●         atlassian                     [sse]     38        15.0k
●         claude-in-chrome              [stdio]   18        8.0k
●         playwright                    [stdio]   20        6.0k
●         context7                      [sse]     2         0.5k
──────────────────────────────────────────────────────────────────────────────

Total: 4 servers, 78 tools, ~29.5k tokens

Issues Found:

  ⚠ atlassian: High context consumption (~15k tokens)
     → Consider disabling when not needed

Mode:        Estimated (use --live for actual data)
```

### Live Mode

Connect to actual MCP servers to get real tool information:

```bash
mcp-optimizer analyze --live
```

Example output (live mode):

```
MCP Server Analysis
Project: /Users/you/your-project
──────────────────────────────────────────────────────────────────────────────

Status    Server                        Type      Tools     Tokens
──────────────────────────────────────────────────────────────────────────────
●         filesystem                    [stdio]   14        1.6k
●         context7                      [sse]     2         0.5k
✗         atlassian                     [sse]     38        15.0k
──────────────────────────────────────────────────────────────────────────────

Total: 3 servers, 54 tools, ~17.1k tokens

Issues Found:

  ✗ atlassian: Failed to connect: Connection timeout
     → Check server configuration and ensure it's running

Mode:        Live (connected to servers)
```

Status indicators:
- `●` Active - Server connected successfully
- `○` Disabled - Server is disabled in config
- `✗` Error - Failed to connect
- `?` Unreachable - Connection timeout

### Options

```bash
# Output as JSON
mcp-optimizer analyze --json

# Check project-specific settings
mcp-optimizer analyze --project /path/to/project

# Connect to servers for actual tool information
mcp-optimizer analyze --live

# Set connection timeout (default: 10000ms)
mcp-optimizer analyze --live --timeout 30000
```

### Usage Tracking

Track which MCP tools you actually use to identify unused servers:

```bash
# Install the tracking hook (globally)
mcp-optimizer hook install --global

# View usage statistics
mcp-optimizer stats

# View tool-level details
mcp-optimizer stats --tools

# Filter by time range
mcp-optimizer stats --since week
```

Example output:

```
MCP Usage Statistics
════════════════════════════════════════════════════════════════════════

Total: 42 tool uses across 5 sessions
Servers: 3 active

Server Usage:
Server                          Uses      Tools     Last Used
─────────────────────────────────────────────────────────────────
context7                        25        2         2m ago
atlassian                       15        8         1h ago
playwright                      2         2         3d ago
```

Hook management:

```bash
# Check hook status
mcp-optimizer hook status

# Uninstall the hook
mcp-optimizer hook uninstall --global
```

### Optimization Suggestions

Analyze usage data and get optimization recommendations:

```bash
mcp-optimizer optimize
```

Example output:

```
MCP Optimization Analysis
════════════════════════════════════════════════════════════════════════

Current: 5 servers, ~32k tokens
Potential savings: ~23k tokens

Suggestions:

  ✗ atlassian [HIGH] (saves ~15k)
     No usage recorded
     → Disable atlassian to save context

  ○ playwright [MED] (saves ~6k)
     Only 2 uses, last used 14 days ago
     → Consider disabling playwright when not needed

  $ claude-in-chrome [HIGH] (saves ~8k)
     High token cost (~8k) with only 3 uses
     → Consider using claude-in-chrome only when actively needed

────────────────────────────────────────────────────────────────────────

Legend:
  ✗ Unused   ○ Rarely used   ⊕ Duplicate   $ High cost

To apply changes, manually edit your Claude configuration:
  ~/.claude.json (global) or .claude/settings.local.json (project)
```

Options:

```bash
# Output as JSON
mcp-optimizer optimize --json

# Set unused threshold (days without usage)
mcp-optimizer optimize --unused-days 7

# Set rarely-used threshold (usage count)
mcp-optimizer optimize --threshold 5
```

### Apply Optimizations

Preview and apply optimization suggestions automatically:

```bash
# Preview changes without applying
mcp-optimizer optimize --dry-run
```

Example output:

```
Dry Run - Changes that would be applied:
════════════════════════════════════════════════════════════════════════

  ○ atlassian → disable [HIGH]
  ○ playwright → disable [MED]

Total: 2 server(s) would be disabled
Run with --apply to apply these changes
```

```bash
# Apply optimizations (disable unused servers)
mcp-optimizer optimize --apply
```

Example output:

```
Applying Optimizations
════════════════════════════════════════════════════════════════════════

  ✓ atlassian disabled (global)
     Backup: ~/.claude.json.backup-2026-01-23T13-45-00
  ✓ playwright disabled (local)
     Backup: .claude/settings.local.json.backup-2026-01-23T13-45-00

────────────────────────────────────────────────────────────────────────

✓ Applied 2 optimization(s)
```

### CI Integration

Check token usage in CI/CD pipelines:

```bash
# Exit with error if token limit exceeded
mcp-optimizer optimize --ci

# Set custom token limit (default: 50000)
mcp-optimizer optimize --ci --max-tokens 30000

# JSON output for CI
mcp-optimizer optimize --ci --json
```

Example GitHub Actions usage:

```yaml
- name: Check MCP token usage
  run: npx mcp-optimizer optimize --ci --max-tokens 30000
```

### Profile Management

Detect project type and get MCP server recommendations:

```bash
# Suggest servers based on project type
mcp-optimizer profile suggest
```

Example output:

```
Project Analysis
════════════════════════════════════════════════════════════════════════

Type: Full-stack
Confidence: high
Frameworks: React, Next.js
Features: Tests, Docker, CI/CD

────────────────────────────────────────────────────────────────────────

Recommended MCP Servers:

  ★ Recommended: context7
     Documentation lookup for any project

  ○ Optional: figma
     Design-to-code for React projects

  ○ Optional: github
     CI/CD integration

  ○ Optional: playwright
     E2E testing for frontend

Already installed: context7
```

Other profile commands:

```bash
# Create project-local settings file
mcp-optimizer profile create

# Show current MCP configuration
mcp-optimizer profile show

# Install recommended servers
mcp-optimizer profile install

# Install all recommended servers (including optional)
mcp-optimizer profile install --all

# Install specific server
mcp-optimizer profile install --server github
```

### Export Statistics

Export usage statistics to a file:

```bash
# Export to CSV
mcp-optimizer stats --export csv

# Export to JSON with custom filename
mcp-optimizer stats --export json --output my-stats.json

# Export with tool details
mcp-optimizer stats --tools --export csv
```

### GitHub Actions

Use mcp-optimizer in your CI/CD pipelines:

```yaml
name: Check MCP Token Usage

on: [push, pull_request]

jobs:
  check-mcp:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Check MCP token usage
        uses: o8n/mcp-optimizer@main
        with:
          max-tokens: 30000
          fail-on-exceed: true
          comment-on-pr: true
```

Inputs:
- `max-tokens`: Maximum allowed token count (default: 50000)
- `project-dir`: Project directory to analyze (default: '.')
- `fail-on-exceed`: Fail if token limit exceeded (default: true)
- `comment-on-pr`: Post results as PR comment (default: false)

## How It Works

1. **Config Discovery**: Reads MCP server configurations from:
   - `~/.claude.json` (global settings)
   - `.claude/settings.local.json` (project settings)

2. **Token Estimation**: Estimates context consumption based on:
   - Known server profiles (built-in estimates for popular servers)
   - Tool count and description complexity
   - Server metadata overhead

3. **Issue Detection**: Identifies potential problems:
   - Duplicate servers (same command, different names)
   - Disabled servers still in configuration
   - High token-cost servers

4. **Usage Tracking**: Records tool usage via Claude Code hooks:
   - Tracks which MCP tools are actually used
   - Stores data in SQLite database (`~/.mcp-optimizer/usage.db`)
   - Enables identification of unused servers

## Roadmap

### v0.1 (Current) - Analysis
- [x] Basic analysis command
- [x] Token estimation
- [x] Duplicate detection
- [x] Actual MCP server connection for accurate tool counts (`--live` mode)

### v0.2 - Tracking
- [x] Usage tracking via Claude Code hooks
- [x] Last-used timestamps
- [x] Usage frequency reports (`stats` command)
- [x] Hook management (`hook install/uninstall/status`)

### v0.3 - Optimization
- [x] Automatic optimization suggestions (`optimize` command)
- [x] Profile management (`profile suggest/create/show`)
- [x] Unused server detection
- [x] Rarely-used server detection
- [x] High-cost server warnings
- [x] Project type detection and server recommendations

### v0.4 - Apply & CI
- [x] Automatic optimization apply (`optimize --apply`)
- [x] Dry run mode (`optimize --dry-run`)
- [x] Config file backup before changes
- [x] CI mode with token threshold (`optimize --ci`)

### v0.5 (Current) - Export & Actions
- [x] Export statistics (`stats --export csv/json`)
- [x] GitHub Actions integration (`action.yml`)
- [x] Install recommended servers (`profile install`)

## Development

```bash
# Clone the repository
git clone https://github.com/o8n/mcp-optimizer.git
cd mcp-optimizer

# Install dependencies
npm install

# Build
npm run build

# Run locally
node dist/cli.js analyze
```

## License

MIT