tools

package
v0.33.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: MIT Imports: 17 Imported by: 0

README ΒΆ

Smart Tool Registry

The Smart Tool Registry is an intelligent tool management system that provides advanced capabilities for tool selection, performance tracking, and automatic discovery from MCP servers.

Features

🧠 Intelligent Tool Selection
  • Bayesian Tool Selector: Uses Bayesian inference to score and select the best tools based on intent matching, performance metrics, and capability analysis
  • Multi-factor Scoring: Combines match score, performance score, and capability score with configurable weights
  • Synonym Recognition: Intelligent matching of related terms (e.g., "search" matches "find", "query", "lookup")
  • Prior Probability Integration: Learns from tool usage patterns to improve selection over time
πŸ“Š Performance Tracking
  • Execution Metrics: Tracks success rate, average latency, and execution count for each tool
  • Reliability Scoring: Computes composite reliability scores based on success rate and performance
  • Real-time Updates: Performance metrics are updated with each tool execution
  • Historical Analysis: Maintains performance history for trend analysis
πŸ” Capability Analysis
  • Automatic Capability Extraction: Infers tool capabilities from metadata and descriptions
  • Capability Matching: Matches user intents to tool capabilities with confidence scoring
  • Keyword-based Inference: Extracts capabilities from tool descriptions using keyword analysis
πŸ”„ Automatic Discovery
  • MCP Integration: Automatically discovers tools from connected MCP servers
  • Real-time Updates: Subscribes to tool updates and dynamically registers new tools
  • Fallback Mechanisms: Provides fallback tool selection when primary tools fail

Usage

Basic Setup
import "github.com/XiaoConstantine/dspy-go/pkg/tools"

// Create a smart tool registry
config := &tools.SmartToolRegistryConfig{
    AutoDiscoveryEnabled:       true,
    PerformanceTrackingEnabled: true,
    FallbackEnabled:           true,
}
registry := tools.NewSmartToolRegistry(config)

// Register tools
searchTool := tools.NewMockTool("search", "Search for information", []string{"search", "query"})
err := registry.Register(searchTool)
Intelligent Tool Selection
// Select the best tool for an intent
ctx := context.Background()
intent := "I need to find user information"
tool, err := registry.SelectBest(ctx, intent)
if err != nil {
    log.Fatal(err)
}

// Execute with performance tracking
params := map[string]interface{}{"query": "user data"}
result, err := registry.ExecuteWithTracking(ctx, tool.Name(), params)
Performance Metrics
// Get performance metrics for a tool
metrics, err := registry.GetPerformanceMetrics("search")
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Success Rate: %.2f%%\n", metrics.SuccessRate*100)
fmt.Printf("Average Latency: %v\n", metrics.AverageLatency)
fmt.Printf("Reliability Score: %.2f\n", metrics.ReliabilityScore)
Fallback Configuration
// Add fallback tools for specific intents
err := registry.AddFallback("search data", "backup_search_tool")
if err != nil {
    log.Fatal(err)
}

Architecture

Components
  1. SmartToolRegistry: Main registry that orchestrates intelligent tool management
  2. BayesianToolSelector: Implements Bayesian inference for tool selection
  3. MCPDiscoveryService: Handles automatic tool discovery from MCP servers
  4. PerformanceMetrics: Tracks and analyzes tool performance
  5. ToolCapability: Represents tool capabilities with confidence scores
Selection Algorithm

The Bayesian tool selector uses a weighted scoring system:

  • Match Score (40%): How well the tool name/description matches the intent
  • Performance Score (35%): Based on historical performance metrics
  • Capability Score (25%): How well tool capabilities match the intent

The final score can be adjusted by prior probabilities based on tool usage patterns.

Performance Metrics

Each tool maintains the following metrics:

  • Execution count and success/failure counts
  • Success rate (success_count / total_executions)
  • Average latency with exponential moving average
  • Reliability score (composite of success rate and latency)
Capability Inference

Tools' capabilities are extracted from:

  1. Explicit capabilities in tool metadata
  2. Keyword analysis of tool descriptions
  3. Pattern matching against common capability types

Configuration

SmartToolRegistryConfig
type SmartToolRegistryConfig struct {
    Selector                   ToolSelector        // Custom tool selector (default: BayesianToolSelector)
    MCPDiscovery              MCPDiscoveryService // MCP discovery service
    AutoDiscoveryEnabled      bool               // Enable automatic tool discovery
    PerformanceTrackingEnabled bool               // Enable performance tracking
    FallbackEnabled           bool               // Enable fallback mechanisms
}
BayesianToolSelector Weights
selector := tools.NewBayesianToolSelector()
selector.MatchWeight = 0.5        // Increase emphasis on name/description matching
selector.PerformanceWeight = 0.3  // Moderate emphasis on performance
selector.CapabilityWeight = 0.2   // Lower emphasis on capabilities

