tools

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 19 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/darwishdev/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 BatchExecutor ΒΆ

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

BatchExecutor provides convenient batch execution with automatic task creation.

func NewBatchExecutor ΒΆ

func NewBatchExecutor(executor *ParallelExecutor, scheduler TaskScheduler) *BatchExecutor

NewBatchExecutor creates a new batch executor.

func (*BatchExecutor) ExecuteBatch ΒΆ

func (be *BatchExecutor) ExecuteBatch(ctx context.Context, calls []ToolCall) ([]ParallelResult, error)

ExecuteBatch executes a batch of tool calls in parallel.

type BayesianToolSelector ΒΆ

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 ΒΆ

func NewBayesianToolSelector() *BayesianToolSelector

NewBayesianToolSelector creates a new Bayesian tool selector with default weights.

func (*BayesianToolSelector) ScoreTools ΒΆ

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 ΒΆ

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 ΒΆ

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

UpdatePriorProbabilities updates the prior probabilities based on tool usage.

type Condition ΒΆ

type Condition struct {
	Field    string      // Field to check in previous step result
	Operator string      // eq, ne, gt, lt, contains, exists
	Value    interface{} // Value to compare against
}

Condition defines when a pipeline step should execute.

func ConditionContains ΒΆ

func ConditionContains(field string, substring string) Condition

ConditionContains creates a condition that checks if a field contains a substring.

func ConditionEquals ΒΆ

func ConditionEquals(field string, value interface{}) Condition

ConditionEquals creates a condition that checks if a field equals a value.

func ConditionExists ΒΆ

func ConditionExists(field string) Condition

ConditionExists creates a condition that checks if a field exists.

func ConditionNotEquals ΒΆ

func ConditionNotEquals(field string, value interface{}) Condition

ConditionNotEquals creates a condition that checks if a field does not equal a value.

type DataTransformer ΒΆ

type DataTransformer func(input interface{}) (map[string]interface{}, error)

DataTransformer defines a function that transforms data between tools in a pipeline.

func TransformAddConstant ΒΆ

func TransformAddConstant(constantFields map[string]interface{}) DataTransformer

TransformAddConstant creates a transformer that adds constant fields.

func TransformChain ΒΆ

func TransformChain(transformers ...DataTransformer) DataTransformer

TransformChain creates a transformer that applies multiple transformers in sequence.

func TransformExtractField ΒΆ

func TransformExtractField(fieldName string) DataTransformer

TransformExtractField creates a transformer that extracts a specific field.

func TransformFilter ΒΆ

func TransformFilter(allowedFields []string) DataTransformer

TransformFilter creates a transformer that filters fields.

func TransformRename ΒΆ

func TransformRename(fieldMappings map[string]string) DataTransformer

TransformRename creates a transformer that renames fields.

type DefaultMCPDiscoveryService ΒΆ

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

DefaultMCPDiscoveryService provides automatic tool discovery from MCP servers.

func NewDefaultMCPDiscoveryService ΒΆ

func NewDefaultMCPDiscoveryService(config *MCPDiscoveryConfig) *DefaultMCPDiscoveryService

NewDefaultMCPDiscoveryService creates a new MCP discovery service.

func (*DefaultMCPDiscoveryService) AddServer ΒΆ

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

AddServer adds an MCP server to the discovery service.

func (*DefaultMCPDiscoveryService) DiscoverTools ΒΆ

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

DiscoverTools discovers tools from all connected MCP servers.

func (*DefaultMCPDiscoveryService) GetConnectedServers ΒΆ

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

GetConnectedServers returns the list of connected servers.

func (*DefaultMCPDiscoveryService) IsRunning ΒΆ

func (d *DefaultMCPDiscoveryService) IsRunning() bool

IsRunning returns true if the discovery service is currently running.

func (*DefaultMCPDiscoveryService) RemoveServer ΒΆ

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

RemoveServer removes an MCP server from the discovery service.

func (*DefaultMCPDiscoveryService) Stop ΒΆ

func (d *DefaultMCPDiscoveryService) Stop()

Stop stops the discovery service.

func (*DefaultMCPDiscoveryService) Subscribe ΒΆ

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

