engine

package module
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: May 28, 2025 License: MIT Imports: 13 Imported by: 0

README ΒΆ

πŸ”§ Agent Master Engine

Agent Master Engine is a Go library for managing Model Context Protocol (MCP) server configurations. It helps you keep MCP servers in sync across different tools.


πŸš€ What It Does

  • No tool-specific code: Works with any system; nothing is hardcoded
  • Multi-format support: Parse Claude Desktop, VS Code/GitHub, and flat MCP configurations
  • Multi-destination sync: Synchronize to multiple targets concurrently
  • Preview changes: See what will be modified before applying
  • Auto-sync: Watch for configuration changes and sync automatically
  • Custom validation: Define your own rules for server names and settings
  • Sync anywhere: Send configurations to any target by implementing the Destination interface
  • Choose your storage: Use files, in-memory, or Redis (more adapters can be added)
  • Track changes: Get notified when configurations change or sync operations occur
  • Variable substitution: Optional environment variable substitution
  • Import configurations: Import from various MCP format files

πŸ“¦ Installation

go get github.com/b-open-io/agent-master-engine

πŸ§ͺ Quick Start

package main

import (
    "context"
    "log"
    agent "github.com/b-open-io/agent-master-engine"
)

func main() {
    engine, err := agent.NewEngine(nil)
    if err != nil {
        log.Fatal(err)
    }

    server := agent.ServerConfig{
        Transport: "stdio",
        Command:   "npx",
        Args:      []string{"my-mcp-server"},
    }

    err = engine.AddServer("my-server", server)
    if err != nil {
        log.Fatal(err)
    }

    dest := agent.NewFileDestination("vscode", "~/.vscode/mcp.json", nil)
    engine.RegisterDestination("vscode", dest)

    // Preview changes before syncing
    preview, err := engine.PreviewSync(dest)
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Will make %d changes", len(preview.Changes))

    // Sync to single destination
    ctx := context.Background()
    result, err := engine.SyncTo(ctx, dest, agent.SyncOptions{})
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Sync completed: %d servers synced", result.ServersAdded)
}
Multi-Destination Sync
// Sync to multiple destinations at once
dest1 := agent.NewFileDestination("vscode", "~/.vscode/mcp.json", nil)
dest2 := agent.NewFileDestination("cursor", "~/.cursor/mcp.json", nil)
dest3 := agent.NewFileDestination("claude", "~/Library/Application Support/Claude/mcp.json", nil)

dests := []agent.Destination{dest1, dest2, dest3}
result, err := engine.SyncToMultiple(ctx, dests, agent.SyncOptions{})
if err != nil {
    log.Fatal(err)
}
log.Printf("Synced to %d/%d destinations successfully", result.SuccessCount, len(dests))
Import MCP Configurations
// Import from various MCP formats
data, err := os.ReadFile("github-mcp-config.json")
if err != nil {
    log.Fatal(err)
}

err = engine.Import(data, agent.ImportFormat("mcp"), agent.ImportOptions{
    OverwriteExisting: true,
    SubstituteEnvVars: true, // Replace ${ENV_VAR} with actual values
})
if err != nil {
    log.Fatal(err)
}
Auto-Sync
// Enable auto-sync to watch for changes
err = engine.StartAutoSync(agent.AutoSyncConfig{
    Enabled:       true,
    WatchInterval: 1 * time.Second,
    DebounceDelay: 500 * time.Millisecond,
    Destinations:  []string{"vscode", "cursor"},
})
if err != nil {
    log.Fatal(err)
}

// Stop auto-sync when done
defer engine.StopAutoSync()

🧠 Core Concepts

MCP Servers

MCP servers provide tools and resources to AI assistants. They support two communication transports:

  • stdio Transport: Communication via standard input/output streams
  • sse Transport: Server-Sent Events over HTTP for real-time updates
Destinations

Destinations are targets where server configurations are synchronized. The engine provides a Destination interface that can be implemented for any target system.

Validation

Customize server name and configuration validation by implementing the ServerValidator interface. This allows enforcement of specific rules and constraints.


πŸ“š Documentation


πŸ—οΈ Architecture Overview

The engine follows a clean architecture pattern with distinct layers:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     Engine      β”‚  ← Main interface
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Storage Layer  β”‚  ← File/Memory backends
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Sync Manager   β”‚  ← Handles synchronization
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Event System   β”‚  ← Configuration monitoring
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ”Œ Custom Integrations

Implementing a Custom Destination
type MyDestination struct {
    apiEndpoint string
}

func (d *MyDestination) GetID() string {
    return "my-destination"
}

func (d *MyDestination) GetDescription() string {
    return "Custom API destination"
}

func (d *MyDestination) Transform(config *agent.Config) (interface{}, error) {
    // Transform the configuration to your desired format
    return myFormat, nil
}

func (d *MyDestination) Write(data []byte) error {
    // Write the transformed data to your destination
    return nil
}

func (d *MyDestination) Read() ([]byte, error) {
    // Read existing configuration
    return existingData, nil
}

func (d *MyDestination) Exists() bool {
    return true
}

func (d *MyDestination) SupportsBackup() bool {
    return false
}

func (d *MyDestination) Backup() (string, error) {
    return "", nil
}

// Register the custom destination with the engine
engine.RegisterDestination("my-api", &MyDestination{
    apiEndpoint: "https://api.example.com",
})
Custom Storage Adapter
// Implement the Storage interface for any backend
type Storage interface {
    Read(key string) ([]byte, error)
    Write(key string, data []byte) error
    Delete(key string) error
    List(prefix string) ([]string, error)
    Watch(key string, handler func([]byte)) (func(), error)
}

// Example: Redis storage adapter
type RedisStorage struct {
    client *redis.Client
    prefix string
}

