feat: Add installation tool, Claude.ai export, and skill standardization (#1)

## Summary

- Add portable installation tool (`install.sh`) for cross-machine setup
- Add Claude.ai export files with proper YAML frontmatter
- Add multi-agent-guide v2.0 with consolidated framework template
- Rename `00-claude-code-setting` → `00-our-settings-audit` (avoid reserved word)
- Add YAML frontmatter to 25+ SKILL.md files for Claude Desktop compatibility

## Commits Included

- `93f604a` feat: Add portable installation tool for cross-machine setup
- `9b84104` feat: Add Claude.ai export for portable skill installation
- `f7ab973` fix: Add YAML frontmatter to Claude.ai export files
- `3fed49a` feat(multi-agent-guide): Add v2.0 with consolidated framework
- `3be26ef` refactor: Rename settings-audit skill and add YAML frontmatter

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Andrew Yim
2026-02-03 16:48:06 +07:00
committed by GitHub
parent 0bc24d00b9
commit b6a478e1df
72 changed files with 4770 additions and 803 deletions

View File

@@ -0,0 +1,125 @@
# Claude Settings Optimizer
Self-audit and optimize Claude configuration for maximum token efficiency.
**Supports both Claude Code (CLI) and Claude Desktop (App).**
## Purpose
- **Diagnose all Claude errors** (8 categories covered)
- Analyze token usage across MCP servers, CLAUDE.md, and extensions
- Troubleshoot MCP connection issues
- Identify optimization opportunities
- Auto-fix common issues with backup safety (Code version)
- Keep working context at 70%+ of 200K limit
## Platform Versions
| Version | Path | Use Case |
|---------|------|----------|
| **Claude Code** | `code/` | CLI with automated scripts |
| **Claude Desktop** | `desktop/` | App-based manual guidance |
## Claude Code Quick Start
```bash
# Install
cd custom-skills/00-our-settings-audit/code
chmod +x install.sh
./install.sh
# Run audit
python3 scripts/run_audit.py
# Apply fixes
python3 scripts/auto_fix.py --apply
```
## Claude Desktop Quick Start
Covers **8 error categories**:
| Category | Example Errors |
|----------|----------------|
| Context/Input | "Exceed response limit" |
| Output | "Response could not be fully generated" |
| Length/File | "Message will exceed length limit", "Files larger than 10mb" |
| Usage Limits | "5-hour limit reached", "X messages left" |
| Server/Capacity | "Unexpected capacity constraints" |
| MCP Connection | "Error connecting to [ServerName]" |
| Account | "Account has been disabled", login errors |
| Output Quality | Output cutoff, gibberish, mixed languages |
**When encountering any error:**
1. Use the Quick Diagnosis Tree in `desktop/SKILL.md`
2. Follow category-specific troubleshooting steps
3. Apply prevention checklist recommendations
**For MCP issues**, share your config file:
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
## What Gets Analyzed
| Component | Checks |
|-----------|--------|
| **MCP Servers** | serverInstructions presence, token estimates, load strategy |
| **CLAUDE.md** | Line count, token estimate, structure quality |
| **Commands** | Frontmatter, description, size limits |
| **Skills** | SKILL.md presence, size limits |
| **Agents** | Tool restrictions |
## Target Metrics
| Metric | Target | Max |
|--------|--------|-----|
| CLAUDE.md tokens | 2,000 | 3,000 |
| MCP tokens (with Tool Search) | 5,000 | 10,000 |
| Baseline total | <30% | <40% |
| Available for work | >70% | — |
## Files
```
00-our-settings-audit/
├── README.md
├── code/ # Claude Code (CLI)
│ ├── CLAUDE.md # Skill directive
│ ├── install.sh # Installation script
│ ├── commands/
│ │ └── settings-audit.md # /settings-audit command
│ ├── scripts/
│ │ ├── run_audit.py # Main orchestrator
│ │ ├── analyze_tokens.py # Token analysis
│ │ ├── analyze_extensions.py
│ │ └── auto_fix.py # Auto-fix with backup
│ └── references/
│ └── token-optimization.md
└── desktop/ # Claude Desktop (App)
├── skill.yaml # Skill metadata
├── SKILL.md # Diagnosis workflow (8 error categories)
├── references/
│ ├── config-locations.md # Config file paths
│ ├── mcp-token-estimates.md # Token budget guide
│ └── our-settings-audit.md # Claude.ai project reference
└── examples/
└── sample-audit-report.md # Example output
```
## Auto-Fix Capabilities
**Safe (automatic with backup):**
- Add serverInstructions to MCP servers
- Add frontmatter to commands
**Manual review required:**
- Disabling MCP servers
- Restructuring CLAUDE.md
- Removing extensions
## Requirements
- Python 3.8+
- PyYAML (optional, for better frontmatter parsing)

View File

@@ -0,0 +1,119 @@
# Claude Code Settings Optimizer
Self-audit and optimize Claude Code configuration for maximum token efficiency and performance.
## Core Focus
1. **Token Budget Management** - Keep baseline under 30% of 200K context
2. **MCP Tool Loading Strategy** - Essential tools always, others lazy-loaded
3. **CLAUDE.md Optimization** - Concise, structured, under 200 lines
4. **Context Preservation** - Maintain original prompt context throughout session
## Quick Commands
```bash
# Run full audit
python3 scripts/run_audit.py
# Check token usage only
python3 scripts/analyze_tokens.py
# Auto-fix with preview
python3 scripts/auto_fix.py
# Apply fixes
python3 scripts/auto_fix.py --apply
```
## Audit Scope
### 1. Token Usage Analysis
| Component | Target | Max | Action if Exceeded |
|-----------|--------|-----|-------------------|
| CLAUDE.md | 2,000 | 3,000 | Compress/split |
| MCP Servers | 5,000 | 10,000 | Enable Tool Search, add serverInstructions |
| Skills metadata | 500 | 1,000 | Reduce descriptions |
| **Working space** | **>140,000** | — | Goal: 70%+ available |
### 2. MCP Server Strategy
**Load Strategy Classification:**
| Strategy | Criteria | Action |
|----------|----------|--------|
| `always` | Essential for daily work (Playwright, Notion) | Keep loaded |
| `lazy` | Occasionally needed (GitHub, Slack) | Load on demand |
| `disable` | Rarely used or token-heavy (Zapier 50+ tools) | Turn off |
**Critical Check:** Every MCP server MUST have `serverInstructions` for Tool Search to work efficiently.
### 3. CLAUDE.md Health
Check for:
- Line count (warn >200)
- Token estimate (warn >3,000)
- Structure quality (headers, lists vs wall of text)
- Redundant information
- Information Claude already knows (don't repeat)
### 4. Extension Efficiency
- Commands: Has frontmatter? Under 100 lines?
- Skills: SKILL.md present? Under 500 lines?
- Agents: Tools restricted appropriately?
## Output Report
```markdown
# Claude Code Settings Audit
## Token Budget
- Baseline usage: X / 200,000 (Y%)
- Available for work: Z tokens
## Health Status
- Overall: [Good/Needs Attention/Critical]
- MCP Servers: X configured, Y missing instructions
- CLAUDE.md: X lines, ~Y tokens
## Findings
### Critical (must fix)
### Warnings (should fix)
### Passing (good)
## Recommendations
[Prioritized action items]
```
## Auto-Fix Capabilities
Safe fixes applied automatically (with backup):
- Add `serverInstructions` to MCP servers
- Add frontmatter to commands missing it
- Suggest CLAUDE.md compression
Manual review required:
- Disabling MCP servers
- Restructuring CLAUDE.md content
- Removing unused extensions
## Best Practices
### Token Optimization Principles
1. **CLAUDE.md**: Only include what Claude doesn't already know
2. **MCP Servers**: Use `serverInstructions` for Tool Search discovery
3. **Skills**: Keep SKILL.md brief, details in `references/`
4. **Context**: Run `/compact` at 70% usage, `/clear` between unrelated tasks
### Ideal Configuration
```
Context Budget: 200,000 tokens
├── System prompt: ~5,000 (fixed)
├── CLAUDE.md: ~2,000 (your control)
├── MCP tools: ~5,000 (with Tool Search)
├── Skills: ~500 (metadata only)
└── Available: ~187,500 (93.75%)
```

View File

@@ -0,0 +1,119 @@
---
description: Audit Claude Code settings for token efficiency. Analyzes MCP servers, CLAUDE.md, extensions and provides optimization recommendations.
argument-hint: [--fix] [--tokens-only]
allowed-tools: Read, Glob, Grep, Bash, Write
---
# Claude Code Settings Audit
Audit your Claude Code configuration to optimize token usage and performance.
## Arguments
- `--fix`: Apply safe fixes automatically (with backup)
- `--tokens-only`: Quick token budget check only
## Audit Process
### 1. Token Budget Check
Calculate current baseline token usage:
```bash
# Quick estimation
echo "=== Token Budget Estimation ==="
```
**Targets:**
- CLAUDE.md: <3,000 tokens (~200 lines)
- MCP with Tool Search: <10,000 tokens
- Working space: >70% of 200K context
### 2. MCP Server Analysis
Check locations:
- `~/.claude/settings.json`
- `./.claude/settings.json`
For each server, evaluate:
- [ ] Has `serverInstructions` (CRITICAL for Tool Search)
- [ ] Appropriate load strategy (always/lazy/disable)
- [ ] Token impact estimation
**Server Token Estimates:**
| Server | Tokens | Strategy |
|--------|--------|----------|
| Playwright | ~13,500 | always |
| Notion | ~5,000 | always |
| GitHub | ~18,000 | lazy |
| PostgreSQL | ~8,000 | lazy |
| Zapier | ~25,000+ | disable |
### 3. CLAUDE.md Analysis
Check:
- `~/.claude/CLAUDE.md` (global)
- `./CLAUDE.md` (project)
Evaluate:
- [ ] Line count (critical if >200)
- [ ] Token estimate (critical if >3,000)
- [ ] Good structure (headers, lists, not wall of text)
- [ ] No redundant information
- [ ] No information Claude already knows
### 4. Extensions Analysis
**Commands** (`~/.claude/commands/`):
- Has YAML frontmatter with description?
- Under 100 lines?
**Skills** (`~/.claude/skills/`):
- Has SKILL.md?
- Under 500 lines?
**Agents** (`~/.claude/agents/`):
- Tools appropriately restricted?
## Output Format
```markdown
# Settings Audit Report
Generated: [timestamp]
## Token Budget Summary
| Component | Tokens | % of 200K | Status |
|-----------|--------|-----------|--------|
| CLAUDE.md | X | Y% | OK/WARN/CRITICAL |
| MCP Servers | X | Y% | OK/WARN/CRITICAL |
| Extensions | X | Y% | OK/WARN/CRITICAL |
| **Baseline** | **X** | **Y%** | — |
| **Available** | **X** | **Y%** | — |
## Critical Issues
[Must fix immediately]
## Warnings
[Should address soon]
## Recommendations
1. [Prioritized action]
2. [...]
## Auto-Fix Available
[List of safe fixes that can be applied with --fix]
```
## Quick Fixes
If `--fix` is provided:
1. Add `serverInstructions` to MCP servers missing them
2. Add frontmatter to commands missing it
3. Create backup before any changes
## Execution
1. Run token budget analysis first
2. Analyze each component
3. Generate prioritized report
4. Offer auto-fix if issues found
5. Save report to `./settings-audit-report.md`

View File

@@ -0,0 +1,68 @@
#!/bin/bash
# Claude Code Settings Optimizer - Installation Script
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CLAUDE_DIR="${HOME}/.claude"
echo "Claude Code Settings Optimizer - Installer"
echo "==========================================="
echo ""
# Create directories
echo "Creating directories..."
mkdir -p "${CLAUDE_DIR}/commands"
mkdir -p "${CLAUDE_DIR}/scripts/settings-audit"
mkdir -p "${CLAUDE_DIR}/references"
# Install command
echo "Installing /settings-audit command..."
cp "${SCRIPT_DIR}/commands/settings-audit.md" "${CLAUDE_DIR}/commands/"
# Install scripts
echo "Installing scripts..."
cp "${SCRIPT_DIR}/scripts/"*.py "${CLAUDE_DIR}/scripts/settings-audit/"
chmod +x "${CLAUDE_DIR}/scripts/settings-audit/"*.py
# Install references
echo "Installing references..."
cp "${SCRIPT_DIR}/references/"*.md "${CLAUDE_DIR}/references/"
# Check Python
echo ""
echo "Checking Python..."
if command -v python3 &> /dev/null; then
echo " Python 3: $(python3 --version)"
else
echo " Warning: Python 3 not found"
fi
# Check PyYAML (optional)
if python3 -c "import yaml" 2>/dev/null; then
echo " PyYAML: installed"
else
echo " PyYAML: not installed (optional)"
echo " Install with: pip3 install pyyaml"
fi
echo ""
echo "Installation complete!"
echo ""
echo "Installed to:"
echo " Command: ${CLAUDE_DIR}/commands/settings-audit.md"
echo " Scripts: ${CLAUDE_DIR}/scripts/settings-audit/"
echo " References: ${CLAUDE_DIR}/references/"
echo ""
echo "Usage:"
echo " In Claude Code: /settings-audit"
echo ""
echo " Or run directly:"
echo " python3 ${CLAUDE_DIR}/scripts/settings-audit/run_audit.py"
echo ""
echo " Auto-fix (preview):"
echo " python3 ${CLAUDE_DIR}/scripts/settings-audit/auto_fix.py"
echo ""
echo " Auto-fix (apply):"
echo " python3 ${CLAUDE_DIR}/scripts/settings-audit/auto_fix.py --apply"
echo ""

View File

@@ -0,0 +1,159 @@
# Token Optimization Best Practices
## Context Window Budget
**Total Available:** 200,000 tokens
### Budget Allocation
| Component | Target | Max | Notes |
|-----------|--------|-----|-------|
| System prompt | ~5,000 | Fixed | Claude Code internal |
| CLAUDE.md | 2,000 | 3,000 | Under your control |
| MCP Servers | 5,000 | 10,000 | With Tool Search enabled |
| Skills metadata | 500 | 1,000 | Description + frontmatter only |
| **Working space** | **>140,000** | — | **Goal: 70%+ available** |
### Why 70%+ Available?
- Complex tasks need context for code, files, conversation
- Long sessions accumulate context
- Safety buffer prevents truncation
## MCP Server Optimization
### serverInstructions (CRITICAL)
Every MCP server MUST have `serverInstructions` for Tool Search to work:
```json
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@anthropic-ai/mcp-playwright"],
"serverInstructions": "Browser automation. Use for: SEO audits, screenshots, page analysis. Keywords: browser, page, DOM, screenshot"
}
}
}
```
**Pattern:** `[What it does]. Use for: [use case 1], [use case 2]. Keywords: [keyword1], [keyword2]`
### Load Strategies
| Strategy | When to Use | Example Servers |
|----------|-------------|-----------------|
| **always** | Essential for daily work | Playwright, Notion, Filesystem |
| **lazy** | Occasionally needed | GitHub, PostgreSQL, Slack |
| **disable** | Rarely used or token-heavy | Zapier (25K+ tokens) |
### Token Estimates by Server
| Server | Approx. Tokens | Strategy |
|--------|----------------|----------|
| Playwright | 13,500 | always |
| Notion | 5,000 | always |
| GitHub | 18,000 | lazy |
| PostgreSQL | 8,000 | lazy |
| Zapier | 25,000+ | disable |
| Memory | 3,000 | lazy |
| Filesystem | 4,000 | always |
## CLAUDE.md Optimization
### Size Limits
- **Lines:** Under 200
- **Tokens:** Under 3,000 (~2,300 words)
### What to Include
1. **Role context** (1-2 sentences)
2. **Output preferences** (format, language)
3. **Domain standards** (brief, essential only)
4. **Available commands** (reference list)
5. **Quality checklist** (3-5 items)
### What to Exclude
- Self-descriptions ("You are Claude...")
- Information Claude already knows
- Verbose explanations
- Long code examples (use skills instead)
- Duplicate information
### Optimal Structure
```markdown
# Project Context
## Role
[1-2 sentences]
## Preferences
- Output: [format]
- Language: [preference]
## Standards
### Domain 1
- [Key point 1]
- [Key point 2]
## Commands
- /command1: [brief description]
- /command2: [brief description]
## Checklist
- [ ] Item 1
- [ ] Item 2
```
## Session Management
### During Work
1. **Check context:** Run `/context` before complex tasks
2. **Compact early:** Run `/compact` at 70% usage
3. **Clear between tasks:** Run `/clear` for unrelated work
### Weekly Maintenance
1. Run `/doctor` for MCP health
2. Review command usage patterns
3. Update CLAUDE.md with new patterns
4. Check for unused extensions
### Monthly Audit
1. Run full settings audit
2. Review and prune unused MCP servers
3. Update serverInstructions
4. Check for new optimization opportunities
## Quick Diagnostics
### High Token Usage Signs
- Slow response times
- Context getting truncated
- Claude "forgetting" earlier context
### Common Fixes
| Issue | Fix |
|-------|-----|
| CLAUDE.md too long | Move details to skills/references |
| MCP missing instructions | Add serverInstructions |
| Too many always-loaded MCPs | Switch some to lazy |
| Unused extensions | Remove or disable |
## Commands Reference
| Command | Purpose |
|---------|---------|
| `/context` | Check current context usage |
| `/compact` | Compress context |
| `/clear` | Clear conversation |
| `/doctor` | Check MCP server health |
| `/settings-audit` | Run this skill's audit |

View File

@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""
Extensions Analyzer
Analyzes Claude Code commands, skills, and agents.
"""
import json
import re
import sys
from pathlib import Path
try:
import yaml
HAS_YAML = True
except ImportError:
HAS_YAML = False
MAX_COMMAND_LINES = 100
MAX_SKILL_LINES = 500
class ExtensionsAnalyzer:
def __init__(self):
self.findings = {
"critical": [],
"warnings": [],
"passing": [],
"recommendations": []
}
self.commands = {}
self.skills = {}
self.agents = {}
def find_extension_dirs(self) -> dict:
"""Find extension directories."""
base_paths = [
Path.home() / ".claude",
Path.cwd() / ".claude",
]
dirs = {"commands": [], "skills": [], "agents": []}
for base in base_paths:
for ext_type in dirs.keys():
path = base / ext_type
if path.exists() and path.is_dir():
dirs[ext_type].append(path)
return dirs
def parse_frontmatter(self, content: str) -> dict | None:
"""Parse YAML frontmatter."""
if not content.startswith('---'):
return None
try:
end = content.find('---', 3)
if end == -1:
return None
yaml_content = content[3:end].strip()
if HAS_YAML:
return yaml.safe_load(yaml_content)
else:
# Basic parsing without yaml
result = {}
for line in yaml_content.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
result[key.strip()] = value.strip()
return result
except Exception:
return None
def analyze_command(self, path: Path) -> dict:
"""Analyze a command file."""
try:
content = path.read_text()
except IOError:
return {"name": path.stem, "error": "Could not read"}
lines = len(content.split('\n'))
frontmatter = self.parse_frontmatter(content)
analysis = {
"name": path.stem,
"lines": lines,
"has_frontmatter": frontmatter is not None,
"has_description": frontmatter and "description" in frontmatter,
"issues": []
}
if not analysis["has_frontmatter"]:
analysis["issues"].append("Missing YAML frontmatter")
elif not analysis["has_description"]:
analysis["issues"].append("Missing description")
if lines > MAX_COMMAND_LINES:
analysis["issues"].append(f"Too long: {lines} lines (max {MAX_COMMAND_LINES})")
if not re.match(r'^[a-z][a-z0-9-]*$', analysis["name"]):
analysis["issues"].append("Name should be kebab-case")
return analysis
def analyze_skill(self, path: Path) -> dict:
"""Analyze a skill directory."""
skill_md = path / "SKILL.md"
if not skill_md.exists():
return {
"name": path.name,
"error": "Missing SKILL.md",
"issues": ["Missing SKILL.md"]
}
try:
content = skill_md.read_text()
except IOError:
return {"name": path.name, "error": "Could not read SKILL.md", "issues": []}
lines = len(content.split('\n'))
frontmatter = self.parse_frontmatter(content)
analysis = {
"name": path.name,
"lines": lines,
"has_frontmatter": frontmatter is not None,
"has_description": frontmatter and "description" in frontmatter,
"issues": []
}
if not analysis["has_frontmatter"]:
analysis["issues"].append("Missing frontmatter in SKILL.md")
if lines > MAX_SKILL_LINES:
analysis["issues"].append(f"Too long: {lines} lines (max {MAX_SKILL_LINES})")
return analysis
def analyze_agent(self, path: Path) -> dict:
"""Analyze an agent file."""
try:
content = path.read_text()
except IOError:
return {"name": path.stem, "error": "Could not read", "issues": []}
frontmatter = self.parse_frontmatter(content)
analysis = {
"name": path.stem,
"has_frontmatter": frontmatter is not None,
"tools_restricted": False,
"issues": []
}
if frontmatter:
tools = frontmatter.get("tools", "*")
analysis["tools_restricted"] = tools != "*" and tools
if not analysis["has_frontmatter"]:
analysis["issues"].append("Missing frontmatter")
if not analysis["tools_restricted"]:
analysis["issues"].append("Tools not restricted (consider limiting)")
return analysis
def analyze(self) -> dict:
"""Run full analysis."""
dirs = self.find_extension_dirs()
# Analyze commands
for cmd_dir in dirs["commands"]:
for cmd_file in cmd_dir.glob("*.md"):
analysis = self.analyze_command(cmd_file)
self.commands[analysis["name"]] = analysis
if analysis.get("issues"):
for issue in analysis["issues"]:
self.findings["warnings"].append(f"Command '{analysis['name']}': {issue}")
else:
self.findings["passing"].append(f"Command '{analysis['name']}': OK")
# Analyze skills
for skill_dir in dirs["skills"]:
for skill_path in skill_dir.iterdir():
if skill_path.is_dir():
analysis = self.analyze_skill(skill_path)
self.skills[analysis["name"]] = analysis
if analysis.get("issues"):
for issue in analysis["issues"]:
if "Missing SKILL.md" in issue:
self.findings["critical"].append(f"Skill '{analysis['name']}': {issue}")
else:
self.findings["warnings"].append(f"Skill '{analysis['name']}': {issue}")
else:
self.findings["passing"].append(f"Skill '{analysis['name']}': OK")
# Analyze agents
for agent_dir in dirs["agents"]:
for agent_file in agent_dir.glob("*.md"):
analysis = self.analyze_agent(agent_file)
self.agents[analysis["name"]] = analysis
if analysis.get("issues"):
for issue in analysis["issues"]:
self.findings["warnings"].append(f"Agent '{analysis['name']}': {issue}")
else:
self.findings["passing"].append(f"Agent '{analysis['name']}': OK")
return {
"commands_count": len(self.commands),
"skills_count": len(self.skills),
"agents_count": len(self.agents),
"commands": self.commands,
"skills": self.skills,
"agents": self.agents,
"findings": self.findings
}
def main():
analyzer = ExtensionsAnalyzer()
report = analyzer.analyze()
print(json.dumps(report, indent=2, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,258 @@
#!/usr/bin/env python3
"""
Token Usage Analyzer
Analyzes MCP servers and CLAUDE.md for token efficiency.
"""
import json
import sys
from pathlib import Path
# Token estimates for known MCP servers
MCP_TOKEN_ESTIMATES = {
"playwright": 13500,
"puppeteer": 13500,
"notion": 5000,
"github": 18000,
"postgres": 8000,
"postgresql": 8000,
"bigquery": 10000,
"firecrawl": 6000,
"zapier": 25000,
"slack": 8000,
"linear": 6000,
"memory": 3000,
"filesystem": 4000,
"brave-search": 3000,
"fetch": 2000,
"sequential-thinking": 2000,
"chrome-devtools": 8000,
"dtm-agent": 5000,
}
# Load strategy recommendations
LOAD_STRATEGIES = {
"playwright": "always",
"puppeteer": "always",
"notion": "always",
"github": "lazy",
"postgres": "lazy",
"postgresql": "lazy",
"bigquery": "lazy",
"firecrawl": "lazy",
"zapier": "disable",
"slack": "lazy",
"linear": "lazy",
"memory": "lazy",
"filesystem": "always",
"chrome-devtools": "always",
}
TOKENS_PER_WORD = 1.3
MAX_CLAUDE_MD_LINES = 200
MAX_CLAUDE_MD_TOKENS = 3000
class TokenAnalyzer:
def __init__(self):
self.findings = {
"critical": [],
"warnings": [],
"passing": [],
"recommendations": []
}
self.mcp_servers = {}
self.claude_md_files = []
self.mcp_tokens = 0
self.claude_md_tokens = 0
def find_settings_files(self) -> list:
"""Find MCP settings files."""
locations = [
Path.home() / ".claude" / "settings.json",
Path.cwd() / ".claude" / "settings.json",
Path.cwd() / ".mcp.json",
]
return [p for p in locations if p.exists()]
def find_claude_md_files(self) -> list:
"""Find CLAUDE.md files."""
locations = [
Path.home() / ".claude" / "CLAUDE.md",
Path.cwd() / "CLAUDE.md",
Path.cwd() / ".claude" / "CLAUDE.md",
]
return [p for p in locations if p.exists()]
def estimate_server_tokens(self, name: str) -> int:
"""Estimate tokens for a server."""
name_lower = name.lower()
for key, tokens in MCP_TOKEN_ESTIMATES.items():
if key in name_lower:
return tokens
return 5000 # Default estimate
def get_load_strategy(self, name: str, config: dict = None) -> str:
"""Get load strategy - checks actual config first, then recommendations."""
# Check actual autoStart setting in config
if config and config.get("autoStart") is False:
return "lazy"
name_lower = name.lower()
for key, strategy in LOAD_STRATEGIES.items():
if key in name_lower:
return strategy
return "lazy" # Default to lazy for unknown
def analyze_mcp_servers(self):
"""Analyze MCP server configurations."""
settings_files = self.find_settings_files()
if not settings_files:
self.findings["warnings"].append("No MCP settings files found")
return
for settings_path in settings_files:
try:
with open(settings_path) as f:
settings = json.load(f)
except (json.JSONDecodeError, IOError) as e:
self.findings["warnings"].append(f"Could not parse {settings_path}: {e}")
continue
servers = settings.get("mcpServers", {})
for name, config in servers.items():
if not isinstance(config, dict):
continue
tokens = self.estimate_server_tokens(name)
has_instructions = "serverInstructions" in config
strategy = self.get_load_strategy(name, config)
self.mcp_servers[name] = {
"tokens": tokens,
"has_instructions": has_instructions,
"strategy": strategy,
"source": str(settings_path)
}
# Only count "always" servers for baseline
if strategy == "always":
self.mcp_tokens += tokens
# Generate findings
if not has_instructions:
self.findings["critical"].append(
f"MCP '{name}': Missing serverInstructions (breaks Tool Search)"
)
else:
self.findings["passing"].append(f"MCP '{name}': Has serverInstructions")
if tokens > 15000 and strategy == "always":
self.findings["warnings"].append(
f"MCP '{name}': Heavy server (~{tokens:,} tokens), consider lazy loading"
)
def analyze_claude_md(self):
"""Analyze CLAUDE.md files."""
files = self.find_claude_md_files()
if not files:
self.findings["warnings"].append("No CLAUDE.md files found")
return
for path in files:
try:
content = path.read_text()
except IOError as e:
self.findings["warnings"].append(f"Could not read {path}: {e}")
continue
lines = len(content.split('\n'))
words = len(content.split())
tokens = int(words * TOKENS_PER_WORD)
self.claude_md_files.append({
"path": str(path),
"lines": lines,
"words": words,
"tokens": tokens
})
self.claude_md_tokens += tokens
# Generate findings
if tokens > MAX_CLAUDE_MD_TOKENS:
self.findings["critical"].append(
f"CLAUDE.md ({path.name}): ~{tokens:,} tokens exceeds {MAX_CLAUDE_MD_TOKENS:,} limit"
)
elif lines > MAX_CLAUDE_MD_LINES:
self.findings["warnings"].append(
f"CLAUDE.md ({path.name}): {lines} lines exceeds {MAX_CLAUDE_MD_LINES} recommended"
)
else:
self.findings["passing"].append(
f"CLAUDE.md ({path.name}): {lines} lines, ~{tokens:,} tokens - Good"
)
# Check structure
if '\n\n\n' in content:
self.findings["warnings"].append(
f"CLAUDE.md ({path.name}): Contains excessive whitespace"
)
# Check for common redundancy
content_lower = content.lower()
if "you are claude" in content_lower or "you are an ai" in content_lower:
self.findings["recommendations"].append(
f"CLAUDE.md ({path.name}): Remove self-descriptions Claude already knows"
)
def analyze(self) -> dict:
"""Run full analysis."""
self.analyze_mcp_servers()
self.analyze_claude_md()
total_tokens = self.mcp_tokens + self.claude_md_tokens
usage_pct = (total_tokens / 200000) * 100
# Overall recommendations
if usage_pct > 30:
self.findings["critical"].append(
f"Baseline uses {usage_pct:.1f}% of context - target is under 30%"
)
elif usage_pct > 20:
self.findings["warnings"].append(
f"Baseline uses {usage_pct:.1f}% of context - consider optimization"
)
missing_instructions = sum(
1 for s in self.mcp_servers.values() if not s.get("has_instructions")
)
if missing_instructions > 0:
self.findings["recommendations"].append(
f"Add serverInstructions to {missing_instructions} MCP server(s) for Tool Search"
)
return {
"total_tokens": total_tokens,
"mcp_tokens": self.mcp_tokens,
"claude_md_tokens": self.claude_md_tokens,
"mcp_count": len(self.mcp_servers),
"mcp_servers": self.mcp_servers,
"claude_md_files": self.claude_md_files,
"usage_percentage": round(usage_pct, 1),
"findings": self.findings
}
def main():
analyzer = TokenAnalyzer()
report = analyzer.analyze()
print(json.dumps(report, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""
Auto-Fix Script
Applies safe fixes to Claude Code configuration with backup.
"""
import json
import shutil
import sys
from datetime import datetime
from pathlib import Path
# serverInstructions templates for common MCP servers
SERVER_INSTRUCTIONS = {
"playwright": "Browser automation for web interaction. Use for: SEO audits, page analysis, screenshots, form testing, Core Web Vitals. Keywords: browser, page, screenshot, click, navigate, DOM, selector",
"puppeteer": "Chrome automation for web testing. Use for: SEO audits, page rendering, JavaScript site testing. Keywords: browser, chrome, headless, screenshot, page",
"notion": "Notion workspace integration. Use for: saving research, documentation, project notes, knowledge base. Keywords: notion, page, database, wiki, notes, save",
"github": "GitHub repository management. Use for: commits, PRs, issues, code review. Keywords: git, github, commit, pull request, issue, repository",
"postgres": "PostgreSQL database queries. Use for: data analysis, SQL queries, analytics. Keywords: sql, query, database, table, select, analytics",
"postgresql": "PostgreSQL database queries. Use for: data analysis, SQL queries, analytics. Keywords: sql, query, database, table, select, analytics",
"bigquery": "Google BigQuery for large-scale analysis. Use for: analytics queries, data warehouse. Keywords: bigquery, sql, analytics, data warehouse",
"firecrawl": "Web scraping and crawling. Use for: site crawling, content extraction, competitor analysis. Keywords: crawl, scrape, extract, spider, sitemap",
"slack": "Slack workspace integration. Use for: messages, notifications, team communication. Keywords: slack, message, channel, notification",
"linear": "Linear issue tracking. Use for: issue management, project tracking. Keywords: linear, issue, task, project, sprint",
"memory": "Persistent memory across sessions. Use for: storing preferences, context recall. Keywords: remember, memory, store, recall",
"filesystem": "Local file operations. Use for: file reading/writing, directory management. Keywords: file, directory, read, write, path",
"chrome-devtools": "Chrome DevTools for debugging. Use for: GTM debugging, network analysis, console logs. Keywords: devtools, chrome, debug, network, console",
}
class AutoFixer:
def __init__(self, dry_run: bool = True):
self.dry_run = dry_run
self.fixes = []
self.backup_dir = Path.home() / ".claude" / "backups" / datetime.now().strftime("%Y%m%d_%H%M%S")
def backup_file(self, path: Path) -> bool:
"""Create backup before modifying."""
if not path.exists():
return True
try:
backup_path = self.backup_dir / path.relative_to(Path.home())
backup_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, backup_path)
return True
except Exception as e:
print(f"Warning: Could not backup {path}: {e}", file=sys.stderr)
return False
def fix_mcp_instructions(self, settings_path: Path) -> list:
"""Add serverInstructions to MCP servers."""
fixes = []
try:
with open(settings_path) as f:
settings = json.load(f)
except (json.JSONDecodeError, IOError) as e:
return [f"Error reading {settings_path}: {e}"]
servers = settings.get("mcpServers", {})
modified = False
for name, config in servers.items():
if not isinstance(config, dict):
continue
if "serverInstructions" in config:
continue
# Find matching template
instructions = None
name_lower = name.lower()
for key, template in SERVER_INSTRUCTIONS.items():
if key in name_lower:
instructions = template
break
if not instructions:
instructions = f"External tool: {name}. Use when this functionality is needed."
if self.dry_run:
fixes.append(f"[DRY RUN] Would add serverInstructions to '{name}'")
else:
config["serverInstructions"] = instructions
modified = True
fixes.append(f"Added serverInstructions to '{name}'")
if modified and not self.dry_run:
self.backup_file(settings_path)
with open(settings_path, 'w') as f:
json.dump(settings, f, indent=2)
return fixes
def fix_command_frontmatter(self, cmd_path: Path) -> str | None:
"""Add frontmatter to command missing it."""
try:
content = cmd_path.read_text()
except IOError:
return None
if content.startswith('---'):
return None
new_content = f'''---
description: {cmd_path.stem.replace('-', ' ').title()} command
---
{content}'''
if self.dry_run:
return f"[DRY RUN] Would add frontmatter to {cmd_path.name}"
self.backup_file(cmd_path)
cmd_path.write_text(new_content)
return f"Added frontmatter to {cmd_path.name}"
def run(self) -> dict:
"""Apply all fixes."""
results = {"applied": [], "skipped": [], "errors": []}
# Fix MCP settings
settings_paths = [
Path.home() / ".claude" / "settings.json",
Path.cwd() / ".claude" / "settings.json"
]
for path in settings_paths:
if path.exists():
fixes = self.fix_mcp_instructions(path)
results["applied"].extend(fixes)
# Fix commands without frontmatter
cmd_dirs = [
Path.home() / ".claude" / "commands",
Path.cwd() / ".claude" / "commands"
]
for cmd_dir in cmd_dirs:
if cmd_dir.exists():
for cmd_file in cmd_dir.glob("*.md"):
fix = self.fix_command_frontmatter(cmd_file)
if fix:
results["applied"].append(fix)
return results
def main():
import argparse
parser = argparse.ArgumentParser(description="Auto-fix Claude Code settings")
parser.add_argument("--apply", action="store_true", help="Apply fixes (default is dry-run)")
args = parser.parse_args()
fixer = AutoFixer(dry_run=not args.apply)
results = fixer.run()
print(json.dumps(results, indent=2))
if fixer.dry_run:
print("\n[DRY RUN] No changes applied. Use --apply to apply fixes.", file=sys.stderr)
else:
print(f"\n[APPLIED] {len(results['applied'])} fixes.", file=sys.stderr)
if fixer.backup_dir.exists():
print(f"Backups: {fixer.backup_dir}", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,7 @@
# Claude Code Settings Optimizer
# No external dependencies - uses only Python standard library
# json, sys, pathlib are built-in
# Optional: For future enhancements
# pyyaml>=6.0 # YAML parsing for MCP configs
# rich>=13.0 # Better terminal output

View File

@@ -0,0 +1,245 @@
#!/usr/bin/env python3
"""
Claude Code Settings Audit - Main Orchestrator
Analyzes configuration for token efficiency and optimization.
"""
import json
import sys
import subprocess
from pathlib import Path
from datetime import datetime
SCRIPT_DIR = Path(__file__).parent
CONTEXT_LIMIT = 200_000
def run_analyzer(script_name: str) -> dict:
"""Run an analyzer script and return its output."""
script_path = SCRIPT_DIR / script_name
if not script_path.exists():
return {"error": f"Script not found: {script_path}"}
try:
result = subprocess.run(
[sys.executable, str(script_path)],
capture_output=True,
text=True,
timeout=60
)
if result.returncode != 0 and not result.stdout:
return {"error": result.stderr or "Unknown error"}
return json.loads(result.stdout)
except subprocess.TimeoutExpired:
return {"error": "Analysis timed out"}
except json.JSONDecodeError as e:
return {"error": f"Invalid JSON: {e}"}
except Exception as e:
return {"error": str(e)}
def calculate_health(token_report: dict, extensions_report: dict) -> str:
"""Determine overall health status."""
total_tokens = token_report.get("total_tokens", 0)
usage_pct = (total_tokens / CONTEXT_LIMIT) * 100
critical_issues = len(token_report.get("findings", {}).get("critical", []))
critical_issues += len(extensions_report.get("findings", {}).get("critical", []))
if usage_pct > 30 or critical_issues > 2:
return "Critical"
elif usage_pct > 20 or critical_issues > 0:
return "Needs Attention"
return "Good"
def generate_report(token_report: dict, extensions_report: dict) -> str:
"""Generate markdown report."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
total_tokens = token_report.get("total_tokens", 0)
available = CONTEXT_LIMIT - total_tokens
usage_pct = (total_tokens / CONTEXT_LIMIT) * 100
available_pct = 100 - usage_pct
health = calculate_health(token_report, extensions_report)
health_emoji = {"Good": "🟢", "Needs Attention": "🟡", "Critical": "🔴"}[health]
# Collect all findings
all_critical = []
all_warnings = []
all_passing = []
all_recommendations = []
for report in [token_report, extensions_report]:
findings = report.get("findings", {})
all_critical.extend(findings.get("critical", []))
all_warnings.extend(findings.get("warnings", []))
all_passing.extend(findings.get("passing", []))
all_recommendations.extend(findings.get("recommendations", []))
report = f"""# Claude Code Settings Audit Report
**Generated:** {timestamp}
---
## Token Budget Summary
| Component | Tokens | % of 200K | Status |
|-----------|--------|-----------|--------|
| CLAUDE.md | {token_report.get('claude_md_tokens', 0):,} | {token_report.get('claude_md_tokens', 0)/CONTEXT_LIMIT*100:.1f}% | {'🟢' if token_report.get('claude_md_tokens', 0) < 3000 else '🔴'} |
| MCP Servers | {token_report.get('mcp_tokens', 0):,} | {token_report.get('mcp_tokens', 0)/CONTEXT_LIMIT*100:.1f}% | {'🟢' if token_report.get('mcp_tokens', 0) < 10000 else '🟡'} |
| **Baseline Total** | **{total_tokens:,}** | **{usage_pct:.1f}%** | {health_emoji} |
| **Available for Work** | **{available:,}** | **{available_pct:.1f}%** | — |
**Target:** Baseline under 30% (60,000 tokens), Available over 70%
---
## Overall Health: {health_emoji} {health}
- Critical Issues: {len(all_critical)}
- Warnings: {len(all_warnings)}
- Passing Checks: {len(all_passing)}
---
## MCP Server Analysis
**Servers:** {token_report.get('mcp_count', 0)} configured
"""
# MCP server details
mcp_servers = token_report.get("mcp_servers", {})
if mcp_servers:
report += "| Server | Tokens | Instructions | Strategy |\n"
report += "|--------|--------|--------------|----------|\n"
for name, info in mcp_servers.items():
instr = "" if info.get("has_instructions") else ""
tokens = info.get("tokens", 0)
strategy = info.get("strategy", "unknown")
report += f"| {name} | ~{tokens:,} | {instr} | {strategy} |\n"
report += "\n"
# CLAUDE.md analysis
report += f"""---
## CLAUDE.md Analysis
"""
claude_files = token_report.get("claude_md_files", [])
for cf in claude_files:
status = "🟢" if cf.get("tokens", 0) < 3000 else "🔴"
report += f"- **{cf.get('path', 'Unknown')}**: {cf.get('lines', 0)} lines, ~{cf.get('tokens', 0):,} tokens {status}\n"
if not claude_files:
report += "*No CLAUDE.md files found*\n"
# Extensions
report += f"""
---
## Extensions Analysis
- Commands: {extensions_report.get('commands_count', 0)}
- Skills: {extensions_report.get('skills_count', 0)}
- Agents: {extensions_report.get('agents_count', 0)}
"""
# Findings
if all_critical:
report += "---\n\n## ❌ Critical Issues\n\n"
for issue in all_critical:
report += f"- {issue}\n"
report += "\n"
if all_warnings:
report += "---\n\n## ⚠️ Warnings\n\n"
for warning in all_warnings[:10]:
report += f"- {warning}\n"
if len(all_warnings) > 10:
report += f"- *...and {len(all_warnings) - 10} more*\n"
report += "\n"
if all_passing:
report += "---\n\n## ✅ Passing\n\n"
for item in all_passing[:5]:
report += f"- {item}\n"
if len(all_passing) > 5:
report += f"- *...and {len(all_passing) - 5} more*\n"
report += "\n"
# Recommendations
if all_recommendations or all_critical:
report += "---\n\n## Recommendations\n\n"
priority = 1
for issue in all_critical[:3]:
report += f"{priority}. **Fix:** {issue}\n"
priority += 1
for rec in all_recommendations[:5]:
report += f"{priority}. {rec}\n"
priority += 1
report += "\n"
report += f"""---
## Next Steps
1. Run `python3 scripts/auto_fix.py` to preview fixes
2. Run `python3 scripts/auto_fix.py --apply` to apply fixes
3. Re-run audit to verify improvements
---
*Generated by Claude Code Settings Optimizer*
"""
return report
def main():
print("🔍 Running Claude Code Settings Audit...\n", file=sys.stderr)
print(" Analyzing tokens...", file=sys.stderr)
token_report = run_analyzer("analyze_tokens.py")
print(" Analyzing extensions...", file=sys.stderr)
extensions_report = run_analyzer("analyze_extensions.py")
print(" Generating report...\n", file=sys.stderr)
markdown_report = generate_report(token_report, extensions_report)
print(markdown_report)
# Save reports
output_dir = SCRIPT_DIR.parent if (SCRIPT_DIR.parent / "CLAUDE.md").exists() else Path.cwd()
report_path = output_dir / "settings-audit-report.md"
json_path = output_dir / "settings-audit-report.json"
full_report = {
"timestamp": datetime.now().isoformat(),
"tokens": token_report,
"extensions": extensions_report,
"total_baseline_tokens": token_report.get("total_tokens", 0),
"health": calculate_health(token_report, extensions_report)
}
try:
report_path.write_text(markdown_report)
json_path.write_text(json.dumps(full_report, indent=2, default=str))
print(f"📄 Report: {report_path}", file=sys.stderr)
print(f"📊 JSON: {json_path}", file=sys.stderr)
except IOError as e:
print(f"Warning: Could not save report: {e}", file=sys.stderr)
return 1 if full_report["health"] == "Critical" else 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,181 @@
{
"timestamp": "2026-01-23T18:06:32.896761",
"tokens": {
"total_tokens": 18911,
"mcp_tokens": 17500,
"claude_md_tokens": 1411,
"mcp_count": 10,
"mcp_servers": {
"filesystem": {
"tokens": 4000,
"has_instructions": true,
"strategy": "always",
"source": "/Users/ourdigital/.claude/settings.json"
},
"sqlite": {
"tokens": 5000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
},
"playwright": {
"tokens": 13500,
"has_instructions": true,
"strategy": "always",
"source": "/Users/ourdigital/.claude/settings.json"
},
"figma": {
"tokens": 5000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
},
"osascript": {
"tokens": 5000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
},
"firecrawl": {
"tokens": 6000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
},
"google-analytics": {
"tokens": 5000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
},
"chrome-devtools": {
"tokens": 8000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
},
"exa": {
"tokens": 5000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
},
"dtm-agent": {
"tokens": 5000,
"has_instructions": true,
"strategy": "lazy",
"source": "/Users/ourdigital/.claude/settings.json"
}
},
"claude_md_files": [
{
"path": "/Users/ourdigital/.claude/CLAUDE.md",
"lines": 110,
"words": 616,
"tokens": 800
},
{
"path": "/Users/ourdigital/Project/claude-skills/custom-skills/00-claude-code-setting/code/CLAUDE.md",
"lines": 120,
"words": 470,
"tokens": 611
}
],
"usage_percentage": 9.5,
"findings": {
"critical": [],
"warnings": [],
"passing": [
"MCP 'filesystem': Has serverInstructions",
"MCP 'sqlite': Has serverInstructions",
"MCP 'playwright': Has serverInstructions",
"MCP 'figma': Has serverInstructions",
"MCP 'osascript': Has serverInstructions",
"MCP 'firecrawl': Has serverInstructions",
"MCP 'google-analytics': Has serverInstructions",
"MCP 'chrome-devtools': Has serverInstructions",
"MCP 'exa': Has serverInstructions",
"MCP 'dtm-agent': Has serverInstructions",
"CLAUDE.md (CLAUDE.md): 110 lines, ~800 tokens - Good",
"CLAUDE.md (CLAUDE.md): 120 lines, ~611 tokens - Good"
],
"recommendations": []
}
},
"extensions": {
"commands_count": 1,
"skills_count": 1,
"agents_count": 5,
"commands": {
"settings-audit": {
"name": "settings-audit",
"lines": 120,
"has_frontmatter": false,
"has_description": null,
"issues": [
"Missing YAML frontmatter",
"Too long: 120 lines (max 100)"
]
}
},
"skills": {
"jamie-brand-guardian": {
"name": "jamie-brand-guardian",
"lines": 480,
"has_frontmatter": true,
"has_description": true,
"issues": []
}
},
"agents": {
"data-analyst": {
"name": "data-analyst",
"has_frontmatter": true,
"tools_restricted": "Read, Glob, Grep, Bash, Write",
"issues": []
},
"seo-advisor": {
"name": "seo-advisor",
"has_frontmatter": true,
"tools_restricted": "Read, Glob, Grep, WebFetch, WebSearch",
"issues": []
},
"python-coach": {
"name": "python-coach",
"has_frontmatter": true,
"tools_restricted": "Read, Glob, Grep, Bash, Write",
"issues": []
},
"gtm-manager": {
"name": "gtm-manager",
"has_frontmatter": true,
"tools_restricted": "Read, Glob, Grep, Bash, WebFetch, mcp__plugin_playwright_playwright__*",
"issues": []
},
"data-engineer": {
"name": "data-engineer",
"has_frontmatter": true,
"tools_restricted": "Read, Glob, Grep, Bash, Write",
"issues": []
}
},
"findings": {
"critical": [],
"warnings": [
"Command 'settings-audit': Missing YAML frontmatter",
"Command 'settings-audit': Too long: 120 lines (max 100)"
],
"passing": [
"Skill 'jamie-brand-guardian': OK",
"Agent 'data-analyst': OK",
"Agent 'seo-advisor': OK",
"Agent 'python-coach': OK",
"Agent 'gtm-manager': OK",
"Agent 'data-engineer': OK"
],
"recommendations": []
}
},
"total_baseline_tokens": 18911,
"health": "Good"
}

View File

@@ -0,0 +1,88 @@
# Claude Code Settings Audit Report
**Generated:** 2026-01-23 18:06:32
---
## Token Budget Summary
| Component | Tokens | % of 200K | Status |
|-----------|--------|-----------|--------|
| CLAUDE.md | 1,411 | 0.7% | 🟢 |
| MCP Servers | 17,500 | 8.8% | 🟡 |
| **Baseline Total** | **18,911** | **9.5%** | 🟢 |
| **Available for Work** | **181,089** | **90.5%** | — |
**Target:** Baseline under 30% (60,000 tokens), Available over 70%
---
## Overall Health: 🟢 Good
- Critical Issues: 0
- Warnings: 2
- Passing Checks: 18
---
## MCP Server Analysis
**Servers:** 10 configured
| Server | Tokens | Instructions | Strategy |
|--------|--------|--------------|----------|
| filesystem | ~4,000 | ✅ | always |
| sqlite | ~5,000 | ✅ | lazy |
| playwright | ~13,500 | ✅ | always |
| figma | ~5,000 | ✅ | lazy |
| osascript | ~5,000 | ✅ | lazy |
| firecrawl | ~6,000 | ✅ | lazy |
| google-analytics | ~5,000 | ✅ | lazy |
| chrome-devtools | ~8,000 | ✅ | lazy |
| exa | ~5,000 | ✅ | lazy |
| dtm-agent | ~5,000 | ✅ | lazy |
---
## CLAUDE.md Analysis
- **/Users/ourdigital/.claude/CLAUDE.md**: 110 lines, ~800 tokens 🟢
- **/Users/ourdigital/Project/claude-skills/custom-skills/00-claude-code-setting/code/CLAUDE.md**: 120 lines, ~611 tokens 🟢
---
## Extensions Analysis
- Commands: 1
- Skills: 1
- Agents: 5
---
## ⚠️ Warnings
- Command 'settings-audit': Missing YAML frontmatter
- Command 'settings-audit': Too long: 120 lines (max 100)
---
## ✅ Passing
- MCP 'filesystem': Has serverInstructions
- MCP 'sqlite': Has serverInstructions
- MCP 'playwright': Has serverInstructions
- MCP 'figma': Has serverInstructions
- MCP 'osascript': Has serverInstructions
- *...and 13 more*
---
## Next Steps
1. Run `python3 scripts/auto_fix.py` to preview fixes
2. Run `python3 scripts/auto_fix.py --apply` to apply fixes
3. Re-run audit to verify improvements
---
*Generated by Claude Code Settings Optimizer*

View File

@@ -0,0 +1,633 @@
---
name: our-settings-audit
description: |
Diagnose all Claude Desktop errors and optimize context usage.
Covers 8 error categories: context limits, output interruption,
length/file errors, usage limits, server capacity, MCP connection,
account issues, and output quality problems.
Triggers: settings audit, exceed response limit, MCP error, token error.
---
# Claude Desktop Settings Checker
Diagnose Claude Desktop errors and optimize context usage.
## Error Quick Reference
| Error Type | Message Pattern | Category |
|------------|-----------------|----------|
| Context too large | "Exceed response limit" | Input |
| Output interrupted | "Response could not be fully generated" | Output |
| Length exceeded | "Message will exceed the length limit" | Input |
| Conversation limit | "This conversation reached its maximum length" | Input |
| File too large | "Files larger than 10mb" / "X% over the length limit" | File |
| Rate limited | "5-hour limit reached" / "X messages left" | Usage |
| Server overload | "Due to unexpected capacity constraints" | Server |
| MCP failure | "Error connecting to [ServerName]" | MCP |
| Account issue | "Account has been disabled" | Account |
## Quick Diagnosis Tree
```
Error occurred?
├─ BEFORE response started?
│ ├─ "Exceed response limit" → Reduce input context
│ ├─ "Length limit" → Break into smaller messages
│ ├─ "File too large" → Reduce file size or excerpt
│ ├─ "Capacity constraints" → Wait and retry
│ └─ "MCP error" → Check MCP configuration
├─ DURING response?
│ ├─ "Could not be fully generated" → Request smaller output
│ └─ Output suddenly stopped → Retry or chunk request
└─ BEFORE even sending?
├─ "5-hour limit reached" → Wait for reset
├─ "Messages left" → Near usage limit
└─ "Account disabled" → Contact support
```
## Understanding Token Limits
| Model | Context Window | Output Limit | Practical Available |
|-------|---------------|--------------|---------------------|
| Claude 3.5 Sonnet | 200K tokens | ~8K tokens | ~150K after system |
| Claude 3 Opus | 200K tokens | ~4K tokens | ~150K after system |
| Claude 3 Haiku | 200K tokens | ~4K tokens | ~160K after system |
---
# CATEGORY 1: Input/Context Errors
## Error: "Exceed response limit"
**Causes:**
1. Loaded context too large (MCP tools + skills + files)
2. Conversation history accumulated
3. Multiple large files attached
## Quick Diagnosis
When user reports "Exceed response limit":
### Step 1: Check Loaded Context
Ask user to share their `claude_desktop_config.json`:
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
Analyze:
- [ ] Number of MCP servers configured
- [ ] Servers with many tools (>20 tools each)
- [ ] Missing or poor `serverInstructions`
### Step 2: Estimate Token Usage
| Component | Tokens (approx) | Notes |
|-----------|-----------------|-------|
| Per MCP server | 500-2,000 | Base overhead |
| Per tool definition | 100-500 | Depends on schema complexity |
| Playwright MCP | ~13,500 | 20+ tools, detailed schemas |
| Notion MCP | ~5,000 | Moderate |
| GitHub MCP | ~18,000 | Many tools |
| Custom SKILL.md | 200-2,000 | Depends on length |
| Attached file | Variable | ~4 tokens per word |
**Red flags:**
- More than 5 MCP servers active
- Any server without `serverInstructions`
- Total MCP tools > 100
### Step 3: Review Loaded Skills
Check for:
- Skills with long SKILL.md files (>1,000 words)
- Multiple skills loaded simultaneously
- Skills with embedded reference data
## Optimization Recommendations
### MCP Server Optimization
**Priority 1: Add serverInstructions**
Every MCP server needs concise instructions:
```json
{
"mcpServers": {
"playwright": {
"command": "...",
"serverInstructions": "Browser automation for web testing. Use for: screenshots, page analysis, form testing. Keywords: browser, DOM, screenshot"
}
}
}
```
Pattern: `[Purpose]. Use for: [case1], [case2]. Keywords: [kw1], [kw2]`
**Priority 2: Reduce Active Servers**
Keep only essential servers active. Disable or remove:
- Servers used less than weekly
- Servers with overlapping functionality
- Servers with 30+ tools (like Zapier)
### Conversation Management
**Before complex tasks:**
1. Start fresh conversation for unrelated work
2. Avoid attaching multiple large files
3. Request concise outputs
**During long sessions:**
1. Start new conversation at natural breakpoints
2. Summarize important context before continuing
3. Remove completed file attachments
### Project File Optimization
For project skills and configurations:
| File Type | Target Length | Max |
|-----------|--------------|-----|
| SKILL.md | 500 words | 1,000 words |
| Project instructions | 200 words | 500 words |
| Embedded data | 0 | Move to external |
**Optimization techniques:**
1. Move reference data to separate files (load on demand)
2. Use tables instead of prose
3. Remove redundant information
4. Link to documentation instead of embedding
## Token Budget Calculator
Help user calculate their baseline:
```
System overhead: ~10,000 tokens (fixed)
MCP servers: [count] × ~3,000 = [estimate]
Loaded skills: [count] × ~500 = [estimate]
Project instructions: ~[estimate based on length]
────────────────────────────────────────────────
Baseline total: [sum]
Available for work: 200,000 - [sum] = [remaining]
Available percentage: [remaining/200,000 × 100]%
```
**Targets:**
- Baseline: < 40,000 tokens (20%)
- Available: > 160,000 tokens (80%)
**Warning zone:**
- Baseline > 60,000 tokens: Likely to hit limits
- Available < 140,000 tokens: Reduce configuration
## Output Format
After diagnosis, provide:
```markdown
## Settings Check Report
### Configuration Summary
- MCP Servers: [count] ([tokens estimate])
- Active Skills: [count] ([tokens estimate])
- Baseline Total: ~[X] tokens ([Y]%)
- Available: ~[Z] tokens ([W]%)
### Issues Found
1. [Critical]: [issue description]
2. [Warning]: [issue description]
### Recommended Actions
1. [Action with specific steps]
2. [Action with specific steps]
### Quick Wins (immediate impact)
- [ ] [Specific change]
- [ ] [Specific change]
```
## Common Scenarios
### Scenario: Too Many MCP Servers
**Symptoms:** Errors on first message of conversation
**Solution:** Disable non-essential servers, add serverInstructions
### Scenario: Long Conversation History
**Symptoms:** Errors after many exchanges
**Solution:** Start new conversation, summarize context
### Scenario: Large File Attachments
**Symptoms:** Errors when attaching files
**Solution:** Attach smaller excerpts, use file references
### Scenario: Complex Skill Loaded
**Symptoms:** Errors when using specific skill
**Solution:** Refactor skill, move data to references
---
## Error 2: "Response could not be fully generated"
This error occurs when **output generation** is interrupted mid-stream.
### Causes
| Cause | Description | Frequency |
|-------|-------------|-----------|
| **Output token limit** | Response exceeded ~4K-8K output limit | Common |
| **Safety filter** | Content flagged during generation | Occasional |
| **Network interruption** | Connection dropped mid-stream | Occasional |
| **Server timeout** | Generation took too long | Rare |
| **Rate limiting** | Too many requests in short time | Rare |
### Common Triggers
**1. Requesting too much output:**
```
❌ "Write a complete 50-page report on..."
❌ "Generate the entire application code"
❌ "List all 500 items with full descriptions"
✅ "Write section 1: introduction and overview"
✅ "Generate the authentication module first"
✅ "List items 1-50 with descriptions"
```
**2. Vague prompts (produce longer responses):**
```
❌ "Explain everything about machine learning"
✅ "Explain gradient descent in 3 paragraphs"
```
**3. Code generation without scope:**
```
❌ "Build me a full-stack e-commerce site"
✅ "Create the product listing component with pagination"
```
### Solutions
| Situation | Fix |
|-----------|-----|
| Long report/document | Request section by section |
| Large codebase | Generate module by module |
| Comprehensive list | Paginate (1-50, 51-100, etc.) |
| Detailed explanation | Ask for "brief" or "concise" version |
| Transient failure | Simply retry the request |
### Prompting Techniques
**Add output constraints:**
- "In under 500 words..."
- "Provide a concise summary..."
- "List the top 10..."
- "Focus only on..."
**Chunk large tasks:**
- "First, outline the structure"
- "Now write section 1"
- "Continue with section 2"
**Request format control:**
- "Use bullet points, not paragraphs"
- "Provide a table summary"
- "Give me just the key points"
### When to Retry vs. Rephrase
| Scenario | Action |
|----------|--------|
| Error on first attempt | Retry once |
| Error persists after retry | Rephrase with smaller scope |
| Error always at same point | Content may be triggering filter |
| Error after long generation | Request was too ambitious |
---
# CATEGORY 3: Length & File Errors
## Error: "Your message will exceed the length limit"
**Full message:** "Your message will exceed the length limit for this chat..."
**Causes:**
- Single message too long (approaching context limit)
- Too much text pasted at once
**Solutions:**
1. Break content into smaller chunks
2. Summarize key sections before sending
3. Ask Claude to identify relevant portions first
4. Start a new conversation
## Error: "This conversation reached its maximum length"
**Cause:** Accumulated conversation history filled context window
**Solutions:**
1. Start a new conversation
2. Copy essential context to new chat
3. Use shorter exchanges going forward
## Error: "Message is X% over the length limit"
**Full message:** "Message is X% over the length limit. Try replacing the attached file with smaller excerpts."
**Cause:** Attached file(s) too large for remaining context
**Solutions:**
1. Extract relevant excerpts only
2. Summarize large documents before attaching
3. Split across multiple messages
4. Use file references instead of full content
## Error: "You may not upload files larger than 10MB"
**Cause:** Single file exceeds 10MB limit
**Solutions:**
1. Compress file if possible
2. Split into smaller files
3. Extract text content only
4. Use external link and describe content
---
# CATEGORY 4: Usage & Rate Limit Errors
## Error: "5-hour limit reached - resets [time]"
**Cause:** Hit plan's usage cap within 5-hour window
**Solutions:**
1. Wait until reset time shown
2. Upgrade plan for higher limits
3. Optimize prompts to use fewer tokens
## Error: "Approaching 5-hour limit"
**Cause:** Warning before hitting limit
**Solutions:**
1. Prioritize remaining important tasks
2. Use concise prompts
3. Avoid exploratory conversations
## Error: "X messages left until [time]"
**Cause:** Near message limit (free tier)
**Solutions:**
1. Combine multiple questions into one
2. Wait for reset
3. Consider paid plan
## Error: "5-hour limit resets [time] - continuing with extra usage"
**Note:** This is informational for paid plans with extra usage enabled
**Action:** Extra usage automatically continues; monitor costs
---
# CATEGORY 5: Server & Capacity Errors
## Error: "Due to unexpected capacity constraints, Claude is unable to respond"
**Cause:** High system-wide demand
**Solutions:**
1. Wait 2-5 minutes and retry
2. Try during off-peak hours
3. Check [status.claude.com](https://status.claude.com) for incidents
## HTTP Error Codes
| Code | Meaning | Solution |
|------|---------|----------|
| 500 | Internal Server Error | Wait and retry |
| 429 | Too Many Requests | Slow down, wait |
| 403 | Forbidden | Check account status |
| 400 | Bad Request | Check input format |
## Error: "Claude AI Saving Chat Failed"
**Cause:** Issue saving conversation to servers
**Solutions:**
1. Refresh the page
2. Check internet connection
3. Copy important content locally
4. Try again later
---
# CATEGORY 6: MCP Connection Errors
## Error: "There was an error connecting to [ServerName]"
**Causes:**
1. Server not running
2. Incorrect configuration
3. Transport type mismatch (stdio vs HTTP)
4. Authentication failure
### Diagnosis Steps
**Step 1: Check server logs**
- macOS: `~/Library/Logs/Claude/mcp-server-SERVERNAME.log`
- Windows: `%APPDATA%\Claude\logs\mcp-server-SERVERNAME.log`
**Step 2: Verify configuration**
```bash
# macOS
cat ~/Library/Application\ Support/Claude/claude_desktop_config.json
# Windows PowerShell
Get-Content "$env:APPDATA\Claude\claude_desktop_config.json"
```
**Step 3: Test server independently**
```bash
# Test if server starts
npx @anthropic-ai/mcp-server-name
```
### Common MCP Issues
| Issue | Symptom | Fix |
|-------|---------|-----|
| Transport mismatch | HTTP server with stdio config | Add `"transport": "http"` |
| Path with spaces | Server fails on Windows | Use escaped paths or `%APPDATA%` |
| Missing env vars | Auth failures | Add to `"env"` in config |
| Server not installed | "command not found" | Run `npm install -g` first |
| Port conflict | Server won't start | Change port or kill existing |
### After Config Changes
**Critical:** Completely quit and restart Claude Desktop after any config changes.
## Error: "Required parameter" validation errors
**Cause:** MCP tool schema mismatch (regression bug)
**Solutions:**
1. Update Claude Desktop to latest version
2. Check MCP server for updates
3. Temporarily disable problematic server
---
# CATEGORY 7: Account Errors
## Error: "Your account has been disabled"
**Full message:** "Your account has been disabled after an automatic review of your recent activities."
**Cause:** Automated system flagged account
**Solutions:**
1. Contact Anthropic support
2. Review Terms of Service
3. Do not create new accounts (may worsen situation)
## Error: "This organization has been disabled"
**Cause:** Organization-level suspension
**Solution:** Organization admin must contact Anthropic
## Error: "There was an error logging you in"
**Causes:**
- VPN interference
- Browser extensions blocking
- Cached credentials issue
**Solutions:**
1. Disable VPN
2. Disable browser extensions temporarily
3. Clear browser cache and cookies
4. Try incognito/private window
5. Check [status.claude.com](https://status.claude.com)
## Error: "Error Sending Codes - Check Your Phone Number"
**Cause:** Phone verification failed during signup
**Solutions:**
1. Verify correct country code
2. Check all digits entered correctly
3. Try different phone number
4. Wait and retry later
---
# CATEGORY 8: Output Quality Issues
## Issue: Output Suddenly Stops (Cutoff)
**Symptoms:** Response ends mid-sentence or mid-code
**Causes:**
1. Hit output token limit (~4K-8K)
2. Safety filter triggered
3. Server timeout
**Solutions:**
1. Ask "Please continue from where you stopped"
2. Request smaller chunks upfront
3. Be more specific in scope
## Issue: Gibberish or Nonsensical Output
**Symptoms:** Incoherent text, random characters
**Causes:**
1. Model confusion from complex prompt
2. Conflicting instructions
3. Edge case in training
**Solutions:**
1. Simplify prompt
2. Start new conversation
3. Rephrase request differently
## Issue: Mixed Languages or Character Issues
**Symptoms:** Unexpected language switches, formatting problems
**Causes:**
1. Ambiguous language context
2. Copy-pasted special characters
**Solutions:**
1. Explicitly state desired language
2. Clean input text of special characters
3. Add "Please respond in [language]"
## Issue: Claude Refuses to Respond
**Symptoms:** Declines request citing policy
**Causes:**
1. Request triggered safety guidelines
2. Ambiguous phrasing interpreted as harmful
**Solutions:**
1. Rephrase more clearly
2. Explain legitimate use case
3. Break into smaller, clearer requests
---
## Prevention Checklist
### Context/Input Errors
- [ ] Maximum 5 MCP servers active
- [ ] All servers have serverInstructions
- [ ] Skills under 1,000 words
- [ ] Start fresh conversations for new topics
- [ ] Avoid attaching files over 50KB (prefer excerpts)
- [ ] Individual files under 10MB
### Output Errors
- [ ] Break large requests into chunks
- [ ] Use specific scope in prompts
- [ ] Request concise/brief outputs when possible
- [ ] Paginate lists and tables (50 items max)
- [ ] Generate code module by module
- [ ] Retry once before rephrasing
### Usage Limits
- [ ] Monitor "messages left" warnings
- [ ] Combine related questions into single prompts
- [ ] Use concise prompts to conserve tokens
- [ ] Know your plan's reset schedule
### MCP Stability
- [ ] Test MCP servers independently before adding
- [ ] Keep server logs accessible for debugging
- [ ] Restart Claude Desktop after config changes
- [ ] Update MCP servers regularly
- [ ] Document working configurations
### General Best Practices
- [ ] Check [status.claude.com](https://status.claude.com) when experiencing issues
- [ ] Keep Claude Desktop updated
- [ ] Clear browser cache periodically (web version)
- [ ] Disable VPN if experiencing login issues
- [ ] Back up important conversations locally

View File

@@ -0,0 +1,76 @@
# Sample Settings Check Report
## Configuration Summary
| Component | Count | Tokens (est.) | Status |
|-----------|-------|---------------|--------|
| MCP Servers | 6 | ~45,000 | ⚠️ High |
| Active Skills | 3 | ~1,500 | ✓ OK |
| Project Files | 2 | ~2,000 | ✓ OK |
| **Baseline Total** | — | ~48,500 | ⚠️ Warning |
| **Available** | — | ~151,500 (76%) | Marginal |
## Issues Found
### Critical
1. **GitHub MCP server loading all tools** (~18,000 tokens)
- 25+ tools loaded but only 3-4 commonly used
- Missing `serverInstructions`
### Warnings
1. **Zapier MCP enabled** (~25,000 tokens)
- 50+ tools, rarely used
- Consider disabling
2. **Playwright missing serverInstructions**
- Tool discovery inefficient
- Add: `"serverInstructions": "Browser automation..."`
3. **Custom skill SKILL.md is 1,500 words**
- Exceeds 1,000 word recommendation
- Move reference data to separate file
## Recommended Actions
### Immediate (save ~35,000 tokens)
1. **Disable Zapier MCP** (saves ~25,000)
```json
// Remove or comment out in claude_desktop_config.json
// "zapier": { ... }
```
2. **Add serverInstructions to all servers** (saves ~5,000)
```json
"github": {
"command": "...",
"serverInstructions": "GitHub operations. Use for: repos, issues, PRs. Keywords: github, repo, issue, pull request"
}
```
3. **Refactor long skill** (saves ~1,000)
- Move data tables to `references/` directory
- Keep SKILL.md under 500 words
### Secondary
4. Consider starting fresh conversations for unrelated tasks
5. Review GitHub usage - if only for viewing, use web instead
## After Optimization
| Component | Tokens (est.) | Status |
|-----------|---------------|--------|
| MCP Servers | ~15,000 | ✓ Good |
| Skills + Files | ~2,500 | ✓ Good |
| **Baseline Total** | ~17,500 | ✓ Good |
| **Available** | ~182,500 (91%) | ✓ Excellent |
## Quick Wins Checklist
- [x] Disable Zapier MCP
- [x] Add serverInstructions to Playwright
- [x] Add serverInstructions to GitHub
- [x] Add serverInstructions to Notion
- [ ] Refactor jamie-brand skill (move procedures data)
- [ ] Review PostgreSQL usage frequency

View File

@@ -0,0 +1,77 @@
# Claude Desktop Configuration Locations
## Primary Config File
### macOS
```
~/Library/Application Support/Claude/claude_desktop_config.json
```
### Windows
```
%APPDATA%\Claude\claude_desktop_config.json
```
### Linux
```
~/.config/Claude/claude_desktop_config.json
```
## MCP Server Configuration Example
```json
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-playwright"],
"serverInstructions": "Browser automation. Use for: screenshots, page testing, DOM inspection. Keywords: browser, page, screenshot, navigate"
},
"notion": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-notion", "--token", "YOUR_TOKEN"],
"serverInstructions": "Notion workspace access. Use for: search pages, create content, update databases. Keywords: notion, page, database, workspace"
}
}
}
```
## Key Fields
| Field | Purpose | Token Impact |
|-------|---------|--------------|
| `command` | Executable path | Minimal |
| `args` | Arguments | Minimal |
| `serverInstructions` | Usage hints | Reduces discovery overhead |
| `env` | Environment vars | None |
## serverInstructions Best Practices
**Good:**
```json
"serverInstructions": "File system access. Use for: read/write files, directory listing. Keywords: file, read, write, directory"
```
**Bad (too vague):**
```json
"serverInstructions": "Various file operations"
```
**Bad (too long):**
```json
"serverInstructions": "This MCP server provides comprehensive file system access capabilities including reading files, writing files, creating directories, listing directory contents, and more. It can be used for any operation that requires..."
```
## Viewing Current Configuration
Ask user to run:
**macOS/Linux:**
```bash
cat ~/Library/Application\ Support/Claude/claude_desktop_config.json | python3 -m json.tool
```
**Windows (PowerShell):**
```powershell
Get-Content "$env:APPDATA\Claude\claude_desktop_config.json" | ConvertFrom-Json | ConvertTo-Json -Depth 10
```

View File

@@ -0,0 +1,88 @@
# MCP Server Token Estimates
Approximate token usage for common MCP servers when loaded.
## Official Anthropic Servers
| Server | Tools | Tokens (est.) | Recommendation |
|--------|-------|---------------|----------------|
| Playwright | 20+ | 13,500 | Keep if testing |
| Filesystem | 8 | 4,000 | Essential |
| Memory | 5 | 3,000 | Optional |
| Brave Search | 2 | 1,500 | Alternative to web |
| Fetch | 2 | 1,200 | Keep for web access |
## Third-Party Servers
| Server | Tools | Tokens (est.) | Recommendation |
|--------|-------|---------------|----------------|
| Notion | 10 | 5,000 | Keep if using Notion |
| GitHub | 25+ | 18,000 | Lazy load only |
| PostgreSQL | 15 | 8,000 | Lazy load only |
| Slack | 12 | 6,000 | Lazy load only |
| Figma | 15 | 10,000 | Lazy load only |
| Zapier | 50+ | 25,000+ | **Avoid** |
| Firecrawl | 5 | 3,500 | Useful for SEO |
| Perplexity | 2 | 1,500 | Alternative to web |
## Token Budget Guidelines
### Conservative Setup (High Available Context)
```
2-3 essential MCP servers
Total: ~10,000-15,000 tokens
Available: 185,000+ tokens (92%+)
```
### Standard Setup
```
4-5 MCP servers
Total: ~20,000-30,000 tokens
Available: 170,000+ tokens (85%+)
```
### Heavy Setup (Risk Zone)
```
6+ MCP servers
Total: 40,000+ tokens
Available: <160,000 tokens (<80%)
⚠️ Higher chance of "Exceed response limit"
```
## Reduction Strategies
### If using GitHub MCP heavily:
- Start conversation specifically for GitHub work
- Don't load other heavy servers simultaneously
### If using multiple API servers:
- Choose ONE per category:
- Web search: Brave OR Perplexity (not both)
- Automation: Zapier OR n8n (not both)
- Database: PostgreSQL OR MySQL (not both)
### If testing/development:
- Playwright OR Puppeteer (not both)
- Load only when actively testing
## Impact of serverInstructions
**Without serverInstructions:**
- Full tool schemas loaded (~500 tokens per tool)
- Discovery overhead on each interaction
**With serverInstructions:**
- Reduced discovery queries
- More efficient tool selection
- Saves ~30-50% on tool-related tokens
## Quick Reference
**Token estimation formula:**
```
Server tokens ≈ (number of tools × 400) + 500 base
```
**Example:**
- 10 tools = (10 × 400) + 500 = 4,500 tokens
- 25 tools = (25 × 400) + 500 = 10,500 tokens

View File

@@ -0,0 +1,349 @@
# Claude Settings Audit Guide
> **Purpose**: Condensed reference for Claude.ai Projects
> **Source**: 00-claude-settings-audit skill
> **Version**: 1.0
Comprehensive reference for diagnosing Claude Desktop errors and optimizing context usage.
## Error Quick Reference
| Error Type | Message Pattern | Category |
|------------|-----------------|----------|
| Context too large | "Exceed response limit" | Input |
| Output interrupted | "Response could not be fully generated" | Output |
| Length exceeded | "Message will exceed the length limit" | Input |
| Conversation limit | "Conversation reached maximum length" | Input |
| File too large | "Files larger than 10mb" | File |
| Rate limited | "5-hour limit reached" | Usage |
| Server overload | "Unexpected capacity constraints" | Server |
| MCP failure | "Error connecting to [ServerName]" | MCP |
| Account issue | "Account has been disabled" | Account |
## Quick Diagnosis Tree
```
Error occurred?
├─ BEFORE response started?
│ ├─ "Exceed response limit" → Reduce input context
│ ├─ "Length limit" → Break into smaller messages
│ ├─ "File too large" → Reduce file size or excerpt
│ ├─ "Capacity constraints" → Wait and retry
│ └─ "MCP error" → Check MCP configuration
├─ DURING response?
│ ├─ "Could not be fully generated" → Request smaller output
│ └─ Output suddenly stopped → Retry or chunk request
└─ BEFORE even sending?
├─ "5-hour limit reached" → Wait for reset
├─ "Messages left" → Near usage limit
└─ "Account disabled" → Contact support
```
---
## Token Limits by Model
| Model | Context Window | Output Limit | Practical Available |
|-------|---------------|--------------|---------------------|
| Claude 3.5 Sonnet | 200K tokens | ~8K tokens | ~150K after system |
| Claude 3 Opus | 200K tokens | ~4K tokens | ~150K after system |
| Claude 3 Haiku | 200K tokens | ~4K tokens | ~160K after system |
---
# ERROR CATEGORIES
## 1. Input/Context Errors
### "Exceed response limit"
**Causes:**
- Loaded context too large (MCP tools + skills + files)
- Conversation history accumulated
- Multiple large files attached
**Solutions:**
1. Reduce MCP servers (max 5 recommended)
2. Add `serverInstructions` to all MCP servers
3. Start fresh conversation
4. Attach file excerpts instead of full files
### "Message will exceed the length limit"
**Solutions:**
1. Break content into smaller chunks
2. Summarize key sections before sending
3. Start a new conversation
### "Conversation reached maximum length"
**Solutions:**
1. Start a new conversation
2. Copy essential context to new chat
---
## 2. Output Errors
### "Response could not be fully generated"
**Causes:**
- Output exceeded ~4K-8K token limit
- Safety filter triggered
- Network interruption
- Server timeout
**Solutions:**
1. Request smaller chunks of output
2. Add constraints: "In under 500 words..."
3. Be more specific in scope
4. Retry once before rephrasing
**Prompting techniques:**
- "Provide a concise summary..."
- "List the top 10..."
- "First, outline the structure"
- "Use bullet points, not paragraphs"
---
## 3. File Errors
### "Files larger than 10MB"
**Solutions:**
1. Compress file if possible
2. Split into smaller files
3. Extract text content only
### "Message is X% over the length limit"
**Solutions:**
1. Extract relevant excerpts only
2. Summarize large documents
3. Split across multiple messages
---
## 4. Usage Limit Errors
### "5-hour limit reached"
**Solutions:**
1. Wait until reset time shown
2. Upgrade plan for higher limits
3. Optimize prompts to use fewer tokens
### "X messages left until [time]"
**Solutions:**
1. Combine multiple questions into one
2. Wait for reset
3. Consider paid plan
---
## 5. Server/Capacity Errors
### "Unexpected capacity constraints"
**Solutions:**
1. Wait 2-5 minutes and retry
2. Try during off-peak hours
3. Check status.claude.com for incidents
### HTTP Error Codes
| Code | Meaning | Solution |
|------|---------|----------|
| 500 | Internal Server Error | Wait and retry |
| 429 | Too Many Requests | Slow down, wait |
| 403 | Forbidden | Check account status |
| 400 | Bad Request | Check input format |
---
## 6. MCP Connection Errors
### "Error connecting to [ServerName]"
**Causes:**
1. Server not running
2. Incorrect configuration
3. Transport type mismatch (stdio vs HTTP)
4. Authentication failure
**Diagnosis steps:**
1. Check server logs:
- macOS: `~/Library/Logs/Claude/mcp-server-SERVERNAME.log`
- Windows: `%APPDATA%\Claude\logs\mcp-server-SERVERNAME.log`
2. Verify configuration in `claude_desktop_config.json`
3. Test server independently
**Common fixes:**
| Issue | Fix |
|-------|-----|
| Transport mismatch | Add `"transport": "http"` to config |
| Path with spaces | Use escaped paths |
| Missing env vars | Add to `"env"` in config |
| Server not installed | Run `npm install -g` first |
**Critical:** Restart Claude Desktop after config changes.
---
## 7. Account Errors
### "Account has been disabled"
**Solutions:**
1. Contact Anthropic support
2. Review Terms of Service
3. Do not create new accounts
### "Error logging you in"
**Solutions:**
1. Disable VPN
2. Clear browser cache and cookies
3. Try incognito window
4. Check status.claude.com
---
## 8. Output Quality Issues
### Output Suddenly Stops
**Solutions:**
1. Ask "Please continue from where you stopped"
2. Request smaller chunks upfront
3. Be more specific in scope
### Gibberish Output
**Solutions:**
1. Simplify prompt
2. Start new conversation
3. Rephrase request differently
### Claude Refuses to Respond
**Solutions:**
1. Rephrase more clearly
2. Explain legitimate use case
3. Break into smaller requests
---
# TOKEN BUDGET GUIDELINES
## MCP Server Token Estimates
| Server | Tokens (approx) |
|--------|-----------------|
| Playwright | ~13,500 |
| Notion | ~5,000 |
| GitHub | ~18,000 |
| Filesystem | ~4,000 |
| Zapier | ~25,000+ (avoid) |
## serverInstructions Pattern
Every MCP server should have:
```json
"serverInstructions": "[Purpose]. Use for: [case1], [case2]. Keywords: [kw1], [kw2]"
```
Example:
```json
"serverInstructions": "Browser automation. Use for: screenshots, page testing. Keywords: browser, DOM, screenshot"
```
## Budget Calculator
```
System overhead: ~10,000 tokens (fixed)
MCP servers: [count] × ~3,000 = [estimate]
Loaded skills: [count] × ~500 = [estimate]
Project instructions: ~[estimate]
────────────────────────────────────────────
Baseline total: [sum]
Available for work: 200,000 - [sum] = [remaining]
```
**Targets:**
- Baseline: < 40,000 tokens (20%)
- Available: > 160,000 tokens (80%)
---
# PREVENTION CHECKLIST
## Context/Input
- [ ] Maximum 5 MCP servers active
- [ ] All servers have serverInstructions
- [ ] Skills under 1,000 words
- [ ] Start fresh conversations for new topics
- [ ] Files under 10MB, prefer excerpts
## Output
- [ ] Break large requests into chunks
- [ ] Use specific scope in prompts
- [ ] Paginate lists (50 items max)
- [ ] Retry once before rephrasing
## Usage Limits
- [ ] Monitor "messages left" warnings
- [ ] Combine related questions
- [ ] Use concise prompts
## MCP Stability
- [ ] Test servers before adding
- [ ] Restart app after config changes
- [ ] Keep servers updated
## General
- [ ] Check status.claude.com when issues occur
- [ ] Keep Claude Desktop updated
- [ ] Back up important conversations
---
# CONFIGURATION LOCATIONS
## Config Files
**macOS:**
```
~/Library/Application Support/Claude/claude_desktop_config.json
```
**Windows:**
```
%APPDATA%\Claude\claude_desktop_config.json
```
## Log Files
**macOS:**
```
~/Library/Logs/Claude/mcp-server-SERVERNAME.log
```
**Windows:**
```
%APPDATA%\Claude\logs\mcp-server-SERVERNAME.log
```
---
*Reference: Claude Settings Audit Skill v1.0*
*Last updated: 2025-02*

View File

@@ -0,0 +1,39 @@
# OurDigital Settings Audit
# Comprehensive error diagnosis and context optimization
name: our-settings-audit
description: |
Diagnose all Claude Desktop errors and optimize context usage.
Covers 8 error categories: context limits, output interruption,
length/file errors, usage limits, server capacity, MCP connection,
account issues, and output quality problems.
allowed-tools:
- Read
- Glob
- Grep
license: Internal-use Only
triggers:
- settings audit
- settings check
- audit settings
- exceed response limit
- response could not be generated
- length limit
- file too large
- conversation limit
- 5-hour limit
- messages left
- rate limit
- capacity constraints
- server error
- MCP error
- server connection failed
- account disabled
- login error
- output cutoff
- token error
- gibberish output