tool

package
v0.3.17 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package tool provides the tool system for LLM function-calling: Tool interface, Registry, concurrent execution, and schema building.

Index

Constants

View Source
const (
	// ScopeAgent marks a tool as available to all agents (default).
	ScopeAgent = "agent"
	// ScopePlatform marks a tool as internal to the CoPilot platform.
	// Platform tools are hidden from tool_list and the frontend ToolSelector,
	// but can still be referenced explicitly in an LLM node's tool_names.
	ScopePlatform = "platform"
)

Tool scope constants control visibility in tool_list and /api/tools. The scope is registry-level metadata and does NOT appear in model.ToolDefinition.

Variables

This section is empty.

Functions

This section is empty.

Types

type Dispatch added in v0.2.6

type Dispatch func(ctx context.Context, call model.ToolCall) model.ToolResult

Dispatch is the function form of "execute one tool call and return its result". The Registry's own Execute method is itself a Dispatch (modulo the receiver). Middleware operates on this signature.

Implementations should treat the input call as immutable and must always return a ToolResult — errors are reported via ToolResult.IsError, never returned out-of-band.

type Middleware added in v0.2.6

type Middleware func(next Dispatch) Dispatch

Middleware decorates a Dispatch, returning a new Dispatch that may run code before/after the wrapped call (audit, approval, rate-limit, secret-resolve, retry, etc.). Middlewares are composed in outermost-first order: the first registered middleware sees the call first and the result last.

A middleware MUST forward to next unless it intentionally short-circuits (e.g. policy denial). Short-circuit responses should set ToolResult.IsError=true and put a human-readable reason in Content; classify the underlying error via sdk/errdefs where possible (PolicyDenied, BudgetExceeded, RateLimit).

type PropertyDef

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

PropertyDef describes a single JSON Schema property.

func ArrayProperty

func ArrayProperty(name, description string, items map[string]any) PropertyDef

ArrayProperty creates an array property with item schema.

func EnumProperty

func EnumProperty(name, typ, description string, values ...string) PropertyDef

EnumProperty creates a property restricted to a set of string values.

func ObjectProperty

func ObjectProperty(name, description string, properties map[string]any) PropertyDef

ObjectProperty creates an object property with nested properties schema.

func Property

func Property(name, typ, description string) PropertyDef

Property creates a simple typed property definition.

func PropertyWithDefault added in v0.1.1

func PropertyWithDefault(name, typ, description string, defaultVal any) PropertyDef

PropertyWithDefault creates a typed property with a default value.

type Registry

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

Registry is a thread-safe collection of Tools.

func NewRegistry

func NewRegistry(opts ...RegistryOption) *Registry

NewRegistry creates a new tool registry.

func (*Registry) Definitions

func (r *Registry) Definitions() []model.ToolDefinition

Definitions returns the ToolDefinition for every registered tool (all scopes).

func (*Registry) DefinitionsByScope

func (r *Registry) DefinitionsByScope(scope string) []model.ToolDefinition

DefinitionsByScope returns only the ToolDefinitions matching the given scope.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, call model.ToolCall) model.ToolResult

Execute runs a single tool call through the registered middleware chain (outermost first) and the core dispatch (lookup + timeout + telemetry). All errors (including tool-not-found) are returned as ToolResult with IsError=true, so callers never need to handle a separate error path.

Tool errors should be classified via sdk/errdefs markers (PolicyDenied, BudgetExceeded, RateLimit, NotFound, ...) when the classification matters for upstream retry / restart decisions. Built-in tools are expected to follow this convention; third-party tools are encouraged to do the same.

func (*Registry) ExecuteAll

func (r *Registry) ExecuteAll(ctx context.Context, calls []model.ToolCall) []model.ToolResult

ExecuteAll runs multiple tool calls concurrently with a semaphore limiting parallelism. Results are returned in the same order as the input calls.

func (*Registry) Get

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

Get returns a tool by name.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered tools.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns the names of all registered tools.

func (*Registry) Register

func (r *Registry) Register(tool Tool)

Register adds a tool to the registry with the default scope (ScopeAgent).

func (*Registry) RegisterWithScope

func (r *Registry) RegisterWithScope(tool Tool, scope string)

RegisterWithScope adds a tool to the registry with the specified scope.

func (*Registry) ScopeOf

func (r *Registry) ScopeOf(name string) string

ScopeOf returns the scope of a registered tool, or ScopeAgent if not found.

func (*Registry) Unregister

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

Unregister removes a tool by name. Returns true if the tool existed.

func (*Registry) Use added in v0.2.6

