config

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package config provides configuration management and MCP proxy functionality for the Centian tool.

Index

Constants

View Source
const (
	DefaultProxyLogLevel  = "info"
	DefaultProxyLogOutput = "file"
)

Default proxy logging settings.

View Source
const DefaultAuthHeader = "X-Centian-Auth"

DefaultAuthHeader represents the default header for authentication at the Centian server.

View Source
const DefaultProxyHost = "127.0.0.1"

DefaultProxyHost represents the default bind address for the Centian server.

Variables

View Source
var ConfigCommand = &cli.Command{
	Name:        "config",
	Usage:       "Manage centian configuration",
	Description: "Commands to manage the global centian configuration at ~/.centian/config.json",
	Commands: []*cli.Command{
		configInitCommand,
		configShowCommand,
		configValidateCommand,
		configRestoreCommand,
		configRemoveCommand,
	},
}

ConfigCommand provides configuration management subcommands for the centian CLI. This is the main entry point for all config-related operations including initialization, validation, and server management.

View Source
var ServerCommand = &cli.Command{
	Name:        "server",
	Usage:       "Manage MCP servers",
	Description: "Add, remove, and configure MCP servers",
	Commands: []*cli.Command{
		{
			Name:        "list",
			Usage:       "List all configured servers",
			Description: "Display all MCP servers in the configuration",
			Flags: []cli.Flag{
				&cli.BoolFlag{
					Name:    "enabled-only",
					Aliases: []string{"e"},
					Usage:   "Show only enabled servers",
				},
			},
			Action: listServers,
		},
		{
			Name:        "add",
			Usage:       "Add a new server",
			Description: "Add a new MCP server configuration",
			Flags: []cli.Flag{
				&cli.StringFlag{
					Name:     "name",
					Aliases:  []string{"n"},
					Usage:    "Server name",
					Required: true,
				},
				&cli.StringFlag{
					Name:    "gateway",
					Aliases: []string{"gw"},
					Usage:   "Gateway name",
					Value:   "default",
				},
				&cli.StringFlag{
					Name:    "command",
					Aliases: []string{"c"},
					Usage:   "Server command",
				},
				&cli.StringSliceFlag{
					Name:    "args",
					Aliases: []string{"a"},
					Usage:   "Command arguments",
				},
				&cli.StringFlag{
					Name:    "url",
					Aliases: []string{"u"},
					Usage:   "Server URL",
				},
				&cli.StringMapFlag{
					Name:    "headers",
					Aliases: []string{"hd"},
					Usage:   "Server Headers",
				},
				&cli.StringFlag{
					Name:    "description",
					Aliases: []string{"d"},
					Usage:   "Server description",
				},
				&cli.BoolFlag{
					Name:  "enabled",
					Usage: "Enable server",
					Value: true,
				},
			},
			Action: addServer,
		},
		{
			Name:        "remove",
			Usage:       "Remove a server",
			Description: "Remove an MCP server from configuration",
			Flags: []cli.Flag{
				&cli.StringFlag{
					Name:     "name",
					Aliases:  []string{"n"},
					Usage:    "Server name to remove",
					Required: true,
				},
			},
			Action: removeServer,
		},
		{
			Name:        "enable",
			Usage:       "Enable a server",
			Description: "Enable an MCP server",
			Flags: []cli.Flag{
				&cli.StringFlag{
					Name:     "name",
					Aliases:  []string{"n"},
					Usage:    "Server name to enable",
					Required: true,
				},
			},
			Action: enableServer,
		},
		{
			Name:        "disable",
			Usage:       "Disable a server",
			Description: "Disable an MCP server",
			Flags: []cli.Flag{
				&cli.StringFlag{
					Name:     "name",
					Aliases:  []string{"n"},
					Usage:    "Server name to disable",
					Required: true,
				},
			},
			Action: disableServer,
		},
	},
}

ServerCommand provides MCP server management functionality.

Functions

func EnsureConfigDir

func EnsureConfigDir() error

EnsureConfigDir creates the config directory if it doesn't exist.

func GetConfigDir

func GetConfigDir() (string, error)

GetConfigDir returns the centian config directory path.

func GetConfigPath

func GetConfigPath() (string, error)

GetConfigPath returns the full path to config.json.

func HasOAuthServers added in v0.0.6

func HasOAuthServers(config *GlobalConfig) bool

HasOAuthServers reports whether any configured downstream server enables OAuth.

func ImportServers added in v0.0.6

func ImportServers(cfg *GlobalConfig, servers []ImportedServer) (int, error)

ImportServers adds imported servers to the default gateway when they validate cleanly.

func InferCommandFromPath added in v0.0.4

func InferCommandFromPath(path string) (command string, args []string, err error)

InferCommandFromPath determines the runtime command and args for a CLI processor based on the file extension of the script path.

func InferProcessorNameFromPath added in v0.0.4

func InferProcessorNameFromPath(path string) string

InferProcessorNameFromPath extracts a processor name from a file path. Strips the directory and extension, lowercases the result.

func InferProcessorNameFromWebhookURL added in v0.0.6

func InferProcessorNameFromWebhookURL(rawURL string) string

InferProcessorNameFromWebhookURL extracts a processor name from a webhook URL. Prefers the last path segment and falls back to hostname when no path segment exists.

func ProcessorConfigStringMap added in v0.0.6

func ProcessorConfigStringMap(value interface{}) (map[string]string, error)

ProcessorConfigStringMap converts a config value into a string map. Accepts both map[string]string and map[string]interface{} with string values.

func SaveConfig

func SaveConfig(config *GlobalConfig) error

SaveConfig saves the configuration to ~/.centian/config.json. Creates the ~/.centian directory if it doesn't exist and writes the configuration as formatted JSON with proper indentation.

func ValidateConfig

func ValidateConfig(config *GlobalConfig, strict bool) error

ValidateConfig performs basic schema validation on the configuration. This validates required fields and structure but allows empty gateways. Use ValidateConfigForServer for operational validation before starting a server.

Types

type CLIProcessorSettings added in v0.0.6

type CLIProcessorSettings struct {
	Command string
	Args    []string
}

CLIProcessorSettings contains parsed runtime settings for a CLI processor.

func ParseCLIProcessorSettings added in v0.0.6

func ParseCLIProcessorSettings(processor *ProcessorConfig) (*CLIProcessorSettings, error)

ParseCLIProcessorSettings validates and extracts CLI processor settings.

type GatewayConfig

type GatewayConfig struct {
	AllowDynamic         bool                        `json:"allowDynamic,omitempty"` // Allow dynamic proxy endpoints
	AllowGatewayEndpoint bool                        `json:"setupGateway,omitempty"` // Setup gateway endpoint with namespacing
	MCPServers           map[string]*MCPServerConfig `json:"mcpServers"`             // HTTP MCP servers in this gateway
	Processors           []*ProcessorConfig          `json:"processors,omitempty"`
}

GatewayConfig represents a logical grouping of HTTP MCP servers.

func (*GatewayConfig) AddServer

func (g *GatewayConfig) AddServer(name string, server *MCPServerConfig)

AddServer adds a the provided server to the gateways MCP servers using name as key.

func (*GatewayConfig) HasServer

func (g *GatewayConfig) HasServer(name string) bool

HasServer returns true if a server with the provided name exists in this gateway.

func (*GatewayConfig) ListServers

func (g *GatewayConfig) ListServers() []*MCPServerConfig

ListServers returns a slice of all available MCPServerConfigs for this GatewayConfig.

func (*GatewayConfig) RemoveServer

func (g *GatewayConfig) RemoveServer(name string)

RemoveServer removes server identified via name.

type GlobalConfig

type GlobalConfig struct {
	Name        string                    `json:"name"`                 // Name of the server - simplifies server identification
	Version     string                    `json:"version"`              // Config schema version
	AuthEnabled *bool                     `json:"auth,omitempty"`       // Enable or disable proxy auth
	AuthHeader  string                    `json:"authHeader,omitempty"` // Header name for proxy auth
	Proxy       *ProxySettings            `json:"proxy,omitempty"`      // Proxy-level settings
	Gateways    map[string]*GatewayConfig `json:"gateways,omitempty"`   // HTTP proxy gateways
	Processors  []*ProcessorConfig        `json:"processors,omitempty"` // Processor chain
	Metadata    map[string]interface{}    `json:"metadata,omitempty"`   // Additional metadata
}

GlobalConfig represents the main configuration structure stored at ~/.centian/config.json. This is the root configuration object that contains all settings for MCP servers, proxy behavior, processors, and additional metadata.

func DefaultConfig

func DefaultConfig() *GlobalConfig

DefaultConfig returns a default configuration.

func LoadConfig

func LoadConfig() (*GlobalConfig, error)

LoadConfig loads the global configuration from ~/.centian/config.json. If the config file doesn't exist, it creates a new one with default settings. The configuration is validated after loading to ensure it's properly formatted.

func LoadConfigFromPath

func LoadConfigFromPath(path string) (*GlobalConfig, error)

LoadConfigFromPath loads configuration from a custom file path. The configuration is validated after loading.

func (*GlobalConfig) AddProcessor added in v0.0.4

func (g *GlobalConfig) AddProcessor(p *ProcessorConfig)

AddProcessor appends a processor to the global processor chain.

func (*GlobalConfig) GetAuthHeader

func (g *GlobalConfig) GetAuthHeader() string

GetAuthHeader returns the configured auth header name or the default.

func (*GlobalConfig) HasProcessor added in v0.0.4

func (g *GlobalConfig) HasProcessor(name string) bool

HasProcessor returns true if a processor with the given name exists in the global config.

func (*GlobalConfig) IsAuthEnabled

func (g *GlobalConfig) IsAuthEnabled() bool

IsAuthEnabled returns true when auth is enabled or unset.

func (*GlobalConfig) ReplaceProcessor added in v0.0.4

func (g *GlobalConfig) ReplaceProcessor(name string, p *ProcessorConfig) bool

ReplaceProcessor replaces an existing processor by name, preserving its position in the chain. Returns false if no processor with the given name was found.

func (*GlobalConfig) SearchServerByName

func (g *GlobalConfig) SearchServerByName(name string) []ServerSearchResult

SearchServerByName searches for a server given a name, can return multiple results for different gateways.

type ImportedServer added in v0.0.6

type ImportedServer struct {
	Name        string
	Command     string
	Args        []string
	Env         map[string]string
	URL         string
	Headers     map[string]string
	Transport   string
	Description string
	Source      string
	SourcePath  string
}

ImportedServer represents a server parsed from an external MCP config file.

func ParseImportedConfigFile added in v0.0.6

func ParseImportedConfigFile(data []byte, filePath string) ([]ImportedServer, error)

ParseImportedConfigFile parses an external MCP config file into importable servers.

type MCPServerConfig

type MCPServerConfig struct {
	Name        string                 `json:"name"`                  // MCP Server name - used to reference this specific server
	Command     string                 `json:"command,omitempty"`     // MCP Server Executable command (for stdio/process transport)
	Args        []string               `json:"args,omitempty"`        // MCP Server Command arguments
	Env         map[string]string      `json:"env,omitempty"`         // Environment variables
	URL         string                 `json:"url,omitempty"`         // MCP Server URL (for http/sse transport)
	Headers     map[string]string      `json:"headers,omitempty"`     // HTTP headers (supports ${ENV_VAR} substitution)
	OAuth       *OAuthConfig           `json:"oauth,omitempty"`       // Downstream OAuth settings for HTTP MCP servers
	Enabled     *bool                  `json:"enabled,omitempty"`     // Whether server is active
	Description string                 `json:"description,omitempty"` // Human readable description
	Source      string                 `json:"source,omitempty"`      // Source file path for auto-discovered servers
	Config      map[string]interface{} `json:"config,omitempty"`      // Server-specific config
}

MCPServerConfig represents a single MCP server configuration. Each server defines how to start and connect to an MCP server process, including all necessary arguments, e.g. command, arguments, environment variables, and metadata.

func (*MCPServerConfig) GetSubstitutedHeaders

func (s *MCPServerConfig) GetSubstitutedHeaders() map[string]string

GetSubstitutedHeaders returns headers with environment variables substituted. Supports both ${VAR_NAME} and $VAR_NAME syntax. Example: "Bearer ${GITHUB_TOKEN}" -> "Bearer ghp_abc123...".

func (*MCPServerConfig) GetTransport added in v0.0.3

func (s *MCPServerConfig) GetTransport() common.McpTransportType

GetTransport returns McpTransportType based on config data.

func (*MCPServerConfig) IsEnabled

func (s *MCPServerConfig) IsEnabled() bool

IsEnabled returns true if the MCP server is either explicitly enabled or the flag is unset (nil).

func (*MCPServerConfig) OAuthEnabled added in v0.0.6

func (s *MCPServerConfig) OAuthEnabled() bool

OAuthEnabled returns true when downstream OAuth is configured and enabled.

type OAuthConfig added in v0.0.6

type OAuthConfig struct {
	Enabled               bool     `json:"enabled"`
	ClientID              string   `json:"clientId,omitempty"`
	ClientSecret          string   `json:"clientSecret,omitempty"`
	ClientAuthMethod      string   `json:"clientAuthMethod,omitempty"`
	Scopes                []string `json:"scopes,omitempty"`
	Resource              string   `json:"resource,omitempty"`
	Issuer                string   `json:"issuer,omitempty"`
	AuthorizationEndpoint string   `json:"authorizationEndpoint,omitempty"`
	TokenEndpoint         string   `json:"tokenEndpoint,omitempty"`
}

OAuthConfig defines downstream OAuth settings for HTTP MCP servers.

type ProcessorConfig

type ProcessorConfig struct {
	Name    string                 `json:"name"`              // Unique processor name
	Type    string                 `json:"type"`              // Processor type: "cli" (future: "http", "builtin")
	Enabled bool                   `json:"enabled"`           // Whether processor is active
	Timeout int                    `json:"timeout,omitempty"` // Timeout in seconds (default: 15)
	Parts   []string               `json:"parts,omitempty"`   // Which context parts to provide: "payload", "meta", "routing", "auth" (default: ["payload","meta"])
	Config  map[string]interface{} `json:"config"`            // Type-specific configuration

	// Determines if processor is required to run, "false" by default,
	// meaning the processor can both fail initiation and
	// processing without causing the whole processor chain to fail.
	// If set to true, a failure will cause subsequent processors NOT to run.
	Required bool `json:"required"`
}

ProcessorConfig defines a single processor that executes during MCP request/response flow. Processors are composable units that can inspect, modify, or reject MCP messages.

Type-specific configuration (Config field):

For CLIProcessor processors:

  • "command" (string, required): Executable command to run (e.g., "python", "bash", "node").
  • "args" (array of strings, optional): Command-line arguments (e.g., ["script.py", "--flag"]).

Example CLI processor:

{.
  "name": "security-validator",
  "type": "cli",
  "enabled": true,
  "timeout": 20,
  "config": {
    "command": "python",
    "args": ["~/processors/security.py", "--strict"]
  }
}.

func (*ProcessorConfig) GetParts added in v0.0.3

func (p *ProcessorConfig) GetParts() []string

GetParts returns the configured parts, defaulting to ["payload"] if not specified.

type ProcessorType

type ProcessorType string

ProcessorType defines the type of processor, e.g. cli, webhook, internal, etc.

const (
	// CLIProcessor represents the type of a CLI-based processor -> "cli".
	CLIProcessor ProcessorType = "cli"
	// WebhookProcessor represents the type of a webhook-based processor -> "webhook".
	WebhookProcessor ProcessorType = "webhook"
)

type ProxySettings

type ProxySettings struct {
	Host            string            `json:"host,omitempty"`            // Bind address for the proxy
	Port            string            `json:"port,omitempty"`            // HTTP proxy port (if enabled)
	LogLevel        string            `json:"logLevel,omitempty"`        // debug, info, warn, error
	LogOutput       string            `json:"logOutput,omitempty"`       // file, console, both
	LogFile         string            `json:"logFile,omitempty"`         // Log file path for internal logger
	Timeout         int               `json:"timeout,omitempty"`         // Request timeout in seconds
	EnableTestTools bool              `json:"enableTestTools,omitempty"` // Register Centian-owned debug/test tools.
	Web             *ProxyWebSettings `json:"web,omitempty"`             // Public web settings for hosted OAuth flows
}

ProxySettings contains proxy-level configuration that affects how the centian proxy operates, including transport method, logging, and timeouts.

func NewDefaultProxySettings

func NewDefaultProxySettings() ProxySettings

NewDefaultProxySettings creates a new ProxySettings with default values.

type ProxyWebSettings added in v0.0.6

type ProxyWebSettings struct {
	PublicBaseURL string `json:"publicBaseUrl,omitempty"`
}

ProxyWebSettings contains public-facing web settings required for browser-based flows.

type ServerSearchResult

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

ServerSearchResult captures data and references when searching for a specific server in the config.

type WebhookProcessorSettings added in v0.0.6

type WebhookProcessorSettings struct {
	URL     string
	Headers map[string]string
}

WebhookProcessorSettings contains parsed runtime settings for a webhook processor.

func ParseWebhookProcessorSettings added in v0.0.6

func ParseWebhookProcessorSettings(processor *ProcessorConfig) (*WebhookProcessorSettings, error)

ParseWebhookProcessorSettings validates and extracts webhook processor settings.

Jump to

Keyboard shortcuts

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