tools

package
v0.0.0-...-fd33c92 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package tools provides a factory-pattern tool registry and built-in tool implementations for the Xyncra Agent system.

The Registry manages tool creation via named factories (D-078). Agent configurations reference tools by name; unregistered names are logged and skipped (fail-open) so that missing optional tools never block agent construction.

Built-in tools registered into DefaultRegistry at init time:

  • get_weather — mock weather data (development/demo)
  • get_current_time — current time in any IANA timezone
  • retrieve_tool_result — retrieve a previously truncated tool result by ID

Index

Constants

View Source
const (
	DefaultTruncationThreshold = 50000 // characters (runes)
	DefaultTTL                 = 1 * time.Hour
	DefaultMaxSize             = 10000 // max entries before oldest eviction
)

Default truncation and TTL settings for the ToolResultStore (D-080).

Variables

View Source
var DefaultRegistry = NewRegistry()

DefaultRegistry is the global registry pre-populated with built-in tools at init time. Custom tools can be registered into it from main.go.

View Source
var DefaultToolResultStore = NewToolResultStore(DefaultMaxSize, DefaultTTL)

DefaultToolResultStore is the global store used by retrieve_tool_result when no explicit store is provided.

Functions

func NewAskUserTool

func NewAskUserTool() (tool.InvokableTool, error)

NewAskUserTool creates a HITL tool that interrupts execution and waits for user input. When invoked, it triggers tool.Interrupt which pauses the agent and saves a checkpoint. After the user responds via agent_resume RPC, the tool returns with the user's answer.

The tool returns a plain string (not a struct) so that Eino's marshalString passes it through without JSON encoding. Returning a struct would produce `{"answer":"..."}` which the LLM tends to copy verbatim into its reply, leaking internal implementation details to the end user.

func NewRetrieveTool

func NewRetrieveTool(store *ToolResultStore) (tool.InvokableTool, error)

NewRetrieveTool creates a retrieve_tool_result tool backed by the given ToolResultStore.

func NewTimeTool

func NewTimeTool() (tool.InvokableTool, error)

NewTimeTool creates a tool that returns the current time in the requested timezone. If the timezone is empty or invalid, UTC is used. A recoverable failure (invalid timezone) is returned as a ToolResult envelope with success=false rather than a Go error, so the LLM can self-correct (D-101).

func NewWeatherTool

func NewWeatherTool() (tool.InvokableTool, error)

NewWeatherTool creates a mock weather tool. The tool returns deterministic fake data based on the city name so that the same city always produces the same result within a process lifetime. A missing city is a recoverable failure returned as a ToolResult envelope (success=false) so the LLM can supply the argument, rather than aborting the run (D-101).

func SoftFailure

func SoftFailure(msg string) string

SoftFailure returns a ToolResult JSON string describing a recoverable failure. It is intended to be returned as normal tool content with a nil Go error, so the LLM can read the reason and recover.

func SuccessResult

func SuccessResult(data any) (string, error)

SuccessResult marshals a successful payload into a ToolResult JSON string. Tools that adopt the envelope may use this for consistency; tools that return domain-specific structs unchanged may continue to do so.

Types

type AskUserInput

type AskUserInput struct {
	Question string `json:"question" jsonschema:"description=The question to ask the user for confirmation"`
}

AskUserInput is the input schema for the ask_user tool.

type MCPBridge

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

MCPBridge manages connections to MCP servers and provides their tools. It supports both SSE and stdio transports (D-086).

The bridge accepts separate ConnectSSE and ConnectStdio methods rather than a single method that takes a config struct. This avoids a circular import between the agent and agent/tools packages.

func NewMCPBridge

func NewMCPBridge(logger *log.Logger) *MCPBridge

NewMCPBridge creates an MCPBridge. If logger is nil, log.Default() is used.

func (*MCPBridge) CloseAll

func (b *MCPBridge) CloseAll()

CloseAll closes all MCP client connections and cleans up resources.

func (*MCPBridge) ConnectSSE

func (b *MCPBridge) ConnectSSE(ctx context.Context, name, url string, toolFilter []string) ([]tool.BaseTool, error)

ConnectSSE establishes a connection to an MCP server over SSE transport and returns its tools as Eino tool.BaseTool slice. If toolFilter is non-empty, only those tools are returned.

func (*MCPBridge) ConnectStdio

func (b *MCPBridge) ConnectStdio(ctx context.Context, name, command string, args, env []string, toolFilter []string) ([]tool.BaseTool, error)

ConnectStdio establishes a connection to an MCP server over stdio transport and returns its tools as Eino tool.BaseTool slice. If toolFilter is non-empty, only those tools are returned.

type Registry

