tool

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package tool defines tools that models can call, their JSON Schemas, a registry and an executor with middleware support.

Index

Constants

This section is empty.

Variables

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

ErrNotFound is returned when a tool is not registered.

Functions

func NeedsApproval

func NeedsApproval(t Tool, args json.RawMessage) bool

NeedsApproval reports whether a call of t with args needs approval: the answer of t's CallApprover, or else Info.RequiresApproval.

func Spec

func Spec(t Tool) *model.ToolSpec

Spec converts a tool to the specification sent to models.

func Truncate

func Truncate(s string, maxBytes int) string

Truncate shortens s to about maxBytes, preserving its head and tail.

func ValidateName

func ValidateName(name string) error

ValidateName reports whether name is accepted by all supported providers.

Types

type Call

type Call struct {
	ID        string
	Name      string
	Arguments json.RawMessage
	Tool      Tool
}

Call is a single tool invocation passed through middleware.

type CallApprover

type CallApprover interface {
	RequiresApprovalFor(args json.RawMessage) bool
}

CallApprover is implemented by tools whose need for approval depends on the arguments of a call, such as a shell that runs sandboxed commands without approval but asks before running one outside the sandbox. The runtime asks it instead of reading Info.RequiresApproval, which should then report whether some calls need approval.

type Executor

type Executor struct {
	Registry    *Registry
	Middlewares []Middleware
}

Executor runs tool calls from a registry through middleware.

func NewExecutor

func NewExecutor(registry *Registry, mws ...Middleware) *Executor

NewExecutor returns an executor for registry.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, tc *model.ToolCall) *model.ToolResult

Execute runs a model tool call. It never returns an error: unknown tools, invalid arguments, failures and panics become error results that are reported to the model so it can recover.

func (*Executor) ExecuteWith

func (e *Executor) ExecuteWith(ctx context.Context, tc *model.ToolCall, mws ...Middleware) *model.ToolResult

ExecuteWith is like Execute but wraps the call in mws outside the executor's own middleware; the first is outermost.

type Handler

type Handler func(ctx context.Context, args json.RawMessage) (*Result, error)

Handler is the raw implementation of a tool.

type Info

type Info struct {
	Name        string
	Description string
	// Parameters describes the arguments. Arguments are validated against it
	// before the tool runs.
	Parameters *Schema
	// RawParameters, when set, is sent to the model instead of Parameters and
	// disables argument validation. It is used for schemas that Schema
	// cannot represent, such as those of MCP tools.
	RawParameters json.RawMessage
	// ReadOnly marks a tool without side effects. The runtime runs adjacent
	// read-only calls concurrently.
	ReadOnly bool
	// Concurrent marks a tool whose calls may run in parallel with adjacent
	// concurrent or read-only calls even though they may have side effects,
	// such as sub-agents. Unlike ReadOnly it does not make a call safe to
	// repeat: a concurrent call with side effects that a stopped run cut off
	// is not run again when the run resumes.
	Concurrent bool
	// RequiresApproval asks the runtime to obtain approval before each call.
	RequiresApproval bool
	// Strict asks providers to guarantee schema-valid arguments. See
	// Strict for how the schema is converted.
	Strict bool
	// Grammar makes the tool freeform where the provider supports it; see
	// Freeform.
	Grammar *model.ToolGrammar
}

Info describes a tool to the model and to the runtime.

type Invoker

type Invoker func(ctx context.Context, call *Call) (*Result, error)

Invoker executes a call.

func Chain

func Chain(final Invoker, mws ...Middleware) Invoker

Chain composes middleware so that the first one is outermost.

type Middleware

type Middleware func(next Invoker) Invoker

Middleware wraps an Invoker.

func Allow

func Allow(names ...string) Middleware

Allow rejects calls to tools that are not in names.

func Timeout

func Timeout(d time.Duration) Middleware

Timeout limits each call to d.

func TruncateOutput

func TruncateOutput(maxBytes int) Middleware

TruncateOutput limits result content to max bytes, keeping the head and tail so the model still sees how the output ends.

type Option

type Option func(*Info)

Option configures a tool's Info.

func Concurrent

func Concurrent() Option

Concurrent lets calls of the tool run in parallel with adjacent concurrent or read-only calls; see Info.Concurrent.

func Freeform

func Freeform(syntax, definition string) Option

