Documentation
¶
Overview ¶
Package config provides configuration loading and parsing.
TOML Configuration Parsing ¶
This package uses BurntSushi/toml v1.6.0+ for robust TOML parsing with:
- TOML 1.1 specification support (default in v1.6.0+)
- Column-level error reporting (Position.Line, Position.Col)
- Duplicate key detection (improved in v1.6.0)
- Metadata tracking for unknown field detection
Design Patterns ¶
Streaming Decoder: Uses toml.NewDecoder() for memory efficiency with large configs Error Reporting: Extracts line/column from ParseError for precise error messages Unknown Fields: Uses MetaData.Undecoded() for typo warnings (not hard errors) Validation: Multi-layer approach (parse → schema → field-level → variable expansion)
TOML 1.1 Features Used ¶
- Multi-line inline arrays: newlines allowed in array definitions
- Improved duplicate detection: duplicate keys now properly reported as errors
- Large float encoding: proper round-trip with exponent syntax
This file defines the core configuration types that are stable and rarely change.
Package config provides configuration loading and parsing. This file defines the feature registration framework for modular config handling.
Package config provides configuration loading and parsing. This file defines operational defaults for payload and logging.
Package config provides configuration loading and parsing. This file defines stdin (JSON) configuration types.
Index ¶
- Constants
- Variables
- func ExpandRawJSONVariables(data []byte) ([]byte, error)
- func GetGatewayAPIKeyFromEnv() string
- func GetGatewayDomainFromEnv() string
- func GetGatewayPortFromEnv() (int, error)
- func RegisterDefaults(fn DefaultsSetter)
- func RegisterStdinConverter(fn StdinConverter)
- func SetDebug(enabled bool)
- func ValidateGuardPolicy(policy *GuardPolicy) error
- func ValidateWriteSinkPolicy(ws *WriteSinkPolicy) error
- type AllowOnlyPolicy
- type Config
- type DefaultsSetter
- type EnvValidationResult
- type FeatureConfig
- type GatewayConfig
- type GuardConfig
- type GuardPolicy
- type NormalizedGuardPolicy
- type ServerConfig
- type StdinConfig
- type StdinConverter
- type StdinGatewayConfig
- type StdinGuardConfig
- type StdinServerConfig
- type ValidationError
- type WriteSinkPolicy
Constants ¶
const ( DefaultPort = 3000 DefaultStartupTimeout = 60 // seconds DefaultToolTimeout = 120 // seconds )
Core constants for configuration defaults
const ( IntegrityNone = "none" IntegrityUnapproved = "unapproved" IntegrityApproved = "approved" IntegrityMerged = "merged" )
const DefaultLogDir = "/tmp/gh-aw/mcp-logs"
DefaultLogDir is the default directory for storing log files.
const DefaultPayloadDir = "/tmp/jq-payloads"
DefaultPayloadDir is the default directory for storing large payloads.
const DefaultPayloadSizeThreshold = 524288
DefaultPayloadSizeThreshold is the default size threshold (in bytes) for storing payloads to disk. Payloads larger than this threshold are stored to disk, smaller ones are returned inline. Default: 524288 bytes (512KB) - chosen to accommodate typical MCP tool responses including GitHub API queries (list_commits, list_issues, etc.) without triggering disk storage. This prevents agent looping issues when payloadPath is not accessible in agent containers.
Variables ¶
var RequiredEnvVars = []string{
"MCP_GATEWAY_PORT",
"MCP_GATEWAY_DOMAIN",
"MCP_GATEWAY_API_KEY",
}
RequiredEnvVars lists the environment variables that must be set for the gateway to operate
Functions ¶
func ExpandRawJSONVariables ¶
ExpandRawJSONVariables expands all ${VAR} expressions in JSON data before schema validation. This ensures the schema validates the expanded values, not the variable syntax. It collects all undefined variables and reports them in a single error.
func GetGatewayAPIKeyFromEnv ¶
func GetGatewayAPIKeyFromEnv() string
GetGatewayAPIKeyFromEnv returns the MCP_GATEWAY_API_KEY value
func GetGatewayDomainFromEnv ¶
func GetGatewayDomainFromEnv() string
GetGatewayDomainFromEnv returns the MCP_GATEWAY_DOMAIN value
func GetGatewayPortFromEnv ¶
GetGatewayPortFromEnv returns the MCP_GATEWAY_PORT value, parsed as int
func RegisterDefaults ¶
func RegisterDefaults(fn DefaultsSetter)
RegisterDefaults registers a function that sets defaults for a config feature. Called during init() in feature-specific config files.
func RegisterStdinConverter ¶
func RegisterStdinConverter(fn StdinConverter)
RegisterStdinConverter registers a function that converts stdin config for a feature. Called during init() in feature-specific config files.
func ValidateGuardPolicy ¶ added in v0.1.10
func ValidateGuardPolicy(policy *GuardPolicy) error
ValidateGuardPolicy validates AllowOnly or WriteSink policy input.
func ValidateWriteSinkPolicy ¶ added in v0.1.14
func ValidateWriteSinkPolicy(ws *WriteSinkPolicy) error
ValidateWriteSinkPolicy validates a write-sink policy.
Types ¶
type AllowOnlyPolicy ¶ added in v0.1.10
type AllowOnlyPolicy struct {
Repos interface{} `toml:"Repos" json:"repos"`
MinIntegrity string `toml:"MinIntegrity" json:"min-integrity"`
}
AllowOnlyPolicy configures scope and minimum required integrity.
func (AllowOnlyPolicy) MarshalJSON ¶ added in v0.1.10
func (p AllowOnlyPolicy) MarshalJSON() ([]byte, error)
func (*AllowOnlyPolicy) UnmarshalJSON ¶ added in v0.1.10
func (p *AllowOnlyPolicy) UnmarshalJSON(data []byte) error
type Config ¶
type Config struct {
// Servers maps server names to their configurations
Servers map[string]*ServerConfig `toml:"servers" json:"servers"`
// Guards maps guard names to their configurations
Guards map[string]*GuardConfig `toml:"guards" json:"guards,omitempty"`
// Gateway holds global gateway settings
Gateway *GatewayConfig `toml:"gateway" json:"gateway,omitempty"`
// DIFCMode specifies the guards enforcement mode: strict (default), filter, or propagate
// strict: deny access that violates guards rules
// filter: silently remove tools/resources that violate guards rules
// propagate: auto-adjust agent labels on reads to allow access
DIFCMode string `toml:"guards_mode" json:"guards_mode,omitempty"`
// SequentialLaunch launches servers sequentially instead of in parallel
SequentialLaunch bool `toml:"sequential_launch" json:"sequential_launch,omitempty"`
// GuardPolicy optionally overrides per-guard policy via CLI/environment precedence.
GuardPolicy *GuardPolicy `toml:"-" json:"-"`
// GuardPolicySource describes where GuardPolicy was resolved from (cli|env|config|legacy).
GuardPolicySource string `toml:"-" json:"-"`
}
Config represents the internal gateway configuration. Feature-specific fields are added in their respective config_*.go files.
func LoadFromFile ¶
LoadFromFile loads configuration from a TOML file.
This function uses the BurntSushi/toml v1.6.0+ parser with TOML 1.1 support, which enables modern syntax features like newlines in inline tables and improved duplicate key detection.
Error Handling:
- Parse errors include both line AND column numbers (v1.5.0+ feature)
- Unknown fields generate warnings instead of hard errors (typo detection)
- Metadata tracks all decoded keys for validation purposes
Example usage with TOML 1.1 multi-line arrays:
[servers.github]
command = "docker"
args = [
"run", "--rm", "-i",
"--name", "awmg-github-mcp"
]
func LoadFromStdin ¶
LoadFromStdin loads configuration from stdin JSON.
type DefaultsSetter ¶
type DefaultsSetter func(cfg *Config)
DefaultsSetter sets default values for a Config. Features register these to apply their defaults during loading.
type EnvValidationResult ¶
type EnvValidationResult struct {
IsContainerized bool
ContainerID string
DockerAccessible bool
MissingEnvVars []string
PortMapped bool
StdinInteractive bool
LogDirMounted bool
ValidationErrors []string
ValidationWarnings []string
}
EnvValidationResult holds the result of environment validation. It captures various aspects of the execution environment including containerization status, Docker accessibility, and validation errors/warnings.
This type implements the error interface through its Error() method, which returns a formatted error message containing all validation failures. Use IsValid() to check if all critical validations passed before attempting to start the gateway.
Fields:
- IsContainerized: Whether the gateway is running inside a Docker container
- ContainerID: The Docker container ID if containerized
- DockerAccessible: Whether the Docker daemon is accessible
- MissingEnvVars: List of required environment variables that are not set
- PortMapped: Whether the gateway port is mapped to the host (containerized mode)
- StdinInteractive: Whether stdin is interactive (containerized mode)
- LogDirMounted: Whether the log directory is mounted (containerized mode)
- ValidationErrors: Critical errors that prevent the gateway from starting
- ValidationWarnings: Non-critical issues that should be addressed
func ValidateContainerizedEnvironment ¶
func ValidateContainerizedEnvironment(containerID string) *EnvValidationResult
ValidateContainerizedEnvironment performs additional validation for containerized mode This is called by run_containerized.sh through the binary or by the Go code directly
func ValidateExecutionEnvironment ¶
func ValidateExecutionEnvironment() *EnvValidationResult
ValidateExecutionEnvironment performs comprehensive validation of the execution environment It checks Docker accessibility, required environment variables, and containerization status
func (*EnvValidationResult) Error ¶
func (r *EnvValidationResult) Error() string
Error returns a combined error message for all validation errors
func (*EnvValidationResult) IsValid ¶
func (r *EnvValidationResult) IsValid() bool
IsValid returns true if all critical validations passed
type FeatureConfig ¶
type FeatureConfig interface {
// FeatureName returns the name of the feature for logging
FeatureName() string
}
FeatureConfig represents a modular configuration feature. Each feature defines its own config processing in a separate file.
type GatewayConfig ¶
type GatewayConfig struct {
// Port is the HTTP port to listen on
Port int `toml:"port" json:"port,omitempty"`
// APIKey is the authentication key for the gateway
APIKey string `toml:"api_key" json:"api_key,omitempty"`
// Domain is the gateway domain for external access
Domain string `toml:"domain" json:"domain,omitempty"`
// StartupTimeout is the maximum time (seconds) to wait for server startup
StartupTimeout int `toml:"startup_timeout" json:"startup_timeout,omitempty"`
// ToolTimeout is the maximum time (seconds) to wait for tool execution
ToolTimeout int `toml:"tool_timeout" json:"tool_timeout,omitempty"`
// PayloadDir is the directory for storing large payloads
PayloadDir string `toml:"payload_dir" json:"payload_dir,omitempty"`
// PayloadPathPrefix is the path prefix to use when returning payloadPath to clients.
// This allows remapping the host filesystem path to a path accessible in the client/agent container.
// If empty, the actual filesystem path (PayloadDir) is returned.
// Example: If PayloadDir="/tmp/jq-payloads" and PayloadPathPrefix="/workspace/payloads",
// then payloadPath will be "/workspace/payloads/{sessionID}/{queryID}/payload.json"
PayloadPathPrefix string `toml:"payload_path_prefix" json:"payload_path_prefix,omitempty"`
// PayloadSizeThreshold is the size threshold (in bytes) for storing payloads to disk.
// Payloads larger than this threshold are stored to disk, smaller ones are returned inline.
// Default: 524288 bytes (512KB)
PayloadSizeThreshold int `toml:"payload_size_threshold" json:"payload_size_threshold,omitempty"`
}
GatewayConfig holds global gateway settings. Feature-specific fields are added in their respective config_*.go files.
type GuardConfig ¶ added in v0.1.10
type GuardConfig struct {
// Type is the guard type: "wasm", "noop", etc.
Type string `toml:"type" json:"type"`
// Path is the path to the guard implementation (e.g., WASM file)
Path string `toml:"path" json:"path,omitempty"`
// Config holds guard-specific configuration
Config map[string]interface{} `toml:"config" json:"config,omitempty"`
// Policy holds guard policy configuration for label_agent lifecycle initialization
Policy *GuardPolicy `toml:"policy" json:"policy,omitempty"`
}
GuardConfig represents a guard configuration for DIFC enforcement.
type GuardPolicy ¶ added in v0.1.10
type GuardPolicy struct {
AllowOnly *AllowOnlyPolicy `toml:"AllowOnly" json:"allow-only,omitempty"`
WriteSink *WriteSinkPolicy `toml:"WriteSink" json:"write-sink,omitempty"`
}
GuardPolicy represents the policy payload passed to guard label_agent.
func ParseGuardPolicyJSON ¶ added in v0.1.10
func ParseGuardPolicyJSON(policyJSON string) (*GuardPolicy, error)
ParseGuardPolicyJSON parses policy JSON and validates it.
func (*GuardPolicy) IsWriteSinkPolicy ¶ added in v0.1.14
func (p *GuardPolicy) IsWriteSinkPolicy() bool
IsWriteSinkPolicy returns true if this policy configures a write-sink guard.
func (GuardPolicy) MarshalJSON ¶ added in v0.1.10
func (p GuardPolicy) MarshalJSON() ([]byte, error)
func (*GuardPolicy) UnmarshalJSON ¶ added in v0.1.10
func (p *GuardPolicy) UnmarshalJSON(data []byte) error
type NormalizedGuardPolicy ¶ added in v0.1.10
type NormalizedGuardPolicy struct {
ScopeKind string `json:"scope_kind"`
ScopeValues []string `json:"scope_values,omitempty"`
MinIntegrity string `json:"min-integrity"`
}
NormalizedGuardPolicy is a canonical policy representation for caching and observability.
func NormalizeGuardPolicy ¶ added in v0.1.10
func NormalizeGuardPolicy(policy *GuardPolicy) (*NormalizedGuardPolicy, error)
NormalizeGuardPolicy validates and normalizes an allow-only policy shape.
type ServerConfig ¶
type ServerConfig struct {
// Type is the server type: "stdio" or "http"
Type string `toml:"type" json:"type,omitempty"`
// Command is the executable command (for stdio servers)
Command string `toml:"command" json:"command,omitempty"`
// Args are the command arguments (for stdio servers)
Args []string `toml:"args" json:"args,omitempty"`
// Env holds environment variables for the server
Env map[string]string `toml:"env" json:"env,omitempty"`
// WorkingDirectory is the working directory for the server
WorkingDirectory string `toml:"working_directory" json:"working_directory,omitempty"`
// URL is the HTTP endpoint (for http servers)
URL string `toml:"url" json:"url,omitempty"`
// Headers are HTTP headers to send (for http servers)
Headers map[string]string `toml:"headers" json:"headers,omitempty"`
// Tools is an optional list of tools to filter/expose
Tools []string `toml:"tools" json:"tools,omitempty"`
// Registry is the URI to the installation location in an MCP registry (informational)
Registry string `toml:"registry" json:"registry,omitempty"`
// GuardPolicies holds guard policies for access control at the MCP gateway level.
// The structure is server-specific. For GitHub MCP server, see the GitHub guard policy schema.
GuardPolicies map[string]interface{} `toml:"guard_policies" json:"guard-policies,omitempty"`
// Guard is the name of the guard to use for this server (requires DIFC)
Guard string `toml:"guard" json:"guard,omitempty"`
}
ServerConfig represents an individual MCP server configuration.
type StdinConfig ¶
type StdinConfig struct {
// MCPServers maps server names to their configurations
MCPServers map[string]*StdinServerConfig `json:"mcpServers"`
// Gateway holds global gateway settings
Gateway *StdinGatewayConfig `json:"gateway,omitempty"`
// Guards holds guard configurations for DIFC enforcement
Guards map[string]*StdinGuardConfig `json:"guards,omitempty"`
// CustomSchemas defines custom server types
CustomSchemas map[string]interface{} `json:"customSchemas,omitempty"`
}
StdinConfig represents the JSON configuration format read from stdin.
type StdinConverter ¶
type StdinConverter func(cfg *Config, stdinCfg *StdinConfig)
StdinConverter converts stdin-specific config to internal Config. Features register these to handle their stdin config fields.
type StdinGatewayConfig ¶
type StdinGatewayConfig struct {
Port *int `json:"port,omitempty"`
APIKey string `json:"apiKey,omitempty"`
Domain string `json:"domain,omitempty"`
StartupTimeout *int `json:"startupTimeout,omitempty"`
ToolTimeout *int `json:"toolTimeout,omitempty"`
PayloadDir string `json:"payloadDir,omitempty"`
}
StdinGatewayConfig represents gateway configuration in stdin JSON format. Uses pointers for optional fields to distinguish between unset and zero values.
type StdinGuardConfig ¶ added in v0.1.10
type StdinGuardConfig struct {
// Type is the guard type: "wasm", "noop", etc.
Type string `json:"type"`
// Path is the path to the guard implementation (e.g., WASM file)
Path string `json:"path,omitempty"`
// Config holds guard-specific configuration
Config map[string]interface{} `json:"config,omitempty"`
// Policy holds guard policy configuration for label_agent lifecycle initialization
Policy *GuardPolicy `json:"policy,omitempty"`
}
StdinGuardConfig represents a guard configuration in stdin JSON format.
type StdinServerConfig ¶
type StdinServerConfig struct {
// Type is the server type: "stdio", "local", or "http"
Type string `json:"type"`
// Container is the Docker image for stdio servers
Container string `json:"container,omitempty"`
// Entrypoint overrides the container entrypoint
Entrypoint string `json:"entrypoint,omitempty"`
// EntrypointArgs are additional arguments to the entrypoint
EntrypointArgs []string `json:"entrypointArgs,omitempty"`
// Args are additional Docker runtime arguments (passed before container image)
Args []string `json:"args,omitempty"`
// Mounts are volume mounts for the container
Mounts []string `json:"mounts,omitempty"`
// Env holds environment variables
Env map[string]string `json:"env,omitempty"`
// URL is the HTTP endpoint (for http servers)
URL string `json:"url,omitempty"`
// Headers are HTTP headers to send (for http servers)
Headers map[string]string `json:"headers,omitempty"`
// Tools is an optional list of tools to filter/expose
Tools []string `json:"tools,omitempty"`
// Registry is the URI to the installation location in an MCP registry (informational)
Registry string `json:"registry,omitempty"`
// GuardPolicies holds guard policies for access control at the MCP gateway level.
// The structure is server-specific. For GitHub MCP server, see the GitHub guard policy schema.
GuardPolicies map[string]interface{} `json:"guard-policies,omitempty"`
// Guard is the name of the guard to use for this server (requires DIFC)
Guard string `json:"guard,omitempty"`
// AdditionalProperties stores any extra fields for custom server types
// This allows custom schemas to define their own fields beyond the standard ones
AdditionalProperties map[string]interface{} `json:"-"`
}
StdinServerConfig represents a single server configuration in stdin JSON format.
func (*StdinServerConfig) UnmarshalJSON ¶ added in v0.1.6
func (s *StdinServerConfig) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling to capture additional properties
type ValidationError ¶
type ValidationError = rules.ValidationError
ValidationError is an alias for rules.ValidationError for backward compatibility
type WriteSinkPolicy ¶ added in v0.1.14
type WriteSinkPolicy struct {
Accept []string `toml:"Accept" json:"accept"`
}
WriteSinkPolicy configures a write-sink guard that accepts writes from agents carrying the listed secrecy labels.