type Registry struct {
	Logger *log.Logger
	// contains filtered or unexported fields
}

Registry manages tool creation and lookup. All methods are safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty Registry. If Logger is nil when Create is called, log.Default() is used.

func (*Registry) Create

func (r *Registry) Create(ctx context.Context, names []string, config map[string]any) ([]tool.BaseTool, error)

Create instantiates the named tools in order.

Unregistered names are logged as warnings and skipped (fail-open, D-078). Factory errors are collected into a single joined error returned at the end so that one broken tool does not prevent the remaining tools from being created.

func (*Registry) ListNames

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

ListNames returns the registered tool names in sorted order.

func (*Registry) Register

func (r *Registry) Register(name string, factory ToolFactory)

Register adds or replaces a tool factory under the given name.

type RetrieveInput

type RetrieveInput struct {
	ResultID string `json:"result_id" jsonschema:"description=The retrieval ID returned in a truncated tool result"`
}

RetrieveInput is the input schema for the retrieve_tool_result tool.

type RetrieveOutput

type RetrieveOutput struct {
	Content string `json:"content"`
}

RetrieveOutput is the output schema for the retrieve_tool_result tool.

type TimeInput

type TimeInput struct {
	Timezone string `json:"timezone,omitempty" jsonschema:"description=IANA timezone name, e.g. Asia/Shanghai (default UTC)"`
}

TimeInput is the input schema for the get_current_time tool.

type TimeOutput

type TimeOutput struct {
	Time     string `json:"time"`
	Timezone string `json:"timezone"`
}

TimeOutput is the output schema for the get_current_time tool.

type ToolFactory

type ToolFactory func(ctx context.Context, config map[string]any) (tool.BaseTool, error)

ToolFactory creates a tool instance on demand. The config map carries per-tool configuration from the agent's YAML tool_config block (D-078).

type ToolResult

type ToolResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
	Data    any    `json:"data,omitempty"`
}

ToolResult is the unified envelope returned by tools for BOTH success and recoverable failure. A "recoverable failure" is any situation where the calling LLM could plausibly correct course if it knew the reason — e.g. an invalid argument, a client device that is offline, or a tool that returned a business error. By returning the failure as normal tool content (not a Go error), the LLM sees the reason and can self-correct or retry, instead of the Eino framework aborting the whole run with a NodeRunError (D-101).

Genuine programming/infrastructure errors (unparseable input, panics, unavailable backing services) should still be returned as Go errors so they fail fast.

type ToolResultStore

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

ToolResultStore stores truncated tool results in memory with TTL (D-080). It is safe for concurrent use.

func NewToolResultStore

func NewToolResultStore(maxSize int, ttl time.Duration) *ToolResultStore

NewToolResultStore creates a ToolResultStore.

  • maxSize: maximum number of stored entries; oldest are evicted when full
  • ttl: time-to-live for each entry
  • threshold: content length (in runes) below which content is returned as-is from Store without generating a retrieval ID

func (*ToolResultStore) Cleanup

func (s *ToolResultStore) Cleanup()

Cleanup removes expired entries. Call periodically from a background goroutine.

func (*ToolResultStore) Len

func (s *ToolResultStore) Len() int

Len returns the number of stored entries (for testing / monitoring).

func (*ToolResultStore) Retrieve

func (s *ToolResultStore) Retrieve(id string) (string, bool)

Retrieve returns the full content for the given retrieval ID. Returns ("", false) if the ID is not found or has expired.

func (*ToolResultStore) SetThreshold

func (s *ToolResultStore) SetThreshold(n int)

SetThreshold overrides the truncation threshold (in runes).

func (*ToolResultStore) StartCleanup

func (s *ToolResultStore) StartCleanup(ctx context.Context, interval time.Duration)

StartCleanup begins a background goroutine that periodically removes expired entries from the store. It runs until ctx is cancelled.

func (*ToolResultStore) Store

func (s *ToolResultStore) Store(id, content string) (truncated string, retrievalID string)

Store saves content and returns a truncated version plus a retrieval ID.

The id parameter is an optional caller-supplied hint for the key; if a collision occurs a random suffix is appended. The returned truncated string contains the first threshold runes of content. If the full content fits within the threshold, it is returned as-is with an empty retrievalID.

type WeatherInput

type WeatherInput struct {
	City string `json:"city" jsonschema:"description=City name"`
}

WeatherInput is the input schema for the get_weather tool.

type WeatherOutput

type WeatherOutput struct {
	Temperature string `json:"temperature"`
	Condition   string `json:"condition"`
	Humidity    string `json:"humidity"`
}

WeatherOutput is the output schema for the get_weather tool.

Jump to

Keyboard shortcuts

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