tool

package
v0.0.0-beta Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package tool defines the tool interface and collection operations.

Index

Constants

This section is empty.

Variables

View Source
var ErrToolCallParse = errors.New("tool call parse error")

ErrToolCallParse indicates a provider returned tool calls with unparseable JSON arguments. The assistant loop can detect this with errors.Is() to retry instead of terminating.

View Source
var ErrToolNotFound = errors.New("tool not found")

Functions

func ComposeDescription

func ComposeDescription(t Tool) string

ComposeDescription builds the full tool description from Description, Usage, and Examples. Used by GenerateSchema and by tools that build Schema dynamically (plugins).

func FileError

func FileError(op, path string, err error) error

FileError produces a clean, single-line error for LLM consumption. It unwraps through godyl's wrapping layers to the root OS error, classifies it, and returns "op path: reason" without stuttering.

Uses %v (not %w) because tool Execute() errors are terminal text for the LLM — they are never inspected with errors.Is() by Go callers.

func HTTPError

func HTTPError(host string, statusCode int) error

HTTPError produces a clean, single-line error for LLM consumption from non-200 HTTP status codes.

func NetworkError

func NetworkError(host string, err error) error

NetworkError produces a clean, single-line error for LLM consumption from network/HTTP client errors. It classifies timeouts, DNS failures, and connection errors into actionable messages.

func ResolvePath

func ResolvePath(ctx context.Context, path string) string

ResolvePath converts a relative path to absolute using the context's workdir. Absolute paths and empty workdir are returned as-is.

func SDKContextFromContext

func SDKContextFromContext(ctx context.Context) any

SDKContextFromContext extracts the SDK context from the Go context, or nil.

func ValidateInput

func ValidateInput[T any](args map[string]any, schema Schema) (*T, error)

ValidateInput converts a map to a typed struct and validates it. Rejects unknown fields and enriches errors with valid parameter names.

func ValidatePath

func ValidatePath(path string) error

ValidatePath rejects root path operations.

func WithSDKContext

func WithSDKContext(ctx context.Context, sc any) context.Context

WithSDKContext returns a derived context carrying an SDK context value. The value is typed as any because this package cannot import sdk.

func WithStreamCallback

func WithStreamCallback(ctx context.Context, cb StreamCallback) context.Context

WithStreamCallback returns a derived context carrying a streaming callback.

func WithWorkDir

func WithWorkDir(ctx context.Context, dir string) context.Context

WithWorkDir returns a derived context carrying the effective working directory.

func WorkDirFromContext

func WorkDirFromContext(ctx context.Context) string

WorkDirFromContext extracts the working directory from the context, or "".

Types

type Base

type Base struct {
	Text Text
}

Base provides default accessors for Description(), Usage(), Examples(), and Available() (true). Embed in tool structs to avoid boilerplate for the core text methods. Optional behaviors (Pre/Post hooks, path declaration, sandbox/parallel overrides, LSP, etc.) are expressed as separate opt-in interfaces — implement only the ones your tool needs.

func (Base) Available

func (Base) Available() bool

func (Base) Description

func (b Base) Description() string

func (Base) Examples

func (b Base) Examples() string

func (*Base) MergeText

func (b *Base) MergeText(t Text)

MergeText overwrites non-empty fields from t into the base text.

func (Base) Usage

func (b Base) Usage() string

type Closer

type Closer interface {
	Close()
}

Closer is optionally implemented by tools needing cleanup on session end.

type Filter

type Filter struct {
	// Enabled lists tool name patterns to include. Empty = all tools.
	Enabled []string
	// Disabled lists tool name patterns to exclude. Takes precedence over Enabled.
	Disabled []string
}

Filter defines enabled/disabled glob patterns for tool filtering. Used by agents, modes, and tasks to control tool availability. Patterns support '*' wildcards (e.g. "mcp__*", "Todo*").

func (Filter) IsSet

func (f Filter) IsSet() bool

IsSet returns true when at least one filter pattern is configured.

func (Filter) String

func (f Filter) String() string

String returns a human-readable summary like "+[Query,Patch] -[Bash]".

type LSPAware

type LSPAware interface {
	WantsLSP() bool
}

LSPAware is optionally implemented by tools whose output benefits from LSP diagnostics on modified files.

type Overrider

type Overrider interface {
	Overrides() bool
}

Overrider is optionally implemented by plugin tools that replace built-in tools.

type ParallelOverride

type ParallelOverride interface {
	Parallel() bool
}

ParallelOverride is optionally implemented by tools that override the default parallel=true behavior.

type Parameters

type Parameters struct {
	Type       string
	Properties map[string]Property
	Required   []string
}

Parameters describes the input parameters for a tool.

type PathDeclarer

type PathDeclarer interface {
	Paths(ctx context.Context, args map[string]any) (read, write []string, err error)
}

