tool

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Call

type Call struct {
	Name   string
	Params map[string]any
	Path   string
	Host   string
	Usage  sandbox.ResourceUsage
	// SessionID optionally ties the invocation to a long-lived runtime session.
	// It is used for features like output persistence and is safe to leave empty.
	SessionID string
	// StreamSink optionally receives incremental output when the target tool
	// supports streaming via StreamingTool. It is ignored by non-streaming
	// tools to preserve backwards compatibility.
	StreamSink func(chunk string, isStderr bool)
}

Call captures a single tool invocation request.

Sandbox related fields (Path, Host, Usage) are optional; when provided the executor will enforce the configured sandbox policies before running the tool.

type CallResult

type CallResult struct {
	Call        Call
	Result      *ToolResult
	Err         error
	StartedAt   time.Time
	CompletedAt time.Time
}

CallResult holds the outcome of executing a Call.

func (CallResult) Duration

func (r CallResult) Duration() time.Duration

Duration reports how long the execution took. Zero when timestamps are not populated.

type DefaultValidator

type DefaultValidator struct{}

DefaultValidator implements a small subset of JSON Schema validation for tool parameters (required fields, primitive types, nested objects/arrays, enum, pattern, minimum/maximum).

func (DefaultValidator) Validate

func (v DefaultValidator) Validate(params map[string]interface{}, schema *JSONSchema) error

Validate ensures that params satisfy the provided schema.

type Executor

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

Executor wires tool registry lookup with sandbox enforcement. A nil sandbox manager disables enforcement.

func NewExecutor

func NewExecutor(registry *Registry, sb *sandbox.Manager) *Executor

NewExecutor constructs an executor backed by the provided registry. When registry is nil a fresh Registry is created so callers never receive a nil executor by accident.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, call Call) (*CallResult, error)

Execute runs a single tool call. Parameters are shallow-cloned before being handed over to the tool to avoid concurrent callers mutating shared maps.

func (*Executor) ExecuteAll

func (e *Executor) ExecuteAll(ctx context.Context, calls []Call) []CallResult

ExecuteAll runs the provided calls concurrently and preserves ordering in the returned slice. Each call is isolated with its own parameter copy. Execution stops early when the context is cancelled; tools observe ctx directly.

func (*Executor) Registry

func (e *Executor) Registry() *Registry

Registry exposes the underlying registry primarily for tests.

func (*Executor) WithOutputPersister

func (e *Executor) WithOutputPersister(persister *OutputPersister) *Executor

WithOutputPersister returns a shallow copy using the provided persister.

func (*Executor) WithPermissionResolver

func (e *Executor) WithPermissionResolver(resolver PermissionResolver) *Executor

WithPermissionResolver returns a shallow copy using the provided resolver.

func (*Executor) WithSandbox

func (e *Executor) WithSandbox(sb *sandbox.Manager) *Executor

WithSandbox returns a shallow copy using the provided sandbox manager.

type FunctionSchema

type FunctionSchema struct {
	Name        string           `json:"name"`
	Description string           `json:"description"`
	Parameters  *ParameterSchema `json:"parameters,omitempty"`
}

FunctionSchema describes a callable tool function.

type JSONSchema

type JSONSchema struct {
	Type       string                 `json:"type"`
	Properties map[string]interface{} `json:"properties"`
	Required   []string               `json:"required"`
	Enum       []interface{}          `json:"enum,omitempty"`
	Pattern    string                 `json:"pattern,omitempty"`
	Minimum    *float64               `json:"minimum,omitempty"`
	Maximum    *float64               `json:"maximum,omitempty"`
	Items      *JSONSchema            `json:"items,omitempty"`
}

JSONSchema captures the subset of JSON Schema we require for tool validation.

type MCPServerOptions

type MCPServerOptions struct {
	Headers       map[string]string
	Env           map[string]string
	Timeout       time.Duration
	EnabledTools  []string
	DisabledTools []string
	ToolTimeout   time.Duration
}

type OutputPersister

type OutputPersister struct {
	BaseDir               string
	DefaultThresholdBytes int
	PerToolThresholdBytes map[string]int
}

OutputPersister stores large ToolResult.Output payloads on disk and replaces the inline output with a reference string plus OutputRef metadata.

The persisted file layout is:

/tmp/agentsdk/tool-output/{session_id}/{tool_name}/{timestamp}.output

Callers may override BaseDir and thresholds for tests or custom deployments.

func NewOutputPersister

func NewOutputPersister() *OutputPersister

func (*OutputPersister) MaybePersist

func (p *OutputPersister) MaybePersist(call Call, result *ToolResult) error

type OutputRef

type OutputRef struct {
	Path      string `json:"path,omitempty"`
	SizeBytes int64  `json:"size_bytes,omitempty"`
	Truncated bool   `json:"truncated,omitempty"`
}

OutputRef describes where tool output has been persisted when it is too large (or otherwise undesirable) to embed directly in ToolResult.Output.

type ParameterSchema

type ParameterSchema struct {
	Type       string                     `json:"type"` // Always "object"
	Properties map[string]*PropertySchema `json:"properties"`
	Required   []string                   `json:"required,omitempty"`
}

