tool

package
v0.0.0-...-d80aada Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package tool provides type definitions for tool metadata.

Package tool provides a unified and extensible tool management system for the assistant.

This package allows the assistant to perform actions beyond generating text, such as searching the web, interacting with the file system, or connecting to external services.

Key Features:

- Unified Registry: All tools, whether built-in or dynamically loaded, are registered and managed through a central `Manager`.

- Dynamic Execution: The assistant can dynamically decide which tool to use based on the user's query. The manager handles the execution and returns the result in a standardized format.

- Built-in Tools: A set of essential tools for common tasks (file I/O, web fetching) are provided out of the box.

- MCP Integration: The system is designed to integrate seamlessly with the Model Context Protocol (MCP), allowing it to discover and use external tools without requiring code changes.

- Natural Language Access: The tool schemas are provided to the LLM, allowing it to understand how to use the tools and formulate the necessary arguments from a natural language query.

Package tool implements a flexible and extensible tool system that enhances the AI assistant's capabilities beyond pure conversation.

The tool system follows Go's philosophy of simplicity and composition, providing a unified interface for diverse functionalities while maintaining clear boundaries and explicit error handling.

Architecture

The tool system is built around a simple but powerful abstraction:

┌─────────────────────────────────────────────┐
│                Tool Manager                 │
├─────────────┬─────────────┬─────────────────┤
│   File I/O  │     Web     │    Memory       │
├─────────────┼─────────────┼─────────────────┤
│   Search    │    Fetch    │    Delete       │
│   Read      │   Scrape    │   Resolve       │
│   Write     │             │   Conflicts     │
└─────────────┴─────────────┴─────────────────┘

Each tool implements a common interface, allowing the assistant to discover and use tools dynamically based on user needs.

Core Concepts

**Tool Interface**: Every tool implements this simple interface:

  • Name(): Returns the tool's unique identifier
  • Description(): Provides human-readable functionality description
  • InputSchema(): Defines expected parameters as JSON Schema
  • Execute(): Performs the tool's action with given inputs

**Tool Manager**: Central registry that:

  • Maintains a thread-safe registry of available tools
  • Handles tool discovery and execution
  • Provides consistent error handling
  • Manages tool configuration

**Tool Categories**:

  • File System: Read, write, search local files
  • Web: Fetch URLs, search the web, scrape content
  • Memory: Manage the assistant's memory system
  • System: Access system information and history
  • Time: Date and time utilities
  • UI: User interface interactions (CLI-specific)

Usage Pattern

// Create manager with configuration
manager := tool.NewManager(tool.Config{
    FileSystem: tool.FileSystemConfig{
        AllowedPaths: []string{"/home/user"},
    },
})

// Register built-in tools
manager.RegisterFileTools()
manager.RegisterWebTools(webService)

// Execute a tool
result, err := manager.Execute(ctx, "file_read", map[string]any{
    "path": "/home/user/document.txt",
})

Tool Development

Creating a new tool is straightforward:

type MyTool struct {
    tool.Info  // Embed for common functionality
}

func (t *MyTool) Execute(ctx context.Context, input any) (any, error) {
    // Parse input, perform action, return result
    return result, nil
}

Input Validation

Tools use JSON Schema for input validation, providing:

  • Type safety without reflection overhead
  • Clear parameter documentation
  • Automatic validation before execution
  • Better error messages for users

Error Handling

Following Go's explicit error handling:

  • Tools return errors with context
  • Transient vs permanent failures are distinguished
  • User-friendly error messages are provided
  • Stack traces are available for debugging

Security Considerations

The tool system implements several security measures:

  • File system access is restricted to allowed paths
  • Web requests have timeouts and size limits
  • Input validation prevents injection attacks
  • Sensitive operations require explicit configuration

Integration with AI

Tools are automatically discovered by the AI assistant:

  • Tool descriptions are included in the system prompt
  • The AI determines when to use tools based on user intent
  • Results are formatted for optimal AI comprehension
  • Errors are handled gracefully without breaking conversation flow

