hooks

package
v0.31.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidateHookConfig

func ValidateHookConfig(config *HookConfig) error

ValidateHookConfig validates the entire hook configuration for correctness and security. It checks event validity, regex patterns, hook definitions, and performs security validation on all commands. Returns an error describing any validation failures.

Types

type CommonInput

type CommonInput struct {
	SessionID      string    `json:"session_id"`      // Unique session identifier
	TranscriptPath string    `json:"transcript_path"` // Path to transcript file (if enabled)
	CWD            string    `json:"cwd"`             // Current working directory
	HookEventName  HookEvent `json:"hook_event_name"` // The hook event type
	Timestamp      int64     `json:"timestamp"`       // Unix timestamp when hook fired
	Model          string    `json:"model"`           // AI model being used
	Interactive    bool      `json:"interactive"`     // Whether in interactive mode
}

CommonInput contains fields common to all hook inputs, providing context information that is available to every hook regardless of the event type. These fields help hooks understand the execution environment and session state.

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor handles hook execution for MCPHost lifecycle events. It manages hook configuration, executes matching hooks in parallel, and processes their outputs to determine application behavior.

func NewExecutor

func NewExecutor(config *HookConfig, sessionID, transcriptPath string) *Executor

NewExecutor creates a new hook executor with the given configuration, session ID, and transcript path. The executor manages hook execution throughout the application lifecycle.

func (*Executor) ExecuteHooks

func (e *Executor) ExecuteHooks(ctx context.Context, event HookEvent, input interface{}) (*HookOutput, error)

ExecuteHooks runs all matching hooks for an event. For tool-related events, it matches hooks based on tool name patterns. Hooks are executed in parallel with configurable timeouts. Returns a combined HookOutput from all executed hooks, with blocking decisions taking precedence.

func (*Executor) PopulateCommonFields

func (e *Executor) PopulateCommonFields(event HookEvent) CommonInput

PopulateCommonFields fills in the common fields for any hook input, including session ID, transcript path, working directory, event name, timestamp, model, and interactive mode. These fields provide context to hooks regardless of event type.

func (*Executor) SetInteractive

func (e *Executor) SetInteractive(interactive bool)

SetInteractive sets whether the application is running in interactive mode. This information is passed to hooks for mode-specific behavior.

func (*Executor) SetModel

func (e *Executor) SetModel(model string)

SetModel sets the model name for hook context. This information is passed to hooks as part of their input data for context-aware processing.

type HookConfig

type HookConfig struct {
	Hooks map[HookEvent][]HookMatcher `yaml:"hooks" json:"hooks"`
}

HookConfig represents the complete hooks configuration containing event-triggered hooks for tool execution lifecycle events.

func LoadHooksConfig

func LoadHooksConfig(customPaths ...string) (*HookConfig, error)

LoadHooksConfig loads and merges hook configurations from multiple sources. It searches for hooks.{json,yml} files in standard locations (XDG config directory, local .mcphost directory) and any custom paths provided. Configurations are merged with later sources taking precedence. Environment variable substitution is applied to all loaded configurations.

type HookEntry

type HookEntry struct {
	Type    string `yaml:"type" json:"type"`
	Command string `yaml:"command" json:"command"`
	Timeout int    `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}

HookEntry defines a single hook command to execute. Type specifies the command type (e.g., "bash"), Command contains the actual command to run, and Timeout optionally specifies the maximum execution time in seconds.

type HookEvent

type HookEvent string

HookEvent represents a point in MCPHost's lifecycle where hooks can be executed. Events can be tool-related (requiring matchers) or lifecycle-related.

const (
	// PreToolUse fires before any tool execution, allowing pre-processing or validation
	PreToolUse HookEvent = "PreToolUse"

	// PostToolUse fires after tool execution completes, allowing post-processing or logging
	PostToolUse HookEvent = "PostToolUse"

	// UserPromptSubmit fires when user submits a prompt, before agent processing
	UserPromptSubmit HookEvent = "UserPromptSubmit"

	// Stop fires when the main agent finishes responding to a user prompt
	Stop HookEvent = "Stop"
)

func (HookEvent) IsValid

func (e HookEvent) IsValid() bool

IsValid returns true if the event is a valid hook event. Valid events are PreToolUse, PostToolUse, UserPromptSubmit, and Stop.

func (HookEvent) RequiresMatcher

func (e HookEvent) RequiresMatcher() bool

RequiresMatcher returns true if the event uses tool matchers. PreToolUse and PostToolUse events require matchers to determine which tools trigger the hooks. Other events apply globally without matchers.

type HookMatcher

type HookMatcher struct {
	Matcher string      `yaml:"matcher,omitempty" json:"matcher,omitempty"`
	Merge   string      `yaml:"_merge,omitempty" json:"_merge,omitempty"`
	Hooks   []HookEntry `yaml:"hooks" json:"hooks"`
}

HookMatcher matches specific tools and defines hooks to execute. The Matcher field contains a pattern to match tool names, and Hooks contains the commands to run when a match occurs. The Merge field controls how this matcher combines with others.

type HookOutput

type HookOutput struct {
	Continue       *bool  `json:"continue,omitempty"`
	StopReason     string `json:"stopReason,omitempty"`
	SuppressOutput bool   `json:"suppressOutput,omitempty"`
	Decision       string `json:"decision,omitempty"` // "approve", "block", or ""
	Reason         string `json:"reason,omitempty"`
}

HookOutput represents the JSON output from a hook that controls MCPHost behavior. Hooks can decide whether to continue execution, provide reasons for stopping, suppress output, or block tool execution. The Decision field can be "approve", "block", or empty (default behavior).

type PostToolUseInput

type PostToolUseInput struct {
	CommonInput
	ToolName     string          `json:"tool_name"`
	ToolInput    json.RawMessage `json:"tool_input"`
	ToolResponse json.RawMessage `json:"tool_response"`
}

PostToolUseInput is passed to PostToolUse hooks after a tool has been executed. It contains the tool name, input parameters, and the tool's response, allowing hooks to log, analyze, or react to tool execution results.

type PreToolUseInput

type PreToolUseInput struct {
	CommonInput
	ToolName  string          `json:"tool_name"`
	ToolInput json.RawMessage `json:"tool_input"`
}

PreToolUseInput is passed to PreToolUse hooks before a tool is executed. It contains the tool name and input parameters, allowing hooks to validate, modify, or block tool execution.

type StopInput

type StopInput struct {
	CommonInput
	StopHookActive bool            `json:"stop_hook_active"`
	Response       string          `json:"response"`       // The agent's final response
	StopReason     string          `json:"stop_reason"`    // "completed", "cancelled", "error"
	Meta           json.RawMessage `json:"meta,omitempty"` // Additional metadata (e.g., token usage, model info)
}

StopInput is passed to Stop hooks when the agent finishes responding to a prompt. It contains the final response, completion reason, and optional metadata about the interaction, allowing hooks to perform cleanup or logging operations.

type UserPromptSubmitInput

type UserPromptSubmitInput struct {
	CommonInput
	Prompt string `json:"prompt"`
}

UserPromptSubmitInput is passed to UserPromptSubmit hooks when a user submits a prompt. It contains the user's input text, allowing hooks to validate, modify, or log user interactions before processing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL