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 MCPPromptInfo, format OutputFormat) error
- func FormatMCPPromptsWithOptions(prompts []MCPPromptInfo, format OutputFormat, noHeaders bool) error
- func FormatMCPResourceDetail(resource MCPResourceInfo, format OutputFormat) error
- func FormatMCPResourcesWithOptions(resources []MCPResourceInfo, format OutputFormat, noHeaders bool) error
- func FormatMCPToolDetail(tool MCPTool, format OutputFormat) error
- func FormatMCPToolsWithOptions(tools []MCPToolInfo, format OutputFormat, noHeaders bool) error
- func GetAggregatorEndpoint(cfg *config.MusterConfig) string
- func GetCallbackPort() int
- 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) GetAccessToken(endpoint string) (string, error)
- func (a *AuthAdapter) GetBearerToken(endpoint string) (string, error)
- func (a *AuthAdapter) GetIDToken(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) Relogin(ctx context.Context, endpoint string) error
- 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 MCPNotification
- type MCPPrompt
- type MCPPromptInfo
- type MCPResource
- type MCPResourceInfo
- type MCPTool
- type MCPToolInfo
- type OutputFormat
- type PlainTableWriter
- type RevocationFailedError
- 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) GetMCPPrompt(ctx context.Context, name string) (*MCPPromptInfo, error)
- func (e *ToolExecutor) GetMCPResource(ctx context.Context, uri, server string) (*MCPResourceInfo, error)
- func (e *ToolExecutor) GetMCPTool(ctx context.Context, name string) (*mcp.Tool, error)
- func (e *ToolExecutor) GetOptions() ExecutorOptions
- func (e *ToolExecutor) ListMCPPromptsWithServer(ctx context.Context, withArguments bool) ([]MCPPromptInfo, error)
- func (e *ToolExecutor) ListMCPResourcesWithServer(ctx context.Context) ([]MCPResourceInfo, error)
- func (e *ToolExecutor) ListMCPTools(ctx context.Context) ([]MCPToolInfo, error)
- func (e *ToolExecutor) OnNotification(handler func(mcp.JSONRPCNotification))
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 AuthRequiredMarker = "auth_required"
AuthRequiredMarker opens every AuthRequiredError message so a script or an agent can tell "sign in first" from any other failure without parsing prose.
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.
const LoginFlag = "login"
LoginFlag is the flag that opts a command into the interactive sign-in.
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 MCPPromptInfo, 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 []MCPPromptInfo, format OutputFormat, noHeaders bool) error
FormatMCPPromptsWithOptions formats and displays MCP prompts with additional options.
func FormatMCPResourceDetail ¶
func FormatMCPResourceDetail(resource MCPResourceInfo, 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 []MCPResourceInfo, 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 []MCPToolInfo, 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 GetCallbackPort ¶
func GetCallbackPort() int
GetCallbackPort returns the OAuth callback port from environment or default.
Exported so every OAuth entry point resolves the port the same way. The agent MCP-server path previously hardcoded its own constant and silently ignored MUSTER_OAUTH_CALLBACK_PORT, so `muster auth login` and `muster agent --mcp-server` could disagree about which port to bind.
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)
- --login: Open the browser to sign in when authentication is required
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.
If this adapter is the one currently registered with the API layer, the registration is cleared first. Register() publishes the adapter into a process-global registry that has no expiry of its own, so without this a closed adapter stays reachable through api.GetAuthHandler() -- and because AuthAdapter carries no closed flag, callers would silently re-create managers on it instead of failing. The compare-and-clear is atomic, and a no-op when a different adapter is registered.
func (*AuthAdapter) GetAccessToken ¶ added in v5.26.0
func (a *AuthAdapter) GetAccessToken(endpoint string) (string, error)
GetAccessToken returns a valid access token for the endpoint. Token refresh is handled by mcp-go's transport layer via AgentTokenStore.
func (*AuthAdapter) GetBearerToken ¶
func (a *AuthAdapter) GetBearerToken(endpoint string) (string, error)
GetBearerToken returns the access token formatted as a Bearer authorization header value.
func (*AuthAdapter) GetIDToken ¶ added in v5.26.0
func (a *AuthAdapter) GetIDToken(endpoint string) (string, error)
GetIDToken returns the stored OIDC ID token for the endpoint. Unlike the access token it is never renewed by the mcp-go transport, so it is returned as stored and the caller judges its exp claim.
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 ¶
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 ¶
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 and the access token via RFC 7009, then performs local cleanup. Local state is cleared either way; a failed revocation is returned afterwards as a *RevocationFailedError.
func (*AuthAdapter) LogoutAll ¶
func (a *AuthAdapter) LogoutAll() error
LogoutAll clears all stored tokens. It revokes each endpoint's refresh and access token via RFC 7009, then calls DELETE /user-tokens to clear server-side downstream state. Local state is cleared either way; failed revocations are returned afterwards as a *RevocationFailedError.
func (*AuthAdapter) Register ¶
func (a *AuthAdapter) Register()
Register registers the adapter with the API layer.
func (*AuthAdapter) Relogin ¶ added in v5.26.0
func (a *AuthAdapter) Relogin(ctx context.Context, endpoint string) error
Relogin runs the interactive OAuth flow although the endpoint may hold a valid session. The stored token, ID token included, is replaced when the flow completes and kept when it does not.
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 opens the browser to sign in when the endpoint requires // authentication and no usable token is stored. Opt in with --login (or // --auth auto): a script, an agent or a CI job can never complete a // browser flow, so it is not the default. AuthModeAuto AuthMode = "auto" // AuthModePrompt asks before opening the browser. AuthModePrompt AuthMode = "prompt" // AuthModeNone is the default: a stored token is used and refreshed as // always, but when the endpoint requires authentication and no usable // token is stored the command fails at once with AuthRequiredError, // which names the login command. Only `muster auth login` (or --login) // opens a browser. 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 auth mode from MUSTER_AUTH_MODE, or "none" (fail fast, no browser) when the variable is unset or invalid.
func ParseAuthMode ¶
ParseAuthMode parses a string into an AuthMode, with validation.
func ResolveAuthMode ¶ added in v5.26.2
ResolveAuthMode resolves the auth mode from the --login flag and the --auth override, falling back to MUSTER_AUTH_MODE and then the default. --login is --auth auto spelled for a person at a terminal and wins over the environment; combined with another explicit --auth value it is a contradiction.
type AuthRequiredError ¶
type AuthRequiredError struct {
// Endpoint is the URL that requires authentication.
Endpoint string
// Context is the named context the endpoint was resolved from, if any.
Context string
// CanLogin says the failing command accepts --login to open the browser.
CanLogin bool
}
AuthRequiredError indicates authentication is needed and no usable token is stored. The message starts with AuthRequiredMarker, names the login command for the context (or endpoint) the command used, and -- when the command accepts --login -- how to sign in from the command itself. The process exits with the auth-required exit code.
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.
func (*AuthRequiredError) LoginCommand ¶ added in v5.26.2
func (e *AuthRequiredError) LoginCommand() string
LoginCommand returns the `muster auth login` invocation for the context or endpoint this error is about.
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
// Login opens the browser to sign in when the endpoint requires it (--auth auto)
Login bool
}
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) CompletionOptions ¶ added in v5.34.17
func (f *CommandFlags) CompletionOptions() ExecutorOptions
CompletionOptions returns the options of a shell-completion lookup: quiet JSON against the aggregator the command itself would reach, so --endpoint, --context and their environment variables pick it, not the default context.
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
// ContinuousListening, when true, makes the streamable-http client open a
// standalone GET stream so it receives server-initiated notifications
// (required for `events --follow`). Has no effect on the SSE transport,
// which always listens.
ContinuousListening bool
// CallTimeout bounds one tool call; zero keeps agent.DefaultCallTimeout.
CallTimeout time.Duration
}
ExecutorOptions contains configuration options for tool execution. These options control how commands are executed and how output is formatted.
type MCPNotification ¶
type MCPNotification = mcp.JSONRPCNotification
MCPNotification is an alias for mcp.JSONRPCNotification for use in cmd package
type MCPPromptInfo ¶ added in v5.34.16
type MCPPromptInfo struct {
MCPPrompt
// Server is the MCPServer the prompt comes from.
Server string
}
MCPPromptInfo is a prompt as list_prompts reports it: the MCP prompt plus the server it comes from. The exposed name carries the server's configured toolPrefix, not its name, so the attribution is carried alongside.
type MCPResource ¶
MCPResource is an alias for mcp.Resource for use in cmd package
type MCPResourceInfo ¶ added in v5.34.16
type MCPResourceInfo struct {
MCPResource
// Server is the MCPServer the resource comes from.
Server string
}
MCPResourceInfo is a resource as list_resources reports it: the MCP resource plus the server it comes from. A resource is exposed under its URI, which carries no server prefix, so the attribution is the only way to tell where it came from.
type MCPToolInfo ¶
type MCPToolInfo struct {
MCPTool
// Server is the MCPServer (or family) an aggregated tool belongs to, as
// the aggregator names it. muster's own tools carry their kind instead:
// "core" or "workflow".
Server string
}
MCPToolInfo is a tool as list_tools reports it: the MCP tool plus the server it belongs to. The exposed name does not encode the server reliably -- a server named "mcp-pro" with toolPrefix "pro" exposes x_pro_<tool> -- so the attribution the aggregator recorded is carried alongside the tool.
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 RevocationFailedError ¶ added in v5.43.1
type RevocationFailedError struct {
// Endpoints are the servers whose revocation failed.
Endpoints []string
// Reason is the underlying error.
Reason error
}
RevocationFailedError reports a sign-out whose local state was cleared but whose tokens the server did not confirm as revoked: the server-side session may stay valid until its tokens expire.
func (*RevocationFailedError) Error ¶ added in v5.43.1
func (e *RevocationFailedError) Error() string
Error returns a user-friendly error message.
func (*RevocationFailedError) Unwrap ¶ added in v5.43.1
func (e *RevocationFailedError) Unwrap() error
Unwrap returns the underlying error.
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) GetMCPPrompt ¶
func (e *ToolExecutor) GetMCPPrompt(ctx context.Context, name string) (*MCPPromptInfo, error)
GetMCPPrompt returns a prompt by name with its arguments and the server it comes from, or nil when the caller has no such prompt.
func (*ToolExecutor) GetMCPResource ¶
func (e *ToolExecutor) GetMCPResource(ctx context.Context, uri, server string) (*MCPResourceInfo, error)
GetMCPResource returns a resource by URI with the server it comes from, or nil when the caller has no such resource. server picks one of several servers exposing the URI.
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) ListMCPPromptsWithServer ¶ added in v5.34.16
func (e *ToolExecutor) ListMCPPromptsWithServer(ctx context.Context, withArguments bool) ([]MCPPromptInfo, error)
ListMCPPromptsWithServer returns the caller's prompts with the server each comes from. list_prompts reports no arguments: with withArguments, those of a prompt the native listing lacks -- every aggregated one -- are read with describe_prompt, one call per prompt.
func (*ToolExecutor) ListMCPResourcesWithServer ¶ added in v5.34.16
func (e *ToolExecutor) ListMCPResourcesWithServer(ctx context.Context) ([]MCPResourceInfo, error)
ListMCPResourcesWithServer returns the caller's resources with the server each comes from, one entry per server that exposes a URI. The resource itself is taken from the native listing where it carries one; muster's own resources (auth://status), which only the native listing has, carry no server.
func (*ToolExecutor) ListMCPTools ¶
func (e *ToolExecutor) ListMCPTools(ctx context.Context) ([]MCPToolInfo, error)
ListMCPTools returns the caller's tool catalogue by paging through the list_tools meta-tool: the actual tools (core_*, x_*, workflow_*) with the server each belongs to, rather than the meta-tools the MCP native tools/list exposes.
func (*ToolExecutor) OnNotification ¶
func (e *ToolExecutor) OnNotification(handler func(mcp.JSONRPCNotification))
OnNotification registers a handler that receives every server notification. Passing nil restores the default (debug-log) drain behavior. The handler runs on the executor's single notification-pump goroutine, so it must not block for long.