func (r *Registry) Use(mws ...Middleware)

Use appends middleware to the Registry's dispatch chain. Middlewares are applied in registration order: Use(a, b) means a runs outermost, then b, then the core dispatch. nil middleware values are silently skipped to keep callers ergonomic when conditionally adding hooks.

type RegistryOption

type RegistryOption func(*Registry)

RegistryOption configures a Registry.

func WithExecTimeout

func WithExecTimeout(d time.Duration) RegistryOption

WithExecTimeout sets the default timeout for individual tool executions.

func WithMaxConcurrency

func WithMaxConcurrency(n int) RegistryOption

WithMaxConcurrency sets the maximum number of concurrent tool executions.

type SchemaBuilder

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

SchemaBuilder constructs a ToolDefinition using a fluent API.

func DefineSchema

func DefineSchema(name, description string, props ...PropertyDef) *SchemaBuilder

DefineSchema starts building a ToolDefinition with the given properties.

func (*SchemaBuilder) Build

func (b *SchemaBuilder) Build() model.ToolDefinition

Build returns the final ToolDefinition.

func (*SchemaBuilder) Required

func (b *SchemaBuilder) Required(names ...string) *SchemaBuilder

Required marks the given property names as required in the JSON Schema. Duplicate names are silently ignored.

type SelfTimeouter

type SelfTimeouter interface {
	SelfTimeout() bool
}

SelfTimeouter is an optional interface a Tool can implement to signal that it manages its own execution timeout internally (e.g. sandbox tools). When Registry detects this, it skips the default per-tool timeout wrapper so the tool's own timeout takes effect.

type Tool

type Tool interface {
	Definition() model.ToolDefinition
	Execute(ctx context.Context, arguments string) (string, error)
}

Tool is the interface that LLM-callable tools must implement.

func FuncTool

func FuncTool(def model.ToolDefinition, fn func(ctx context.Context, args string) (string, error)) Tool

FuncTool wraps a plain function as a Tool.

type ToolMeta added in v0.2.6

type ToolMeta struct {
	// RateLimit is the maximum number of executions per second this
	// tool can sustain. Zero means "no claim" (no rate limit applied).
	// A negative value is treated as zero.
	RateLimit float64

	// MutatesState declares that this tool has side effects beyond
	// returning a result (writes, posts, sends mail, ...). Conservative
	// callers (retry middleware, "redo last call" prompts) should
	// refuse to re-invoke a MutatesState tool with the same input
	// without explicit user confirmation.
	//
	// Zero value (false) is the conservative default in the *opposite*
	// direction: callers that don't know better should assume the tool
	// MAY mutate state. Tools that are provably side-effect free should
	// declare MutatesState=false explicitly via Metadata().
	MutatesState bool
}

ToolMeta carries optional, sandbox-relevant metadata about a Tool.

All fields are advisory; a zero ToolMeta means "no claims, treat conservatively" (no rate limit, assume the tool may mutate state so retries are unsafe).

The shape is intentionally minimal — only fields a pod-side sandbox can act on today are present:

  • RateLimit drives request-per-second throttling middleware.
  • MutatesState gates whether retry-on-failure logic may safely re-invoke the tool with the same arguments.

Network / filesystem / cost claims were deliberately deferred: the in-process runtime cannot enforce process-boundary isolation, and $-denominated cost caps presuppose an LLM pricing catalog that is also deferred. Add fields here when (and only when) a concrete sandbox component is ready to consume them.

func MetadataOf added in v0.2.6

func MetadataOf(t Tool) ToolMeta

MetadataOf returns the ToolMeta declared by t, or a zero ToolMeta if t does not implement ToolMetadata. Safe to call on any Tool, including nil-interface values (returns zero ToolMeta).

type ToolMetadata added in v0.2.6

type ToolMetadata interface {
	Metadata() ToolMeta
}

ToolMetadata is an optional interface a Tool may implement to declare sandbox-relevant metadata. Tools that do not implement this interface are treated as if they returned a zero ToolMeta (no rate limit, side-effects unknown).

Directories

Path Synopsis
builtin
askuser
Package askuser exposes the built-in `ask_user` LLM tool — a human-in-the-loop bridge that lets the model explicitly hand a question back to the operator via engine.Host.AskUser.
Package askuser exposes the built-in `ask_user` LLM tool — a human-in-the-loop bridge that lets the model explicitly hand a question back to the operator via engine.Host.AskUser.
Package tooltest provides a generic contract test suite for tool.Tool implementations.
Package tooltest provides a generic contract test suite for tool.Tool implementations.

Jump to

Keyboard shortcuts

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