Documentation
¶
Index ¶
- func IsOAuthError(err error) bool
- type BufferedDebugLogger
- type ConnectionPoolConfig
- type DebugLogger
- type FileTokenStore
- type MCPAuthHandler
- type MCPConnection
- type MCPConnectionPool
- func (p *MCPConnectionPool) Close() error
- func (p *MCPConnectionPool) GetClients() map[string]client.MCPClient
- func (p *MCPConnectionPool) GetConnection(ctx context.Context, serverName string, serverConfig config.MCPServerConfig) (*MCPConnection, error)
- func (p *MCPConnectionPool) GetConnectionStats() map[string]any
- func (p *MCPConnectionPool) GetConnectionWithHealthCheck(ctx context.Context, serverName string, serverConfig config.MCPServerConfig) (*MCPConnection, error)
- func (p *MCPConnectionPool) HandleConnectionError(serverName string, err error)
- func (p *MCPConnectionPool) SetDebugLogger(logger DebugLogger)
- func (p *MCPConnectionPool) SetOAuthFlow(flow *OAuthFlowRunner)
- type MCPToolManager
- func (m *MCPToolManager) Close() error
- func (m *MCPToolManager) GetLoadedServerNames() []string
- func (m *MCPToolManager) GetTools() []fantasy.AgentTool
- func (m *MCPToolManager) LoadTools(ctx context.Context, config *config.Config) error
- func (m *MCPToolManager) SetAuthHandler(handler MCPAuthHandler)
- func (m *MCPToolManager) SetDebugLogger(logger DebugLogger)
- func (m *MCPToolManager) SetModel(model fantasy.LanguageModel)
- type OAuthFlowRunner
- type SimpleDebugLogger
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsOAuthError ¶ added in v0.39.0
IsOAuthError returns true if the error is an OAuthAuthorizationRequiredError.
Types ¶
type BufferedDebugLogger ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 FileTokenStore ¶ added in v0.39.0
type FileTokenStore struct {
// contains filtered or unexported fields
}
FileTokenStore is a file-backed implementation of transport.TokenStore that persists OAuth tokens as JSON on disk. Tokens are stored in a shared JSON file keyed by server URL, allowing multiple MCP servers to maintain independent tokens.
The token file is located at $XDG_CONFIG_HOME/.kit/mcp_tokens.json, falling back to ~/.config/.kit/mcp_tokens.json when XDG_CONFIG_HOME is not set.
FileTokenStore is safe for concurrent use.
func NewFileTokenStore ¶ added in v0.39.0
func NewFileTokenStore(serverKey string) (*FileTokenStore, error)
NewFileTokenStore creates a new FileTokenStore for the given server URL. The serverKey is used as the map key in the shared token file, and should typically be the MCP server's base URL.
Returns an error if the token file path cannot be resolved.
func (*FileTokenStore) GetToken ¶ added in v0.39.0
GetToken returns the stored token for this store's server key. Returns transport.ErrNoToken if no token exists for the server key or if the token file does not yet exist. Returns context.Canceled or context.DeadlineExceeded if the context is done.
func (*FileTokenStore) SaveToken ¶ added in v0.39.0
SaveToken persists the given token for this store's server key. If the token file or its parent directories do not exist, they are created. Existing tokens for other server keys are preserved. Returns context.Canceled or context.DeadlineExceeded if the context is done.
type MCPAuthHandler ¶ added in v0.39.0
type MCPAuthHandler interface {
// RedirectURI returns the OAuth redirect URI for transport setup.
RedirectURI() string
// HandleAuth is called when a server requires OAuth authorization.
// It receives the server name and the authorization URL the user must visit.
// It returns the full callback URL (containing code and state query params)
// after the user completes authorization.
HandleAuth(ctx context.Context, serverName string, authURL string) (callbackURL string, err error)
}
MCPAuthHandler is the internal interface for handling MCP OAuth flows. The SDK-level kit.MCPAuthHandler is adapted to this interface in cmd/root.go or pkg/kit/kit.go, keeping the tools package decoupled from the SDK.
type MCPConnection ¶
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 ¶
func (c *MCPConnection) ServerName() string
ServerName returns the server name associated with this MCP connection. This is the configured name from the KIT configuration, not necessarily the actual server implementation name.
type MCPConnectionPool ¶
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 ¶
func NewMCPConnectionPool(config *ConnectionPoolConfig, model fantasy.LanguageModel, debug bool, authHandler MCPAuthHandler) *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 ¶
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 ¶
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 ¶
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 ¶
func (p *MCPConnectionPool) GetConnectionStats() map[string]any
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 ¶
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 ¶
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 ¶
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.
func (*MCPConnectionPool) SetOAuthFlow ¶ added in v0.39.0
func (p *MCPConnectionPool) SetOAuthFlow(flow *OAuthFlowRunner)
SetOAuthFlow sets the OAuth flow runner for the connection pool. When set, the pool can trigger OAuth re-authorization when a tool call fails with an OAuth error (e.g. expired token). 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 ¶
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() []fantasy.AgentTool
GetTools returns all loaded tools as fantasy AgentTools from all configured MCP servers. Tools are returned with their prefixed names (serverName__toolName) to ensure uniqueness.
func (*MCPToolManager) LoadTools ¶
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) SetAuthHandler ¶ added in v0.39.0
func (m *MCPToolManager) SetAuthHandler(handler MCPAuthHandler)
SetAuthHandler sets the OAuth handler for remote MCP server authentication. When set, remote transports (streamable HTTP, SSE) are configured with OAuth support, enabling automatic authorization flows when servers require authentication. This method should be called before LoadTools.
func (*MCPToolManager) SetDebugLogger ¶
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 ¶
func (m *MCPToolManager) SetModel(model fantasy.LanguageModel)
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 OAuthFlowRunner ¶ added in v0.39.0
type OAuthFlowRunner struct {
// contains filtered or unexported fields
}
OAuthFlowRunner handles the OAuth authorization flow when an MCP server returns an OAuthAuthorizationRequiredError. It coordinates dynamic client registration, PKCE generation, user authorization (via MCPAuthHandler), and token exchange.
func NewOAuthFlowRunner ¶ added in v0.39.0
func NewOAuthFlowRunner(handler MCPAuthHandler) *OAuthFlowRunner
NewOAuthFlowRunner creates a new OAuthFlowRunner with the given auth handler.
func (*OAuthFlowRunner) RunAuthFlow ¶ added in v0.39.0
RunAuthFlow executes the OAuth authorization flow for the given server. It extracts the OAuthHandler from the error, performs dynamic client registration if needed, generates PKCE parameters, delegates to the MCPAuthHandler for user interaction, and exchanges the authorization code for a token.
type SimpleDebugLogger ¶
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 ¶
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 ¶
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 ¶
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.