mcp

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// JSON-RPC 2.0 standard error codes
	ParseError     = -32700 // Invalid JSON was received
	InvalidRequest = -32600 // The JSON sent is not a valid Request object
	MethodNotFound = -32601 // The method does not exist
	InvalidParams  = -32602 // Invalid method parameters
	InternalError  = -32603 // Internal JSON-RPC error

	// Custom domain error codes (10xxx range)
	LanguageNotFound = 10001 // No provider for the specified language
	SyntaxError      = 10002 // Source code parsing failed
	NoMatches        = 10003 // Query returned no results
	TransformFailed  = 10004 // Transformation operation failed
	StageNotFound    = 10005 // Staging ID doesn't exist
	StageExpired     = 10006 // Staging has expired
	AlreadyApplied   = 10007 // Stage was already applied
	DatabaseError    = 10008 // Database operation failed
	ConfidenceTooLow = 10009 // Confidence below threshold
	ValidationFailed = 10010 // Code validation failed
	FileSystemError  = 10011 // File system operation failed

	// Safety error codes (11xxx range)
	SafetyViolation      = 11001 // General safety violation
	FileTooLarge         = 11002 // File exceeds size limit
	TooManyFiles         = 11003 // Too many files in operation
	TotalSizeTooLarge    = 11004 // Total operation size too large
	FileModified         = 11005 // File was modified externally
	FileLocked           = 11006 // File is locked by another process
	LockTimeout          = 11007 // Could not acquire file lock
	AtomicWriteFailed    = 11008 // Atomic write operation failed
	BackupFailed         = 11009 // Backup creation failed
	RollbackFailed       = 11010 // Rollback operation failed
	PerFileConfidenceLow = 11011 // Individual file confidence too low
)

Error codes following JSON-RPC 2.0 standard and custom domain errors

View Source
const JSONRPCVersion = "2.0"

JSON-RPC protocol constants used by the MCP transport layer.

Variables

View Source
var ErrToolNotFound = errors.New("tool not found")

ErrToolNotFound indicates that a requested tool is not registered.

Functions

func GetPromptDefinitions

func GetPromptDefinitions() []types.PromptDefinition

Types

type AsyncStagingManager

type AsyncStagingManager struct {
	*StagingManager
	// contains filtered or unexported fields
}

AsyncStagingManager handles staging with goroutine pool

func NewAsyncStagingManager

func NewAsyncStagingManager(db *gorm.DB, config Config, safety *SafetyManager) *AsyncStagingManager

NewAsyncStagingManager creates concurrent staging manager

func (*AsyncStagingManager) BatchCreateStages

func (asm *AsyncStagingManager) BatchCreateStages(stages []*models.Stage) []error

BatchCreateStages creates multiple stages concurrently

func (*AsyncStagingManager) Close

func (asm *AsyncStagingManager) Close()

Close shuts down worker pool

func (*AsyncStagingManager) CreateStageAsync

func (asm *AsyncStagingManager) CreateStageAsync(stage *models.Stage) <-chan error

func (*AsyncStagingManager) CreateStageAsyncWithContext

func (asm *AsyncStagingManager) CreateStageAsyncWithContext(ctx context.Context, stage *models.Stage) <-chan error

CreateStageAsyncWithContext stages transformation without blocking, honoring cancellation.

type AtomicWriteHandle

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

AtomicWriteHandle allows callers to finalize or revert a logged atomic write.

func (*AtomicWriteHandle) Commit

func (h *AtomicWriteHandle) Commit()

Commit marks the associated transaction as completed.

func (*AtomicWriteHandle) Rollback

func (h *AtomicWriteHandle) Rollback() error

Rollback reverts the write using the recorded backup.

type BaseRegistry

type BaseRegistry[T any] struct {
	// contains filtered or unexported fields
}

BaseRegistry provides a thread-safe generic registry implementation

func NewBaseRegistry

func NewBaseRegistry[T any]() *BaseRegistry[T]

NewBaseRegistry creates a new generic registry

func (*BaseRegistry[T]) Get

func (r *BaseRegistry[T]) Get(name string) (T, bool)

Get retrieves a component by name

func (*BaseRegistry[T]) List

func (r *BaseRegistry[T]) List() []T

List returns all components in registration order

func (*BaseRegistry[T]) Names

func (r *BaseRegistry[T]) Names() []string

Names returns all component names in registration order

func (*BaseRegistry[T]) Register