Subscribe adds a callback for tool discovery updates.

type DependencyGraph ΒΆ

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

DependencyGraph manages tool dependencies and execution planning.

func NewDependencyGraph ΒΆ

func NewDependencyGraph() *DependencyGraph

NewDependencyGraph creates a new dependency graph.

func (*DependencyGraph) AddNode ΒΆ

func (dg *DependencyGraph) AddNode(node *DependencyNode) error

AddNode adds a tool node to the dependency graph.

func (*DependencyGraph) CreateExecutionPlan ΒΆ

func (dg *DependencyGraph) CreateExecutionPlan() (*ExecutionPlan, error)

CreateExecutionPlan creates an optimized execution plan for the dependency graph.

func (*DependencyGraph) GetDependencies ΒΆ

func (dg *DependencyGraph) GetDependencies(toolName string) ([]string, error)

GetDependencies returns the direct dependencies of a tool.

func (*DependencyGraph) GetDependents ΒΆ

func (dg *DependencyGraph) GetDependents(toolName string) ([]string, error)

GetDependents returns the tools that depend on the given tool.

func (*DependencyGraph) GetNode ΒΆ

func (dg *DependencyGraph) GetNode(toolName string) (*DependencyNode, error)

GetNode returns a dependency node by tool name.

func (*DependencyGraph) RemoveNode ΒΆ

func (dg *DependencyGraph) RemoveNode(toolName string) error

RemoveNode removes a tool node from the dependency graph.

type DependencyNode ΒΆ

type DependencyNode struct {
	ToolName     string                 // Name of the tool
	Dependencies []string               // Names of tools this depends on
	Outputs      []string               // Output fields this tool produces
	Inputs       []string               // Required input fields
	Config       map[string]interface{} // Tool-specific configuration
	Priority     int                    // Execution priority (higher = earlier)
}

DependencyNode represents a tool with its dependencies.

type DependencyPipeline ΒΆ

type DependencyPipeline struct {
	*ToolPipeline
	// contains filtered or unexported fields
}

DependencyPipeline extends ToolPipeline with dependency-aware execution.

func NewDependencyPipeline ΒΆ

func NewDependencyPipeline(name string, registry core.ToolRegistry, graph *DependencyGraph, options PipelineOptions) (*DependencyPipeline, error)

NewDependencyPipeline creates a new dependency-aware pipeline.

func (*DependencyPipeline) ExecuteWithDependencies ΒΆ

func (dp *DependencyPipeline) ExecuteWithDependencies(ctx context.Context, initialInput map[string]interface{}) (*PipelineResult, error)

ExecuteWithDependencies executes the pipeline using the dependency graph.

func (*DependencyPipeline) GetExecutionPlan ΒΆ

func (dp *DependencyPipeline) GetExecutionPlan() *ExecutionPlan

GetExecutionPlan returns the execution plan.

type ExecutionPhase ΒΆ

type ExecutionPhase struct {
	Tools       []string // Tools to execute in this phase
	ParallelOk  bool     // Whether tools in this phase can run in parallel
	MaxParallel int      // Maximum number of parallel executions
}

ExecutionPhase contains tools that can be executed in parallel.

type ExecutionPlan ΒΆ

type ExecutionPlan struct {
	Phases []ExecutionPhase // Phases of execution (tools within a phase can run in parallel)
	Graph  *DependencyGraph // The dependency graph
}

ExecutionPlan represents the optimized execution plan for tools.

type ExecutorMetrics ΒΆ

type ExecutorMetrics struct {
	TotalExecutions   int64         `json:"total_executions"`
	ParallelTasks     int64         `json:"parallel_tasks"`
	AverageWaitTime   time.Duration `json:"average_wait_time"`
	AverageExecTime   time.Duration `json:"average_exec_time"`
	WorkerUtilization float64       `json:"worker_utilization"`
	// contains filtered or unexported fields
}

ExecutorMetrics tracks parallel execution statistics.

type FailureStrategy ΒΆ

type FailureStrategy int

FailureStrategy defines how to handle step failures.

