claudeers.

🔓 unclaimed — this page was auto-generated from GitHub. Are you the creator?

Claim this page →
// Finance & Trading

claude-warden

Security hooks and monitoring for Claude Code — quiet overrides, SSRF protection, MCP compression, OTEL tracing

Slowing down
83/100
last commit 3 months ago
last release 3 months ago
releases 6
open issues 0
// install
git clone https://github.com/johnzfitch/claude-warden
claude-warden
# claude-warden

claude-warden(token guardian) is a hook system for Claude Code that intercepts every tool call before and after execution. It silences verbose commands, compresses large outputs, blocks unsafe network calls, enforces subagent budgets, and surfaces a live statusline — saving tens of thousands of tokens per session with negligible added latency.

claude-warden Quickstart

  1. Install prerequisites: jq (required). Optional: rg, fd.
  2. Install hooks into ~/.claude/ (symlink mode):
    ./install.sh
    
  3. Choose a profile when prompted (or pass --profile standard).
  4. Start a new Claude Code session. Hooks run automatically.

[!TIP] Run ./install.sh --dry-run first to preview every change before anything touches ~/.claude/.

./install.sh --dry-run

claude-warden What it does

claude-warden installs shell hooks that intercept every Claude Code tool call. Each hook enforces token-efficient patterns and blocks unsafe operations.

Guard catalog

Guard catalog — 15 hooks organized by lifecycle phase: pre-execution, post-execution, lifecycle, and observation
HookDimensions — 3D visualization of the hook enforcement layers

claude-warden Architecture

WardenPipelineFlow — animated token savings walkthrough showing data flowing through all three layers
Token savings pipeline — tool calls enter the hook membrane, get silenced/compressed/blocked, and exit with fewer tokens. Three-layer architecture: Claude Code → Hook Membrane (bash) → warden-collector (Go) → SQLite + OTLP Claude Code tool calls pass through the hook membrane (bash enforcement) into the warden-collector Go backbone, which stores spans in WAL-mode SQLite and enforces subagent budgets via sub-millisecond stat() checks.

claude-warden Requirements

DependencyPurpose
RequiredjqJSON processing
Go 1.23+Builds the warden-collector binary
Recommendedrg, fdFaster search/find in hooks
Optionalpython3Warden-viewer web UI
mitmdumpAPI capture tool only

claude-warden Install

Quick install (latest release)

curl -fsSL https://raw.githubusercontent.com/johnzfitch/claude-warden/master/install-remote.sh | bash

Downloads a release tarball, verifies its SHA-256 checksum, validates contents, then runs install.sh --copy.

To pin a version:

curl -fsSL https://raw.githubusercontent.com/johnzfitch/claude-warden/master/install-remote.sh | bash -s -- v0.6.1
Install from source (development)
git clone https://github.com/johnzfitch/claude-warden.git ~/dev/claude-warden
cd ~/dev/claude-warden
./install.sh

claude-warden Profiles

The installer applies a configuration profile that sets token limits, tool permissions, and internal thresholds. Choose one during install or pass --profile:

ProfileWhat it sets
minimalHooks only. No env or permission changes. For users who manage settings.json themselves.
standardToken/output limits, OTEL monitoring, 40 safe tool permissions. Recommended.
strict~40% tighter limits. Fewer pre-approved tools (19). Lower subagent budgets.
./install.sh --profile standard

Profiles live in config/profiles/. Create config/user.json (gitignored) for personal overrides:

cp config/user.json.template config/user.json
# Edit config/user.json, then re-install:
./install.sh --profile standard

Merge order: defaults.json ← profile ← user.json ← existing settings.json (non-warden keys preserved).

Install modes & what install.sh does
ModeCommandBehavior
Symlink (default)./install.shEdits to repo take effect immediately
Copy./install.sh --copyFiles independent of repo
Dry run./install.sh --dry-runPreview changes, write nothing

