Skip to content

curtis-arch/context7-hooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 

Repository files navigation

Context7 Hooks for Claude Code

Production-ready hooks for managing Context7 MCP queries with token limiting and automatic archival.

Overview

This repository contains two Claude Code hooks that work together to provide intelligent Context7 query management:

  1. Token Limiter (PreToolUse) - Enforces a 3000 token limit on Context7 queries
  2. Archive (PostToolUse) - Automatically saves all Context7 query results to disk

Why These Hooks Matter

Token Limiter

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

Archive Hook

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

Hook Files

Both hooks are located in .claude/hooks/:

  • context7_token_limiter.sh - PreToolUse hook (3.3 KB)
  • context7_archive.sh - PostToolUse hook (6.2 KB)

Installation Options

Global Installation (Recommended)

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/*.sh

Then 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

Local Installation (Project-Specific)

Install hooks for a single project only:

# Hooks already exist in .claude/hooks/
# Just need to configure them

Update 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

Archive Behavior

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/

Archive Filename Format

Archives use structured filenames for easy searching:

{YYYYMMDD}_{project-name}_{library-slug}_{topic-slug}.md

Examples:

  • 20251016_myapp_nextjs_server-actions.md
  • 20251016_api_cloudflare-workers_durable-objects.md
  • 20251016_droids_hono_routing-basics-and-patterns.md

Delimiters:

  • Underscore (_) separates fields
  • Hyphen (-) separates words within fields

Archive File Structure

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...]

Usage Examples

Normal Query (Under Limit)

// 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

Blocked Query (Over Limit)

// 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

Iterative Approach (Recommended)

// 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
});

Advanced Configuration

Environment Variables

Both hooks support environment variable configuration:

Token Limiter

# Override default 3000 token limit
export MAX_TOKENS=5000

# Custom log location
export LOG_FILE="$HOME/my-custom-hooks.log"

Archive Hook

# Enable debug logging
export DEBUG=1

# Save raw JSON responses
export RAW_JSON=1

# Custom archive directory
export ARCHIVE_DIR="/path/to/my/archives"

Debug Mode

Enable debug logging to troubleshoot hook behavior:

DEBUG=1 claude

Debug logs are written to:

  • Token limiter: $LOG_FILE (default: ~/.claude/hooks.log)
  • Archive: $ARCHIVE_DIR/hook-debug.log

Troubleshooting

Hook Not Running

Check hook activation:

# In Claude Code, use the /hooks command to view and activate hooks
/hooks

Note: Hooks added during a session require activation via /hooks menu before they work.

Permission Errors

Ensure hooks are executable:

chmod +x ~/.claude/hooks/*.sh
# or
chmod +x $CLAUDE_PROJECT_DIR/.claude/hooks/*.sh

jq Not Found

Both hooks require jq for JSON parsing:

# macOS
brew install jq

# Ubuntu/Debian
sudo apt-get install jq

# Arch Linux
sudo pacman -S jq

Archives Not Appearing

Check 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

Token Limit Still Allowing Large Queries

  1. Verify hook is configured in settings.json
  2. Check hook was activated via /hooks command
  3. Ensure hook file path is correct (use absolute paths or ~ expansion)
  4. Check hook logs for errors: cat ~/.claude/hooks.log

Security

File Permissions

Both hooks use umask 077 to create files with restrictive permissions:

  • Archive files: 600 (rw-------)
  • Hook scripts: 755 (rwxr-xr-x)

Sensitive Data

Archives may contain:

  • API documentation snippets
  • Code examples
  • Library usage patterns

Recommendations:

  • Add context7-archive/ to .gitignore if archives contain sensitive info
  • Review archives before committing to public repositories
  • Use RAW_JSON=0 (default) to avoid storing full JSON responses

Hook Versions

  • Token Limiter: v2 (2025-10-16)
  • Archive Hook: v2 (2025-10-16)

Version 2 Improvements

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 -N suffix)
  • Robust tool_response parsing (string, array, object)
  • Project directory fallback
  • RAW_JSON mode for debugging

Contributing

Found a bug or have an improvement? Please:

  1. Test thoroughly with multiple Context7 queries
  2. Ensure backward compatibility
  3. Update version numbers in hook headers
  4. Document changes in this README

License

MIT License - Use freely in your projects.

Questions?

For issues or questions about these hooks, please open an issue in the repository.


Happy Context7 querying! 🚀

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages