Production-ready hooks for managing Context7 MCP queries with token limiting and automatic archival.
This repository contains two Claude Code hooks that work together to provide intelligent Context7 query management:
- Token Limiter (PreToolUse) - Enforces a 3000 token limit on Context7 queries
- Archive (PostToolUse) - Automatically saves all Context7 query results to disk
Problem: Context7 can return massive documentation dumps (10K+ tokens) that flood your context window, leaving little room for actual coding work.
Solution: The token limiter enforces a 3000 token ceiling and provides educational feedback to guide you toward iterative querying:
- Better context management - More room for your actual code and tasks
- More focused results - Smaller, targeted queries return more relevant information
- Iterative workflow - Break research into logical steps, refining as you learn
- Educational feedback - The hook teaches you the iterative approach with examples
Problem: Context7 queries are ephemeral - once they scroll out of your context, that knowledge is lost.
Solution: The archive hook automatically saves every Context7 query to a searchable markdown file:
- Persistent knowledge base - Build up a searchable archive of documentation
- No re-fetching - Reference past queries without burning tokens
- Team sharing - Commit archives to git for team-wide knowledge base
- Metadata rich - YAML frontmatter makes archives grep-able and indexable
Both hooks are located in .claude/hooks/:
context7_token_limiter.sh- PreToolUse hook (3.3 KB)context7_archive.sh- PostToolUse hook (6.2 KB)
Install hooks globally to apply them across all Claude Code projects:
# Copy hooks to global directory
mkdir -p ~/.claude/hooks
cp .claude/hooks/context7_token_limiter.sh ~/.claude/hooks/
cp .claude/hooks/context7_archive.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.shThen update your global ~/.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__context7__get-library-docs",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/context7_token_limiter.sh",
"timeout": 5000
}
]
}
],
"PostToolUse": [
{
"matcher": "mcp__context7__get-library-docs",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/context7_archive.sh",
"timeout": 5000
}
]
}
]
}
}Benefits:
- ✅ Works in all projects automatically
- ✅ Single source of truth for hook updates
- ✅ Archives saved to each project's directory
- ✅ Falls back to
~/.claude/context7-archive/outside projects
Install hooks for a single project only:
# Hooks already exist in .claude/hooks/
# Just need to configure themUpdate your project .claude/settings.local.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__context7__get-library-docs",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/context7_token_limiter.sh",
"timeout": 5000
}
]
}
],
"PostToolUse": [
{
"matcher": "mcp__context7__get-library-docs",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/context7_archive.sh",
"timeout": 5000
}
]
}
]
}
}Benefits:
- ✅ Version controlled with your project
- ✅ Team members get same hooks when cloning
- ✅ Per-project customization possible
The archive hook intelligently chooses where to save files:
When inside a project:
$CLAUDE_PROJECT_DIR/context7-archive/
When outside a project (global install only):
~/.claude/context7-archive/
Archives use structured filenames for easy searching:
{YYYYMMDD}_{project-name}_{library-slug}_{topic-slug}.md
Examples:
20251016_myapp_nextjs_server-actions.md20251016_api_cloudflare-workers_durable-objects.md20251016_droids_hono_routing-basics-and-patterns.md
Delimiters:
- Underscore (
_) separates fields - Hyphen (
-) separates words within fields
Each archive includes YAML frontmatter:
---
query_date: 2025-10-16 20:07:23 UTC
library: /honojs/hono
topic: routing basics and patterns
tokens: 3000
project: myapp
tool: mcp__context7__get-library-docs
---
# Context7 Query: routing basics and patterns
[Documentation content here...]// Query with 3000 tokens - allowed
await context7.getLibraryDocs({
libraryId: '/honojs/hono',
topic: 'middleware patterns',
tokens: 3000
});Result:
- ✅ Query executes normally
- ✅ Archive saved to
context7-archive/20251016_myapp_hono_middleware-patterns.md
// Query with 5000 tokens - blocked
await context7.getLibraryDocs({
libraryId: '/vercel/next.js',
topic: 'everything about routing',
tokens: 5000
});Result:
- ❌ Query blocked before execution
- 📚 Educational message with iterative approach guidance
- 💡 Suggests breaking into smaller, focused queries
// Query 1: Start broad
await context7.getLibraryDocs({
libraryId: '/vercel/next.js',
topic: 'app router basics',
tokens: 3000
});
// Review results, identify gaps...
// Query 2: Go deeper on specific topic
await context7.getLibraryDocs({
libraryId: '/vercel/next.js',
topic: 'server actions with forms',
tokens: 3000
});
// Query 3: Focus on implementation details
await context7.getLibraryDocs({
libraryId: '/vercel/next.js',
topic: 'progressive enhancement patterns',
tokens: 3000
});Both hooks support environment variable configuration:
# Override default 3000 token limit
export MAX_TOKENS=5000
# Custom log location
export LOG_FILE="$HOME/my-custom-hooks.log"# Enable debug logging
export DEBUG=1
# Save raw JSON responses
export RAW_JSON=1
# Custom archive directory
export ARCHIVE_DIR="/path/to/my/archives"Enable debug logging to troubleshoot hook behavior:
DEBUG=1 claudeDebug logs are written to:
- Token limiter:
$LOG_FILE(default:~/.claude/hooks.log) - Archive:
$ARCHIVE_DIR/hook-debug.log
Check hook activation:
# In Claude Code, use the /hooks command to view and activate hooks
/hooksNote: Hooks added during a session require activation via /hooks menu before they work.
Ensure hooks are executable:
chmod +x ~/.claude/hooks/*.sh
# or
chmod +x $CLAUDE_PROJECT_DIR/.claude/hooks/*.shBoth hooks require jq for JSON parsing:
# macOS
brew install jq
# Ubuntu/Debian
sudo apt-get install jq
# Arch Linux
sudo pacman -S jqCheck that the archive directory exists:
# For project archives
ls -la $CLAUDE_PROJECT_DIR/context7-archive/
# For global archives
ls -la ~/.claude/context7-archive/Enable debug mode to see detailed logging:
DEBUG=1 claude
tail -f $CLAUDE_PROJECT_DIR/context7-archive/hook-debug.log- Verify hook is configured in settings.json
- Check hook was activated via
/hookscommand - Ensure hook file path is correct (use absolute paths or
~expansion) - Check hook logs for errors:
cat ~/.claude/hooks.log
Both hooks use umask 077 to create files with restrictive permissions:
- Archive files:
600(rw-------) - Hook scripts:
755(rwxr-xr-x)
Archives may contain:
- API documentation snippets
- Code examples
- Library usage patterns
Recommendations:
- Add
context7-archive/to.gitignoreif archives contain sensitive info - Review archives before committing to public repositories
- Use
RAW_JSON=0(default) to avoid storing full JSON responses
- Token Limiter: v2 (2025-10-16)
- Archive Hook: v2 (2025-10-16)
Token Limiter v2:
- Robust numeric parsing (handles floats, strings)
- Environment variable configuration
- Secure logging with
umask 077 - jq dependency check with graceful fallback
- Portable shebang (
#!/usr/bin/env bash)
Archive Hook v2:
- YAML frontmatter instead of Markdown headers
- Improved library slug derivation (no hardcoded rules)
- Word-boundary truncation for topic slugs
- Collision handling (adds
-Nsuffix) - Robust tool_response parsing (string, array, object)
- Project directory fallback
- RAW_JSON mode for debugging
Found a bug or have an improvement? Please:
- Test thoroughly with multiple Context7 queries
- Ensure backward compatibility
- Update version numbers in hook headers
- Document changes in this README
MIT License - Use freely in your projects.
For issues or questions about these hooks, please open an issue in the repository.
Happy Context7 querying! 🚀