What install.sh does:

  1. Checks prerequisites (jq required, warns if rg/fd missing). Detects platform. Backs up existing hooks and settings.json.
  2. Prompts for a profile (or uses --profile). Deep-merges defaults.json + profile + user.json.
  3. Symlinks (or copies) hook scripts + lib/ + statusline.sh into ~/.claude/.
  4. Builds the Go collector and installs to ~/.local/bin/.
  5. Generates warden.env (thresholds). Merges env vars and permissions into settings.json.
  6. Validates JSON and shell syntax for every installed script.

claude-warden Uninstall

./uninstall.sh

Restores your most recent settings.json backup. Removes ~/.claude/.warden/ config. Hook backups remain in ~/.claude/hooks.bak.*/.

claude-warden Configuration

claude-warden Tuning thresholds

All thresholds are configurable via config/defaults.json, profiles, or config/user.json. After editing, re-run ./install.sh to regenerate ~/.claude/.warden/warden.env.

ThresholdConfig keyDefaultStrict
Output truncationwarden.truncate_bytes20KB10KB
Subagent read capwarden.subagent_read_bytes10KB6KB
Output suppressionwarden.suppress_bytes512KB256KB
Read file size limitwarden.read_guard_max_mb2MB1MB
Write max sizewarden.write_max_bytes100KB50KB
Edit max sizewarden.edit_max_bytes50KB25KB
Subagent call limitswarden.subagent_call_limits.*15–4010–25
Subagent byte limitswarden.subagent_byte_limits.*80–150KB50–100KB

Token limits and tool permissions are set in the env and permissions sections of the config files and merged into settings.json during install.

  • Read compression: read-compress — subagent threshold at 300 lines, main agent at 500 lines
  • Binary detection: post-tool-use — POSIX od + grep for NUL bytes (full-stream scan)
Shell environment, token accounting, disabling guards, custom allow-list

Shell environment

Add to ~/.zshrc or ~/.bashrc:

# claude-warden env
source "$HOME/.claude/.warden/warden.env.sh"

Exports OTEL, token limit, timeout, and sandbox vars from your profile into every new shell.

Token savings accounting

All hooks report savings to ~/.claude/.statusline/events.jsonl at ~3.5 bytes/token (estimated). For exact counts:

export WARDEN_TOKEN_COUNT=api

Each truncation event spawns a background call to the Anthropic token counting API (free, separate rate limits) and appends a correction event. Zero added latency.

Requirements for API mode
ANTHROPIC_API_KEY in environment; python3 with anthropic installed
Custom Python path
Set WARDEN_PYTHON=/path/to/venv/bin/python3 if needed
Graceful degradation
Missing key, missing package, or network failure → silently exits, estimate stands

Disabling specific guards

Remove the corresponding matcher from settings.hooks.json and re-run ./install.sh. Example — disable read compression:

{
  "matcher": "Read",
  "hooks": [{"type": "command", "command": "$HOME/.claude/hooks/read-compress", "timeout": 7}]
}

Adding your own permission allow-list

cp config/user.json.template config/user.json
{
  "permissions": {
    "allow": ["Bash(gh api:*)", "Bash(pacman -Q:*)", "mcp__filesystem__list_directory"]
  }
}

Re-run ./install.sh to merge. User permissions are unioned with profile permissions — nothing is removed.

claude-warden Platform support

PlatformStatusNotes
LinuxFull supportPrimary development platform
macOSFull supportgtimeout fallback, osascript notifications, macOS stat flags
WSLFull supportDetected via /proc/version
Cross-platform details
  • timeout: Falls back to gtimeout (coreutils), then no-timeout
  • stat: Uses -c%s (Linux) with -f%z (macOS) fallback
  • flock: Replaced with mkdir-based locking (atomic on all POSIX)
  • notify-send: Falls back to osascript (macOS), silently skips if neither available
  • rg: Falls back to grep where used
  • Binary detection: Uses od -An -tx1 | grep ' 00' (POSIX, works on macOS/Linux/BSD)

claude-warden Go Collector

The warden-collector is a Go service that provides session tracking, subagent budget enforcement, and OTLP span ingestion. It starts automatically on session-start and stops when idle.

