Documentation
¶
Overview ¶
Package cli provides sophisticated command-line interface utilities for the muster application.
This package offers a comprehensive CLI experience with intelligent data formatting, robust server connectivity, and professional output presentation. It serves as the primary interface layer between user commands and the muster aggregator system.
Core Components ¶
ToolExecutor provides high-level tool execution with multiple output formats:
- MCP (Message Control Protocol) client integration with the aggregator
- Multiple output formats: professional tables, JSON, and YAML
- Progress indicators with spinners for long-running operations
- Server connectivity validation and health checking
- Both formatted and programmatic execution modes
TableFormatter offers intelligent table creation and optimization:
- Auto-detection of muster resource types (services, workflows, capabilities, etc.)
- Smart column selection and optimization based on data structure
- Specialized formatting rules for different resource types
- Professional styling with consistent iconography and color coding
- Handles both simple arrays and complex nested object structures
TableBuilder provides cell-level formatting and styling utilities:
- Status indicators with color-coded icons (✅ healthy, ❌ unhealthy, etc.)
- Resource-specific formatting (tool names, metadata, descriptions)
- Consistent styling for names, IDs, types, and other common fields
- Smart truncation and summarization of complex data
- Icon assignment based on resource types
Common utilities handle server connectivity and message formatting:
- Auto-detection of aggregator endpoints from configuration
- Server health checks with appropriate error messages
- Consistent formatting for success (✓), error, and warning (⚠) messages
- Configuration-aware endpoint resolution
Output Formats ¶
The package supports three output formats to accommodate different use cases:
- Table: Professional tables with optimized columns, styling, and summaries
- JSON: Raw JSON output for programmatic consumption
- YAML: Human-readable YAML format converted from JSON responses
Resource Type Intelligence ¶
The formatter automatically detects and optimizes display for muster resource types:
- Services: Health status, state, service type, and metadata
- MCP Servers: Server state, type, and configuration details
- Workflows: Steps, input args, and execution details
Usage Patterns ¶
The package is designed for use by muster CLI commands that need to:
- Execute tools through the aggregator with professional output
- Display complex data structures in user-friendly formats
- Provide consistent styling and iconography across all commands
- Validate server connectivity before attempting operations
- Support both interactive and programmatic usage scenarios
Integration ¶
All CLI commands should use this package for consistent user experience. The package handles the complexity of MCP communication, data formatting, and output presentation, allowing commands to focus on their core logic.
Index ¶
- Constants
- Variables
- func CheckServerRunning(endpoint string) error
- func ExtractServerType(data map[string]interface{}) string
- func FormatMCPPromptDetail(prompt MCPPrompt, format OutputFormat) error
- func FormatMCPPromptsWithOptions(prompts []MCPPrompt, format OutputFormat, noHeaders bool) error
- func FormatMCPResourceDetail(resource MCPResource, format OutputFormat) error
- func FormatMCPResourcesWithOptions(resources []MCPResource, format OutputFormat, noHeaders bool) error
- func FormatMCPToolDetail(tool MCPTool, format OutputFormat) error
- func FormatMCPToolsWithOptions(tools []MCPTool, format OutputFormat, noHeaders bool) error
- func GetAggregatorEndpoint(cfg *config.MusterConfig) string
- func GetDefaultEndpoint() string
- func IsMCPServerData(data map[string]interface{}) bool
- func IsRemoteEndpoint(endpoint string) bool
- func IsRemoteServerType(serverType string) bool
- func ParseTimeFilter(timeStr string) (time.Time, error)
- func RegisterCommonFlags(cmd *cobra.Command, flags *CommandFlags)
- func ResolveEndpoint(explicitEndpoint, contextName string) (string, error)
- func ValidateOutputFormat(format string) error
- type AuthAdapter
- func (a *AuthAdapter) CheckAuthRequired(ctx context.Context, endpoint string) (bool, error)
- func (a *AuthAdapter) Close() error
- func (a *AuthAdapter) GetBearerToken(endpoint string) (string, error)
- func (a *AuthAdapter) GetStatus() []api.AuthStatus
- func (a *AuthAdapter) GetStatusForEndpoint(endpoint string) *api.AuthStatus
- func (a *AuthAdapter) HasCredentials(endpoint string) bool
- func (a *AuthAdapter) InvalidateCache(endpoint string)
- func (a *AuthAdapter) Login(ctx context.Context, endpoint string) error
- func (a *AuthAdapter) LoginWithIssuer(ctx context.Context, endpoint, issuerURL string) error
- func (a *AuthAdapter) Logout(endpoint string) error
- func (a *AuthAdapter) LogoutAll() error
- func (a *AuthAdapter) Register()
- func (a *AuthAdapter) SetNoSilentRefresh(noSilent bool)
- type AuthAdapterConfig
- type AuthExpiredError
- type AuthFailedError
- type AuthMode
- type AuthRequiredError
- type CommandFlags
- type ConnectionError
- type ConnectionErrorType
- type ExecutorOptions
- type MCPPrompt
- type MCPResource
- type MCPTool
- type OutputFormat
- type PlainTableWriter
- type ServerStatus
- type TableBuilder
- type TableFormatter
- type ToolExecutor
- func (e *ToolExecutor) Close() error
- func (e *ToolExecutor) Connect(ctx context.Context) error
- func (e *ToolExecutor) Execute(ctx context.Context, toolName string, args map[string]interface{}) error
- func (e *ToolExecutor) ExecuteJSON(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error)
- func (e *ToolExecutor) GetClient() *agent.Client
- func (e *ToolExecutor) GetMCPPrompt(ctx context.Context, name string) (*mcp.Prompt, error)
- func (e *ToolExecutor) GetMCPResource(ctx context.Context, uri string) (*mcp.Resource, error)
- func (e *ToolExecutor) GetMCPTool(ctx context.Context, name string) (*mcp.Tool, error)
- func (e *ToolExecutor) GetOptions() ExecutorOptions
- func (e *ToolExecutor) ListMCPPrompts(ctx context.Context) ([]mcp.Prompt, error)
- func (e *ToolExecutor) ListMCPResources(ctx context.Context) ([]mcp.Resource, error)
- func (e *ToolExecutor) ListMCPTools(ctx context.Context) ([]mcp.Tool, error)
Constants ¶
const ( // ServerTypeStdio represents a local stdio-based MCP server. ServerTypeStdio = "stdio" // ServerTypeStreamableHTTP represents a remote streamable HTTP MCP server. ServerTypeStreamableHTTP = "streamable-http" // ServerTypeSSE represents a remote Server-Sent Events MCP server. ServerTypeSSE = "sse" )
Server type constants for MCP server classification.
const AuthModeEnvVar = "MUSTER_AUTH_MODE"
AuthModeEnvVar is the environment variable name for setting the default auth mode.
const CallbackPortEnvVar = "MUSTER_OAUTH_CALLBACK_PORT"
CallbackPortEnvVar is the environment variable for configuring the OAuth callback port.
const ContextEnvVar = musterctx.ContextEnvVar
ContextEnvVar is the environment variable name for overriding the current context.
const DefaultCallbackPort = 3000
DefaultCallbackPort is the default port for OAuth callbacks if not configured.
const DefaultConnectionCheckTimeout = 5 * time.Second
DefaultConnectionCheckTimeout is the timeout for checking connection state and tokens.
const DefaultHTTPClientTimeout = 5 * time.Second
DefaultHTTPClientTimeout is the timeout for HTTP client operations.
const EndpointEnvVar = "MUSTER_ENDPOINT"
EndpointEnvVar is the environment variable name for setting the default endpoint.
Variables ¶
var ValidOutputFormats = []OutputFormat{ OutputFormatTable, OutputFormatWide, OutputFormatJSON, OutputFormatYAML, }
ValidOutputFormats contains all valid output format values.
Functions ¶
func CheckServerRunning ¶
CheckServerRunning verifies that the muster aggregator server is running and responsive. It performs a health check by sending a GET request to the MCP endpoint and validates the response status code. This is typically used before attempting to execute commands that require server connectivity.
Returns:
- error: nil if server is running and responsive, otherwise an error with guidance
func ExtractServerType ¶
ExtractServerType extracts the server type from a data map. It checks common field names that indicate the server type in MCP server data.
The function checks the following fields in order:
- "type": Direct server type field
- "metadata": May contain server type as a string
Args:
- data: Map containing server data
Returns:
- string: The server type (stdio, streamable-http, sse) or empty string if not found
func FormatMCPPromptDetail ¶
func FormatMCPPromptDetail(prompt MCPPrompt, format OutputFormat) error
FormatMCPPromptDetail formats and displays detailed MCP prompt info. For table format, it uses a kubectl-describe-like plain text output.
func FormatMCPPromptsWithOptions ¶
func FormatMCPPromptsWithOptions(prompts []MCPPrompt, format OutputFormat, noHeaders bool) error
FormatMCPPromptsWithOptions formats and displays MCP prompts with additional options.
func FormatMCPResourceDetail ¶
func FormatMCPResourceDetail(resource MCPResource, format OutputFormat) error
FormatMCPResourceDetail formats and displays detailed MCP resource info. For table format, it uses a kubectl-describe-like plain text output.
func FormatMCPResourcesWithOptions ¶
func FormatMCPResourcesWithOptions(resources []MCPResource, format OutputFormat, noHeaders bool) error
FormatMCPResourcesWithOptions formats and displays MCP resources with additional options.
func FormatMCPToolDetail ¶
func FormatMCPToolDetail(tool MCPTool, format OutputFormat) error
FormatMCPToolDetail formats and displays detailed MCP tool info. For table format, it uses a kubectl-describe-like plain text output.
func FormatMCPToolsWithOptions ¶
func FormatMCPToolsWithOptions(tools []MCPTool, format OutputFormat, noHeaders bool) error
FormatMCPToolsWithOptions formats and displays MCP tools with additional options.
func GetAggregatorEndpoint ¶
func GetAggregatorEndpoint(cfg *config.MusterConfig) string
GetAggregatorEndpoint detects and returns the aggregator endpoint URL from a specific configuration.
Args:
- cfg: Pointer to MusterConfig to use for detecting the endpoint.
Returns:
- string: The complete HTTP endpoint URL (e.g., "http://localhost:8090/mcp")
- error: Always nil (kept for future compatibility)
func GetDefaultEndpoint ¶
func GetDefaultEndpoint() string
GetDefaultEndpoint returns the endpoint from environment variable if set.
func IsMCPServerData ¶
IsMCPServerData checks if the data represents an MCP server. It analyzes the data structure to identify MCP server-specific patterns.
Args:
- data: Map containing potential MCP server data
Returns:
- bool: true if the data appears to be MCP server related
func IsRemoteEndpoint ¶
IsRemoteEndpoint checks if an endpoint URL points to a remote server. It properly parses the URL and checks only the hostname, avoiding false positives when "localhost" appears in the path or query string.
Args:
- endpoint: The endpoint URL to check
Returns:
- bool: true if the endpoint is remote (not localhost), false otherwise
func IsRemoteServerType ¶
IsRemoteServerType returns true if the server type represents a remote connection. Remote servers use network connections (streamable-http or sse) rather than local process communication (stdio).
Args:
- serverType: The server type string to check
Returns:
- bool: true if the server type is remote (streamable-http or sse)
func ParseTimeFilter ¶
ParseTimeFilter parses time strings in various formats for event filtering and other time-based queries. It supports duration format (e.g., "1h", "30m"), RFC3339 format (e.g., "2024-01-15T10:00:00Z"), date-only format (e.g., "2024-01-15"), and datetime format (e.g., "2024-01-15 10:00:00").
For duration format, the returned time is calculated as now minus the duration.
Args:
- timeStr: The time string to parse
Returns:
- time.Time: The parsed time
- error: An error if the format is not recognized
func RegisterCommonFlags ¶
func RegisterCommonFlags(cmd *cobra.Command, flags *CommandFlags)
RegisterCommonFlags registers the common flags used by most CLI commands that connect to a muster aggregator. This reduces duplication across command files and ensures consistent flag naming and descriptions.
The registered flags are:
- --output/-o: Output format (table, wide, json, yaml), default: "table"
- --no-headers: Suppress header row in table output
- --quiet/-q: Suppress non-essential output
- --debug: Enable debug logging (show MCP protocol messages)
- --config-path: Configuration directory
- --endpoint: Remote muster aggregator endpoint URL (env: MUSTER_ENDPOINT)
- --context: Use a specific context (env: MUSTER_CONTEXT)
- --auth: Authentication mode (env: MUSTER_AUTH_MODE)
func ResolveEndpoint ¶
ResolveEndpoint resolves the endpoint URL using the precedence order: 1. Explicit endpoint (from --endpoint flag) 2. Context name (from --context flag) 3. MUSTER_CONTEXT environment variable 4. current-context from contexts.yaml 5. Empty string (caller should fall back to config-based endpoint)
Returns the resolved endpoint URL and any error encountered. If no context is configured, returns an empty string (not an error).
func ValidateOutputFormat ¶
ValidateOutputFormat validates that the given format string is a supported output format. Returns nil if valid, or an error with a helpful message listing valid formats.
Types ¶
type AuthAdapter ¶
type AuthAdapter struct {
// contains filtered or unexported fields
}
AuthAdapter implements api.AuthHandler using internal/agent/oauth. It wraps the AuthManager and TokenStore to provide OAuth authentication for CLI commands following the project's service locator pattern.
Thread-safe: All public methods are safe for concurrent use.
func NewAuthAdapter ¶
func NewAuthAdapter() (*AuthAdapter, error)
NewAuthAdapter creates a new auth adapter with default configuration.
func NewAuthAdapterWithConfig ¶
func NewAuthAdapterWithConfig(cfg AuthAdapterConfig) (*AuthAdapter, error)
NewAuthAdapterWithConfig creates a new auth adapter with the specified configuration. This is useful for testing or advanced use cases where custom token storage is needed.
func (*AuthAdapter) CheckAuthRequired ¶
CheckAuthRequired probes the endpoint to determine if OAuth is required.
func (*AuthAdapter) Close ¶
func (a *AuthAdapter) Close() error
Close cleans up any resources held by the auth adapter.
func (*AuthAdapter) GetBearerToken ¶
func (a *AuthAdapter) GetBearerToken(endpoint string) (string, error)
GetBearerToken returns a valid Bearer token for the endpoint. Token refresh is handled by mcp-go's transport layer via AgentTokenStore.
func (*AuthAdapter) GetStatus ¶
func (a *AuthAdapter) GetStatus() []api.AuthStatus
GetStatus returns authentication status for all known endpoints.
func (*AuthAdapter) GetStatusForEndpoint ¶
func (a *AuthAdapter) GetStatusForEndpoint(endpoint string) *api.AuthStatus
GetStatusForEndpoint returns authentication status for a specific endpoint.
func (*AuthAdapter) HasCredentials ¶ added in v0.1.1
func (a *AuthAdapter) HasCredentials(endpoint string) bool
HasCredentials reports whether usable credentials exist for the endpoint: a valid access token or an expired token with a refresh token.
func (*AuthAdapter) InvalidateCache ¶ added in v0.1.1
func (a *AuthAdapter) InvalidateCache(endpoint string)
InvalidateCache removes the cached auth manager for an endpoint. This forces the next GetStatusForEndpoint call to create a fresh manager that reads the latest token from the file store. This is needed after mcp-go's transport refreshes a token, since the refreshed token is persisted to file by AgentTokenStore but the AuthAdapter's in-memory TokenStore cache is stale.
func (*AuthAdapter) Login ¶
func (a *AuthAdapter) Login(ctx context.Context, endpoint string) error
Login initiates the OAuth flow for the given endpoint. If a previous session exists, it first attempts silent re-authentication using prompt=none. If silent auth fails, it falls back to interactive login.
func (*AuthAdapter) LoginWithIssuer ¶
func (a *AuthAdapter) LoginWithIssuer(ctx context.Context, endpoint, issuerURL string) error
LoginWithIssuer initiates the OAuth flow with a known issuer.
func (*AuthAdapter) Logout ¶
func (a *AuthAdapter) Logout(endpoint string) error
Logout clears stored tokens for the endpoint. It first revokes the refresh token via RFC 7009 (best-effort), then performs local cleanup.
func (*AuthAdapter) LogoutAll ¶
func (a *AuthAdapter) LogoutAll() error
LogoutAll clears all stored tokens. It revokes each endpoint's refresh token via RFC 7009, then calls DELETE /user-tokens to clear server-side downstream state.
func (*AuthAdapter) Register ¶
func (a *AuthAdapter) Register()
Register registers the adapter with the API layer.
func (*AuthAdapter) SetNoSilentRefresh ¶
func (a *AuthAdapter) SetNoSilentRefresh(noSilent bool)
SetNoSilentRefresh enables or disables silent re-authentication. When disabled (the default), Login() attempts silent re-auth before interactive login. When enabled, Login() always uses interactive authentication.
type AuthAdapterConfig ¶
type AuthAdapterConfig struct {
// TokenStorageDir is the directory for storing OAuth tokens.
// If empty, defaults to ~/.config/muster/tokens
TokenStorageDir string
// NoSilentRefresh disables silent re-authentication attempts.
// When true, Login() always uses interactive authentication.
NoSilentRefresh bool
}
AuthAdapterConfig provides configuration options for the AuthAdapter.
type AuthExpiredError ¶
type AuthExpiredError struct {
// Endpoint is the URL whose token has expired.
Endpoint string
}
AuthExpiredError indicates the token has expired. Implements error with actionable guidance.
func (*AuthExpiredError) Error ¶
func (e *AuthExpiredError) Error() string
Error returns a user-friendly error message with actionable guidance.
func (*AuthExpiredError) Is ¶
func (e *AuthExpiredError) Is(target error) bool
Is allows errors.Is() to work with wrapped errors.
type AuthFailedError ¶
type AuthFailedError struct {
// Endpoint is the URL where authentication failed.
Endpoint string
// Reason is the underlying error.
Reason error
}
AuthFailedError indicates authentication failed.
func (*AuthFailedError) Error ¶
func (e *AuthFailedError) Error() string
Error returns a user-friendly error message with actionable guidance.
func (*AuthFailedError) Is ¶
func (e *AuthFailedError) Is(target error) bool
Is allows errors.Is() to work with wrapped errors.
func (*AuthFailedError) Unwrap ¶
func (e *AuthFailedError) Unwrap() error
Unwrap returns the underlying error.
type AuthMode ¶
type AuthMode string
AuthMode represents authentication behavior for CLI commands.
const ( // AuthModeAuto automatically triggers OAuth browser login when authentication is required. // This is the default behavior. AuthModeAuto AuthMode = "auto" // AuthModePrompt prompts the user before triggering authentication. AuthModePrompt AuthMode = "prompt" // AuthModeNone fails immediately on 401 without attempting authentication. AuthModeNone AuthMode = "none" )
func GetAuthModeWithOverride ¶
GetAuthModeWithOverride returns the auth mode from the provided override string, falling back to the environment variable default if the override is empty. This consolidates the common pattern used across CLI commands.
Note: ParseAuthMode already handles empty string as "auto", so this function adds environment variable lookup as an intermediate step.
func GetDefaultAuthMode ¶
func GetDefaultAuthMode() AuthMode
GetDefaultAuthMode returns the default auth mode from environment or "auto".
func ParseAuthMode ¶
ParseAuthMode parses a string into an AuthMode, with validation.
type AuthRequiredError ¶
type AuthRequiredError struct {
// Endpoint is the URL that requires authentication.
Endpoint string
}
AuthRequiredError indicates authentication is needed. Implements error with actionable guidance.
func (*AuthRequiredError) Error ¶
func (e *AuthRequiredError) Error() string
Error returns a user-friendly error message with actionable guidance.
func (*AuthRequiredError) Is ¶
func (e *AuthRequiredError) Is(target error) bool
Is allows errors.Is() to work with wrapped errors.
type CommandFlags ¶
type CommandFlags struct {
// OutputFormat specifies the desired output format (table, json, yaml)
OutputFormat string
// NoHeaders suppresses the header row in table output
NoHeaders bool
// Quiet suppresses progress indicators and non-essential output
Quiet bool
// Debug enables verbose logging of MCP protocol messages
Debug bool
// ConfigPath specifies a custom configuration directory path
ConfigPath string
// Endpoint overrides the aggregator endpoint URL for remote connections
Endpoint string
// Context specifies a named context to use for endpoint resolution
Context string
// AuthMode controls authentication behavior (auto, prompt, none)
AuthMode string
}
CommandFlags holds the common flag values used across CLI commands that connect to a muster aggregator. This struct consolidates the repetitive flag pattern used by commands like get, list, check, start, stop, create, and events.
func (*CommandFlags) ToExecutorOptions ¶
func (f *CommandFlags) ToExecutorOptions() (ExecutorOptions, error)
ToExecutorOptions converts CommandFlags to ExecutorOptions for use with NewToolExecutor. This provides a convenient bridge between the flag registration and executor creation. It validates the output format and returns an error for unsupported formats.
type ConnectionError ¶
type ConnectionError struct {
// Endpoint is the URL that could not be reached.
Endpoint string
// Type categorizes the connection error.
Type ConnectionErrorType
// Reason is the underlying error.
Reason error
}
ConnectionError indicates a connection failure to an endpoint. It wraps the underlying error and provides categorization for better user feedback.
func ClassifyConnectionError ¶
func ClassifyConnectionError(err error, endpoint string) *ConnectionError
ClassifyConnectionError analyzes an error and returns a ConnectionError with the appropriate type. If the error is nil, returns nil.
type ConnectionErrorType ¶
type ConnectionErrorType int
ConnectionErrorType categorizes the type of connection error.
const ( // ConnectionErrorUnknown indicates an unclassified connection error. ConnectionErrorUnknown ConnectionErrorType = iota // ConnectionErrorTLS indicates a TLS/certificate verification error. ConnectionErrorTLS // ConnectionErrorNetwork indicates a network connectivity error (e.g., refused, unreachable). ConnectionErrorNetwork // ConnectionErrorTimeout indicates a connection timeout. ConnectionErrorTimeout // ConnectionErrorDNS indicates a DNS resolution failure. ConnectionErrorDNS )
func (ConnectionErrorType) String ¶
func (t ConnectionErrorType) String() string
String returns a human-readable name for the connection error type.
type ExecutorOptions ¶
type ExecutorOptions struct {
// Format specifies the desired output format (table, json, yaml)
Format OutputFormat
// NoHeaders suppresses the header row in table output
NoHeaders bool
// Quiet suppresses progress indicators and non-essential output
Quiet bool
// Debug enables verbose logging of MCP protocol messages and initialization
Debug bool
// ConfigPath specifies a custom configuration directory path
ConfigPath string
// Endpoint overrides the aggregator endpoint URL for remote connections
Endpoint string
// Context specifies a named context to use for endpoint resolution
Context string
// AuthMode controls authentication behavior (auto, prompt, none)
AuthMode AuthMode
}
ExecutorOptions contains configuration options for tool execution. These options control how commands are executed and how output is formatted.
type MCPResource ¶
MCPResource is an alias for mcp.Resource for use in cmd package
type OutputFormat ¶
type OutputFormat string
OutputFormat represents the supported output formats for CLI commands. This allows users to choose how they want to receive command results.
const ( // OutputFormatTable formats output as a kubectl-style plain table OutputFormatTable OutputFormat = "table" // OutputFormatWide formats output as a table with additional columns OutputFormatWide OutputFormat = "wide" // OutputFormatJSON formats output as raw JSON data OutputFormatJSON OutputFormat = "json" // OutputFormatYAML formats output as YAML data converted from JSON OutputFormatYAML OutputFormat = "yaml" )
type PlainTableWriter ¶
type PlainTableWriter struct {
// contains filtered or unexported fields
}
PlainTableWriter provides kubectl-style plain table output without box-drawing characters. This format is optimized for:
- Easy copy/paste operations
- Piping to grep, awk, cut and other command-line tools
- Terminal-agnostic rendering (no Unicode issues)
- Familiar kubectl-like appearance
func NewPlainTableWriter ¶
func NewPlainTableWriter(output io.Writer) *PlainTableWriter
NewPlainTableWriter creates a new plain table writer with kubectl-style formatting. By default, headers are shown. Use SetNoHeaders(true) to suppress them.
func (*PlainTableWriter) AppendRow ¶
func (w *PlainTableWriter) AppendRow(row []string)
AppendRow adds a row to the table.
func (*PlainTableWriter) Render ¶
func (w *PlainTableWriter) Render()
Render outputs the table in kubectl-style format.
func (*PlainTableWriter) SetHeaders ¶
func (w *PlainTableWriter) SetHeaders(headers []string)
SetHeaders sets the column headers for the table. Headers are displayed in uppercase by default.
func (*PlainTableWriter) SetNoHeaders ¶
func (w *PlainTableWriter) SetNoHeaders(noHeaders bool)
SetNoHeaders controls whether to suppress the header row.
type ServerStatus ¶
type ServerStatus struct {
// Endpoint is the URL of the server.
Endpoint string
// Reachable indicates whether the server responded to probes.
Reachable bool
// AuthRequired indicates whether the server requires authentication.
AuthRequired bool
// Authenticated indicates whether we have a valid token for this server.
Authenticated bool
// Error holds any error that occurred during the check.
Error error
}
ServerStatus represents the connectivity and auth status of a server.
type TableBuilder ¶
type TableBuilder struct{}
TableBuilder handles cell formatting and styling for table display. It provides specialized formatting for different types of data commonly encountered in muster operations, including status indicators, metadata, and resource-specific information. The builder applies consistent styling and iconography to create professional-looking table output.
func NewTableBuilder ¶
func NewTableBuilder() *TableBuilder
NewTableBuilder creates a new table builder instance. The builder is stateless and can be reused for multiple formatting operations.
Returns:
- *TableBuilder: New table builder ready for use
func (*TableBuilder) FormatCellValuePlain ¶
func (b *TableBuilder) FormatCellValuePlain(column string, value interface{}, rowContext map[string]interface{}) string
FormatCellValuePlain formats individual cell values as plain text without ANSI styling. This is used for kubectl-style table output where we don't want color codes.
Args:
- column: The column name/type to determine formatting rules
- value: The raw value to format
- rowContext: The full row data for context-aware formatting (may be nil)
Returns:
- string: Formatted value as plain text
func (*TableBuilder) SimplifyToolName ¶
func (b *TableBuilder) SimplifyToolName(toolName string) string
SimplifyToolName removes common prefixes to make tool names more readable. Many muster tools have predictable prefixes that add noise to table display. This function strips common prefixes to improve readability.
Args:
- toolName: The full tool name to simplify
Returns:
- string: Simplified tool name with common prefixes removed
func (*TableBuilder) SortDataByName ¶
func (b *TableBuilder) SortDataByName(data []interface{}, columns []string) []interface{}
SortDataByName sorts data by the first column (usually name/id). This provides consistent ordering in tables, making it easier for users to find specific resources.
Args:
- data: Array of data objects to sort
- columns: Column names, with the first used for sorting
Returns:
- []interface{}: Sorted data array
type TableFormatter ¶
type TableFormatter struct {
// contains filtered or unexported fields
}
TableFormatter handles table creation and optimization for muster CLI output. It provides intelligent formatting for different types of data structures, automatically optimizing column layouts and applying consistent styling. The formatter can handle both simple arrays and complex nested objects, adapting the display format to provide the best user experience.
func NewTableFormatter ¶
func NewTableFormatter(options ExecutorOptions) *TableFormatter
NewTableFormatter creates a new table formatter with the specified options. The formatter uses the provided options to determine output behavior, including format selection and verbosity settings.
Args:
- options: Configuration options for formatting behavior
Returns:
- *TableFormatter: Configured table formatter ready for use
func (*TableFormatter) FormatData ¶
func (f *TableFormatter) FormatData(data interface{}) error
FormatData formats data according to its type and structure. It intelligently handles different data types including objects, arrays, and simple values, applying the most appropriate formatting strategy for optimal readability and information density.
Args:
- data: The data to format (can be object, array, or simple value)
Returns:
- error: Formatting error, if any
type ToolExecutor ¶
type ToolExecutor struct {
// contains filtered or unexported fields
}
ToolExecutor provides high-level tool execution functionality with formatted output. It handles the connection to the muster aggregator, executes tools, and formats the results according to the specified output format. This is the main interface for CLI commands that need to interact with muster services.
func NewToolExecutor ¶
func NewToolExecutor(options ExecutorOptions) (*ToolExecutor, error)
NewToolExecutor creates a new tool executor with the specified options. It establishes the connection configuration and initializes the MCP client for communication with the muster aggregator server.
Args:
- options: Configuration options for execution and output formatting
Returns:
- *ToolExecutor: Configured tool executor ready for use
- error: Configuration or connection setup error
func (*ToolExecutor) Close ¶
func (e *ToolExecutor) Close() error
Close gracefully closes the connection to the aggregator server. This should be called when the executor is no longer needed to free resources.
Returns:
- error: Error during connection cleanup, if any
func (*ToolExecutor) Connect ¶
func (e *ToolExecutor) Connect(ctx context.Context) error
Connect establishes a connection to the muster aggregator server. It shows a progress spinner unless quiet mode is enabled, and handles connection errors with appropriate user feedback. For remote servers, it uses mcp-go's OAuth transport for automatic token injection and typed 401 error handling.
Args:
- ctx: Context for connection timeout and cancellation
Returns:
- error: Connection error, if any
func (*ToolExecutor) Execute ¶
func (e *ToolExecutor) Execute(ctx context.Context, toolName string, args map[string]interface{}) error
Execute executes a tool with the given args and formats the output. This is the main method for running muster tools through the CLI interface. It handles progress indication, error formatting, and output formatting according to the configured options.
Args:
- ctx: Context for execution timeout and cancellation
- toolName: Name of the tool to execute
- args: Tool args as key-value pairs
Returns:
- error: Execution or formatting error, if any
func (*ToolExecutor) ExecuteJSON ¶
func (e *ToolExecutor) ExecuteJSON(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error)
ExecuteJSON executes a tool and returns the result as parsed JSON. This method is useful when you need to work with structured data programmatically rather than displaying it to users.
Args:
- ctx: Context for execution timeout and cancellation
- toolName: Name of the tool to execute
- args: Tool args as key-value pairs
Returns:
- interface{}: Parsed JSON result as Go data structures
- error: Execution or JSON parsing error, if any
func (*ToolExecutor) GetClient ¶
func (e *ToolExecutor) GetClient() *agent.Client
GetClient returns the underlying agent client for advanced use cases like streaming.
func (*ToolExecutor) GetMCPPrompt ¶
GetMCPPrompt returns detailed info for a specific prompt. This method retrieves the prompt list and finds the specified prompt by name.
Args:
- ctx: Context for execution timeout and cancellation
- name: The exact name of the prompt to find
Returns:
- *mcp.Prompt: Pointer to the found prompt, or nil if not found
- error: Connection or retrieval error, if any
func (*ToolExecutor) GetMCPResource ¶
GetMCPResource returns detailed info for a specific resource. This method retrieves the resource list and finds the specified resource by URI.
Args:
- ctx: Context for execution timeout and cancellation
- uri: The exact URI of the resource to find
Returns:
- *mcp.Resource: Pointer to the found resource, or nil if not found
- error: Connection or retrieval error, if any
func (*ToolExecutor) GetMCPTool ¶
GetMCPTool returns detailed info for a specific tool by calling describe_tool meta-tool. This method retrieves the tool information from the actual tools (core_*, x_*, workflow_*) rather than the meta-tools exposed by the MCP native protocol.
Args:
- ctx: Context for execution timeout and cancellation
- name: The exact name of the tool to find
Returns:
- *mcp.Tool: Pointer to the found tool, or nil if not found
- error: Connection or retrieval error, if any
func (*ToolExecutor) GetOptions ¶
func (e *ToolExecutor) GetOptions() ExecutorOptions
GetOptions returns the executor options. This allows callers to check the configured output format and other settings.
func (*ToolExecutor) ListMCPPrompts ¶
ListMCPPrompts returns all MCP prompts using native protocol. This method retrieves prompts directly from the MCP server without going through the tool execution interface.
Args:
- ctx: Context for execution timeout and cancellation
Returns:
- []mcp.Prompt: Slice of all available prompts from the server
- error: Connection or retrieval error, if any
func (*ToolExecutor) ListMCPResources ¶
ListMCPResources returns all MCP resources using native protocol. This method retrieves resources directly from the MCP server without going through the tool execution interface.
Args:
- ctx: Context for execution timeout and cancellation
Returns:
- []mcp.Resource: Slice of all available resources from the server
- error: Connection or retrieval error, if any
func (*ToolExecutor) ListMCPTools ¶
ListMCPTools returns all MCP tools by calling the list_tools meta-tool. This method retrieves the actual tools (core_*, x_*, workflow_*) rather than the meta-tools exposed by the MCP native tools/list protocol.
Args:
- ctx: Context for execution timeout and cancellation
Returns:
- []mcp.Tool: Slice of all available tools from the server
- error: Connection or retrieval error, if any