func (r *BaseRegistry[T]) Register(name string, component T)

Register adds a component to the registry

type Config

type Config struct {
	// Database
	DatabaseURL string

	// Auto-apply settings
	AutoApplyEnabled   bool
	AutoApplyThreshold float64

	// Staging
	StagingTTL time.Duration

	// Session limits
	MaxStagesPerSession  int
	MaxAppliesPerSession int

	// Safety Configuration
	Safety SafetyConfig

	// Debug
	Debug bool

	// LogWriter allows tests to redirect debug logging; defaults to stderr.
	LogWriter io.Writer
}

Config holds the MCP server configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a config with sensible defaults

type Error

type Error = ErrorObject

Legacy aliases retained temporarily while refactoring call sites. They will be removed once all handlers are migrated to the new naming.

type ErrorObject

type ErrorObject struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

ErrorObject represents a JSON-RPC 2.0 error payload.

type FileIntegrityCheck

type FileIntegrityCheck struct {
	Path         string `json:"path"`
	ExpectedHash string `json:"expected_hash"`
}

type FileLock

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

func (*FileLock) Release

func (fl *FileLock) Release() error

type LogData

type LogData map[string]any

LogData represents structured data for a log message

type LogLevel

type LogLevel string

LogLevel represents the severity level of a log message

const (
	LogLevelDebug     LogLevel = "debug"
	LogLevelInfo      LogLevel = "info"
	LogLevelNotice    LogLevel = "notice"
	LogLevelWarning   LogLevel = "warning"
	LogLevelError     LogLevel = "error"
	LogLevelCritical  LogLevel = "critical"
	LogLevelAlert     LogLevel = "alert"
	LogLevelEmergency LogLevel = "emergency"
)

type LogMessage

type LogMessage struct {
	Level  LogLevel `json:"level"`
	Data   LogData  `json:"data,omitempty"`
	Logger string   `json:"logger,omitempty"`
}

LogMessage represents a log message according to MCP specification

type MCPError

type MCPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

MCPError represents a structured error for the MCP protocol

func NewMCPError

func NewMCPError(code int, message string, data ...any) *MCPError

NewMCPError creates a new MCP error with optional data

func WrapError

func WrapError(code int, message string, err error) *MCPError

WrapError wraps a regular error into an MCP error

func (*MCPError) Error

func (e *MCPError) Error() string

Error implements the error interface

type MCPMetrics

type MCPMetrics struct {
	InboundMessages  int64 `json:"inbound_messages"`
	OutboundMessages int64 `json:"outbound_messages"`
	PendingRequests  int   `json:"pending_requests"`
}

MCPMetrics captures lightweight counters for observability.

type Meta

type Meta map[string]any

Meta represents the optional `_meta` envelope that can accompany any request, notification, or response in the MCP transport. The structure is intentionally open-ended to support spec-defined fields like `progressToken` while allowing experimental metadata.

func (Meta) ProgressToken

func (m Meta) ProgressToken() (string, bool)

ProgressToken returns the `_meta.progressToken` value if present.

func (Meta) WithProgressToken

func (m Meta) WithProgressToken(token string) Meta

WithProgressToken returns a copy of the metadata map with the provided progress token value applied. A zero-length token removes the field.

type Notification

type Notification = NotificationMessage

Legacy aliases retained temporarily while refactoring call sites. They will be removed once all handlers are migrated to the new naming.

type NotificationHandler

type NotificationHandler func(ctx context.Context, msg NotificationMessage) error

NotificationHandler processes a JSON-RPC notification.

type NotificationMessage

