tools

package
v0.31.4 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BufferedDebugLogger added in v0.28.0

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

BufferedDebugLogger implements DebugLogger by storing debug messages in memory until they can be retrieved and displayed. This is useful when debug output needs to be deferred or batch-processed rather than immediately displayed. All methods are thread-safe for concurrent use.

func NewBufferedDebugLogger added in v0.28.0

func NewBufferedDebugLogger(enabled bool) *BufferedDebugLogger

NewBufferedDebugLogger creates a new buffered debug logger instance. The enabled parameter determines whether debug messages will be stored. If enabled is false, all LogDebug calls become no-ops for performance.

func (*BufferedDebugLogger) GetMessages added in v0.28.0

func (l *BufferedDebugLogger) GetMessages() []string

GetMessages returns all buffered debug messages and clears the internal buffer. The returned slice contains all messages logged since the last call to GetMessages. After this call, the internal buffer is empty and ready to accumulate new messages. Thread-safe for concurrent calls.

func (*BufferedDebugLogger) IsDebugEnabled added in v0.28.0

func (l *BufferedDebugLogger) IsDebugEnabled() bool

IsDebugEnabled returns whether debug logging is enabled for this logger. This can be used to conditionally execute expensive debug operations only when debugging is actually enabled.

func (*BufferedDebugLogger) LogDebug added in v0.28.0

func (l *BufferedDebugLogger) LogDebug(message string)

LogDebug stores a debug message in the internal buffer if debug logging is enabled. Messages are appended to the buffer and retained until GetMessages is called. If debug logging is disabled, this method is a no-op. Thread-safe for concurrent calls.

type ConnectionPoolConfig added in v0.27.0

type ConnectionPoolConfig struct {
	MaxIdleTime         time.Duration // Maximum time a connection can remain idle before being marked unhealthy
	MaxRetries          int           // Maximum number of retry attempts for failed operations
	HealthCheckInterval time.Duration // Interval between background health checks of all connections
	MaxErrorCount       int           // Maximum consecutive errors before marking a connection unhealthy
	ReconnectDelay      time.Duration // Delay before attempting to reconnect after connection failure
}

ConnectionPoolConfig defines configuration parameters for the MCP connection pool. It controls connection lifecycle, health checking, and error handling behaviors.

func DefaultConnectionPoolConfig added in v0.27.0

func DefaultConnectionPoolConfig() *ConnectionPoolConfig

DefaultConnectionPoolConfig returns a connection pool configuration with sensible defaults. Default values: 5 minute max idle time, 3 retries, 30 second health check interval, 3 max errors before marking unhealthy, and 2 second reconnect delay. These defaults are suitable for most MCP server deployments.

type DebugLogger added in v0.28.0

type DebugLogger interface {
	// LogDebug logs a debug message. Implementations determine how the message is handled.
	LogDebug(message string)
	// IsDebugEnabled returns true if debug logging is enabled, allowing callers
	// to skip expensive debug operations when debugging is disabled.
	IsDebugEnabled() bool
}

DebugLogger defines the interface for debug logging in the MCP tools package. Implementations can provide different strategies for handling debug output, such as immediate console output, buffering, or file logging. All implementations must be thread-safe for concurrent use.

type MCPConnection added in v0.27.0

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

MCPConnection represents a single MCP client connection with health tracking and metadata. It wraps an MCP client and maintains state about connection health, usage patterns, and error history. Access to connection state is protected by a read-write mutex for thread-safe concurrent access.

func (*MCPConnection) ServerName added in v0.27.0

func (c *MCPConnection) ServerName() string

ServerName returns the server name associated with this MCP connection. This is the configured name from the MCPHost configuration, not necessarily the actual server implementation name.

type MCPConnectionPool added in v0.27.0

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

MCPConnectionPool manages a pool of MCP client connections with automatic health checking, connection reuse, and failure recovery. It provides thread-safe connection management across multiple MCP servers, automatically handling connection lifecycle including creation, health monitoring, and cleanup. The pool runs background health checks to proactively identify and remove unhealthy connections.

func NewMCPConnectionPool added in v0.27.0

func NewMCPConnectionPool(config *ConnectionPoolConfig, model model.ToolCallingChatModel, debug bool) *MCPConnectionPool

NewMCPConnectionPool creates a new MCP connection pool with the specified configuration. If config is nil, default configuration values will be used. The pool starts a background goroutine for periodic health checks that runs until Close is called. The model parameter is used for MCP servers that require sampling support. Thread-safe for concurrent use immediately after creation.

func (*MCPConnectionPool) Close added in v0.27.0

func (p *MCPConnectionPool) Close() error

Close gracefully shuts down the connection pool, closing all client connections and stopping the background health check goroutine. It attempts to close all connections even if some fail, logging any errors encountered. Safe to call multiple times; subsequent calls are no-ops. Always call Close when done with the pool to prevent resource leaks.

func (*MCPConnectionPool) GetClients added in v0.27.0

func (p *MCPConnectionPool) GetClients() map[string]client.MCPClient

GetClients returns a map of all MCP clients currently in the pool. The map keys are server names and values are the corresponding MCP client instances. The returned map is a copy and modifications won't affect the pool. Note that clients may be unhealthy; use GetConnectionStats to check health status.

func (*MCPConnectionPool) GetConnection added in v0.27.0

func (p *MCPConnectionPool) GetConnection(ctx context.Context, serverName string, serverConfig config.MCPServerConfig) (*MCPConnection, error)

GetConnection retrieves or creates a connection for the specified MCP server. If a healthy, non-idle connection exists in the pool, it will be reused. Otherwise, a new connection is created and added to the pool. Returns an error if connection creation or initialization fails. Thread-safe for concurrent calls.

func (*MCPConnectionPool) GetConnectionStats added in v0.27.0

func (p *MCPConnectionPool) GetConnectionStats() map[string]interface{}

GetConnectionStats returns detailed statistics for all connections in the pool. The returned map includes health status, last usage time, error counts, and last error for each connection. Useful for monitoring and debugging connection pool behavior. The returned data is a snapshot and safe for concurrent access.

func (*MCPConnectionPool) GetConnectionWithHealthCheck added in v0.27.0

func (p *MCPConnectionPool) GetConnectionWithHealthCheck(ctx context.Context, serverName string, serverConfig config.MCPServerConfig) (*MCPConnection, error)

GetConnectionWithHealthCheck retrieves a connection with an additional proactive health check. Unlike GetConnection, this method performs a health check on existing connections before returning them, ensuring the connection is truly healthy. This is useful for critical operations where connection reliability is paramount. Creates a new connection if the existing one fails the health check or doesn't exist. Thread-safe for concurrent calls.

func (*MCPConnectionPool) HandleConnectionError added in v0.27.0

func (p *MCPConnectionPool) HandleConnectionError(serverName string, err error)

HandleConnectionError records and handles errors for a specific connection. It increments the error count and may mark the connection as unhealthy based on the error type and configured thresholds. Connection errors (network, transport, 404) immediately mark the connection as unhealthy for removal on next access. Thread-safe for concurrent error reporting.

func (*MCPConnectionPool) SetDebugLogger added in v0.28.0

func (p *MCPConnectionPool) SetDebugLogger(logger DebugLogger)

SetDebugLogger sets the debug logger for the connection pool. The logger will be used to output detailed information about connection lifecycle, health checks, and error conditions. Thread-safe and can be called at any time.

type MCPToolManager

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

MCPToolManager manages MCP (Model Context Protocol) tools and clients across multiple servers. It provides a unified interface for loading, managing, and executing tools from various MCP servers, including stdio, SSE, streamable HTTP, and built-in server types. The manager handles connection pooling, health checks, tool name prefixing to avoid conflicts, and sampling support for LLM interactions. Thread-safe for concurrent tool invocations.

func NewMCPToolManager

func NewMCPToolManager() *MCPToolManager

NewMCPToolManager creates a new MCP tool manager instance. Returns an initialized manager with empty tool collections ready to load tools from MCP servers. The manager must be configured with SetModel and LoadTools before use.

func (*MCPToolManager) Close

func (m *MCPToolManager) Close() error

Close closes all MCP client connections and cleans up resources. This method should be called when the tool manager is no longer needed to ensure proper cleanup of stdio processes, network connections, and other resources. It is safe to call Close multiple times.

func (*MCPToolManager) GetLoadedServerNames added in v0.19.0

func (m *MCPToolManager) GetLoadedServerNames() []string

GetLoadedServerNames returns the names of all successfully loaded MCP servers. This includes servers that are currently connected and have had their tools loaded, regardless of their current health status. Useful for debugging and status reporting.

func (*MCPToolManager) GetTools

func (m *MCPToolManager) GetTools() []tool.BaseTool

GetTools returns all loaded tools from all configured MCP servers. Tools are returned with their prefixed names (serverName__toolName) to ensure uniqueness. The returned slice is a copy and can be safely modified by the caller.

func (*MCPToolManager) LoadTools

func (m *MCPToolManager) LoadTools(ctx context.Context, config *config.Config) error

LoadTools loads tools from all configured MCP servers based on the provided configuration. It initializes the connection pool, connects to each configured server, and loads their tools. Tools from different servers are prefixed with the server name to avoid naming conflicts. Returns an error only if all configured servers fail to load; partial failures are logged as warnings. This method is thread-safe and idempotent.

func (*MCPToolManager) SetDebugLogger added in v0.28.0

func (m *MCPToolManager) SetDebugLogger(logger DebugLogger)

SetDebugLogger sets the debug logger for the tool manager. The logger will be used to output detailed debugging information about MCP connections, tool loading, and execution. If a connection pool exists, it will also be configured to use the same logger for consistent debugging output.

func (*MCPToolManager) SetModel added in v0.23.0

func (m *MCPToolManager) SetModel(model model.ToolCallingChatModel)

SetModel sets the LLM model for sampling support. The model is used when MCP servers request sampling operations, allowing them to leverage the host's LLM capabilities for text generation tasks. This method should be called before LoadTools if any MCP servers require sampling support.

type SimpleDebugLogger added in v0.28.0

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

SimpleDebugLogger provides a minimal implementation of the DebugLogger interface. It is intentionally silent by default to prevent duplicate or unstyled debug output during initialization. Debug messages are only displayed when using the CLI debug logger which provides proper formatting and styling.

func NewSimpleDebugLogger added in v0.28.0

func NewSimpleDebugLogger(enabled bool) *SimpleDebugLogger

NewSimpleDebugLogger creates a new simple debug logger instance. The enabled parameter determines whether IsDebugEnabled will return true. Note that LogDebug is intentionally a no-op to avoid unstyled output; actual debug output is handled by the CLI's debug logger.

func (*SimpleDebugLogger) IsDebugEnabled added in v0.28.0

func (l *SimpleDebugLogger) IsDebugEnabled() bool

IsDebugEnabled returns whether debug logging is enabled for this logger. This allows code to conditionally execute expensive debug operations only when debugging is active, improving performance in production.

func (*SimpleDebugLogger) LogDebug added in v0.28.0

func (l *SimpleDebugLogger) LogDebug(message string)

LogDebug is intentionally a no-op in SimpleDebugLogger. Debug messages are only displayed when using the CLI debug logger which provides proper formatting and styling. This prevents duplicate or unstyled debug output during initialization and ensures consistent debug output presentation.

Jump to

Keyboard shortcuts

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