Documentation
¶
Overview ¶
Package tool defines tools that models can call, their JSON Schemas, a registry and an executor with middleware support.
Index ¶
- Variables
- func NeedsApproval(t Tool, args json.RawMessage) bool
- func Spec(t Tool) *model.ToolSpec
- func Truncate(s string, maxBytes int) string
- func ValidateName(name string) error
- type Call
- type CallApprover
- type Executor
- type Handler
- type Info
- type Invoker
- type Middleware
- type Option
- type PanicError
- type Registry
- func (r *Registry) Clone() *Registry
- func (r *Registry) Get(name string) (Tool, bool)
- func (r *Registry) Len() int
- func (r *Registry) List() []Tool
- func (r *Registry) Register(tools ...Tool) error
- func (r *Registry) Remove(names ...string)
- func (r *Registry) Specs() []*model.ToolSpec
- func (r *Registry) Subset(names ...string) (*Registry, error)
- type Result
- type Schema
- func Array(items *Schema, description string) *Schema
- func Boolean(description string) *Schema
- func Enum(description string, values ...string) *Schema
- func Integer(description string) *Schema
- func Number(description string) *Schema
- func Object(props map[string]*Schema, required ...string) *Schema
- func Reflect(t reflect.Type) *Schema
- func SchemaOf[T any]() *Schema
- func String(description string) *Schema
- type Tool
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
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 ValidateName ¶
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 ¶
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 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 ¶
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 ¶
Middleware wraps an Invoker.
func Allow ¶
func Allow(names ...string) Middleware
Allow rejects calls to tools that are not in names.
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 ¶
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 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 ¶
WithSchema overrides the derived parameter schema.
type PanicError ¶
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 ¶
NewRegistry returns a registry containing tools.
func (*Registry) List ¶
List returns the tools sorted by name. The stable order keeps prompts byte-identical across requests, which preserves provider prompt caches.
func (*Registry) Register ¶
Register adds tools. It fails without registering anything if a name is invalid or already registered.
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.
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 Object ¶
Object returns an object schema with the given properties. Every property listed in required must exist in props.
func SchemaOf ¶
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 (*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.
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. |