guardrail

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	FallbackDeny      = "deny"      // reject everything that needs approval
	FallbackAllow     = "allow"     // allow all, rely on client-side tool approval
	FallbackDowngrade = "downgrade" // allow moderate ops, still deny dangerous
)

Fallback policies when client does not support Elicitation.

Variables

This section is empty.

Functions

func DefaultGuardrailConfig

func DefaultGuardrailConfig() *config.GuardrailConfig

DefaultGuardrailConfig returns sensible defaults when no config is provided.

func IsBlocked

func IsBlocked(cmd string) bool

IsBlocked returns true if the command matches a hard-blocked pattern.

func RequestApproval

func RequestApproval(ctx context.Context, session *mcp.ServerSession, risk RiskLevel, input RiskInput, fallback string) error

RequestApproval sends an Elicitation request to the MCP client, asking the user to approve a dangerous operation.

If the client does not support Elicitation, it falls back to the configured policy (deny / allow / downgrade).

func ValidateConfig added in v0.12.0

func ValidateConfig(cfg *config.GuardrailConfig) error

ValidateConfig checks if all glob patterns in the config are syntactically valid.

func WithGuardrail

func WithGuardrail[In, Out any](
	g *Guardrail,
	toolName string,
	riskInputFn func(In) RiskInput,
	handler mcp.ToolHandlerFor[In, Out],
) mcp.ToolHandlerFor[In, Out]

WithGuardrail wraps any typed tool handler with the full guardrail pipeline: classify -> policy -> approval -> pre-audit intent -> execute -> post-audit result.

riskInputFn extracts a RiskInput from the tool-specific input type.

Types

type AuditEntry

type AuditEntry struct {
	Timestamp   time.Time `json:"ts"`
	OperationID string    `json:"op_id"`
	Tool        string    `json:"tool"`
	NodeID      string    `json:"node,omitempty"`
	Command     string    `json:"command,omitempty"`
	Paths       []string  `json:"paths,omitempty"`
	RiskLevel   string    `json:"risk"`
	Decision    string    `json:"decision"`
	Outcome     string    `json:"outcome"` // "intent", "executed", "denied", "error"
	Error       string    `json:"error,omitempty"`
}

AuditEntry is a single line in the audit log.

type AuditLogger

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

AuditLogger writes JSON Lines to a file.

func NewAuditLogger

func NewAuditLogger(path string) *AuditLogger

NewAuditLogger creates a logger that writes to the given path. The path may contain ~ which is expanded to the user's home directory.

func (*AuditLogger) Log

func (a *AuditLogger) Log(entry AuditEntry) (err error)

Log appends an audit entry to the log file and returns any error encountered.

type AuditWriter added in v0.12.0

type AuditWriter interface {
	Log(entry AuditEntry) error
}

AuditWriter is the interface for writing audit entries.

type Decision

type Decision int

Decision represents the outcome of a policy evaluation.

const (
	Allow        Decision = iota // execute without approval
	NeedApproval                 // require user confirmation via Elicitation
	Deny                         // reject unconditionally
)

func (Decision) String

func (d Decision) String() string

type ExecutedPostAuditError added in v0.12.0

type ExecutedPostAuditError struct {
	OperationID string
	Err         error
}

ExecutedPostAuditError indicates the operation has already been executed successfully on the target, but the subsequent post-execution audit logging failed. Callers MUST NOT automatically retry.

func (*ExecutedPostAuditError) Error added in v0.12.0

func (e *ExecutedPostAuditError) Error() string

func (*ExecutedPostAuditError) Unwrap added in v0.12.0

func (e *ExecutedPostAuditError) Unwrap() error

type Guardrail

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

Guardrail coordinates risk classification, policy evaluation, approval, and audit logging for MCP tool invocations.

func New

func New(cfg *config.GuardrailConfig) *Guardrail

New creates a Guardrail from configuration. If cfg is nil, defaults are used.

func (*Guardrail) SetAuditWriter added in v0.12.0

func (g *Guardrail) SetAuditWriter(w AuditWriter)

SetAuditWriter replaces the underlying AuditWriter (useful for testing or custom sinks).

type Policy

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

Policy evaluates tool invocations against configurable rules.

func NewPolicy

func NewPolicy(cfg *config.GuardrailConfig) *Policy

NewPolicy creates a policy engine from config.

func (*Policy) Evaluate

func (p *Policy) Evaluate(risk RiskLevel, input RiskInput) Decision

Evaluate determines whether an invocation should be allowed, needs approval, or is denied.

type RiskInput

type RiskInput struct {
	ToolName string
	NodeID   string
	Command  string   // populated only for ssh_run
	Paths    []string // file/directory paths involved
	Sudo     bool     // whether sudo is requested
}

RiskInput carries contextual information about a single tool invocation for risk assessment.

type RiskLevel

type RiskLevel int

RiskLevel represents the danger level of a tool invocation.

const (
	Safe      RiskLevel = iota // read-only, no side effects
	Moderate                   // creates or modifies data, recoverable
	Dangerous                  // destructive or arbitrary execution
)

func AnalyzeCommand

func AnalyzeCommand(cmd string) RiskLevel

AnalyzeCommand returns the risk level for an ssh_run command string.

func AnalyzePaths

func AnalyzePaths(paths []string) RiskLevel

AnalyzePaths returns the highest risk level implied by the given paths.

func Classify

func Classify(input RiskInput) RiskLevel

Classify returns the effective risk level for a tool invocation. For ssh_run, it refines the level based on command analysis.

func ParseRiskLevel

func ParseRiskLevel(s string) RiskLevel

ParseRiskLevel converts a string to RiskLevel, defaulting to Dangerous.

func (RiskLevel) String

func (r RiskLevel) String() string

Jump to

Keyboard shortcuts

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