type NotificationMessage struct {
	JSONRPC string          `json:"jsonrpc"`
	Meta    Meta            `json:"_meta,omitempty"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

NotificationMessage represents a JSON-RPC 2.0 notification with no ID.

func NewNotificationMessage

func NewNotificationMessage(method string, params any) (NotificationMessage, error)

NewNotificationMessage constructs a notification envelope for the method.

type PromptContent

type PromptContent struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

PromptContent represents the content of a prompt response

type PromptMessage

type PromptMessage struct {
	Role    string          `json:"role"`
	Content []PromptContent `json:"content"`
}

PromptMessage represents a prompt message

type PromptRegistry

type PromptRegistry struct {
	*BaseRegistry[types.Prompt]
}

PromptRegistry manages prompt registration

func NewPromptRegistry

func NewPromptRegistry() *PromptRegistry

NewPromptRegistry creates a new prompt registry

type Registry

type Registry[T any] interface {
	Register(name string, component T)
	Get(name string) (T, bool)
	List() []T
	Names() []string
}

Registry is a generic registry for MCP components

type Request

type Request = RequestMessage

Legacy aliases retained temporarily while refactoring call sites. They will be removed once all handlers are migrated to the new naming.

type RequestHandler

type RequestHandler func(ctx context.Context, msg RequestMessage) ResponseMessage

RequestHandler processes a JSON-RPC request message and returns a response.

type RequestMessage

type RequestMessage struct {
	JSONRPC string          `json:"jsonrpc"`
	Meta    Meta            `json:"_meta,omitempty"`
	ID      any             `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

RequestMessage represents a JSON-RPC 2.0 request that expects a response.

func NewRequestMessage

func NewRequestMessage(id any, method string, params any) (RequestMessage, error)

NewRequestMessage constructs a request envelope for the supplied method.

type ResourceContent

type ResourceContent struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType"`
	Text     string `json:"text,omitempty"`
	Blob     []byte `json:"blob,omitempty"`
}

ResourceContent represents the content of a resource

type ResourceRegistry

type ResourceRegistry struct {
	*BaseRegistry[types.Resource]
}

ResourceRegistry manages resource registration

func NewResourceRegistry

func NewResourceRegistry() *ResourceRegistry

NewResourceRegistry creates a new resource registry

type ResourceTemplateRegistry

type ResourceTemplateRegistry struct {
	*BaseRegistry[types.ResourceTemplateDefinition]
}

ResourceTemplateRegistry manages resource template registration

func NewResourceTemplateRegistry

func NewResourceTemplateRegistry() *ResourceTemplateRegistry

NewResourceTemplateRegistry creates a new resource template registry

type Response

type Response = ResponseMessage

Legacy aliases retained temporarily while refactoring call sites. They will be removed once all handlers are migrated to the new naming.

func ErrorResponseWithData

func ErrorResponseWithData(id any, code int, message string, data any) Response

ErrorResponseWithData creates a JSON-RPC error response with additional data

type ResponseMessage

type ResponseMessage struct {
	JSONRPC string       `json:"jsonrpc"`
	Meta    Meta         `json:"_meta,omitempty"`
	ID      any          `json:"id"`
	Result  any          `json:"result,omitempty"`
	Error   *ErrorObject `json:"error,omitempty"`
}

ResponseMessage represents a JSON-RPC 2.0 response to a request.

func ErrorResponse

func ErrorResponse(id any, code int, message string, data ...any) ResponseMessage

ErrorResponse builds a response containing the supplied error object.

func SuccessResponse

func SuccessResponse(id, result any) ResponseMessage

SuccessResponse builds a success response with the provided result payload.

type Router

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

Router maintains a registry of MCP request and notification handlers and provides centralized dispatch with JSON-RPC compliance checks.

func NewRouter

func NewRouter() *Router

NewRouter creates an empty router instance.

func (*Router) DispatchNotification

func (r *Router) DispatchNotification(ctx context.Context, msg NotificationMessage) error

DispatchNotification routes a notification message. If validation fails or the method is unknown the handler returns an error for logging.

func (*Router) DispatchRequest

func (r *Router) DispatchRequest(ctx context.Context, msg RequestMessage) ResponseMessage

DispatchRequest routes a request message to the appropriate handler. It returns a JSON-RPC error response if validation fails or the method is unknown.

func (*Router) RegisterNotification

func (r *Router) RegisterNotification(method string, handler NotificationHandler)

RegisterNotification associates a notification handler with a method name.

func (*Router) RegisterRequest

func (r *Router) RegisterRequest(method string, handler RequestHandler)

RegisterRequest associates a handler with a JSON-RPC method name. Existing registrations are replaced.

type SafetyConfig

