Files
kit/examples/hooks/bash-validator.py
T
Ed Zynda cdc4abfb36 Add comprehensive hooks system for MCPHost lifecycle events (#111)
* Add comprehensive hooks system for MCPHost lifecycle events

Implements a flexible hooks system based on Anthropic Claude Code specification:

- **Hook Events**: PreToolUse, PostToolUse, UserPromptSubmit, Stop
- **Hook Types**: Command execution with JSON input/output
- **Configuration**: XDG-compliant with layered config support
- **Security**: Command validation, timeout controls, safe execution
- **Common Fields**: Consistent session ID, timestamps, model info across all hooks

Key features:
- Hooks receive JSON via stdin and can control flow via stdout
- Pattern matching for tool-specific hooks (regex support)
- Enhanced Stop hook with agent response and metadata
- Centralized session management with consistent IDs
- Built-in examples for logging, validation, and monitoring

This enables users to:
- Log and audit all tool usage and prompts
- Implement custom security policies
- Track usage metrics and model performance
- Integrate with external systems
- Build custom workflows around MCPHost

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <noreply@opencode.ai>

* Enable hooks in script mode

Previously, hooks were only initialized and executed in normal mode but not
in script mode. This was because script mode had its own execution path that
bypassed the hook initialization code.

This fix:
- Adds hook initialization to runScriptMode function
- Creates hook executor with proper session ID and model info
- Passes the hook executor to runAgenticLoop

Now hooks work consistently across all execution modes (normal, script, and
interactive), ensuring uniform behavior for logging, validation, and monitoring.

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <noreply@opencode.ai>

* Remove unnecessary hooks.local.yml pattern

The .local.yml pattern adds unnecessary complexity. Users who want project-specific
hooks that aren't committed to git can simply add .mcphost/ to their .gitignore.

This simplifies the hooks configuration loading and makes it clearer that:
- Global user hooks go in ~/.config/mcphost/hooks.yml
- Project-specific hooks go in .mcphost/hooks.yml
- Git ignore management is left to the user

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <noreply@opencode.ai>

* Fix hooks test isolation and add --no-hooks flag

- Fix TestLoadHooksConfig by setting temporary XDG_CONFIG_HOME to prevent loading global hooks
- Add --no-hooks flag to disable all hooks execution across all modes
- Update README with documentation for the new flag
- Add test to verify hooks loading behavior

This allows users to temporarily disable hooks for security or debugging purposes.

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <noreply@opencode.ai>

---------

Co-authored-by: opencode <noreply@opencode.ai>
2025-07-24 13:56:33 +03:00

57 lines
1.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Validates bash commands before execution.
Blocks dangerous commands and suggests alternatives.
"""
import json
import sys
import re
# Define validation rules
DANGEROUS_PATTERNS = [
(r'\brm\s+-rf\s+/', "Dangerous command: rm -rf /"),
(r'\bdd\s+.*\bof=/dev/[sh]d[a-z]', "Direct disk write detected"),
(r'>\s*/dev/null\s+2>&1', "Consider using proper error handling instead of discarding stderr"),
]
SUGGEST_ALTERNATIVES = {
r'\bgrep\b': "Use 'rg' (ripgrep) for better performance",
r'\bfind\s+.*-name': "Use 'fd' for faster file finding",
}
def main():
try:
# Read input
input_data = json.load(sys.stdin)
# Only process bash commands
if input_data.get('tool_name') != 'bash':
sys.exit(0)
command = json.loads(input_data.get('tool_input', '{}')).get('command', '')
# Check dangerous patterns
for pattern, message in DANGEROUS_PATTERNS:
if re.search(pattern, command, re.IGNORECASE):
print(message, file=sys.stderr)
sys.exit(2) # Block execution
# Suggest alternatives
suggestions = []
for pattern, suggestion in SUGGEST_ALTERNATIVES.items():
if re.search(pattern, command):
suggestions.append(suggestion)
if suggestions:
output = {
"decision": "approve",
"reason": "Command approved. Suggestions: " + "; ".join(suggestions)
}
print(json.dumps(output))
except Exception as e:
print(f"Hook error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()