tools

package
v0.56.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsOAuthError added in v0.39.0

func IsOAuthError(err error) bool

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

func (s *FileTokenStore) GetToken(ctx context.Context) (*transport.Token, error)

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

func (s *FileTokenStore) SaveToken(ctx context.Context, token *transport.Token) error

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, debug bool, authHandler MCPAuthHandler, tokenStoreFactory TokenStoreFactory) *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. 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) RemoveConnection added in v0.47.0

func (p *MCPConnectionPool) RemoveConnection(serverName string) error

RemoveConnection closes and removes a single connection from the pool. Returns an error if the connection does not exist or if closing fails. Thread-safe for concurrent use.

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 MCPFilePart added in v0.51.0

type MCPFilePart struct {
	// Filename is a best-effort name derived from the resource URI or content type.
	Filename string
	// Data is the raw binary content (already base64-decoded).
	Data []byte
	// MediaType is the MIME type (e.g. "image/png", "audio/wav").
	MediaType string
}

MCPFilePart represents a binary file attachment extracted from an MCP prompt content block (ImageContent, AudioContent, or EmbeddedResource with blob data).

type MCPPrompt added in v0.51.0

type MCPPrompt struct {
	// Name is the prompt name on the MCP server.
	Name string
	// Description is the human-readable prompt description.
	Description string
	// Arguments lists the prompt's expected arguments.
	Arguments []MCPPromptArgument
	// ServerName is the MCP server this prompt belongs to.
	ServerName string
}

MCPPrompt represents a prompt discovered from an MCP server.

type MCPPromptArgument added in v0.51.0

type MCPPromptArgument struct {
	// Name is the argument name.
	Name string
	// Description is a human-readable description.
	Description string
	// Required indicates whether this argument must be provided.
	Required bool
}

MCPPromptArgument describes an argument that a prompt template can accept.

type MCPPromptMessage added in v0.51.0

type MCPPromptMessage struct {
	// Role is "user" or "assistant".
	Role string
	// Content is the text content of the message.
	Content string
	// FileParts contains binary attachments extracted from embedded resources,
	// images, or audio content blocks. Empty for text-only messages.
	FileParts []MCPFilePart
}

MCPPromptMessage is a single message returned by a prompt expansion.

type MCPPromptResult added in v0.51.0

type MCPPromptResult struct {
	// Description is an optional description returned by the server.
	Description string
	// Messages contains the expanded prompt messages.
	Messages []MCPPromptMessage
}

MCPPromptResult is the result of expanding an MCP prompt via GetPrompt.

type MCPResource added in v0.51.0

type MCPResource struct {
	// URI is the unique resource identifier (e.g. "file:///path" or custom scheme).
	URI string
	// Name is a human-readable name for the resource.
	Name string
	// Description is an optional description of the resource.
	Description string
	// MIMEType is the MIME type of the resource, if known.
	MIMEType string
	// ServerName is the MCP server this resource belongs to.
	ServerName string
}

MCPResource represents a resource discovered from an MCP server.

type MCPResourceContent added in v0.51.0

type MCPResourceContent struct {
	// URI is the resource URI that was read.
	URI string
	// MIMEType is the MIME type of the content.
	MIMEType string
	// Text is the text content (non-empty for text resources).
	Text string
	// BlobData is the decoded binary content (non-empty for blob resources).
	BlobData []byte
	// IsBlob is true when the content is binary (BlobData is set).
	IsBlob bool
}

MCPResourceContent is the result of reading an MCP resource via ReadResource.

type MCPTool added in v0.51.0

type MCPTool struct {
	// Name is the prefixed tool name: "serverName__toolName".
	Name string
	// Description is the human-readable tool description.
	Description string
	// Parameters is the JSON Schema properties for the tool's input.
	Parameters map[string]any
	// Required lists the required parameter names.
	Required []string
	// ServerName is the MCP server this tool belongs to.
	ServerName string
	// OriginalName is the unprefixed tool name on the MCP server.
	OriginalName string
}

MCPTool represents a tool discovered from an MCP server. It contains all the metadata needed to present the tool to an LLM (name, description, JSON schema) plus the server origin information needed to execute it.

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 OAuth re-authorization. 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 LoadTools before use.

func (*MCPToolManager) AddServer added in v0.47.0

func (m *MCPToolManager) AddServer(ctx context.Context, name string, cfg config.MCPServerConfig) (int, error)

AddServer connects to a new MCP server at runtime and loads its tools. The server's tools are immediately available to the agent after this call. Returns the number of tools loaded from the server.

If the connection pool has not been initialised yet (i.e. LoadTools was never called), AddServer creates one automatically using the manager's current configuration.

Returns an error if a server with the same name is already loaded, or if the connection or tool loading fails.

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) ExecuteTool added in v0.51.0

func (m *MCPToolManager) ExecuteTool(ctx context.Context, prefixedName, inputJSON string) (*MCPToolResult, error)