func (r *RedisStorage) Read(key string) ([]byte, error) {
    return r.client.Get(context.Background(), r.prefix+":"+key).Bytes()
}

func (r *RedisStorage) Write(key string, data []byte) error {
    return r.client.Set(context.Background(), r.prefix+":"+key, data, 0).Err()
}

// ... implement other methods

// Use custom storage with the engine
storage := &RedisStorage{client: redisClient, prefix: "agent-master"}
engine, err := agent.NewEngine(agent.WithStorage(storage))
Custom Validation
type MyValidator struct{}

func (v *MyValidator) ValidateName(name string) error {
    // Implement custom name validation logic
    if len(name) > 50 {
        return fmt.Errorf("name too long (max 50 characters)")
    }
    return nil
}

func (v *MyValidator) ValidateConfig(config agent.ServerConfig) error {
    // Implement custom configuration validation
    if config.Transport == "stdio" && config.Command == "" {
        return fmt.Errorf("stdio transport requires a command")
    }
    return nil
}

// Set the custom validator on the engine
engine.SetValidator(&MyValidator{})

πŸ§ͺ Testing

# Run unit tests
go test ./...

# Run tests with race detector
go test -race ./...

# Run benchmarks
go test -bench=. ./...

# Run with coverage
go test -cover ./...

🀝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • Built for managing Model Context Protocol servers
  • Inspired by the need for unified MCP server management across AI tools

πŸ“ž Support

  • πŸ“§ Create an issue for bug reports or feature requests
  • πŸ’¬ Join the discussion in our GitHub Discussions
  • πŸ“– Check out the examples directory for more usage patterns

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	DefaultWatchInterval  = 1000 // milliseconds
	DefaultDebounceDelay  = 500  // milliseconds
	DefaultMaxBackups     = 10
	DefaultMaxSyncWorkers = 5
	DefaultConfigVersion  = "1.0.2"
)

Default configuration values

View Source
const (
	ClaudeConfigFile = ".claude.json"
	MCPConfigFile    = ".mcp.json"
	BackupExtension  = ".backup"
)

File patterns

View Source
const (
	ErrServerNotFound    = "server not found"
	ErrTargetNotFound    = "target not found"
	ErrInvalidTransport  = "invalid transport type"
	ErrInvalidServerName = "invalid server name"
	ErrDuplicateServer   = "server already exists"
)

Error messages

View Source
const (
	ChangeTypeAdd    = "add"
	ChangeTypeUpdate = "update"
	ChangeTypeDelete = "remove"
)

Change type constants

Variables ΒΆ

View Source
var Keys = StorageKeys{}

Functions ΒΆ

func CopyKey ΒΆ

func CopyKey(storage Storage, srcKey, dstKey string) error

CopyKey copies data from one key to another

func ExportStorage ΒΆ

func ExportStorage(storage Storage, w io.Writer) error

ExportStorage exports all data to a writer

func FormatToolName ΒΆ

func FormatToolName(serverName, toolName string) string

FormatToolName formats a tool name according to Claude Code conventions MCP tools follow pattern: mcp__<serverName>__<toolName>

func HandleDuplicateName ΒΆ

func HandleDuplicateName(baseName string, existingNames map[string]bool, maxLength int) string

HandleDuplicateName generates unique name by appending number

func ImportStorage ΒΆ

func ImportStorage(storage Storage, r io.Reader) error

ImportStorage imports data from a reader

func LoadJSON ΒΆ

func LoadJSON(storage Storage, key string, v interface{}) error

LoadJSON loads and unmarshals JSON data

func ParseToolName ΒΆ

func ParseToolName(toolName string) (serverName, tool string, isMCP bool)

ParseToolName parses a Claude Code tool name

func SanitizeServerName ΒΆ

func SanitizeServerName(name string) string

SanitizeServerName sanitizes a server name

func SaveJSON ΒΆ

func SaveJSON(storage Storage, key string, v interface{}) error

SaveJSON marshals and saves JSON data

func ValidateServer ΒΆ

func ValidateServer(name string, config ServerConfig) error

ValidateServer validates a server configuration

Types ΒΆ

type AutoSyncConfig ΒΆ

type AutoSyncConfig struct {
	Enabled         bool          `json:"enabled"`
	WatchInterval   time.Duration `json:"watchInterval"`
	DebounceDelay   time.Duration `json:"debounceDelay"`
	TargetWhitelist []string      `json:"targetWhitelist,omitempty"`
	TargetBlacklist []string      `json:"targetBlacklist,omitempty"`
	IgnorePatterns  []string      `json:"ignorePatterns"`
}

AutoSyncConfig configures automatic synchronization

type AutoSyncSettings ΒΆ

type AutoSyncSettings struct {
	Enabled       bool          `json:"enabled"`
	WatchInterval time.Duration `json:"watchInterval,omitempty"`
	DebounceDelay time.Duration `json:"debounceDelay,omitempty"`
	Destinations  []string      `json:"destinations,omitempty"`
}

AutoSyncSettings controls automatic synchronization

type AutoSyncStatus ΒΆ

type AutoSyncStatus struct {
	Enabled       bool          `json:"enabled"`
	Running       bool          `json:"running"`
	LastSync      time.Time     `json:"lastSync,omitempty"`
	NextSync      time.Time     `json:"nextSync,omitempty"`
	WatchInterval time.Duration `json:"watchInterval"`
}

AutoSyncStatus represents auto-sync state

type BackupEvent ΒΆ added in v0.1.3

type BackupEvent struct {
	BackupInfo BackupInfo
}

type BackupInfo ΒΆ

type BackupInfo struct {
	ID          string    `json:"id"`
	Path        string    `json:"path"`
	Timestamp   time.Time `json:"timestamp"`
	Size        int64     `json:"size"`
	Type        string    `json:"type"` // "manual", "auto", "pre-sync"
	Description string    `json:"description,omitempty"`
}