type SafetyConfig struct {
	// File operation limits
	MaxFiles     int   `json:"max_files"`      // Max files per operation
	MaxFileSize  int64 `json:"max_file_size"`  // Max size per file (bytes)
	MaxTotalSize int64 `json:"max_total_size"` // Max total operation size (bytes)

	// Confidence validation
	ConfidenceMode   string  `json:"confidence_mode"`    // "global", "per_file", "both"
	PerFileThreshold float64 `json:"per_file_threshold"` // Individual file threshold
	GlobalThreshold  float64 `json:"global_threshold"`   // Overall operation threshold

	// Hash validation
	ValidateFileHashes bool `json:"validate_file_hashes"` // Check files weren't modified externally

	// Atomic writes (always enabled for safety)
	UseFsync bool `json:"use_fsync"` // Use fsync for durability

	// Backup & rollback
	CreateBackups  bool   `json:"create_backups"`  // Create .bak files before writes
	BackupSuffix   string `json:"backup_suffix"`   // Backup file suffix
	TransactionLog bool   `json:"transaction_log"` // Enable transaction logging

	// Concurrency safety
	FileLocking bool          `json:"file_locking"` // Use file locking
	LockTimeout time.Duration `json:"lock_timeout"` // Lock acquisition timeout
}

SafetyConfig holds safety-related configuration

type SafetyFile

type SafetyFile struct {
	Path       string  `json:"path"`
	Size       int64   `json:"size"`
	Confidence float64 `json:"confidence"`
}

type SafetyManager

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

SafetyManager handles all safety-related operations

func NewSafetyManager

func NewSafetyManager(config SafetyConfig) *SafetyManager

NewSafetyManager creates a new safety manager with the given config

func (*SafetyManager) AtomicWrite

func (sm *SafetyManager) AtomicWrite(path, content string) (*AtomicWriteHandle, error)

AtomicWrite performs an atomic write operation and, when transaction logging is enabled, returns a handle that can later be used to commit or roll back the persisted change. Atomic writes are always enabled for safety.

func (*SafetyManager) LockFile

func (sm *SafetyManager) LockFile(path string) (*FileLock, error)

LockFile acquires an exclusive lock on a file

func (*SafetyManager) ReleaseLock

func (sm *SafetyManager) ReleaseLock(path string) error

ReleaseLock releases a file lock

func (*SafetyManager) ValidateFileIntegrity

func (sm *SafetyManager) ValidateFileIntegrity(files []FileIntegrityCheck) error

ValidateFileIntegrity checks if files haven't been modified externally

func (*SafetyManager) ValidateOperation

func (sm *SafetyManager) ValidateOperation(op *SafetyOperation) error

ValidateOperation checks if an operation meets safety requirements

type SafetyOperation

type SafetyOperation struct {
	Files            []SafetyFile `json:"files"`
	GlobalConfidence float64      `json:"global_confidence"`
}

type ServerInterface

type ServerInterface = types.ServerInterface

ServerInterface is now an alias to types.ServerInterface

type SessionState

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

SessionState captures negotiated protocol details and client preferences for the active MCP connection.

func NewSessionState

func NewSessionState() *SessionState

NewSessionState returns a session state with sensible defaults.

func (*SessionState) AppendElicitationRecord

func (s *SessionState) AppendElicitationRecord(params map[string]any, result map[string]any)

AppendElicitationRecord stores an elicitation exchange.

func (*SessionState) AppendSamplingRecord

func (s *SessionState) AppendSamplingRecord(params map[string]any, result map[string]any)

AppendSamplingRecord stores a sampling exchange for later inspection.

func (*SessionState) ClientCapabilities

func (s *SessionState) ClientCapabilities() map[string]any

ClientCapabilities returns a shallow copy of the negotiated capabilities.

func (*SessionState) ClientRoots

func (s *SessionState) ClientRoots() []string

ClientRoots returns the negotiated root directories from the client, if any.

func (*SessionState) ElicitationHistory

func (s *SessionState) ElicitationHistory() []types.ElicitationRecord

ElicitationHistory returns recorded elicitation exchanges.

func (*SessionState) Initialized

func (s *SessionState) Initialized() bool

Initialized reports whether the handshake has completed.

func (*SessionState) LoggingLevel

func (s *SessionState) LoggingLevel() LogLevel

LoggingLevel returns the currently configured minimum logging level.

func (*SessionState) MarkInitialized

func (s *SessionState) MarkInitialized(protocolVersion string, capabilities map[string]any)

MarkInitialized records the negotiated protocol version and client capabilities.

func (*SessionState) ProtocolVersion

func (s *SessionState) ProtocolVersion() string

ProtocolVersion returns the negotiated protocol version.

func (*SessionState) SamplingHistory

func (s *SessionState) SamplingHistory() []types.SamplingRecord

SamplingHistory retrieves a copy of recorded sampling exchanges.

func (*SessionState) SetClientRoots