Testing

The Smart Tool Registry includes comprehensive test coverage:

  • Unit tests for all major components
  • Integration tests for tool selection workflows
  • Performance benchmarks for large tool sets
  • Mock implementations for testing

Run tests:

go test ./pkg/tools/ -v

Run benchmarks:

go test ./pkg/tools/ -bench=. -benchmem

Performance

The Smart Tool Registry is designed for high performance:

  • Tool selection typically completes in microseconds
  • Performance metrics updates are non-blocking
  • Memory-efficient scoring algorithms
  • Concurrent-safe operations with minimal locking

Benchmark results on typical hardware:

  • Tool selection: ~10ΞΌs for 100 tools
  • Performance update: ~1ΞΌs per execution
  • Auto-discovery: ~100ms for MCP server polling

Future Enhancements

  • Machine learning-based capability inference
  • Advanced performance prediction models
  • Tool recommendation system
  • Integration with external tool marketplaces
  • Real-time tool performance dashboards

Documentation ΒΆ

Overview ΒΆ

pkg/tools/func.go

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func NewMCPClientFromStdio ΒΆ

func NewMCPClientFromStdio(reader io.Reader, writer io.Writer, options MCPClientOptions) (*client.Client, error)

NewMCPClientFromStdio creates a new MCP client using standard I/O for communication. This is useful for connecting to an MCP server launched as a subprocess.

func RegisterMCPTools ΒΆ

func RegisterMCPTools(registry core.ToolRegistry, mcpClient MCPClientInterface) error

RegisterMCPTools dynamically discovers tools from an MCP client and registers them into a core.ToolRegistry, wrapping them to conform to the core.Tool interface.

Types ΒΆ

type BayesianToolSelector ΒΆ added in v0.33.0

type BayesianToolSelector struct {
	// Weights for different scoring components
	MatchWeight       float64 `json:"match_weight"`
	PerformanceWeight float64 `json:"performance_weight"`
	CapabilityWeight  float64 `json:"capability_weight"`

	// Prior probabilities for tool selection
	PriorProbabilities map[string]float64 `json:"prior_probabilities"`
}

BayesianToolSelector implements intelligent tool selection using Bayesian scoring.

func NewBayesianToolSelector ΒΆ added in v0.33.0

func NewBayesianToolSelector() *BayesianToolSelector

NewBayesianToolSelector creates a new Bayesian tool selector with default weights.

func (*BayesianToolSelector) ScoreTools ΒΆ added in v0.33.0

func (s *BayesianToolSelector) ScoreTools(ctx context.Context, intent string, tools []core.Tool) ([]ToolScore, error)

ScoreTools scores all tools for a given intent using Bayesian inference.

func (*BayesianToolSelector) SelectBest ΒΆ added in v0.33.0

func (s *BayesianToolSelector) SelectBest(ctx context.Context, intent string, candidates []ToolScore) (core.Tool, error)

SelectBest selects the best tool from scored candidates.

func (*BayesianToolSelector) UpdatePriorProbabilities ΒΆ added in v0.33.0

func (s *BayesianToolSelector) UpdatePriorProbabilities(toolUsageStats map[string]int)

UpdatePriorProbabilities updates the prior probabilities based on tool usage.

type DefaultMCPDiscoveryService ΒΆ added in v0.33.0

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

DefaultMCPDiscoveryService provides automatic tool discovery from MCP servers.

func NewDefaultMCPDiscoveryService ΒΆ added in v0.33.0

func NewDefaultMCPDiscoveryService(config *MCPDiscoveryConfig) *DefaultMCPDiscoveryService

NewDefaultMCPDiscoveryService creates a new MCP discovery service.

func (*DefaultMCPDiscoveryService) AddServer ΒΆ added in v0.33.0

func (d *DefaultMCPDiscoveryService) AddServer(server MCPServer) error

AddServer adds an MCP server to the discovery service.

func (*DefaultMCPDiscoveryService) DiscoverTools ΒΆ added in v0.33.0

func (d *DefaultMCPDiscoveryService) DiscoverTools(ctx context.Context) ([]core.Tool, error)

DiscoverTools discovers tools from all connected MCP servers.

func (*DefaultMCPDiscoveryService) GetConnectedServers ΒΆ added in v0.33.0

func (d *DefaultMCPDiscoveryService) GetConnectedServers() []string

