tools

package
v0.0.0-...-f424d6d Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package tools provides the built-in gage.Tool set (filesystem, shell, search, web) and a concurrency-safe ToolRegistry implementation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Func

func Func(name, description string, schema gage.JSONSchema, fn func(ctx context.Context, input json.RawMessage) (gage.ToolResult, error)) gage.Tool

Func builds a gage.Tool from a function and an explicit parameter schema.

func FuncWithMetadata

func FuncWithMetadata(name, description string, schema gage.JSONSchema, meta gage.ToolMetadata, fn func(ctx context.Context, input json.RawMessage) (gage.ToolResult, error)) gage.Tool

FuncWithMetadata builds a gage.Tool from a function and advisory metadata.

func Guard

func Guard(t gage.Tool, approver gage.Approver, agentName string) gage.Tool

Guard wraps a Tool so an Approver is consulted before every execution. A Deny decision returns an error ToolResult (visible to the model) without running the tool. agentName, if set, is passed to the Approver for context.

func GuardAll

func GuardAll(tools []gage.Tool, approver gage.Approver, agentName string) []gage.Tool

GuardAll wraps each tool with Guard.

func LimitConcurrency

func LimitConcurrency(t gage.Tool, max int) gage.Tool

LimitConcurrency wraps a Tool with a semaphore limiting concurrent executions. A max <= 0 leaves the tool unwrapped.

func LimitConcurrencyAll

func LimitConcurrencyAll(tools []gage.Tool, max int) []gage.Tool

LimitConcurrencyAll wraps every tool with LimitConcurrency.

func LimitResultSize

func LimitResultSize(t gage.Tool, maxBytes int) gage.Tool

LimitResultSize wraps a Tool so the total text content of its results is capped at maxBytes; oversized text is cut and a "...(result truncated)" marker appended, so giant results (MCP servers, custom tools) cannot blow the context window. Non-text content parts pass through untouched. A maxBytes <= 0 leaves the tool unwrapped.

func LimitResultSizeAll

func LimitResultSizeAll(tools []gage.Tool, maxBytes int) []gage.Tool

LimitResultSizeAll wraps every tool with LimitResultSize.

func NewBashTool

func NewBashTool(cfg BashConfig) gage.Tool

NewBashTool returns the bash tool.

func NewFSTools

func NewFSTools(cfg FSConfig) []gage.Tool

NewFSTools returns the read, write, edit and list_dir tools.

func NewSearchTools

func NewSearchTools(cfg FSConfig) []gage.Tool

NewSearchTools returns the grep and glob tools confined to cfg.Root.

func NewWebTools

func NewWebTools(cfg WebConfig) []gage.Tool

NewWebTools returns webfetch and (if a SearchProvider is set) websearch.

func SchemaOf

func SchemaOf[T any]() gage.JSONSchema

SchemaOf returns the JSON Schema reflected from the struct type T. It reflects exactly the same subset as Typed (json tag names, desc/enum tags, pointer/",omitempty" optionality, "additionalProperties": false) and, like Typed, panics when T is not a struct (after dereferencing pointers) or uses an unsupported field type: it is meant to run at program construction time. Use it to derive structured-output schemas (gage.ResponseFormat) from the same types you use for tool parameters.

func ToolFuncMust

func ToolFuncMust(name, description string, fn func(ctx context.Context, input json.RawMessage) (gage.ToolResult, error)) gage.Tool

ToolFuncMust builds a gage.Tool from a function with a permissive empty-object schema. Use Func when you need to describe parameters.

func Typed

func Typed[T any](name, description string, fn func(ctx context.Context, args T) (gage.ToolResult, error)) gage.Tool

Typed builds a gage.Tool whose parameter schema is derived from the struct type T by reflection, and whose inputs are unmarshaled into T before the handler runs.

Field mapping:

  • `json` tags name the parameters; fields tagged `json:"-"` are skipped.
  • `desc:"..."` tags become property descriptions.
  • `enum:"a,b,c"` tags constrain string fields to the listed values.
  • A field is required unless it is a pointer or its json tag carries ",omitempty".
  • Supported field types: string, bool, integers, floats, slices, arrays, nested structs, map[string]X, pointers to any of these, json.RawMessage and any/interface{} (both unconstrained). Anything else panics at construction time.

The top-level schema sets "additionalProperties": false. The schema is computed once at construction. Malformed input produces a model-visible error result naming the offending field, not a Go error.

func TypedWithMetadata

func TypedWithMetadata[T any](name, description string, meta gage.ToolMetadata, fn func(ctx context.Context, args T) (gage.ToolResult, error)) gage.Tool

TypedWithMetadata is Typed with advisory tool metadata attached.

Types

type BashConfig

