guardrail

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 20 Imported by: ? 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() *policy.Config

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 OperationID

func OperationID(ctx context.Context) string

OperationID returns the ID assigned by the guardrail to an admitted handler.

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

func ValidateConfig(cfg *policy.Config) 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.

func WithPolicy

func WithPolicy(ctx context.Context, cfg policy.Config, binding string) context.Context

WithPolicy binds a defensive policy and operation identity to one invocation. Approval state stays owned by the original Guardrail across round trips.

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"`
	NodeIDs     []string  `json:"nodes,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"`
	Details     string    `json:"details,omitempty"`
	Binding     string    `json:"binding,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 host must explicitly resolve any home-directory shorthand.

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 AuditSink

type AuditSink interface {
	Append(context.Context, AuditEntry) error
}

AuditSink is a host-owned, context-aware audit destination. Append must finish within its context and must never retry the remote operation being recorded.

type AuditWriter

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

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

func (e *ExecutedPostAuditError) Error() string

func (*ExecutedPostAuditError) Unwrap

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 *policy.Config) *Guardrail

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

func NewWithAuditSink

func NewWithAuditSink(cfg *policy.Config, sink AuditSink) *Guardrail

NewWithAuditSink borrows a host-owned audit sink; it does not close it or discover a file path. The runtime validates the sink before construction.

func (*Guardrail) Authorize

func (g *Guardrail) Authorize(ctx context.Context, req *mcp.CallToolRequest, input RiskInput, completeInput any) (string, *mcp.CallToolResult, error)

Authorize prepares a deferred operation. It intentionally does not report executed: the caller must audit actual streaming and commit with the returned operation ID. Complete typed input is bound by the existing approval flow.

func (*Guardrail) Evaluate

func (g *Guardrail) Evaluate(input RiskInput) Decision

Evaluate checks policy without executing an operation or requesting approval. It allows callers to reject a forbidden path before resolving remote metadata.

func (*Guardrail) EvaluateContext

func (g *Guardrail) EvaluateContext(ctx context.Context, input RiskInput) Decision

func (*Guardrail) RecordAuthorized

func (g *Guardrail) RecordAuthorized(operationID string, input RiskInput, outcome string, cause error) error

RecordAuthorized records a phase of an already-authorized immutable task. It grants no permissions and is not a replacement for Authorize.

func (*Guardrail) RecordAuthorizedContext

func (g *Guardrail) RecordAuthorizedContext(ctx context.Context, operationID string, input RiskInput, outcome string, cause error) error

RecordAuthorizedContext records a bounded phase without granting permission.

func (*Guardrail) SetAuditWriter

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 *policy.Config) *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
	Action     string // polymorphic sub-action (e.g. read/write/patch/stat, push/pull, create/list/status/stop)
	NodeID     string
	NodeIDs    []string // additional canonical nodes covered by a batch operation
	Command    string   // populated for terminal command execution
	Text       string   // keystrokes typed into a remote GUI session (gui type)
	Paths      []string // file/directory paths involved
	Sudo       bool     // whether sudo is requested
	Details    string   // deferred-operation size, digest and overwrite information
	TunnelMode string   // local, remote, or dynamic SSH forwarding
	ListenHost string   // normalized IP literal, never resolved through DNS
	Execution  *ssh.ExecutionConfig
	Dialect    string
	PlanDigest string
}

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 under POSIX dialect.

func AnalyzeCommandWithDialect

func AnalyzeCommandWithDialect(cmd string, dialect string) RiskLevel

AnalyzeCommandWithDialect returns the risk level for an ssh_run command string under a specified launch dialect. If the launch dialect is unknown or non-POSIX, POSIX safe prefixes cannot be trusted, and the command is treated as at least Moderate.

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.

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