GetConnectedServers returns the list of connected servers.

func (*DefaultMCPDiscoveryService) IsRunning ΒΆ added in v0.33.0

func (d *DefaultMCPDiscoveryService) IsRunning() bool

IsRunning returns true if the discovery service is currently running.

func (*DefaultMCPDiscoveryService) RemoveServer ΒΆ added in v0.33.0

func (d *DefaultMCPDiscoveryService) RemoveServer(serverName string) error

RemoveServer removes an MCP server from the discovery service.

func (*DefaultMCPDiscoveryService) Stop ΒΆ added in v0.33.0

func (d *DefaultMCPDiscoveryService) Stop()

Stop stops the discovery service.

func (*DefaultMCPDiscoveryService) Subscribe ΒΆ added in v0.33.0

func (d *DefaultMCPDiscoveryService) Subscribe(callback func(tools []core.Tool)) error

Subscribe adds a callback for tool discovery updates.

type FuncTool ΒΆ

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

FuncTool wraps a Go function as a Tool implementation.

func NewFuncTool ΒΆ

func NewFuncTool(name, description string, schema models.InputSchema, fn ToolFunc) *FuncTool

NewFuncTool creates a new function-based tool.

func (*FuncTool) Call ΒΆ

func (t *FuncTool) Call(ctx context.Context, args map[string]interface{}) (*models.CallToolResult, error)

Call executes the wrapped function with the provided arguments.

func (*FuncTool) CanHandle ΒΆ

func (t *FuncTool) CanHandle(ctx context.Context, intent string) bool

CanHandle checks if the tool can handle a specific action/intent.

func (*FuncTool) Description ΒΆ

func (t *FuncTool) Description() string

Description returns human-readable explanation of the tool.

func (*FuncTool) Execute ΒΆ

func (t *FuncTool) Execute(ctx context.Context, params map[string]interface{}) (core.ToolResult, error)

Execute runs the tool with provided parameters and adapts the result to the core interface.

func (*FuncTool) InputSchema ΒΆ

func (t *FuncTool) InputSchema() models.InputSchema

InputSchema returns the expected parameter structure.

func (*FuncTool) Metadata ΒΆ

func (t *FuncTool) Metadata() *core.ToolMetadata

Metadata returns the tool's metadata for intent matching.

func (*FuncTool) Name ΒΆ

func (t *FuncTool) Name() string

Name returns the tool's identifier.

func (*FuncTool) Type ΒΆ

func (t *FuncTool) Type() ToolType

Type returns the tool type.

func (*FuncTool) Validate ΒΆ

func (t *FuncTool) Validate(params map[string]interface{}) error

Validate checks if the parameters match the expected schema.

type InMemoryToolRegistry ΒΆ added in v0.27.0

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

InMemoryToolRegistry provides a basic in-memory implementation of the ToolRegistry interface.

func NewInMemoryToolRegistry ΒΆ added in v0.27.0

func NewInMemoryToolRegistry() *InMemoryToolRegistry

NewInMemoryToolRegistry creates a new, empty InMemoryToolRegistry.

func (*InMemoryToolRegistry) Get ΒΆ added in v0.27.0

func (r *InMemoryToolRegistry) Get(name string) (core.Tool, error)

Get retrieves a tool by its name. It returns an error if the tool is not found.

func (*InMemoryToolRegistry) List ΒΆ added in v0.27.0

func (r *InMemoryToolRegistry) List() []core.Tool

List returns a slice of all registered tools. The order is not guaranteed.

func (*InMemoryToolRegistry) Match ΒΆ added in v0.27.0

func (r *InMemoryToolRegistry) Match(intent string) []core.Tool

Match finds tools that might match a given intent string. This basic implementation checks if the intent contains the tool name (case-insensitive). More sophisticated matching (e.g., using descriptions or CanHandle) could be added.

func (*InMemoryToolRegistry) Register ΒΆ added in v0.27.0

func (r *InMemoryToolRegistry) Register(tool core.Tool) error

Register adds a tool to the registry. It returns an error if a tool with the same name already exists.

type MCPClientInterface ΒΆ added in v0.27.0

type MCPClientInterface interface {
	ListTools(ctx context.Context, cursor *models.Cursor) (*models.ListToolsResult, error)
	// Add CallTool if the wrapper's Execute needs it indirectly via the interface
	CallTool(ctx context.Context, name string, args map[string]interface{}) (*models.CallToolResult, error)
}

This improves testability by allowing mocks.

type MCPClientOptions ΒΆ

