Skip to main content

Hook system and MCP tool server for Claude Code agents

Project description

agentihooks

Standalone License: MIT CI Python 3.11+ Docs

Hook system and MCP tool server for Claude Code agents. Designed to work with agenticore and meant to be forked and extended for custom workflows.

agentihooks intercepts every Claude Code lifecycle event (session start/end, tool use, prompts, stops) and provides 26 MCP tools across 8 categories for interacting with external services. A built-in Token Control Layer monitors context window usage, truncates verbose command output, deduplicates file reads, and warns before quota exhaustion — targeting 30–50% token reduction in agentic sessions.

Full documentation: the-cloud-clock-work.github.io/agentihooks

Cost management guide: the-cloud-clock-work.github.io/agentihooks/docs/cost-management/ — see how AgentiHooks saves 100K–250K tokens per session

Architecture

Claude Code
  │
  ├── Hook Events (stdin JSON) ──► python -m hooks ──► hook_manager.py
  │     SessionStart, PreToolUse,       │
  │     PostToolUse, Stop, ...          ├── transcript logging
  │     (10 events total)               ├── tool error memory
  │                                     ├── token control layer
  │                                     ├── metrics parsing
  │                                     └── email notifications
  │
  ├── statusLine (native setting) ──► python -m hooks.statusline
  │     pipes JSON on every turn        └── 2-3 line status bar (ctx%, burn rate, cost, git)
  │
  └── MCP Tools ──► python -m hooks.mcp ──► 8 category modules
        aws, email, messaging,                │
        database, compute, ...                └── hooks/integrations/*

Quick Start

Requirement: uv must be installed.

git clone https://github.com/The-Cloud-Clock-Work/agentihooks
cd agentihooks

# 1. Create the dedicated venv at ~/.agentihooks/.venv and install everything
uv venv ~/.agentihooks/.venv
uv pip install --python ~/.agentihooks/.venv/bin/python -e ".[all]"

# 2. Install hooks + settings + MCP into ~/.claude
~/.agentihooks/.venv/bin/python scripts/install.py global

agentihooks global wires hooks into ~/.claude/settings.json, symlinks skills/agents, merges MCP servers into ~/.claude.json, and installs the CLI globally. Critically, every hook command in settings.json is written with the Python that ran the installer — so by running the installer from ~/.agentihooks/.venv, all hook subprocesses find the right packages regardless of which shell or virtual environment is active when Claude Code fires them.

Re-run any time — it's idempotent. See Installation for the full step-by-step walkthrough including Redis setup and quota display.

Hook Events

10 lifecycle events, all handled by python -m hooks:

Event What happens
SessionStart Injects session awareness, MCP hygiene reminder
PreToolUse Secret scan (blocks on detection), file read deduplication, injects tool error memory
PostToolUse Truncates verbose bash output, marks files read, records tool errors
Stop Scans transcript for errors, parses metrics, auto-saves memory
SessionEnd Logs transcript, clears file read cache
SubagentStop Logs subagent transcript
UserPromptSubmit Warns on detected secrets
Notification Logs notifications
PreCompact Logs before context compaction
PermissionRequest Logs permission requests

StatusLine is not a hook event — it is a native Claude Code setting ("statusLine" key in settings.json) handled by hooks/statusline.py. It emits a 2–3 line terminal status bar with context fill %, burn rate, cost, cache ratio, and git branch on every turn. used_pct is recomputed from total_input_tokens / context_window_size * 100 to avoid stale payload values.

Full payload schemas and handler details: Hook Events

MCP Tool Categories

26 tools across 8 categories, selectively loaded via MCP_CATEGORIES:

Category Tools Description
aws 4 Profile listing, account discovery
email 2 SMTP send with text / HTML / markdown
messaging 3 SQS + webhook with state enrichment
storage 1 S3 upload
database 3 DynamoDB put, PostgreSQL insert + execute
compute 1 Lambda invocation (sync/async)
observability 7 Timers, metrics, structured logging, container log tailing
utilities 3 Markdown writer, env vars, tool listing

Per-tool signatures, parameters, and environment variables: MCP Tools

CLI

agentihooks global [--profile <name>]   # install/re-apply to ~/.claude
agentihooks project <path>              # write .mcp.json into a project
agentihooks mcp                         # list MCP files in ~/.agentihooks/
agentihooks mcp install                 # two-stage: pick file → pick servers
agentihooks mcp uninstall               # two-stage: pick file → pick servers to remove
agentihooks mcp add <path>              # install a file directly by path
agentihooks mcp sync                    # re-apply all installed MCP files
agentihooks quota                       # start background quota watcher daemon
agentihooks quota auth                  # open browser, paste sessionKey, import cookie, start daemon
agentihooks quota import-cookies        # paste sessionKey without opening browser
agentihooks quota status                # print last known quota JSON
agentihooks quota logs                  # tail -f daemon log
agentihooks quota stop                  # kill daemon
agentihooks ignore [path] [--force]     # create .claudeignore in cwd (or given path)
agentihooks uninstall                   # remove everything
agentihooks --loadenv                   # install agentienv shell function into ~/.bashrc

Full reference: CLI Commands

Configuration

All integrations are configured via environment variables. Key ones:

Variable Default Description
AGENTIHOOKS_HOME ~/.agentihooks Root for logs, memory, and state
CLAUDE_CODE_HOME_DIR $HOME Home-directory root override (.claude appended automatically)
AGENTIHOOKS_CLAUDE_HOME ~/.claude Legacy: direct path to .claude directory
AGENTIHOOKS_PROFILE default Profile to use for agentihooks global / project (env alternative to --profile)
AGENTIHOOKS_MCP_FILE Path to an MCP JSON file to auto-merge during agentihooks global
MCP_CATEGORIES all Comma-separated list of tool categories to load
LOG_ENABLED true Enable hook logging
MEMORY_AUTO_SAVE true Auto-save session digest on Stop
REDIS_URL Redis connection string — format: redis://:PASSWORD@host:port/db. Used by token monitor (burn rate), file read cache (dedup), and warning edge-triggers. Graceful degradation when unavailable.
TOKEN_CONTROL_ENABLED true Master switch for the token control layer
TOKEN_WARN_PCT 60 Context fill % that triggers a warning injection
TOKEN_CRITICAL_PCT 80 Context fill % that triggers a critical banner
BASH_FILTER_ENABLED true Truncate verbose bash output (docker logs, git log, etc.)
FILE_READ_CACHE_ENABLED true Block redundant file re-reads within a session
MCP_HYGIENE_ENABLED true Inject MCP server usage reminder at session start
ENABLE_TOOL_SEARCH true Make all MCP tools lazy-loaded on demand (set in env block of settings.json); eliminates ~79K token upfront cost from MCP tool schemas
CLAUDE_USAGE_FILE Path to quota JSON file (e.g. ~/.agentihooks/claude_usage.json). Must be set to enable statusline line 3 quota display.
CLAUDE_USAGE_STALE_SEC 300 Quota data older than this (seconds) shows "stale" on statusline
CLAUDE_USAGE_POLL_SEC 60 Quota watcher daemon poll interval (seconds)

Complete table covering all 50+ variables across every integration: Configuration Reference

Profiles

Profiles bundle a system prompt (CLAUDE.md), MCP category selection, and model settings. Switch with agentihooks global --profile <name>.

Portability

Everything user-specific lives in ~/.agentihooks/:

~/.agentihooks/
├── .venv/                     # Canonical Python venv — all hook subprocesses run from here
├── .env                       # Main credentials (seeded from .env.example, loaded first)
├── *.env                      # Companion env files (auto-sourced after .env)
├── *.json                     # Drop MCP server files here → agentihooks mcp install
├── state.json                 # Tracked MCP files and other state
├── logs/                      # Hook + MCP logs
│   └── quota-watcher.log      # Quota watcher daemon log
├── memory/                    # Cross-session agent memory
├── claude_auth_state.json     # Playwright storage state (sessionKey cookie for quota watcher)
├── claude_usage.json          # Written by quota watcher daemon; read by statusline (optional)
└── quota-watcher.pid          # Daemon PID file

To move to a new machine: clone the repo, copy ~/.agentihooks/.env, recreate the venv, run the installer. Done:

uv venv ~/.agentihooks/.venv
uv pip install --python ~/.agentihooks/.venv/bin/python -e ".[all]"
~/.agentihooks/.venv/bin/python scripts/install.py global

Install the agentienv shell function (sources .env into any shell on demand — also auto-called on every new shell):

agentihooks --loadenv   # writes managed block to ~/.bashrc
source ~/.bashrc
agentienv          # load vars into current shell before launching claude

Manage MCP server files — drop .json files into ~/.agentihooks/:

agentihooks mcp             # list available MCP files
agentihooks mcp install     # interactive: pick one to install
agentihooks mcp uninstall   # interactive: pick one to remove
agentihooks mcp add <path>  # install directly by path

Details: Portability & Reusability

Extending

Add a new MCP tool category with a register(server) function + one line in _registry.py. Add a new hook handler with one function + one entry in the dispatcher dict.

Guide: Extending AgentiHooks

Code Quality

Continuously analyzed by SonarQube.

Related Projects

Project Description
agenticore Claude Code runner and orchestrator
agentibridge MCP server for session persistence and remote control
agentihub (private) Agent identities — CLAUDE.md, workflows, evaluation. Provisioned directly by agenticore.

License

See LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agentihooks-0.3.0.tar.gz (145.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agentihooks-0.3.0-py3-none-any.whl (157.1 kB view details)

Uploaded Python 3

File details

Details for the file agentihooks-0.3.0.tar.gz.

File metadata

  • Download URL: agentihooks-0.3.0.tar.gz
  • Upload date:
  • Size: 145.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for agentihooks-0.3.0.tar.gz
Algorithm Hash digest
SHA256 de1ce859df769abfcb5e3508568bf17a6070022a8723b6832d07ac2741b314f4
MD5 fcec2390d2f003166bd9ed9ed200c00e
BLAKE2b-256 13b0f326b3886a0a8477350fcfe741a0f7f0f1a29daed6f8b27c00eb6a465941

See more details on using hashes here.

Provenance

The following attestation bundles were made for agentihooks-0.3.0.tar.gz:

Publisher: publish-pypi.yml on The-Cloud-Clock-Work/agentihooks

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file agentihooks-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: agentihooks-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 157.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for agentihooks-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5084128ad9372d46892d7ffda3f07b656814a9add1aaa4ffdfd186a647fe27b1
MD5 bd9626b087d76c9257258ab89650d9e7
BLAKE2b-256 d5bc2812ef88634a5d6c2fdc3fe5cfc4a2b216c7bea05ca083e023af08b188d2

See more details on using hashes here.

Provenance

The following attestation bundles were made for agentihooks-0.3.0-py3-none-any.whl:

Publisher: publish-pypi.yml on The-Cloud-Clock-Work/agentihooks

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page