type BashConfig struct {
	// Dir is the working directory for commands (default: process cwd).
	Dir string
	// Shell is the shell binary (default: "/bin/bash").
	Shell string
	// Env is the exact environment for commands. When nil, a minimal sanitized
	// environment is used: only PATH, HOME, LANG, TERM and TMPDIR are copied
	// from the parent process, so secrets in the agent's environment do not
	// leak to model-driven commands. Set Env explicitly (e.g. os.Environ())
	// to opt out.
	Env []string
	// DefaultTimeout applies when the model does not specify one (default 60s).
	DefaultTimeout time.Duration
	// MaxTimeout caps any requested timeout (default 600s).
	MaxTimeout time.Duration
	// MaxOutputBytes caps combined stdout+stderr returned (default 256 KiB).
	MaxOutputBytes int
	// Sandbox, when set, wraps command execution in an external sandbox runner
	// such as a container, VM launcher, firejail, bubblewrap, or platform
	// sandbox. gage still applies timeout, output cap and process-group kill.
	Sandbox BashSandbox
	// RequireSandbox makes Execute fail when Sandbox is nil. Use it for agents
	// that may receive untrusted model instructions.
	RequireSandbox bool
}

BashConfig configures the bash tool.

type BashInvocation

type BashInvocation struct {
	Command string
	Shell   string
	Dir     string
	Env     []string
}

BashInvocation is the command payload passed to a BashSandbox.

type BashSandbox

type BashSandbox interface {
	Name() string
	Command(ctx context.Context, inv BashInvocation) (*exec.Cmd, error)
}

BashSandbox constructs the process that should execute a bash invocation. Implementations should return an *exec.Cmd that runs inside a real external isolation boundary. The bash tool owns stdout/stderr, cancellation, timeout, and process-group termination around the returned command.

type ExternalSandbox

type ExternalSandbox struct {
	Label  string
	Binary string
	Args   []string
	Env    []string
	Dir    string
}

ExternalSandbox wraps bash execution in a caller-provided binary. Args may contain {{shell}}, {{command}}, and {{dir}} placeholders. If neither {{shell}} nor {{command}} appears, the invocation is appended as "<shell> -c <command>" after Args.

func (ExternalSandbox) Command

func (s ExternalSandbox) Command(ctx context.Context, inv BashInvocation) (*exec.Cmd, error)

func (ExternalSandbox) Name

func (s ExternalSandbox) Name() string

type FSConfig

type FSConfig struct {
	// Root, when set, is the base directory. Paths are resolved against it and
	// may not escape it.
	Root string
	// MaxReadBytes caps the bytes a single read returns: the text window of a
	// file, or the size of an image/PDF attachment (default 1 MiB).
	MaxReadBytes int64
	// MaxReadLines is the default and maximum number of lines read returns
	// per call (default 2000).
	MaxReadLines int
	// MaxLineBytes truncates longer lines in read output (default 2000).
	MaxLineBytes int
}

FSConfig confines filesystem tools to a root directory. A zero Root means the process working directory with no confinement.

type MapRegistry

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

MapRegistry is a concurrency-safe gage.ToolRegistry backed by a map.

func NewRegistry

func NewRegistry() *MapRegistry

NewRegistry returns an empty registry.

func (*MapRegistry) Get

func (r *MapRegistry) Get(name string) (gage.Tool, bool)

Get returns the tool with the given name.

func (*MapRegistry) List

func (r *MapRegistry) List() []gage.Tool

List returns all tools, sorted by name for determinism.

func (*MapRegistry) MustRegister

func (r *MapRegistry) MustRegister(ts ...gage.Tool)

MustRegister registers tools, panicking on error. Handy at startup.

func (*MapRegistry) Register

func (r *MapRegistry) Register(t gage.Tool) error

Register adds a tool, erroring on a duplicate name.

func (*MapRegistry) Schemas

func (r *MapRegistry) Schemas() []gage.ToolSchema

Schemas returns the ToolSchema of every tool.

func (*MapRegistry) Unregister

func (r *MapRegistry) Unregister(name string) bool

Unregister removes a tool by name, reporting whether it was present.

type WebConfig

type WebConfig struct {
	// Search backs the websearch tool. If nil, websearch is not returned by
	// NewWebTools.
	Search gage.SearchProvider
	// HTTP is the client used by webfetch (default: 30s timeout client).
	HTTP *http.Client
	// MaxFetchBytes caps webfetch output (default 512 KiB).
	MaxFetchBytes int64
	// UserAgent for webfetch requests.
	UserAgent string
	// AllowPrivateHosts permits localhost/private/link-local targets. Leave
	// false when webfetch is exposed to untrusted model input.
	AllowPrivateHosts bool
}

WebConfig configures the web tools.

Jump to

Keyboard shortcuts

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