ExecuteTool calls an MCP tool through the connection pool, handling health checks, OAuth re-authorization, and connection error tracking. The inputJSON parameter is the raw JSON arguments from the LLM. Returns the result content, error flag, and any execution error.

func (*MCPToolManager) GetAuthHandler added in v0.48.1

func (m *MCPToolManager) GetAuthHandler() MCPAuthHandler

GetAuthHandler returns the OAuth handler for remote MCP server authentication. Returns nil if no handler is configured.

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) GetPrompt added in v0.51.0

func (m *MCPToolManager) GetPrompt(ctx context.Context, serverName, promptName string, args map[string]string) (*MCPPromptResult, error)

GetPrompt retrieves and expands a specific prompt from an MCP server. The serverName identifies which server to query, promptName is the prompt's name on that server, and args are the template arguments to substitute. This call is lazy — it contacts the MCP server on each invocation.

func (*MCPToolManager) GetPrompts added in v0.51.0

func (m *MCPToolManager) GetPrompts() []MCPPrompt

GetPrompts returns all prompts discovered from connected MCP servers.

func (*MCPToolManager) GetResources added in v0.51.0

func (m *MCPToolManager) GetResources() []MCPResource

GetResources returns all resources discovered from connected MCP servers.

func (*MCPToolManager) GetTools

func (m *MCPToolManager) GetTools() []MCPTool

GetTools returns all loaded MCP tools from all configured MCP servers. Tools are returned with their prefixed names (serverName__toolName) to ensure uniqueness.

func (*MCPToolManager) LoadTools

func (m *MCPToolManager) LoadTools(ctx context.Context, cfg *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) ReadResource added in v0.51.0

func (m *MCPToolManager) ReadResource(ctx context.Context, serverName, uri string) (*MCPResourceContent, error)

ReadResource reads a specific resource from an MCP server by URI. Returns the resource content (text or binary blob).

func (*MCPToolManager) RefreshServerResources added in v0.51.0

func (m *MCPToolManager) RefreshServerResources(ctx context.Context, serverName string)

RefreshServerResources re-fetches resources from a specific server. Called when a resource change notification is received.

func (*MCPToolManager) RemoveServer added in v0.47.0

func (m *MCPToolManager) RemoveServer(name string) error

RemoveServer disconnects an MCP server and removes all its tools and prompts. After this call the agent will no longer see or be able to call tools from the named server. Returns an error if the server is not loaded.

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) SetOnResourcesChanged added in v0.51.0

func (m *MCPToolManager) SetOnResourcesChanged(cb func())

SetOnResourcesChanged sets the callback invoked when a subscribed resource changes. Used by the UI layer to refresh autocomplete or re-read content.

func (*MCPToolManager) SetOnServerLoaded added in v0.41.2

func (m *MCPToolManager) SetOnServerLoaded(cb func(serverName string, toolCount int, err error))

SetOnServerLoaded sets the callback that's invoked when each MCP server finishes loading. The callback receives the server name, tool count, and any error. Call this before LoadTools to receive per-server notifications.

func (*MCPToolManager) SetOnToolsChanged added in v0.47.0

func (m *MCPToolManager) SetOnToolsChanged(cb func())

SetOnToolsChanged sets the callback that's invoked after AddServer or RemoveServer mutates the tool list. The agent layer uses this to trigger a rebuild so the LLM sees the updated tool set.

func (*MCPToolManager) SetTokenStoreFactory added in v0.47.0

func (m *MCPToolManager) SetTokenStoreFactory(factory TokenStoreFactory)

SetTokenStoreFactory sets a custom factory for creating per-server OAuth token stores. When set, the factory is called for each remote MCP server instead of using the default file-based token store. This method should be called before LoadTools.

func (*MCPToolManager) SubscribeResource added in v0.51.0

func (m *MCPToolManager) SubscribeResource(ctx context.Context, serverName, uri string) error

SubscribeResource subscribes to change notifications for a resource. When the resource changes on the server, onResourcesChanged is called and the resource list is refreshed automatically.

func (*MCPToolManager) UnsubscribeResource added in v0.51.0

func (m *MCPToolManager) UnsubscribeResource(ctx context.Context, serverName, uri string) error

UnsubscribeResource cancels change notifications for a resource.

type MCPToolResult added in v0.51.0

type MCPToolResult struct {
	// Content is the JSON-encoded result from the MCP server.
	Content string
	// IsError indicates the MCP server reported a tool-level error.
	IsError bool
}

MCPToolResult is the result of executing an MCP tool via ExecuteTool.

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

func (r *OAuthFlowRunner) RunAuthFlow(ctx context.Context, serverName string, authErr error) error

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.

type TokenStoreFactory added in v0.47.0

type TokenStoreFactory func(serverURL string) (transport.TokenStore, error)

TokenStoreFactory creates a transport.TokenStore for a given MCP server URL. When provided to the connection pool, it is called once per remote MCP server instead of using the default file-based token store. Implementations can return any transport.TokenStore — in-memory, database-backed, encrypted, etc.

Jump to

Keyboard shortcuts

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