const (
	FailFast        FailureStrategy = iota // Stop on first failure
	ContinueOnError                        // Continue with remaining steps
	Retry                                  // Retry failed steps
)

type FairShareScheduler ΒΆ

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

FairShareScheduler provides fair sharing among different tools.

func NewFairShareScheduler ΒΆ

func NewFairShareScheduler() *FairShareScheduler

func (*FairShareScheduler) Name ΒΆ

func (fs *FairShareScheduler) Name() string

func (*FairShareScheduler) Schedule ΒΆ

func (fs *FairShareScheduler) Schedule(tasks []*ParallelTask) []*ParallelTask

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 ΒΆ

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

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

func NewInMemoryToolRegistry ΒΆ

func NewInMemoryToolRegistry() *InMemoryToolRegistry

NewInMemoryToolRegistry creates a new, empty InMemoryToolRegistry.

func (*InMemoryToolRegistry) Get ΒΆ

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 ΒΆ

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

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

func (*InMemoryToolRegistry) Match ΒΆ

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 ΒΆ

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 InterceptableTool ΒΆ

type InterceptableTool interface {
	Tool

	// CallWithInterceptors executes the tool with interceptor support
	CallWithInterceptors(ctx context.Context, args map[string]interface{}, interceptors []core.ToolInterceptor) (*models.CallToolResult, error)

	// SetInterceptors sets the default interceptors for this tool instance
	SetInterceptors(interceptors []core.ToolInterceptor)

	// GetInterceptors returns the current interceptors for this tool
	GetInterceptors() []core.ToolInterceptor

	// ClearInterceptors removes all interceptors from this tool
	ClearInterceptors()

	// GetToolType returns the category/type of this tool
	GetToolType() string

	// GetVersion returns the tool version
	GetVersion() string
}

InterceptableTool extends Tool with interceptor support. This interface provides backward-compatible enhancement for tools that support interceptors.

func WrapToolWithInterceptors ΒΆ

func WrapToolWithInterceptors(tool Tool, toolType, version string, interceptors ...core.ToolInterceptor) InterceptableTool

WrapToolWithInterceptors is a convenience function to wrap any tool with interceptor support.

type InterceptorToolWrapper ΒΆ

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

InterceptorToolWrapper wraps an existing Tool to provide interceptor support. This allows any existing tool to be used with interceptors without modifying its implementation.

func NewInterceptorToolWrapper ΒΆ

func NewInterceptorToolWrapper(tool Tool, toolType, version string) *InterceptorToolWrapper

NewInterceptorToolWrapper creates a new wrapper that adds interceptor support to an existing tool.

func (*InterceptorToolWrapper) Call ΒΆ

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

Call executes the tool with the provided arguments using the wrapped tool.

func (*InterceptorToolWrapper) CallWithInterceptors ΒΆ

func (itw *InterceptorToolWrapper) CallWithInterceptors(ctx context.Context, args map[string]interface{}, interceptors []core.ToolInterceptor) (*models.CallToolResult, error)

CallWithInterceptors executes the tool with interceptor support.

func (*InterceptorToolWrapper) ClearInterceptors ΒΆ

func (itw *InterceptorToolWrapper) ClearInterceptors()

ClearInterceptors removes all interceptors from this wrapper.

func (*InterceptorToolWrapper) Description ΒΆ

func (itw *InterceptorToolWrapper) Description() string

Description returns human-readable explanation from the wrapped tool.

func (*InterceptorToolWrapper) GetInterceptors ΒΆ

func (itw *InterceptorToolWrapper) GetInterceptors() []core.ToolInterceptor

GetInterceptors returns the current interceptors for this wrapper.

func (*InterceptorToolWrapper) GetLastExecutionAnnotations ΒΆ

func (itw *InterceptorToolWrapper) GetLastExecutionAnnotations() map[string]interface{}

GetLastExecutionAnnotations returns the annotations from the most recent interceptor execution. This allows access to additional context added by interceptors (e.g., tracing, debugging info).

func (*InterceptorToolWrapper) GetLastExecutionMetadata ΒΆ

func (itw *InterceptorToolWrapper) GetLastExecutionMetadata() map[string]interface{}