func (s *SessionState) SetClientRoots(roots []string)

SetClientRoots records the roots returned by the client.

func (*SessionState) SetLoggingLevel

func (s *SessionState) SetLoggingLevel(level LogLevel)

SetLoggingLevel stores the requested minimum logging level.

type StagingManager

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

StagingManager handles staging and applying transformations

func NewStagingManager

func NewStagingManager(db *gorm.DB, config Config, safety *SafetyManager) *StagingManager

NewStagingManager creates a new staging manager

func (*StagingManager) ApplyStage

func (sm *StagingManager) ApplyStage(ctx context.Context, stageID string, autoApplied bool) (*models.Apply, error)

ApplyStage applies a staged transformation while honoring cancellation.

func (*StagingManager) CleanupExpiredStages

func (sm *StagingManager) CleanupExpiredStages() error

CleanupExpiredStages marks expired stages

func (*StagingManager) CreateStage

func (sm *StagingManager) CreateStage(ctx context.Context, stage *models.Stage) error

CreateStage creates a new staged transformation while honoring cancellation.

func (*StagingManager) DeleteAppliedStages

func (sm *StagingManager) DeleteAppliedStages(sessionID string) error

DeleteAppliedStages removes applied stages from database

func (*StagingManager) DeleteStage

func (sm *StagingManager) DeleteStage(stageID string) error

DeleteStage removes a specific stage by ID

func (*StagingManager) GetStage

func (sm *StagingManager) GetStage(id string) (*models.Stage, error)

GetStage retrieves a stage by ID

func (*StagingManager) IsEnabled

func (sm *StagingManager) IsEnabled() bool

IsEnabled reports whether staging support is active. The manager is enabled whenever it has a backing database connection.

func (*StagingManager) ListPendingStages

func (sm *StagingManager) ListPendingStages(sessionID string) ([]models.Stage, error)

ListPendingStages lists all pending stages for a session

type StdioServer

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

StdioServer handles MCP communication over stdio

func NewStdioServer

func NewStdioServer(config Config) (*StdioServer, error)

NewStdioServer creates a new MCP server that communicates over stdio

func (*StdioServer) Close

func (s *StdioServer) Close() error

Close cleans up resources

func (*StdioServer) ConfirmApply

func (s *StdioServer) ConfirmApply(ctx context.Context, summary string) error

ConfirmApply requests client confirmation before applying staged changes. If the client does not support elicitation, auto-confirms.

func (*StdioServer) FinalizeTransform

func (s *StdioServer) FinalizeTransform(ctx context.Context, req types.TransformRequest) (map[string]any, error)

func (*StdioServer) GetFileProcessor

func (s *StdioServer) GetFileProcessor() *core.FileProcessor

GetFileProcessor returns the file processor

func (*StdioServer) GetProviders

func (s *StdioServer) GetProviders() *providers.Registry

GetProviders returns the provider registry

func (*StdioServer) GetSafety

func (s *StdioServer) GetSafety() any

GetSafety returns the safety manager

func (*StdioServer) GetSessionID

func (s *StdioServer) GetSessionID() string

GetSessionID returns the current persistence session identifier if available.

func (*StdioServer) GetStaging

func (s *StdioServer) GetStaging() any

GetStaging returns the staging manager

func (*StdioServer) LogDebug

func (s *StdioServer) LogDebug(message string, data ...LogData)

LogDebug sends a debug level log notification

func (*StdioServer) LogError

func (s *StdioServer) LogError(message string, data ...LogData)

LogError sends an error level log notification

func (*StdioServer) LogInfo

func (s *StdioServer) LogInfo(message string, data ...LogData)

LogInfo sends an info level log notification

func (*StdioServer) LogWarning

func (s *StdioServer) LogWarning(message string, data ...LogData)

LogWarning sends a warning level log notification

func (*StdioServer) Metrics

func (s *StdioServer) Metrics() MCPMetrics

Metrics exposes lightweight counters useful for debugging and observability.

func (*StdioServer) RegisterResource

func (s *StdioServer) RegisterResource(resource types.Resource)

RegisterResource adds or overrides a resource in the server registry.

func (*StdioServer) RegisterTool

func (s *StdioServer) RegisterTool(name string, handler types.ToolHandler)

RegisterTool adds or overrides a tool handler in the modular registry. Primarily used in tests to stub tool behavior.

func (*StdioServer) ReportProgress