ParameterSchema defines the input parameters for a tool.

type PermissionResolver

PermissionResolver allows callers to approve or deny sandbox PermissionAsk outcomes (for example via a host UI). Returning PermissionAsk keeps the request pending.

type PropertySchema

type PropertySchema struct {
	Type        string          `json:"type"`        // "string", "number", "boolean", "array", "object"
	Description string          `json:"description"` // Human-readable description
	Enum        []string        `json:"enum,omitempty"`
	Items       *PropertySchema `json:"items,omitempty"` // For array types
}

PropertySchema describes a single parameter property.

type Registry

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

Registry keeps the mapping between tool names and implementations.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a registry backed by the default validator.

func (*Registry) Close

func (r *Registry) Close()

Close terminates all tracked MCP sessions. Errors are logged and ignored to avoid masking shutdown flows.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name string, params map[string]interface{}) (_ *ToolResult, err error)

func (*Registry) Get

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

Get fetches a tool by name.

func (*Registry) List

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

List produces a snapshot of all registered tools.

func (*Registry) Register

func (r *Registry) Register(tool Tool) error

Register inserts a tool when its name is not in use.

func (*Registry) RegisterMCPServer

func (r *Registry) RegisterMCPServer(ctx context.Context, serverPath, serverName string) error

RegisterMCPServer discovers tools exposed by an MCP server and registers them. serverPath accepts either an http(s) URL (SSE transport) or a stdio command.

func (*Registry) RegisterMCPServerWithOptions

func (r *Registry) RegisterMCPServerWithOptions(ctx context.Context, serverPath, serverName string, opts MCPServerOptions) error

func (*Registry) SetValidator

func (r *Registry) SetValidator(v Validator)

SetValidator swaps the validator instance used before execution.

type SpoolFileFactory

type SpoolFileFactory func() (io.WriteCloser, string, error)

SpoolFileFactory creates (or opens) the file backing a SpoolWriter once it crosses its in-memory threshold. It must return a valid file handle and a non-empty path.

type SpoolWriter

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

SpoolWriter buffers writes in-memory until the configured threshold is exceeded, then spills to a file created via the provided factory. When the spill fails, the writer is truncated: it preserves whatever data was already buffered, swallows further writes, and surfaces the error on Close.

Write never returns an error. Callers that need to observe failures should check Close and Truncated.

func NewSpoolWriter

func NewSpoolWriter(threshold int, fileFactory SpoolFileFactory) *SpoolWriter

func (*SpoolWriter) Close

func (w *SpoolWriter) Close() error

func (*SpoolWriter) Path

func (w *SpoolWriter) Path() string

func (*SpoolWriter) String

func (w *SpoolWriter) String() string

func (*SpoolWriter) Truncated

func (w *SpoolWriter) Truncated() bool

func (*SpoolWriter) Write

func (w *SpoolWriter) Write(p []byte) (int, error)

func (*SpoolWriter) WriteString

func (w *SpoolWriter) WriteString(s string) (int, error)

type StreamChunk

type StreamChunk struct {
	Content   string
	IsStderr  bool
	Timestamp time.Time
}

StreamChunk represents a single streaming emission. This is an optional helper type to standardise event payloads.

type StreamingTool

type StreamingTool interface {
	Tool

	// StreamExecute mirrors Execute but emits incremental chunks as they become
	// available. Emit MUST be safe for concurrent calls and MUST return
	// promptly to avoid blocking tool execution.
	StreamExecute(ctx context.Context, params map[string]interface{}, emit func(chunk string, isStderr bool)) (*ToolResult, error)
}

StreamingTool extends Tool with optional streaming support. Implementations should send incremental output through emit while still returning a final ToolResult for compatibility with Execute callers.

Example usage when invoking a streaming tool:

streamSink := func(chunk string, isStderr bool) { fmt.Print(chunk) }
executor.Execute(ctx, tool.Call{
	Name:       "bash",
	Params:     map[string]any{"cmd": "echo hi"},
	StreamSink: streamSink,
})

type Tool

type Tool interface {
	// Name returns the unique identifier of the tool.
	Name() string

	// Description gives a short human readable summary.
	Description() string

	// Schema describes the tool parameters. Nil means the tool does not expect input.
	Schema() *JSONSchema

	// Execute runs the tool with validated parameters.
	Execute(ctx context.Context, params map[string]interface{}) (*ToolResult, error)
}

Tool represents an executable capability exposed to the agent runtime.

type ToolResult

type ToolResult struct {
	Success   bool
	Output    string
	OutputRef *OutputRef
	Data      interface{}
	Error     error
}

ToolResult captures the outcome of a tool invocation.

type ToolSchema

type ToolSchema struct {
	Type     string          `json:"type"` // Always "function"
	Function *FunctionSchema `json:"function"`
}

ToolSchema defines the structure for tool definitions passed to LLM. It follows the OpenAI/Anthropic tool schema format.

type Validator

type Validator interface {
	Validate(params map[string]interface{}, schema *JSONSchema) error
}

Validator validates tool parameters before execution.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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