Thread Safety

The Manager and all built-in tools are safe for concurrent use. Custom tools should follow the same pattern, avoiding shared mutable state.

Package tool provides type-safe tool implementations.

Package tool provides a unified interface for AI tool execution.

This package defines the core Tool interface and common functionality for all tools in the system. Tools are the bridge between AI reasoning and real-world actions, enabling the AI to perform tasks like file operations, web searches, calculations, and more.

Package tool provides type definitions for tool execution.

Package tool provides validation utilities for tool inputs.

Index

Constants

View Source
const (
	MemoryTool     = "memory"
	DateTimeTool   = "datetime"
	WebSearchTool  = "web_search"
	CalculatorTool = "calculator"
)

Tool names

Variables

This section is empty.

Functions

func ParseInput

func ParseInput[T any](input any) (T, error)

ParseInput parses raw input into a typed struct. This is exported so tools can use it directly if needed.

func ValidateInput

func ValidateInput(schema json.RawMessage, input any) error

ValidateInput validates input data against a JSON Schema. It uses the MCP SDK's jsonschema package for validation.

Types

type Call

type Call struct {
	ID   string          `json:"id"`
	Name string          `json:"name"`
	Args json.RawMessage `json:"args"`
}

Call represents a tool invocation.

type Config

type Config struct {
	FileSystem FileSystemConfig
	Web        WebConfig
}

Config for tools initialization

type Definition

type Definition struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Schema      json.RawMessage `json:"schema"`
}

Definition provides exported metadata about a tool. This allows external code to inspect tool properties without needing to execute the tool.

func DefinitionOf

func DefinitionOf(t Tool) Definition

DefinitionOf extracts the definition from any Tool.

func DefinitionsOf

func DefinitionsOf(tools []Tool) []Definition

DefinitionsOf extracts definitions from multiple tools.

type FileSystemConfig

type FileSystemConfig struct {
	AllowedDirs []string
	EnableWrite bool
	CreateDirs  bool
	MaxFileSize int64
}

FileSystemConfig contains configuration for file system tools

type Info

type Info struct {
	ToolName        string `json:"name"`
	ToolDescription string `json:"description"`
	// contains filtered or unexported fields
}

Info provides common tool information fields. Embed this to quickly implement the Tool interface. Following Go conventions, metadata fields are exported with different names to avoid conflicts with interface methods.

func NewInfo

func NewInfo(name, description string, schema json.RawMessage) Info

NewInfo creates new tool information.

func (Info) Description

func (i Info) Description() string

Description implements the Tool interface.

func (Info) Name

func (i Info) Name() string

Name implements the Tool interface.

func (Info) Schema

func (i Info) Schema() json.RawMessage

Schema returns the JSON Schema.

type Manager

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

Manager provides unified tool management with a simple registry. Tools are registered by name and executed dynamically.

func NewManager

func NewManager(cfg Config) *Manager

NewManager creates a new tool manager with the given configuration.

func (*Manager) Execute

func (m *Manager) Execute(ctx context.Context, call Call) Result

Execute executes a tool by name with the given input.

func (*Manager) Get

func (m *Manager) Get(name string) (Tool, bool)

Get retrieves a tool by name.

func (*Manager) GetToolMetadata

func (m *Manager) GetToolMetadata() []Metadata

GetToolMetadata returns tool metadata for AI systems.

func (*Manager) HasTool

func (m *Manager) HasTool(name string) bool

HasTool checks if a tool exists.

func (*Manager) List

func (m *Manager) List() []Tool

List returns all available tools in deterministic order (sorted by name).

func (*Manager) Register

func (m *Manager) Register(tool Tool) error

Register registers a tool in the manager.

func (*Manager) RegisterTools

func (m *Manager) RegisterTools(tools []Tool, prefix string) error

RegisterTools registers multiple tools at once with optional prefix.

func (*Manager) Unregister