func (s *StdioServer) ReportProgress(ctx context.Context, progress, total float64, message string)

ReportProgress emits a progress notification if the context carries a token.

func (*StdioServer) RequestElicitation

func (s *StdioServer) RequestElicitation(ctx context.Context, params map[string]any) (map[string]any, error)

RequestElicitation requests an elicitation flow and records the interaction.

func (*StdioServer) RequestRoots

func (s *StdioServer) RequestRoots(ctx context.Context, params any, meta Meta) (ResponseMessage, error)

RequestRoots negotiates shared roots/list with the client.

func (*StdioServer) RequestSampling

func (s *StdioServer) RequestSampling(ctx context.Context, params map[string]any) (map[string]any, error)

RequestSampling requests a sampling message from the client and records it.

func (*StdioServer) RequestSamplingMessage

func (s *StdioServer) RequestSamplingMessage(ctx context.Context, params any, meta Meta) (ResponseMessage, error)

RequestSamplingMessage asks the client to generate a sampling message per MCP spec.

func (*StdioServer) ResourceDefinitions

func (s *StdioServer) ResourceDefinitions() []types.ResourceDefinition

func (*StdioServer) Start

func (s *StdioServer) Start() error

Start begins processing JSON-RPC requests from stdin

type ToolRegistry

type ToolRegistry struct {
	*BaseRegistry[types.Tool]
	// contains filtered or unexported fields
}

ToolRegistry manages tool registration and execution

func NewToolRegistry

func NewToolRegistry(server ServerInterface) *ToolRegistry

NewToolRegistry creates a new tool registry

func (*ToolRegistry) Execute

func (tr *ToolRegistry) Execute(ctx context.Context, name string, params json.RawMessage) (any, error)

Execute runs a tool by name with the given parameters

func (*ToolRegistry) GetDefinitions

func (tr *ToolRegistry) GetDefinitions() []types.ToolDefinition

GetDefinitions returns tool definitions for MCP protocol

type Transaction

type Transaction struct {
	ID         string    `json:"id"`
	TargetPath string    `json:"target_path"`
	TmpPath    string    `json:"tmp_path"`
	BackupPath string    `json:"backup_path"`
	Status     string    `json:"status"` // "pending", "completed", "failed", "rolled_back"
	Error      string    `json:"error,omitempty"`
	StartTime  time.Time `json:"start_time"`
	EndTime    time.Time `json:"end_time"`
}

Transaction represents a file operation transaction

type TransactionLog

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

TransactionLog manages transaction logging for rollback capability

func NewTransactionLog

func NewTransactionLog() *TransactionLog

NewTransactionLog creates a new transaction log

func (*TransactionLog) BeginTransaction

func (tl *TransactionLog) BeginTransaction(targetPath, tmpPath, backupPath string) string

BeginTransaction starts a new transaction

func (*TransactionLog) CompleteTransaction

func (tl *TransactionLog) CompleteTransaction(txID string)

CompleteTransaction marks a transaction as completed

func (*TransactionLog) FailTransaction

func (tl *TransactionLog) FailTransaction(txID string, reason error) error

FailTransaction marks a transaction as failed and triggers rollback

func (*TransactionLog) GetPendingTransactions

func (tl *TransactionLog) GetPendingTransactions() []*Transaction

GetPendingTransactions returns all pending transactions

func (*TransactionLog) GetSummary

func (tl *TransactionLog) GetSummary() TransactionSummary

GetSummary returns a summary of the transaction log

func (*TransactionLog) RollbackAll

func (tl *TransactionLog) RollbackAll() error

RollbackAll rolls back all pending transactions

func (*TransactionLog) RollbackTransaction

func (tl *TransactionLog) RollbackTransaction(txID string) error

RollbackTransaction performs rollback for a specific transaction

type TransactionSummary

type TransactionSummary struct {
	TotalTransactions      int `json:"total_transactions"`
	PendingTransactions    int `json:"pending_transactions"`
	CompletedTransactions  int `json:"completed_transactions"`
	FailedTransactions     int `json:"failed_transactions"`
	RolledBackTransactions int `json:"rolled_back_transactions"`
}

TransactionSummary provides a summary of transaction log state

Directories

Path Synopsis
Package types provides shared types and interfaces for MCP components This avoids circular dependencies between packages
Package types provides shared types and interfaces for MCP components This avoids circular dependencies between packages

Jump to

Keyboard shortcuts

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