Collector internals, data storage & viewer
  • Session tracking — per-session token counts, model info, context window in WAL-mode SQLite
  • OTLP receiver — listens on :4319 for traces from Claude Code, extracts llm_request spans
  • Subagent budgets — tracks call counts and bytes; writes deny files checked by pre-tool-use via stat()
  • Hook events — accepts events via POST /v1/ingest/hook over Unix domain socket
  • Query APIGET /v1/sessions, GET /v1/sessions/{id}/context (used by statusline)

Data storage${XDG_STATE_HOME:-~/.local/state}/claude-warden/:

FilePurpose
collector.dbSQLite database (sessions, events, budgets, OTLP spans)
collector.sockUnix domain socket for hook → collector communication
collector.pidPID file for lifecycle management
budget-deny-*Deny files written when subagent budgets are exceeded

Viewer — optional htmx web UI on port 8477:

python3 viewer/warden-viewer.py

claude-warden Monitoring stack (optional)

Optional Docker stack in monitoring/ for log aggregation, metrics, and tracing. Supplements the Go collector with Grafana dashboards and long-term storage.

Components, setup, data flow, dashboards
ServiceImagePortPurpose
Lokigrafana/loki:3.4.23100Log aggregation (30-day retention)
OTEL Collectorotel/opentelemetry-collector-contrib4317/4318OTLP logs + traces, tails events.jsonl
Prometheusprom/prometheus9090Metrics
Node Exporterprom/node-exporter9101Textfile collector for budget metrics
Tempografana/tempo:2.7.23200/3205Trace storage
Grafanagrafana/grafana3000Dashboards (admin/admin)

Start (Linux):

cd monitoring && docker compose up -d

macOS / Docker Desktop:

cd monitoring && docker compose -f docker-compose.yml -f docker-compose.macos.yml up -d

Dashboards — four provisioned in monitoring/grafana/dashboards/: cost/tokens/budget (claude-code-otel), tool latency/traces (warden-tool-latency), output size/tokens (warden-output-size), subagent/session lifecycle (warden-subagent-lifecycle).

Verification:

curl -s http://localhost:3100/ready   # Loki
curl -s http://localhost:3200/ready   # Tempo
grep tool_latency ~/.claude/.statusline/events.jsonl | tail -5
claude-warden API capture

MITM proxy wrapper in capture/ for recording Claude Code API traffic.

capture/claude                          # interactive session
capture/claude -p "prompt"             # non-interactive

Logs land in ~/claude-captures/YYYY-MM-DD/capture-HHMMSS.jsonl.

[!IMPORTANT] Bodies are truncated to 200 chars by default. Set WARDEN_CAPTURE_BODIES=1 for full capture. Sensitive keys (system, messages) are always redacted.

  • Requires: mitmdump + trusted CA cert at ~/.mitmproxy/mitmproxy-ca-cert.pem
  • Permissions: JSONL files created with mode 600
  • Scrubbing: x-api-key, authorization, proxy-authorization headers redacted
claude-warden Project layout
PathPurpose
hooks/Hook scripts (bash)
hooks/lib/common.shShared library: parsing, events, latency, cross-platform shims
hooks/lib/otel-trace.shOTLP/HTTP trace span emitter
config/Defaults, profiles (minimal/standard/strict), user overrides
collector/Go collector: SQLite, OTLP receiver, budget enforcement
viewer/htmx web UI (sessions, tokens, events)
capture/MITM proxy for API traffic capture
statusline.shClaude Code statusline script
settings.hooks.jsonHook config merged into ~/.claude/settings.json
install.shInstall hooks, merge config, generate warden.env
uninstall.shRemove hooks, restore settings backup
monitoring/Optional Docker stack (Loki, OTEL Collector, Prometheus, Tempo, Grafana)
tests/Fixture-driven test harness

claude-warden How it works

Claude Code supports hooks — shell commands that run at specific points in the tool-use lifecycle. Hooks receive JSON on stdin describing the tool call and can:

  • Exit 0: Allow the tool call (optionally with {"suppressOutput":true})
  • Exit 2: Block the tool call (stderr message is fed back to Claude as feedback)
  • Output JSON: Modify tool output ({"modifyOutput":"..."}) or suppress it