PathDeclarer is optionally implemented by tools that declare filesystem paths for sandbox pre-filtering.

type PostHook

type PostHook interface {
	Post(ctx context.Context, args map[string]any)
}

PostHook is optionally implemented by tools that need state updates after execution (e.g. filetime recording).

type PreHook

type PreHook interface {
	Pre(ctx context.Context, args map[string]any) error
}

PreHook is optionally implemented by tools that need validation before execution (e.g. filetime read-before-write enforcement).

type Previewer

type Previewer interface {
	Preview(ctx context.Context, args map[string]any) (string, error)
}

Previewer is optionally implemented by tools that can generate a diff preview for confirmation dialogs.

type Property

type Property struct {
	Type        string
	Description string
	Enum        []any

	// Items describes the element type for arrays (e.g., array of objects).
	Items *Property

	// Properties and Required describe fields for object types.
	Properties map[string]Property
	Required   []string
}

Property describes a single parameter. Supports nested schemas: Items for array element types, Properties/Required for object fields.

type ReadBeforePolicy

type ReadBeforePolicy struct {
	Write  bool // require read before overwriting existing files (default: true)
	Delete bool // require read before deleting files (default: false)
}

ReadBeforePolicy controls which file operations require a prior read.

func DefaultReadBeforePolicy

func DefaultReadBeforePolicy() ReadBeforePolicy

DefaultReadBeforePolicy returns the default policy: write enforcement on, delete off.

type SandboxOverride

type SandboxOverride interface {
	Sandboxable() bool
}

SandboxOverride is optionally implemented by tools that override the default sandboxable=true behavior.

type Schema

type Schema struct {
	Name        string
	Description string
	Parameters  Parameters
}

Schema represents a provider-agnostic tool definition.

func GenerateSchema

func GenerateSchema[T any](t Tool) Schema

GenerateSchema creates a tool schema from a type using JSON schema reflection.

func (Schema) ParamNames

func (s Schema) ParamNames() []string

ParamNames returns sorted parameter names for error messages.

func (Schema) Render

func (s Schema) Render() string

Render returns a text representation of the schema for token estimation.

func (Schema) ValidateArgs

func (s Schema) ValidateArgs(args map[string]any) error

ValidateArgs validates dynamic arguments against the schema. It collects all errors before returning, so the caller can fix everything in one pass.

type Schemas

type Schemas []Schema

Schemas is a collection of tool schemas.

func (Schemas) Render

func (ss Schemas) Render() string

Render returns a text representation of all schemas for token estimation.

type StreamCallback

type StreamCallback func(line string)

StreamCallback is called with each complete line of output during streaming execution.

func StreamCallbackFromContext

func StreamCallbackFromContext(ctx context.Context) StreamCallback

StreamCallbackFromContext extracts the streaming callback from the context, or nil.

type Text

type Text struct {
	Description string `yaml:"description"`
	Usage       string `yaml:"usage"`
	Examples    string `yaml:"examples"`
}

Text holds the user-facing text for a tool (description, usage instructions, examples). Loaded from Go defaults and optionally overridden by YAML config.

type Tool

type Tool interface {
	Name() string
	Description() string
	Usage() string
	Examples() string
	Schema() Schema
	Execute(ctx context.Context, args map[string]any) (string, error)
	Available() bool
}

Tool represents a callable tool for LLM function calling.

type Tools

type Tools []Tool

Tools is a collection of tools.

func (*Tools) Add

func (ts *Tools) Add(t Tool)

Add adds a tool if it doesn't already exist.

func (Tools) ExcludeOptIn

func (ts Tools) ExcludeOptIn(optIn, enabled []string) Tools

ExcludeOptIn removes tools that are in the optIn set unless they are explicitly mentioned (by name or narrow glob) in the enabled patterns. Bare "*" does not satisfy opt-in — only explicit names or narrow globs do.

func (Tools) Filtered

func (ts Tools) Filtered(include, exclude []string) Tools

Filtered returns the list of tools that match include/exclude slices. Patterns support '*' wildcards (e.g. "mcp__echo__*", "Todo*").

func (Tools) Get

func (ts Tools) Get(name string) (Tool, error)

Get retrieves a tool by name.

func (Tools) Has

func (ts Tools) Has(name string) bool

Has checks if a tool exists by name.

func (Tools) Names

func (ts Tools) Names() []string

Names returns the names of all tools.

func (*Tools) Remove

func (ts *Tools) Remove(name string)

Remove removes a tool by name.

func (Tools) Schemas

func (ts Tools) Schemas() Schemas

Schemas returns the schemas for all tools.

Directories

Path Synopsis
Package call defines the tool call type used in LLM messages.
Package call defines the tool call type used in LLM messages.

Jump to

Keyboard shortcuts

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