Freeform lets providers that support freeform tools, such as the OpenAI Responses API, have the model write the tool's input as plain text matching a grammar instead of JSON. syntax is "lark" or "regex"; an empty definition accepts any text. The text arrives as the string argument model.FreeformInput ("input"), which the parameters must declare and which carries the same text from providers without freeform tools.

func ReadOnly

func ReadOnly() Option

ReadOnly marks the tool as free of side effects.

func RequireApproval

func RequireApproval() Option

RequireApproval requires approval before each call.

func Strict

func Strict() Option

Strict enables strict argument generation where supported. The schema sent to the model is converted with Schema.StrictJSON; RawParameters are sent unchanged and must already satisfy the provider's strict rules.

func WithSchema

func WithSchema(s *Schema) Option

WithSchema overrides the derived parameter schema.

type PanicError

type PanicError struct {
	Tool  string
	Value any
	Stack []byte
}

PanicError reports a panic recovered from a tool. Only the panic value is shown to the model; Stack is available to middleware for logging.

func (*PanicError) Error

func (e *PanicError) Error() string

type Registry

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

Registry is a concurrency-safe set of tools keyed by name.

func NewRegistry

func NewRegistry(tools ...Tool) (*Registry, error)

NewRegistry returns a registry containing tools.

func (*Registry) Clone

func (r *Registry) Clone() *Registry

Clone returns a shallow copy of the registry.

func (*Registry) Get

func (r *Registry) Get(name string) (Tool, bool)

Get returns the named tool.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered tools.

func (*Registry) List

func (r *Registry) List() []Tool

List returns the tools sorted by name. The stable order keeps prompts byte-identical across requests, which preserves provider prompt caches.

func (*Registry) Register

func (r *Registry) Register(tools ...Tool) error

Register adds tools. It fails without registering anything if a name is invalid or already registered.

func (*Registry) Remove

func (r *Registry) Remove(names ...string)

Remove deletes tools by name.

func (*Registry) Specs

func (r *Registry) Specs() []*model.ToolSpec

Specs returns model specifications for all tools, sorted by name.

func (*Registry) Subset

func (r *Registry) Subset(names ...string) (*Registry, error)

Subset returns a new registry with only the named tools. Unknown names are reported as an error.

type Result

type Result struct {
	// Content is the text output.
	Content string
	// Parts holds output beyond text, such as images and documents, that
	// follows Content. See model.ToolResult.Parts for how providers send it.
	Parts   []model.Part
	IsError bool
	// Metadata is information for the application, such as for middleware
	// or event consumers; it is not sent to the model.
	Metadata map[string]any
}

Result is the output of a tool call.

func Errorf

func Errorf(format string, args ...any) *Result

Errorf returns an error result that is reported to the model.

func Media

func Media(content string, parts ...model.Part) *Result

Media returns a successful result with text and parts, such as images or documents: model.ImagePart, model.DocumentPart or model.MediaPart.

func Text

func Text(content string) *Result

Text returns a successful result.

type Schema