BackupInfo contains backup details

type BackupSettings ΒΆ

type BackupSettings struct {
	Enabled     bool   `json:"enabled"`
	MaxBackups  int    `json:"maxBackups,omitempty"`
	BackupPath  string `json:"backupPath,omitempty"`
	Location    string `json:"location,omitempty"` // Alternative to BackupPath
	BeforeSync  bool   `json:"beforeSync,omitempty"`
	Compression bool   `json:"compression,omitempty"`
}

BackupSettings controls backup behavior

type Change ΒΆ

type Change struct {
	Type        string      `json:"type"` // "add", "update", "remove"
	Server      string      `json:"server"`
	Description string      `json:"description,omitempty"`
	Before      interface{} `json:"before,omitempty"`
	After       interface{} `json:"after,omitempty"`
}

Change represents a configuration change

type ClaudeCodeAdapter ΒΆ

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

ClaudeCodeAdapter provides integration with Claude Code

func NewClaudeCodeAdapter ΒΆ

func NewClaudeCodeAdapter() (*ClaudeCodeAdapter, error)

NewClaudeCodeAdapter creates a new Claude Code adapter

func (*ClaudeCodeAdapter) GetAllowedTools ΒΆ

func (c *ClaudeCodeAdapter) GetAllowedTools(projectPath string) ([]string, error)

GetAllowedTools extracts allowed tools from Claude Code configuration

func (*ClaudeCodeAdapter) ReadClaudeCodeConfig ΒΆ

func (c *ClaudeCodeAdapter) ReadClaudeCodeConfig() (*ClaudeCodeConfig, error)

ReadClaudeCodeConfig reads the Claude Code configuration

func (*ClaudeCodeAdapter) TestMCPServer ΒΆ

func (c *ClaudeCodeAdapter) TestMCPServer(name string, config ServerConfig) error

TestMCPServer tests if an MCP server starts correctly

func (*ClaudeCodeAdapter) ValidateServerConfig ΒΆ

func (c *ClaudeCodeAdapter) ValidateServerConfig(name string, config ServerConfig) error

ValidateServerConfig validates a server config using Claude Code SDK

func (*ClaudeCodeAdapter) WriteClaudeCodeConfig ΒΆ

func (c *ClaudeCodeAdapter) WriteClaudeCodeConfig(config *ClaudeCodeConfig) error

WriteClaudeCodeConfig writes the Claude Code configuration

type ClaudeCodeConfig ΒΆ

type ClaudeCodeConfig struct {
	MCPServers map[string]ServerConfig    `json:"mcpServers"`
	Projects   map[string]ProjectSettings `json:"projects"`
	Theme      string                     `json:"theme,omitempty"`
}

ClaudeCodeConfig represents the full Claude Code configuration

type Config ΒΆ

type Config struct {
	Version  string                        `json:"version"`
	Servers  map[string]ServerWithMetadata `json:"servers"`
	Settings Settings                      `json:"settings,omitempty"`
	Targets  map[string]TargetConfig       `json:"targets,omitempty"` // Legacy field
	Metadata map[string]interface{}        `json:"metadata,omitempty"`
}

Config represents the MCP configuration Renamed from MasterConfig for clarity and brevity

func ParseMCPConfig ΒΆ added in v0.1.2

func ParseMCPConfig(data []byte) (*Config, error)

ParseMCPConfig attempts to parse various MCP configuration formats

func ParseMCPConfigWithOptions ΒΆ added in v0.1.2

func ParseMCPConfigWithOptions(data []byte, substituteEnvVars bool) (*Config, error)

ParseMCPConfigWithOptions parses MCP config with options

type ConfigChange ΒΆ