type MCPClientOptions struct {
	ClientName    string
	ClientVersion string
	Logger        logging.Logger
}

MCPClientOptions contains configuration options for creating an MCP client.

type MCPDiscoveryConfig ΒΆ added in v0.33.0

type MCPDiscoveryConfig struct {
	PollInterval time.Duration
	Servers      []MCPServer
}

MCPDiscoveryConfig configures the MCP discovery service.

type MCPDiscoveryService ΒΆ added in v0.33.0

type MCPDiscoveryService interface {
	DiscoverTools(ctx context.Context) ([]core.Tool, error)
	Subscribe(callback func(tools []core.Tool)) error
}

MCPDiscoveryService handles automatic tool discovery from MCP servers.

type MCPServer ΒΆ added in v0.33.0

type MCPServer interface {
	Name() string
	IsConnected() bool
	ListTools(ctx context.Context) ([]core.Tool, error)
	Connect(ctx context.Context) error
	Disconnect(ctx context.Context) error
}

MCPServer represents an MCP server connection.

type MCPTool ΒΆ

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

MCPTool represents a tool that delegates to an MCP server.

func NewMCPTool ΒΆ

func NewMCPTool(name, description string, schema models.InputSchema,
	client *client.Client, toolName string) *MCPTool

NewMCPTool creates a new MCP-based tool.

func (*MCPTool) Call ΒΆ

func (t *MCPTool) Call(ctx context.Context, args map[string]interface{}) (*models.CallToolResult, error)

Call forwards the call to the MCP server and returns the result.

func (*MCPTool) CanHandle ΒΆ

func (t *MCPTool) CanHandle(ctx context.Context, intent string) bool

CanHandle checks if the tool can handle a specific action/intent.

func (*MCPTool) Description ΒΆ

func (t *MCPTool) Description() string

Description returns human-readable explanation of the tool.

func (*MCPTool) Execute ΒΆ

func (t *MCPTool) Execute(ctx context.Context, params map[string]interface{}) (core.ToolResult, error)

Execute runs the tool with provided parameters and adapts the result to the core interface.

func (*MCPTool) InputSchema ΒΆ

func (t *MCPTool) InputSchema() models.InputSchema

InputSchema returns the expected parameter structure.

func (*MCPTool) Metadata ΒΆ

func (t *MCPTool) Metadata() *core.ToolMetadata

Metadata returns the tool's metadata for intent matching.

func (*MCPTool) Name ΒΆ

func (t *MCPTool) Name() string

Name returns the tool's identifier.

func (*MCPTool) Type ΒΆ

func (t *MCPTool) Type() ToolType

Type returns the tool type.

func (*MCPTool) Validate ΒΆ

func (t *MCPTool) Validate(params map[string]interface{}) error

Validate checks if the parameters match the expected schema.

type PerformanceMetrics ΒΆ added in v0.33.0

type PerformanceMetrics struct {
	ExecutionCount    int64         `json:"execution_count"`
	SuccessCount      int64         `json:"success_count"`
	FailureCount      int64         `json:"failure_count"`
	AverageLatency    time.Duration `json:"average_latency"`
	LastExecutionTime time.Time     `json:"last_execution_time"`
	SuccessRate       float64       `json:"success_rate"`
	ReliabilityScore  float64       `json:"reliability_score"` // 0.0 to 1.0
}

PerformanceMetrics tracks tool execution statistics.

type SmartToolRegistry ΒΆ added in v0.33.0

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

SmartToolRegistry provides intelligent tool selection and management.

func NewSmartToolRegistry ΒΆ added in v0.33.0

func NewSmartToolRegistry(config *SmartToolRegistryConfig) *SmartToolRegistry

NewSmartToolRegistry creates a new smart tool registry.

func (*SmartToolRegistry) AddFallback ΒΆ added in v0.33.0

func (r *SmartToolRegistry) AddFallback(intent string, fallbackToolName string) error

AddFallback adds a fallback tool for a specific intent.

func (*SmartToolRegistry) ExecuteWithTracking ΒΆ added in v0.33.0

func (r *SmartToolRegistry) ExecuteWithTracking(ctx context.Context, toolName string, params map[string]interface{}) (core.ToolResult, error)

ExecuteWithTracking executes a tool and tracks performance metrics.

func (*SmartToolRegistry) Get ΒΆ added in v0.33.0

func (r *SmartToolRegistry) Get(name string) (core.Tool, error)

Get retrieves a tool by name.

func (*SmartToolRegistry) GetCapabilities ΒΆ added in v0.33.0

func (r *SmartToolRegistry) GetCapabilities(toolName string) ([]ToolCapability, error)