func (m *Manager) Unregister(name string) error

Unregister removes a tool from the registry.

type Metadata

type Metadata struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	InputSchema Schema `json:"input_schema"`
}

Metadata represents an available tool.

func GetToolMetadata

func GetToolMetadata(tools []Tool) []Metadata

GetToolMetadata converts tools to metadata format for AI providers. This is used for registering tools with AI services.

type Operation

type Operation[Input, Output any] struct {
	// Exported fields with different names to avoid method conflicts
	ToolName        string // The tool's name (exported for direct access)
	ToolDescription string // The tool's description (exported for direct access)
	// contains filtered or unexported fields
}

Operation provides a structured implementation of the Tool interface. It handles input parsing, schema generation, and output marshaling automatically.

Following Go conventions, configuration fields (Name, Description) are exported while internal state (handler, schema cache) remains private.

Type parameters:

  • Input: the input type for the tool
  • Output: the output type for the tool

func NewOperation

func NewOperation[Input, Output any](
	name, description string,
	handler func(context.Context, Input) (Output, error),
) *Operation[Input, Output]

NewOperation creates a new tool operation with structured input and output.

func (*Operation[Input, Output]) Description

func (o *Operation[Input, Output]) Description() string

Description implements the Tool interface.

func (*Operation[Input, Output]) Execute

func (o *Operation[Input, Output]) Execute(ctx context.Context, input any) (any, error)

Execute implements the Tool interface with automatic type conversion.

func (*Operation[Input, Output]) Name

func (o *Operation[Input, Output]) Name() string

Name implements the Tool interface.

func (*Operation[Input, Output]) Schema

func (o *Operation[Input, Output]) Schema() json.RawMessage

Schema returns the JSON Schema for the input type.

type Property

type Property struct {
	Type        string   `json:"type"`
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
	Default     any      `json:"default,omitempty"`
}

Property defines a parameter property.

type Result

type Result struct {
	ID      string `json:"id"` // Matches Call.ID
	Content string `json:"content"`
	Error   string `json:"error,omitempty"`
}

Result represents the result of tool execution.

type Schema

type Schema struct {
	Type       string              `json:"type"` // Usually "object"
	Properties map[string]Property `json:"properties"`
	Required   []string            `json:"required,omitempty"`
}

Schema defines tool parameter schema.

type Tool

type Tool interface {
	// Name returns the tool name
	Name() string
	// Description returns the tool description
	Description() string
	// Execute runs the tool with given input
	Execute(ctx context.Context, input any) (any, error)
	// Schema returns the JSON Schema for input parameters
	Schema() json.RawMessage
}

Tool represents an executable tool. This interface matches the existing tool implementation pattern.

func Simple

func Simple(name, description string, fn func(context.Context, map[string]any) (any, error)) Tool

Simple provides a simplified way to create tools with just a function. This is useful for tools that don't need complex input validation.

type WebConfig

type WebConfig struct {
	UserAgent string
}

WebConfig contains configuration for web tools

Directories

Path Synopsis
Package file provides comprehensive file system tools.
Package file provides comprehensive file system tools.
Package httptool provides configuration for HTTP client tools.
Package httptool provides configuration for HTTP client tools.
Package memory provides memory management tools for the AI assistant.
Package memory provides memory management tools for the AI assistant.
Package registry provides tool registration utilities.
Package registry provides tool registration utilities.
Package schema provides JSON Schema generation from Go structs for tool input validation.
Package schema provides JSON Schema generation from Go structs for tool input validation.
Package system provides system-level tools for the assistant.
Package system provides system-level tools for the assistant.
Package time provides time and date utility tools.
Package time provides time and date utility tools.
ui
Package ui provides interactive terminal UI tools for the AI assistant.
Package ui provides interactive terminal UI tools for the AI assistant.
web
Package web provides web interaction tools for the AI assistant.
Package web provides web interaction tools for the AI assistant.

Jump to

Keyboard shortcuts

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