GetLastExecutionMetadata returns the metadata from the most recent interceptor execution. This allows access to rich data added by interceptors (e.g., timing, logging, metrics).

func (*InterceptorToolWrapper) GetToolType ΒΆ

func (itw *InterceptorToolWrapper) GetToolType() string

GetToolType returns the category/type of this tool.

func (*InterceptorToolWrapper) GetVersion ΒΆ

func (itw *InterceptorToolWrapper) GetVersion() string

GetVersion returns the tool version.

func (*InterceptorToolWrapper) InputSchema ΒΆ

func (itw *InterceptorToolWrapper) InputSchema() models.InputSchema

InputSchema returns the expected parameter structure from the wrapped tool.

func (*InterceptorToolWrapper) Name ΒΆ

func (itw *InterceptorToolWrapper) Name() string

Name returns the tool's identifier from the wrapped tool.

func (*InterceptorToolWrapper) SetInterceptors ΒΆ

func (itw *InterceptorToolWrapper) SetInterceptors(interceptors []core.ToolInterceptor)

SetInterceptors sets the default interceptors for this wrapper.

type MCPClientInterface ΒΆ

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 ΒΆ

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

MCPDiscoveryConfig configures the MCP discovery service.

type MCPDiscoveryService ΒΆ

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 ΒΆ

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 ParallelExecutor ΒΆ

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

ParallelExecutor manages parallel execution of tools with advanced scheduling.

func NewParallelExecutor ΒΆ

func NewParallelExecutor(registry core.ToolRegistry, maxWorkers int) *ParallelExecutor

NewParallelExecutor creates a new parallel executor.

func (*ParallelExecutor) ExecuteParallel ΒΆ

func (pe *ParallelExecutor) ExecuteParallel(ctx context.Context, tasks []*ParallelTask, scheduler TaskScheduler) ([]ParallelResult, error)

ExecuteParallel executes multiple tasks in parallel with advanced scheduling.

func (*ParallelExecutor) GetMetrics ΒΆ

func (pe *ParallelExecutor) GetMetrics() ExecutorMetrics

GetMetrics returns a copy of the current metrics.

func (*ParallelExecutor) GetWorkerPoolStatus ΒΆ

func (pe *ParallelExecutor) GetWorkerPoolStatus() (total, active, available int)

GetWorkerPoolStatus returns current worker pool status.

type ParallelPipelineExecutor ΒΆ

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

ParallelPipelineExecutor combines pipeline execution with parallel capabilities.

func NewParallelPipelineExecutor ΒΆ

func NewParallelPipelineExecutor(pipeline *ToolPipeline, executor *ParallelExecutor) *ParallelPipelineExecutor

NewParallelPipelineExecutor creates a new parallel pipeline executor.

func (*ParallelPipelineExecutor) ExecuteWithParallelSteps ΒΆ

func (ppe *ParallelPipelineExecutor) ExecuteWithParallelSteps(ctx context.Context, input map[string]interface{}) (*PipelineResult, error)

ExecuteWithParallelSteps executes pipeline with parallel step execution where possible.

type ParallelResult ΒΆ

type ParallelResult struct {
	TaskID   string          // Task identifier
	Result   core.ToolResult // Tool execution result
	Error    error           // Execution error
	Duration time.Duration   // Execution duration
	WaitTime time.Duration   // Time spent waiting for execution
	WorkerID int             // ID of worker that executed the task
	Retries  int             // Number of retries performed
}

ParallelResult contains the result of parallel task execution.

type ParallelTask ΒΆ

type ParallelTask struct {
	ID         string                 // Unique task identifier
	ToolName   string                 // Tool to execute
	Input      map[string]interface{} // Input parameters
	Priority   int                    // Task priority (higher = more urgent)
	Timeout    time.Duration          // Task-specific timeout
	Retries    int                    // Number of retries on failure
	Context    context.Context        // Task-specific context
	ResultChan chan ParallelResult    // Channel to receive results
	SubmitTime time.Time              // When the task was submitted
}

ParallelTask represents a task to be executed in parallel.

type PerformanceMetrics ΒΆ

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 PipelineBuilder ΒΆ

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