GetCapabilities returns the capabilities for a tool.

func (*SmartToolRegistry) GetPerformanceMetrics ΒΆ added in v0.33.0

func (r *SmartToolRegistry) GetPerformanceMetrics(toolName string) (*PerformanceMetrics, error)

GetPerformanceMetrics returns performance metrics for a tool.

func (*SmartToolRegistry) List ΒΆ added in v0.33.0

func (r *SmartToolRegistry) List() []core.Tool

List returns all registered tools.

func (*SmartToolRegistry) Match ΒΆ added in v0.33.0

func (r *SmartToolRegistry) Match(intent string) []core.Tool

Match finds and ranks tools for a given intent using intelligent selection.

func (*SmartToolRegistry) Register ΒΆ added in v0.33.0

func (r *SmartToolRegistry) Register(tool core.Tool) error

Register adds a tool to the registry with capability analysis.

func (*SmartToolRegistry) SelectBest ΒΆ added in v0.33.0

func (r *SmartToolRegistry) SelectBest(ctx context.Context, intent string) (core.Tool, error)

SelectBest selects the best tool for a given intent.

type SmartToolRegistryConfig ΒΆ added in v0.33.0

type SmartToolRegistryConfig struct {
	Selector                   ToolSelector
	MCPDiscovery               MCPDiscoveryService
	AutoDiscoveryEnabled       bool
	PerformanceTrackingEnabled bool
	FallbackEnabled            bool
}

SmartToolRegistryConfig configures the smart registry.

type Tool ΒΆ

type Tool interface {
	// Name returns the tool's identifier
	Name() string

	// Description returns human-readable explanation of the tool's purpose
	Description() string

	// InputSchema returns the expected parameter structure
	InputSchema() models.InputSchema

	// Call executes the tool with the provided arguments
	Call(ctx context.Context, args map[string]interface{}) (*models.CallToolResult, error)
}

Tool defines a callable tool interface that abstracts both local functions and remote MCP tools. This provides a unified way to interact with tools regardless of their implementation details.

type ToolCapability ΒΆ added in v0.33.0

type ToolCapability struct {
	Name        string  `json:"name"`
	Confidence  float64 `json:"confidence"` // 0.0 to 1.0
	Description string  `json:"description"`
}

ToolCapability represents a specific capability a tool can handle.

type ToolFunc ΒΆ

type ToolFunc func(ctx context.Context, args map[string]interface{}) (*models.CallToolResult, error)

ToolFunc represents a function that can be called as a tool.

type ToolScore ΒΆ added in v0.33.0

type ToolScore struct {
	Tool             core.Tool `json:"-"`
	MatchScore       float64   `json:"match_score"`       // How well it matches the intent
	PerformanceScore float64   `json:"performance_score"` // Based on historical performance
	CapabilityScore  float64   `json:"capability_score"`  // Based on capability match
	FinalScore       float64   `json:"final_score"`       // Weighted combination
}

ToolScore represents the computed score for tool selection.

type ToolSelector ΒΆ added in v0.33.0

type ToolSelector interface {
	SelectBest(ctx context.Context, intent string, candidates []ToolScore) (core.Tool, error)
	ScoreTools(ctx context.Context, intent string, tools []core.Tool) ([]ToolScore, error)
}

ToolSelector defines the interface for tool selection algorithms.

type ToolType ΒΆ

type ToolType string

ToolType represents the source/type of a tool.

const (
	// ToolTypeFunc represents a tool backed by a local Go function.
	ToolTypeFunc ToolType = "function"

	// ToolTypeMCP represents a tool backed by an MCP server.
	ToolTypeMCP ToolType = "mcp"
)

type XMLAction ΒΆ added in v0.26.0

type XMLAction struct {
	XMLName   xml.Name      `xml:"action"`
	ToolName  string        `xml:"tool_name,omitempty"`
	Arguments []XMLArgument `xml:"arguments>arg,omitempty"`

	Content string `xml:",chardata"`
}

func (*XMLAction) GetArgumentsMap ΒΆ added in v0.26.0

func (xa *XMLAction) GetArgumentsMap() map[string]interface{}

Helper to convert XML arguments to map[string]interface{} Note: This currently stores all values as strings. More sophisticated type inference or checking could be added later if needed based on tool schemas.

type XMLArgument ΒΆ added in v0.26.0

type XMLArgument struct {
	XMLName xml.Name `xml:"arg"`
	Key     string   `xml:"key,attr"`
	Value   string   `xml:",chardata"` // Store raw value as string for now
}

Jump to

Keyboard shortcuts

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