type ConfigChange struct {
	Type      string                 `json:"type"` // "server-added", "server-removed", "server-updated", "settings-changed"
	Name      string                 `json:"name,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
	Source    string                 `json:"source"` // "user", "sync", "import", "auto-sync"
	Details   map[string]interface{} `json:"details,omitempty"`
}

ConfigChange represents a configuration change event

type ConfigChangeEvent ΒΆ added in v0.1.3

type ConfigChangeEvent struct {
	Config     *Config
	OldConfig  *Config
	ChangeType string
}

Event data types

type ConfigChangeHandler ΒΆ

type ConfigChangeHandler func(change ConfigChange)

Event handler types

type ConfigTransformer ΒΆ

type ConfigTransformer interface {
	Transform(config *Config) (interface{}, error)
	Format() string
}

ConfigTransformer transforms configuration for specific formats

type ConflictSettings ΒΆ

type ConflictSettings struct {
	Mode string `json:"mode"` // "interactive", "master-wins", "target-wins"
}

ConflictSettings controls conflict resolution behavior

type DefaultProjectDetector ΒΆ added in v0.1.7

type DefaultProjectDetector struct {
	// ConfigFiles are the files that indicate a project root
	ConfigFiles []string
}

DefaultProjectDetector provides a basic implementation of ProjectDetector

func NewDefaultProjectDetector ΒΆ added in v0.1.7

func NewDefaultProjectDetector() *DefaultProjectDetector

NewDefaultProjectDetector creates a new default project detector

func (*DefaultProjectDetector) DetectProject ΒΆ added in v0.1.7

func (d *DefaultProjectDetector) DetectProject(path string) (*ProjectConfig, error)

DetectProject detects and creates a project configuration for the given path

func (*DefaultProjectDetector) IsProjectRoot ΒΆ added in v0.1.7

func (d *DefaultProjectDetector) IsProjectRoot(path string) bool

IsProjectRoot checks if the given path is a project root

type DefaultValidator ΒΆ

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

DefaultValidator provides basic MCP validation rules

func NewDefaultValidator ΒΆ

func NewDefaultValidator() *DefaultValidator

NewDefaultValidator creates a validator with standard MCP rules

func (*DefaultValidator) ValidateConfig ΒΆ

func (v *DefaultValidator) ValidateConfig(config ServerConfig) error

ValidateConfig validates a server configuration

func (*DefaultValidator) ValidateName ΒΆ

func (v *DefaultValidator) ValidateName(name string) error

ValidateName validates a server name

type Destination ΒΆ

type Destination interface {
	// Identity
	GetID() string
	GetDescription() string

	// Configuration transformation
	Transform(config *Config) (interface{}, error)

	// IO operations
	Read() ([]byte, error)
	Write(data []byte) error
	Exists() bool

	// Optional features
	SupportsBackup() bool
	Backup() (string, error)
}

Destination represents any sync target (file, API, etc.)

type DirectTransformer ΒΆ

type DirectTransformer struct{}

DirectTransformer returns config as-is

func (*DirectTransformer) Format ΒΆ

func (d *DirectTransformer) Format() string

func (*DirectTransformer) Transform ΒΆ

func (d *DirectTransformer) Transform(config *Config) (interface{}, error)

type Engine ΒΆ

type Engine interface {
	// Configuration Management
	LoadConfig(path string) error
	SaveConfig() error
	GetConfig() (*Config, error)
	SetConfig(config *Config) error

	// Server Management
	AddServer(name string, server ServerConfig) error
	UpdateServer(name string, server ServerConfig) error
	RemoveServer(name string) error
	GetServer(name string) (*ServerWithMetadata, error)
	ListServers(filter ServerFilter) ([]*ServerInfo, error)
	EnableServer(name string) error
	DisableServer(name string) error

	// Destination Management
	RegisterDestination(name string, dest Destination) error
	RemoveDestination(name string) error
	GetDestination(name string) (Destination, error)
	ListDestinations() map[string]Destination

	// Generic Sync Operations
	SyncTo(ctx context.Context, dest Destination, options SyncOptions) (*SyncResult, error)
	SyncToMultiple(ctx context.Context, dests []Destination, options SyncOptions) (*MultiSyncResult, error)
	PreviewSync(dest Destination) (*SyncPreview, error)

	// Import/Export (format agnostic)
	Export(format ExportFormat) ([]byte, error)
	Import(data []byte, format ImportFormat, options ImportOptions) error
	MergeConfigs(configs ...*Config) (*Config, error)

	// Validation (pluggable)
	SetValidator(validator ServerValidator)
	SetSanitizer(sanitizer NameSanitizer)
	ValidateServer(name string, server ServerConfig) error
	SanitizeName(name string) string

	// Project Management
	ScanForProjects(paths []string, detector ProjectDetector) ([]*ProjectConfig, error)
	RegisterProject(path string, config ProjectConfig) error
	GetProjectConfig(path string) (*ProjectConfig, error)
	ListProjects() ([]*ProjectInfo, error)

	// Auto-sync Management
	StartAutoSync(config AutoSyncConfig) error
	StopAutoSync() error
	GetAutoSyncStatus() (*AutoSyncStatus, error)

	// Backup/Restore
	CreateBackup(description string) (*BackupInfo, error)
	ListBackups() ([]*BackupInfo, error)
	RestoreBackup(backupID string) error

	// Event Handling
	OnConfigChange(handler ConfigChangeHandler) func()
	OnSyncComplete(handler SyncCompleteHandler) func()
	OnError(handler ErrorHandler) func()
}

Engine is a generic MCP server configuration manager

func NewEngine ΒΆ

func NewEngine(opts ...Option) (Engine, error)

NewEngine creates a new engine instance

type ErrorEvent ΒΆ added in v0.1.3

type ErrorEvent struct {
	Error   error
	Context string
}

type ErrorHandler ΒΆ

type ErrorHandler func(err error)

type EventType ΒΆ

type EventType string

EventType represents different event types in the system

const (
	// Configuration Events
	EventConfigLoaded  EventType = "config.loaded"
	EventConfigSaved   EventType = "config.saved"
	EventServerAdded   EventType = "server.added"
	EventServerUpdated EventType = "server.updated"
	EventServerRemoved EventType = "server.removed"

	// Sync Events
	EventSyncStarted      EventType = "sync.started"
	EventSyncCompleted    EventType = "sync.completed"
	EventSyncFailed       EventType = "sync.failed"
	EventConflictDetected EventType = "sync.conflict"

	// Auto-Sync Events
	EventAutoSyncStarted EventType = "autosync.started"
	EventAutoSyncStopped EventType = "autosync.stopped"
	EventFileChanged     EventType = "autosync.file.changed"

	// Project Events
	EventProjectDiscovered EventType = "project.discovered"
	EventProjectRegistered EventType = "project.registered"
	EventProjectRemoved    EventType = "project.removed"

	// Error Events
	EventError   EventType = "error"
	EventWarning EventType = "warning"

	// Additional Events
	EventConfigChanged  EventType = "config.changed"
	EventBackupCreated  EventType = "backup.created"
	EventBackupRestored EventType = "backup.restored"
)

Event type constants

type ExportFormat ΒΆ

type ExportFormat string

ExportFormat represents supported export formats

const (
	ExportFormatJSON ExportFormat = "json"
	ExportFormatYAML ExportFormat = "yaml"
	ExportFormatTOML ExportFormat = "toml"
)

type FileChange ΒΆ

type FileChange struct {
	Path      string    `json:"path"`
	Type      string    `json:"type"` // "create", "modify", "delete"
	Timestamp time.Time `json:"timestamp"`
}

FileChange represents a file system change

type FileDestination ΒΆ

type FileDestination struct {
	ID          string
	Path        string
	Format      ExportFormat
	Transformer ConfigTransformer
}

FileDestination is a generic file-based destination

func NewFileDestination ΒΆ

func NewFileDestination(id, path string, format ExportFormat) *FileDestination

NewFileDestination creates a new file destination

func (*FileDestination) Backup ΒΆ

func (f *FileDestination) Backup() (string, error)

Backup creates a backup of the current file

func (*FileDestination) Exists ΒΆ

func (f *FileDestination) Exists() bool

Exists checks if the destination exists

func (*FileDestination) GetDescription ΒΆ

func (f *FileDestination) GetDescription() string

GetDescription returns a human-readable description

func (*FileDestination) GetID ΒΆ

func (f *FileDestination) GetID() string

GetID returns the destination identifier

func (*FileDestination) Read ΒΆ

func (f *FileDestination) Read() ([]byte, error)

Read reads the current configuration

func (*FileDestination) SupportsBackup ΒΆ

func (f *FileDestination) SupportsBackup() bool

SupportsBackup returns true

func (*FileDestination) Transform ΒΆ

func (f *FileDestination) Transform(config *Config) (interface{}, error)

Transform converts the config to the appropriate format

func (*FileDestination) Write ΒΆ

func (f *FileDestination) Write(data []byte) error

Write writes the configuration

type FileStorage ΒΆ

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

FileStorage implements Storage interface using filesystem

func NewFileStorage ΒΆ

func NewFileStorage(basePath string) (*FileStorage, error)

NewFileStorage creates a new file-based storage

func (*FileStorage) Delete ΒΆ

func (fs *FileStorage) Delete(key string) error

Delete removes data from storage

func (*FileStorage) GetBasePath ΒΆ

func (fs *FileStorage) GetBasePath() string

GetBasePath returns the base path of the file storage

func (*FileStorage) List ΒΆ

func (fs *FileStorage) List(prefix string) ([]string, error)

List lists keys with given prefix

func (*FileStorage) Read ΒΆ

func (fs *FileStorage) Read(key string) ([]byte, error)

Read reads data from storage

func (*FileStorage) Watch ΒΆ

func (fs *FileStorage) Watch(key string, handler func([]byte)) (func(), error)

Watch watches for changes to a key

func (*FileStorage) Write ΒΆ

func (fs *FileStorage) Write(key string, data []byte) error

Write writes data to storage

type FlatTransformer ΒΆ

type FlatTransformer struct {
	WrapperKey string // e.g., "mcpServers"
}

FlatTransformer creates a flat structure

func (*FlatTransformer) Format ΒΆ

func (f *FlatTransformer) Format() string

func (*FlatTransformer) Transform ΒΆ

func (f *FlatTransformer) Transform(config *Config) (interface{}, error)

type ImportFormat ΒΆ

type ImportFormat string

ImportFormat represents supported import formats

const (
	ImportFormatJSON ImportFormat = "json"
	ImportFormatYAML ImportFormat = "yaml"
	ImportFormatTOML ImportFormat = "toml"
)

type ImportOptions ΒΆ

type ImportOptions struct {
	Overwrite         bool     `json:"overwrite"`
	OverwriteExisting bool     `json:"overwriteExisting"` // Alias for Overwrite
	MergeStrategy     string   `json:"mergeStrategy"`     // "replace", "merge", "skip"
	MergeMode         string   `json:"mergeMode"`         // Alias for MergeStrategy
	ServerWhitelist   []string `json:"serverWhitelist,omitempty"`
	ServerBlacklist   []string `json:"serverBlacklist,omitempty"`
	ImportMetadata    bool     `json:"importMetadata"`
	SkipInvalid       bool     `json:"skipInvalid"`
	SubstituteEnvVars bool     `json:"substituteEnvVars"` // Whether to replace ${ENV_VAR} patterns
}

ImportOptions controls import behavior

type ImportResult ΒΆ

type ImportResult struct {
	Source          string   `json:"source"`
	ServersImported int      `json:"serversImported"`
	ServersSkipped  int      `json:"serversSkipped"`
	ServersUpdated  int      `json:"serversUpdated"`
	Errors          []string `json:"errors,omitempty"`
}

ImportResult contains the outcome of an import operation

type InternalMetadata ΒΆ

type InternalMetadata struct {
	Enabled            bool      `json:"enabled,omitempty"`
	LastSynced         time.Time `json:"lastSynced,omitempty"`
	LastModified       time.Time `json:"lastModified,omitempty"`
	Source             string    `json:"source,omitempty"`
	CreatedBy          string    `json:"createdBy,omitempty"`
	Version            string    `json:"version,omitempty"`
	SyncTargets        []string  `json:"syncTargets,omitempty"`
	ExcludeFromTargets []string  `json:"excludeFromTargets,omitempty"`
	Tags               []string  `json:"tags,omitempty"`
	ProjectPath        string    `json:"projectPath,omitempty"`
	ProjectSpecific    bool      `json:"projectSpecific,omitempty"`
	ErrorCount         int       `json:"errorCount,omitempty"`
}

InternalMetadata contains engine-specific metadata

type LogLevel ΒΆ

type LogLevel int

LogLevel represents logging levels

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

type MCPConfig ΒΆ added in v0.1.2

type MCPConfig struct {
	MCP *MCPWrapper `json:"mcp,omitempty"`
	// Also support direct mcpServers for Claude/Cursor format
	MCPServers map[string]ServerConfig `json:"mcpServers,omitempty"`
	// And direct servers for simpler formats
	Servers map[string]ServerConfig `json:"servers,omitempty"`
}

MCPConfig represents the newer MCP configuration format with inputs support

func (*MCPConfig) ToConfig ΒΆ added in v0.1.2

func (m *MCPConfig) ToConfig() (*Config, error)

ToConfig converts MCPConfig to the standard Config format (with env var substitution)

func (*MCPConfig) ToConfigWithOptions ΒΆ added in v0.1.2

func (m *MCPConfig) ToConfigWithOptions(substituteEnvVars bool) (*Config, error)

ToConfigWithOptions converts MCPConfig with options

type MCPInput ΒΆ added in v0.1.2

type MCPInput struct {
	Type        string `json:"type"`               // "promptString", "promptNumber", etc.
	ID          string `json:"id"`                 // Variable identifier
	Description string `json:"description"`        // Human-readable description
	Default     string `json:"default,omitempty"`  // Default value
	Password    bool   `json:"password,omitempty"` // Hide input (for secrets)
	Required    bool   `json:"required,omitempty"` // Is this input required?
}

MCPInput defines an input variable for MCP configurations

type MCPVersion ΒΆ added in v0.1.2

type MCPVersion string

MCPVersion represents different MCP protocol versions

const (
	MCPVersion20241105 MCPVersion = "2024-11-05"
	MCPVersion20250326 MCPVersion = "2025-03-26"
	MCPVersionDraft    MCPVersion = "draft"
)

type MCPWrapper ΒΆ added in v0.1.2

type MCPWrapper struct {
	Inputs  []MCPInput              `json:"inputs,omitempty"`
	Servers map[string]ServerConfig `json:"servers"`
}

MCPWrapper contains the MCP-specific configuration

type MemoryStorage ΒΆ

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

MemoryStorage implements Storage interface in memory

func NewMemoryStorage ΒΆ

func NewMemoryStorage() *MemoryStorage

NewMemoryStorage creates a new memory-based storage

func (*MemoryStorage) Delete ΒΆ

func (ms *MemoryStorage) Delete(key string) error

Delete removes data from memory

func (*MemoryStorage) List ΒΆ

func (ms *MemoryStorage) List(prefix string) ([]string, error)

List lists keys with given prefix

func (*MemoryStorage) Read ΒΆ

func (ms *MemoryStorage) Read(key string) ([]byte, error)

Read reads data from memory

func (*MemoryStorage) Watch ΒΆ

func (ms *MemoryStorage) Watch(key string, handler func([]byte)) (func(), error)

Watch watches for changes to a key

func (*MemoryStorage) Write ΒΆ

func (ms *MemoryStorage) Write(key string, data []byte) error

Write writes data to memory

type MultiSyncResult ΒΆ

type MultiSyncResult struct {
	Results       []SyncResult  `json:"results"`
	TotalDuration time.Duration `json:"totalDuration"`
	SuccessCount  int           `json:"successCount"`
	FailureCount  int           `json:"failureCount"`
}

MultiSyncResult aggregates multiple sync results

type NameSanitizer ΒΆ

type NameSanitizer interface {
	Sanitize(name string) string
	NeedsSanitization(name string) bool
}

NameSanitizer can sanitize server names

type NestedTransformer ΒΆ

type NestedTransformer struct {
	RootKey    string // e.g., "mcp"
	ServersKey string // e.g., "servers"
}

NestedTransformer creates a nested structure

func (*NestedTransformer) Format ΒΆ

func (n *NestedTransformer) Format() string

func (*NestedTransformer) Transform ΒΆ

func (n *NestedTransformer) Transform(config *Config) (interface{}, error)

type NoOpSanitizer ΒΆ

type NoOpSanitizer struct{}

NoOpSanitizer doesn't modify names

func (*NoOpSanitizer) NeedsSanitization ΒΆ

func (n *NoOpSanitizer) NeedsSanitization(name string) bool

NeedsSanitization always returns false

func (*NoOpSanitizer) Sanitize ΒΆ

func (n *NoOpSanitizer) Sanitize(name string) string

Sanitize returns the name unchanged

type Option ΒΆ

type Option func(*engineConfig) error

Option configuration

func WithDefaultTargets ΒΆ

func WithDefaultTargets() Option

func WithFileStorage ΒΆ

func WithFileStorage(path string) Option

func WithMemoryStorage ΒΆ added in v0.1.2

func WithMemoryStorage() Option

func WithStorage ΒΆ

func WithStorage(storage Storage) Option

type PatternValidator ΒΆ

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

PatternValidator validates names against a regex pattern

func NewPatternValidator ΒΆ

func NewPatternValidator(pattern string, maxLength int) (*PatternValidator, error)

NewPatternValidator creates a validator with a custom pattern

func (*PatternValidator) ValidateConfig ΒΆ

func (p *PatternValidator) ValidateConfig(config ServerConfig) error

ValidateConfig delegates to default validator

func (*PatternValidator) ValidateName ΒΆ

func (p *PatternValidator) ValidateName(name string) error

ValidateName validates against the pattern

type ProjectConfig ΒΆ

type ProjectConfig struct {
	Name         string                        `json:"name"`
	Path         string                        `json:"path"`
	Servers      map[string]ServerWithMetadata `json:"servers,omitempty"`
	Destinations []string                      `json:"destinations,omitempty"`
	AutoSync     bool                          `json:"autoSync,omitempty"`
	Metadata     map[string]interface{}        `json:"metadata,omitempty"`
}

ProjectConfig represents project-specific configuration

type ProjectDetector ΒΆ

type ProjectDetector interface {
	DetectProject(path string) (*ProjectConfig, error)
	IsProjectRoot(path string) bool
}

ProjectDetector can detect project configurations

type ProjectInfo ΒΆ

type ProjectInfo struct {
	Name        string   `json:"name"`
	Path        string   `json:"path"`
	ServerCount int      `json:"serverCount"`
	Servers     []string `json:"servers,omitempty"`
}

ProjectInfo contains project information

type ProjectScanSettings ΒΆ

type ProjectScanSettings struct {
	Enabled      bool     `json:"enabled"`
	ScanPaths    []string `json:"scanPaths,omitempty"`
	ExcludePaths []string `json:"excludePaths,omitempty"`
	MaxDepth     int      `json:"maxDepth,omitempty"`
}

ProjectScanSettings controls project scanning behavior

type ProjectSettings ΒΆ

type ProjectSettings struct {
	MCPServers                 map[string]ServerConfig `json:"mcpServers,omitempty"`
	AllowedTools               []string                `json:"allowedTools,omitempty"`
	DisabledMCPJSONServers     []string                `json:"disabledMcpjsonServers,omitempty"`
	EnabledMCPJSONServers      []string                `json:"enabledMcpjsonServers,omitempty"`
	EnableAllProjectMCPServers bool                    `json:"enableAllProjectMcpServers,omitempty"`
	DontCrawlDirectory         bool                    `json:"dontCrawlDirectory,omitempty"`
}

ProjectSettings represents Claude Code project-specific settings

type ReplacementSanitizer ΒΆ

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

ReplacementSanitizer sanitizes names by replacing characters

func NewReplacementSanitizer ΒΆ

func NewReplacementSanitizer(replacements map[string]string, removeChars string, maxLength int) *ReplacementSanitizer

NewReplacementSanitizer creates a sanitizer with custom replacements

func (*ReplacementSanitizer) NeedsSanitization ΒΆ

func (r *ReplacementSanitizer) NeedsSanitization(name string) bool

NeedsSanitization checks if sanitization would change the name

func (*ReplacementSanitizer) Sanitize ΒΆ

func (r *ReplacementSanitizer) Sanitize(name string) string

Sanitize applies replacements and removals

type ServerChangeEvent ΒΆ added in v0.1.3

type ServerChangeEvent struct {
	ServerName string
	Server     ServerWithMetadata
	ChangeType string
}

type ServerConfig ΒΆ

type ServerConfig struct {
	Transport string                 `json:"transport"` // "stdio" or "sse"
	Command   string                 `json:"command,omitempty"`
	Args      []string               `json:"args,omitempty"`
	Env       map[string]string      `json:"env,omitempty"`
	URL       string                 `json:"url,omitempty"`
	Headers   map[string]string      `json:"headers,omitempty"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

ServerConfig represents a basic server configuration

func SubstituteVariables ΒΆ added in v0.1.2

func SubstituteVariables(config ServerConfig, inputs map[string]string, env map[string]string) ServerConfig

SubstituteVariables replaces ${input:xxx} and ${ENV_VAR} in server configs

type ServerFilter ΒΆ

type ServerFilter struct {
	Enabled         *bool    `json:"enabled,omitempty"`
	Transport       string   `json:"transport,omitempty"`
	SyncTargets     []string `json:"syncTargets,omitempty"`
	ProjectSpecific *bool    `json:"projectSpecific,omitempty"`
	Source          string   `json:"source,omitempty"`
	NamePattern     string   `json:"namePattern,omitempty"`
}

ServerFilter for listing servers

type ServerInfo ΒΆ

type ServerInfo struct {
	Name            string                 `json:"name"`
	Config          ServerConfig           `json:"config"`
	Transport       string                 `json:"transport,omitempty"`
	Enabled         bool                   `json:"enabled"`
	Internal        InternalMetadata       `json:"internal,omitempty"`
	Metadata        map[string]interface{} `json:"metadata,omitempty"`
	SyncTargetCount int                    `json:"syncTargetCount,omitempty"`
	LastModified    time.Time              `json:"lastModified,omitempty"`
	HasErrors       bool                   `json:"hasErrors,omitempty"`
}

ServerInfo contains detailed server information

type ServerValidator ΒΆ

type ServerValidator interface {
	ValidateName(name string) error
	ValidateConfig(config ServerConfig) error
	ValidateServerConfig(name string, config ServerConfig) error
}

ServerValidator can validate server configurations

type ServerWithMetadata ΒΆ

type ServerWithMetadata struct {
	ServerConfig
	Internal InternalMetadata `json:"internal,omitempty"`
}

ServerWithMetadata includes internal metadata

type Settings ΒΆ

type Settings struct {
	AutoSync           AutoSyncSettings         `json:"autoSync,omitempty"`
	Backup             BackupSettings           `json:"backup,omitempty"`
	Sync               SyncSettings             `json:"sync,omitempty"`
	ConflictResolution ConflictSettings         `json:"conflictResolution,omitempty"`
	ProjectScanning    ProjectScanSettings      `json:"projectScanning,omitempty"`
	Validation         ValidationSettings       `json:"validation,omitempty"`
	DefaultTransport   string                   `json:"defaultTransport,omitempty"`
	Projects           map[string]ProjectConfig `json:"projects,omitempty"`
}

Settings contains global configuration settings Renamed from GlobalSettings for brevity

type Storage ΒΆ

type Storage interface {
	Read(key string) ([]byte, error)
	Write(key string, data []byte) error
	Delete(key string) error
	List(prefix string) ([]string, error)
	Watch(key string, handler func([]byte)) (func(), error)
}

Storage interface for persistence layer abstraction

type StorageKeys ΒΆ

type StorageKeys struct{}

StorageKeys defines standard storage keys

func (StorageKeys) AutoSyncState ΒΆ

func (StorageKeys) AutoSyncState() string

func (StorageKeys) Backup ΒΆ

func (StorageKeys) Backup(id string) string

func (StorageKeys) BackupList ΒΆ

func (StorageKeys) BackupList() string

func (StorageKeys) Config ΒΆ

func (StorageKeys) Config() string

func (StorageKeys) LastSync ΒΆ

func (StorageKeys) LastSync(target string) string

func (StorageKeys) Project ΒΆ

func (StorageKeys) Project(path string) string

func (StorageKeys) ProjectCache ΒΆ

func (StorageKeys) ProjectCache(path string) string

func (StorageKeys) ServerCache ΒΆ

func (StorageKeys) ServerCache() string

func (StorageKeys) Target ΒΆ

func (StorageKeys) Target(name string) string

type SyncCompleteHandler ΒΆ

type SyncCompleteHandler func(result SyncResult)

type SyncError ΒΆ

type SyncError struct {
	Error       string `json:"error"`
	Recoverable bool   `json:"recoverable"`
}

SyncError represents an error during sync

type SyncEvent ΒΆ added in v0.1.3

type SyncEvent struct {
	Result SyncResult
}

type SyncManager ΒΆ

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

SyncManager handles synchronization operations

func NewSyncManager ΒΆ

func NewSyncManager(engine *engineImpl) *SyncManager

NewSyncManager creates a new sync manager

func (*SyncManager) PreviewSync ΒΆ

func (sm *SyncManager) PreviewSync(targetName string) (*SyncPreview, error)

PreviewSync previews what changes would be made

func (*SyncManager) SyncToAllTargets ΒΆ

func (sm *SyncManager) SyncToAllTargets(ctx context.Context, options SyncOptions) (*MultiSyncResult, error)

SyncToAllTargets synchronizes to all enabled targets

func (*SyncManager) SyncToTarget ΒΆ

func (sm *SyncManager) SyncToTarget(ctx context.Context, targetName string, options SyncOptions) (*SyncResult, error)

SyncToTarget synchronizes configuration to a specific target

type SyncOptions ΒΆ

type SyncOptions struct {
	DryRun            bool              `json:"dryRun,omitempty"`
	Force             bool              `json:"force,omitempty"`
	CreateBackup      bool              `json:"createBackup,omitempty"`
	BackupFirst       bool              `json:"backupFirst,omitempty"` // Alias for CreateBackup
	IncludeDisabled   bool              `json:"includeDisabled,omitempty"`
	ServerFilter      []string          `json:"serverFilter,omitempty"`
	DestinationConfig map[string]string `json:"destinationConfig,omitempty"`
	Verbose           bool              `json:"verbose,omitempty"`
}

SyncOptions controls a synchronization operation

type SyncPreview ΒΆ

type SyncPreview struct {
	Destination    string        `json:"destination"`
	Changes        []Change      `json:"changes"`
	EstimatedTime  time.Duration `json:"estimatedTime"`
	RequiresBackup bool          `json:"requiresBackup"`
	HasConflicts   bool          `json:"hasConflicts"`
}

SyncPreview shows what will happen in a sync

type SyncResult ΒΆ

type SyncResult struct {
	Target         string        `json:"target,omitempty"` // Legacy field for compatibility
	Destination    string        `json:"destination"`
	Success        bool          `json:"success"`
	ServersAdded   int           `json:"serversAdded"`
	ServersUpdated int           `json:"serversUpdated"`
	ServersRemoved int           `json:"serversRemoved"`
	Changes        []Change      `json:"changes,omitempty"`
	Errors         []SyncError   `json:"errors,omitempty"`
	BackupPath     string        `json:"backupPath,omitempty"`
	ConfigPath     string        `json:"configPath,omitempty"`
	Duration       time.Duration `json:"duration"`
	Timestamp      time.Time     `json:"timestamp"`
}

SyncResult represents the outcome of a sync operation

type SyncSettings ΒΆ

type SyncSettings struct {
	Strategy           string        `json:"strategy,omitempty"`           // "merge", "replace", "selective"
	ConflictResolution string        `json:"conflictResolution,omitempty"` // "master-wins", "target-wins", "manual"
	PreserveMissing    bool          `json:"preserveMissing,omitempty"`
	BatchSize          int           `json:"batchSize,omitempty"`
	Timeout            time.Duration `json:"timeout,omitempty"`
}

SyncSettings controls synchronization behavior

type TargetConfig ΒΆ

type TargetConfig struct {
	Name                 string `json:"name"`
	Type                 string `json:"type"`
	Enabled              bool   `json:"enabled"`
	ConfigPath           string `json:"configPath"`
	RequiresSanitization bool   `json:"requiresSanitization"`
	SupportsProjects     bool   `json:"supportsProjects"`
	ConfigFormat         string `json:"configFormat"`
	ServerNamePattern    string `json:"serverNamePattern,omitempty"`
}

TargetConfig represents legacy target configuration

type TargetInfo ΒΆ

type TargetInfo struct {
	Name        string    `json:"name"`
	Type        string    `json:"type"`
	Enabled     bool      `json:"enabled"`
	ConfigPath  string    `json:"configPath"`
	LastSync    time.Time `json:"lastSync,omitempty"`
	ServerCount int       `json:"serverCount"`
}

TargetInfo contains target information

type ValidationSettings ΒΆ

type ValidationSettings struct {
	Enabled             bool `json:"enabled"`
	ValidateBeforeWrite bool `json:"validateBeforeWrite"`
	ValidateAfterWrite  bool `json:"validateAfterWrite"`
	StrictMode          bool `json:"strictMode"`
}

ValidationSettings controls validation behavior

Directories ΒΆ

Path Synopsis
cmd
daemon command
examples
basic_usage command
redis_storage command
github.com
Package presets provides common MCP destination configurations This is separate from the core engine and completely optional
Package presets provides common MCP destination configurations This is separate from the core engine and completely optional
storage
redis
Package redis provides a Redis-based storage implementation for the Agent Master Engine.
Package redis provides a Redis-based storage implementation for the Agent Master Engine.

Jump to

Keyboard shortcuts

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