PipelineBuilder provides a fluent API for constructing tool pipelines.

func NewPipelineBuilder ΒΆ

func NewPipelineBuilder(name string, registry core.ToolRegistry) *PipelineBuilder

NewPipelineBuilder creates a new pipeline builder.

func (*PipelineBuilder) AdvancedStep ΒΆ

func (pb *PipelineBuilder) AdvancedStep(toolName string, timeout time.Duration, retries int, transformer DataTransformer, conditions ...Condition) *PipelineBuilder

AdvancedStep adds a fully configured step.

func (*PipelineBuilder) Build ΒΆ

func (pb *PipelineBuilder) Build() (*ToolPipeline, error)

Build creates the final pipeline.

func (*PipelineBuilder) ConditionalStep ΒΆ

func (pb *PipelineBuilder) ConditionalStep(toolName string, conditions ...Condition) *PipelineBuilder

ConditionalStep adds a step that executes only if conditions are met.

func (*PipelineBuilder) ContinueOnError ΒΆ

func (pb *PipelineBuilder) ContinueOnError() *PipelineBuilder

ContinueOnError sets the pipeline to continue executing even after errors.

func (*PipelineBuilder) DisableCaching ΒΆ

func (pb *PipelineBuilder) DisableCaching() *PipelineBuilder

DisableCaching disables result caching for pipeline steps.

func (*PipelineBuilder) EnableCaching ΒΆ

func (pb *PipelineBuilder) EnableCaching() *PipelineBuilder

EnableCaching enables result caching for pipeline steps.

func (*PipelineBuilder) FailFast ΒΆ

func (pb *PipelineBuilder) FailFast() *PipelineBuilder

FailFast sets the pipeline to fail on the first error.

func (*PipelineBuilder) Parallel ΒΆ

func (pb *PipelineBuilder) Parallel() *PipelineBuilder

Parallel enables parallel execution of independent steps.

func (*PipelineBuilder) Sequential ΒΆ

func (pb *PipelineBuilder) Sequential() *PipelineBuilder

Sequential sets execution to sequential mode.

func (*PipelineBuilder) Step ΒΆ

func (pb *PipelineBuilder) Step(toolName string) *PipelineBuilder

Step adds a basic step to the pipeline.

func (*PipelineBuilder) StepWithRetries ΒΆ

func (pb *PipelineBuilder) StepWithRetries(toolName string, retries int) *PipelineBuilder

StepWithRetries adds a step with retry configuration.

func (*PipelineBuilder) StepWithTimeout ΒΆ

func (pb *PipelineBuilder) StepWithTimeout(toolName string, timeout time.Duration) *PipelineBuilder

StepWithTimeout adds a step with a custom timeout.

func (*PipelineBuilder) StepWithTransformer ΒΆ

func (pb *PipelineBuilder) StepWithTransformer(toolName string, transformer DataTransformer) *PipelineBuilder

StepWithTransformer adds a step with a data transformer.

func (*PipelineBuilder) Timeout ΒΆ

func (pb *PipelineBuilder) Timeout(timeout time.Duration) *PipelineBuilder

Timeout sets the overall pipeline timeout.

type PipelineOptions ΒΆ

type PipelineOptions struct {
	Timeout         time.Duration   // Overall pipeline timeout
	FailureStrategy FailureStrategy // How to handle step failures
	Parallel        bool            // Execute steps in parallel when possible
	CacheResults    bool            // Cache intermediate results
}

PipelineOptions configures pipeline execution.

type PipelineResult ΒΆ

type PipelineResult struct {
	Results      []core.ToolResult          // Results from each step
	StepMetadata map[string]StepMetadata    // Metadata for each step
	Duration     time.Duration              // Total execution time
	Success      bool                       // Whether pipeline succeeded
	FailedStep   string                     // Name of failed step (if any)
	Error        error                      // Error details
	Cache        map[string]core.ToolResult // Cached intermediate results
}

PipelineResult contains the results of pipeline execution.

type PipelineStep ΒΆ

type PipelineStep struct {
	ToolName    string          // Name of the tool to execute
	Transformer DataTransformer // Optional data transformer
	Timeout     time.Duration   // Step-specific timeout
	Retries     int             // Number of retries on failure
	Conditions  []Condition     // Conditions for step execution
}