type Schema struct {
	Type                 string             `json:"type,omitempty"`
	Title                string             `json:"title,omitempty"`
	Description          string             `json:"description,omitempty"`
	Properties           map[string]*Schema `json:"properties,omitempty"`
	Required             []string           `json:"required,omitempty"`
	Items                *Schema            `json:"items,omitempty"`
	Enum                 []any              `json:"enum,omitempty"`
	Default              any                `json:"default,omitempty"`
	Format               string             `json:"format,omitempty"`
	Minimum              *float64           `json:"minimum,omitempty"`
	Maximum              *float64           `json:"maximum,omitempty"`
	ExclusiveMinimum     *float64           `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum     *float64           `json:"exclusiveMaximum,omitempty"`
	MinLength            *int               `json:"minLength,omitempty"`
	MaxLength            *int               `json:"maxLength,omitempty"`
	MinItems             *int               `json:"minItems,omitempty"`
	MaxItems             *int               `json:"maxItems,omitempty"`
	Pattern              string             `json:"pattern,omitempty"`
	AnyOf                []*Schema          `json:"anyOf,omitempty"`
	AdditionalProperties *bool              `json:"additionalProperties,omitempty"`
}

Schema is a JSON Schema subset suitable for describing tool arguments.

func Array

func Array(items *Schema, description string) *Schema

Array returns an array schema.

func Boolean

func Boolean(description string) *Schema

Boolean returns a boolean schema.

func Enum

func Enum(description string, values ...string) *Schema

Enum returns a string schema restricted to values.

func Integer

func Integer(description string) *Schema

Integer returns an integer schema.

func Number

func Number(description string) *Schema

Number returns a number schema.

func Object

func Object(props map[string]*Schema, required ...string) *Schema

Object returns an object schema with the given properties. Every property listed in required must exist in props.

func Reflect

func Reflect(t reflect.Type) *Schema

Reflect derives a schema from a Go type.

func SchemaOf

func SchemaOf[T any]() *Schema

SchemaOf derives an object schema from a Go struct type.

Properties are the fields encoding/json decodes, under the same names: json tags rename or omit fields, the exported fields of embedded structs are promoted, and outer fields shadow embedded ones. Fields promoted through an embedded pointer to an unexported struct type are left out, since encoding/json cannot allocate that struct when decoding. Fields with the ",string" option are strings, and byte slices, but not byte arrays, are base64 strings; arrays of length N require exactly N items. Fields without omitempty or omitzero that are not pointers are required.

The jsonschema struct tag describes a field in one of the two forms common in the Go ecosystem. A tag that starts with one of the keywords or flags below uses the keyword form of github.com/invopop/jsonschema: comma-separated key=value pairs and flags. A comma inside a value is escaped with a backslash, which the tag literal doubles:

jsonschema:"title=Unit,description=Unit\\, as a word,enum=celsius,enum=fahrenheit,default=celsius"

Any other tag is the field's description, as in github.com/google/jsonschema-go, which the official MCP Go SDK and ADK Go use; commas need no escaping there:

jsonschema:"City name, e.g. Tokyo"

The keywords are title, description, default, enum, format, pattern, minimum, maximum, exclusiveMinimum, exclusiveMaximum, minLength, maxLength, minItems and maxItems. enum may repeat, and so may default for slices and arrays. On a slice or array, enum, format, pattern and the numeric and length limits apply to its elements; minItems, maxItems and default to the slice itself. Values are parsed as the type of the field or element. The flag required makes a field required and nullable lets it be null; required=false makes a field optional. Unknown keywords are ignored, and a tag of "-" leaves the field out of the schema.

func String

func String(description string) *Schema

String returns a string schema.

func (*Schema) JSON

func (s *Schema) JSON() json.RawMessage

JSON returns the schema encoded as JSON.

func (*Schema) StrictJSON

func (s *Schema) StrictJSON() json.RawMessage

StrictJSON returns the schema encoded for providers' strict modes, which require every object to set additionalProperties to false and to list all of its properties as required. Optional properties become nullable instead, and Validate accepts null for them.

func (*Schema) Validate

func (s *Schema) Validate(raw json.RawMessage) error

Validate checks that raw JSON satisfies the schema. It supports the keywords represented by Schema.

The JSON must also be an I-JSON message (RFC 7493): objects that repeat a member name and strings that are not valid UTF-8 are rejected, since parsers disagree on which duplicate wins and how to repair invalid text, and the arguments of a call are read by hooks, permission rules and remote servers as well as by the tool.

type Tool

type Tool interface {
	Info() Info
	// Call runs the tool. Returning an error produces an error result that
	// the model can see; it does not stop the agent.
	Call(ctx context.Context, args json.RawMessage) (*Result, error)
}

Tool is a capability the model can invoke.

func Func

func Func[In, Out any](name, description string, fn func(ctx context.Context, in In) (Out, error), opts ...Option) Tool

Func returns a tool whose arguments are decoded into In. The parameter schema is derived from In with SchemaOf.

A string result becomes the tool output, a *Result is used as-is and any other value is encoded as JSON.

func New

func New(name, description string, params *Schema, fn Handler, opts ...Option) Tool

New returns a tool backed by a raw handler.

type ValidationError

type ValidationError struct {
	Problems []string
}

ValidationError describes arguments that do not satisfy a schema.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
Package builtin provides general-purpose tools modeled on those of coding agents such as Claude Code and Codex: file reading, writing and editing, patches, glob and grep search, shell commands, web fetching and a todo list.
Package builtin provides general-purpose tools modeled on those of coding agents such as Claude Code and Codex: file reading, writing and editing, patches, glob and grep search, shell commands, web fetching and a todo list.

Jump to

Keyboard shortcuts

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