Hooks are pure bash with a single dependency (jq). They run in milliseconds. All paths use $HOME for portability. Every decision (block, truncate, compress, strip) is logged to events.jsonl with token savings estimates.

claude-warden Testing

Run the test harness:

bash tests/run.sh

It runs shell syntax checks, validates JSON fixtures, and executes fixture-driven behavioral assertions covering pre-tool-use blocking/allow, post-tool-use output tracking/truncation, read-compress, permission-request, and statusline rendering.

Manual checks
# Shell syntax
find hooks -maxdepth 1 -type f -print0 | xargs -0 bash -n
bash -n install.sh uninstall.sh statusline.sh

# JSON validity
jq . settings.hooks.json config/defaults.json config/profiles/*.json >/dev/null

# Exercise post-tool-use fixture (system reminder stripping)
cat demo/mock-inputs/post-tool-use-reminder-bash.json | hooks/post-tool-use | jq -r '.modifyOutput'

claude-warden Troubleshooting

Hooks don't seem to run
  1. Confirm ~/.claude/settings.json contains the hooks key: jq '.hooks | keys' ~/.claude/settings.json
  2. Start a fresh session — hooks load at startup, not mid-session.
  3. Commands in permissions.allow bypass the permission-request hook entirely.
Read is being blocked unexpectedly

read-guard blocks bundled/generated patterns (node_modules/, dist/, minified JS) and files larger than 2MB (configurable via warden.read_guard_max_mb). Use bounded reads or find the source file.

macOS Docker Desktop networking issues

The base docker-compose.yml uses network_mode: host, which Docker Desktop does not support. Use the macOS override:

docker compose -f docker-compose.yml -f docker-compose.macos.yml up -d

This switches to bridge networking and replaces localhost with Docker service DNS names.

Hooks don't run in a specific project directory

Claude Code gates hooks on workspace trust. Until the project's CLAUDE.md is accepted at launch, all hooks are skipped. Symptom:

Skipping PreToolUse:Bash hook execution - workspace trust not accepted

Fix: create a CLAUDE.md in the project root. Press Enter to accept it on next session start.

Contributing

See CONTRIBUTING.md.

claude-warden Security

See SECURITY.md for security assumptions, data handling notes, and reporting guidance.

License

MIT

// compatibility

Platformsapi, desktop, web
Operating systems
AI compatibilityclaude
LicenseMIT
Pricingopen-source
LanguageShell

// faq

What is claude-warden?

Security hooks and monitoring for Claude Code — quiet overrides, SSRF protection, MCP compression, OTEL tracing. It is open-source on GitHub.

Is claude-warden free to use?

claude-warden is open-source under the MIT license, so it is free to use.

What category does claude-warden belong to?

claude-warden is listed under security in the Claudeers registry of Claude-compatible tools.

0 views
57 stars
unclaimed
updated 15 days ago

// embed badge

claude-warden on Claudeers
[![Claudeers](https://claudeers.com/api/badge/claude-warden.svg)](https://claudeers.com/claude-warden)

// retro hit counter

claude-warden hit counter
[![Hits](https://claudeers.com/api/counter/claude-warden.svg)](https://claudeers.com/claude-warden)

// reviews

// guestbook

0/500

// related in Finance & Trading

🔓

An AI SKILL that provide design intelligence for building professional UI/UX multiple platforms

// financenextlevelbuilder/Python100,423MIT[ claude ]
🔓

TradingAgents: Multi-Agents LLM Financial Trading Framework

// financeTauricResearch/Python90,619Apache-2.0[ claude ]
🔓

"AI-Trader: 100% Fully-Automated Agent-Native Trading"

// financeHKUDS/Python20,389[ claude ]
🔓

"Vibe-Trading: Your Personal Trading Agent"

// financeHKUDS/Python17,979MIT[ claude ]
→ see how claude-warden connects across the ecosystem