PipelineStep represents a single step in a tool pipeline.

type PriorityScheduler ΒΆ

type PriorityScheduler struct{}

PriorityScheduler schedules tasks based on priority and submit time.

func (*PriorityScheduler) Name ΒΆ

func (ps *PriorityScheduler) Name() string

func (*PriorityScheduler) Schedule ΒΆ

func (ps *PriorityScheduler) Schedule(tasks []*ParallelTask) []*ParallelTask

type SmartToolRegistry ΒΆ

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

SmartToolRegistry provides intelligent tool selection and management.

func NewSmartToolRegistry ΒΆ

func NewSmartToolRegistry(config *SmartToolRegistryConfig) *SmartToolRegistry

NewSmartToolRegistry creates a new smart tool registry.

func (*SmartToolRegistry) AddFallback ΒΆ

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

AddFallback adds a fallback tool for a specific intent.

func (*SmartToolRegistry) ExecuteWithTracking ΒΆ

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 ΒΆ

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

Get retrieves a tool by name.

func (*SmartToolRegistry) GetCapabilities ΒΆ

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

GetCapabilities returns the capabilities for a tool.

func (*SmartToolRegistry) GetPerformanceMetrics ΒΆ

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

GetPerformanceMetrics returns performance metrics for a tool.

func (*SmartToolRegistry) List ΒΆ

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

List returns all registered tools.

func (*SmartToolRegistry) Match ΒΆ

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

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

func (*SmartToolRegistry) Register ΒΆ

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

Register adds a tool to the registry with capability analysis.

func (*SmartToolRegistry) SelectBest ΒΆ

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

SelectBest selects the best tool for a given intent.

type SmartToolRegistryConfig ΒΆ

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

SmartToolRegistryConfig configures the smart registry.

type StepMetadata ΒΆ

type StepMetadata struct {
	ToolName    string        // Tool that was executed
	Duration    time.Duration // Step execution time
	Success     bool          // Whether step succeeded
	Retries     int           // Number of retries attempted
	Cached      bool          // Whether result was cached
	Transformed bool          // Whether data was transformed
}

StepMetadata contains execution metadata for a pipeline step.

type TaskScheduler ΒΆ

type TaskScheduler interface {
	Schedule(tasks []*ParallelTask) []*ParallelTask
	Name() string
}

TaskScheduler defines the interface for task scheduling algorithms.

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 ToolCall ΒΆ

type ToolCall struct {
	ToolName string                 `json:"tool_name"`
	Input    map[string]interface{} `json:"input"`
	Priority int                    `json:"priority"`
	Timeout  time.Duration          `json:"timeout"`
	Retries  int                    `json:"retries"`
}

ToolCall represents a tool call for batch execution.

type ToolCapability ΒΆ

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 ToolPipeline ΒΆ

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

ToolPipeline manages the execution of a sequence of tools.

func NewToolPipeline ΒΆ

func NewToolPipeline(name string, registry core.ToolRegistry, options PipelineOptions) *ToolPipeline

NewToolPipeline creates a new tool pipeline.

func (*ToolPipeline) AddStep ΒΆ

func (tp *ToolPipeline) AddStep(step PipelineStep) error

AddStep adds a step to the pipeline.

func (*ToolPipeline) ClearCache ΒΆ

func (tp *ToolPipeline) ClearCache()

ClearCache clears the pipeline cache.

func (*ToolPipeline) Execute ΒΆ

func (tp *ToolPipeline) Execute(ctx context.Context, initialInput map[string]interface{}) (*PipelineResult, error)

Execute runs the pipeline with the given initial input.

func (*ToolPipeline) GetName ΒΆ

func (tp *ToolPipeline) GetName() string

GetName returns the pipeline name.

func (*ToolPipeline) GetSteps ΒΆ

func (tp *ToolPipeline) GetSteps() []PipelineStep

GetSteps returns a copy of the pipeline steps.

type ToolScore ΒΆ

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 ΒΆ

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 ΒΆ

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 ΒΆ

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 ΒΆ

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