app

package
v0.0.0-...-be7b520 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: Apache-2.0 Imports: 85 Imported by: 0

Documentation

Overview

Package app provides the main application logic.

Index

Constants

This section is empty.

Variables

View Source
var BuiltinServiceTemplates []*configv1.ServiceTemplate

BuiltinServiceTemplates contains the rich seed configurations for the UI wizard.

View Source
var BuiltinTemplates []*configv1.UpstreamServiceConfig

BuiltinTemplates contains the seed configurations for high-value MCP servers. Deprecated: Use BuiltinServiceTemplates instead.

Functions

func HealthCheck

func HealthCheck(out io.Writer, addr string, timeout time.Duration) error

HealthCheck performs a health check against a running server.

Summary: Checks the health of a running server.

The function constructs the health check URL from the provided address and sends an HTTP GET request. It expects a 200 OK status code for a successful health check.

Parameters:

  • out: io.Writer. The writer to which the success message will be written.
  • addr: string. The address (host:port) on which the server is running.
  • timeout: time.Duration. The maximum duration to wait for the health check.

Returns:

  • error: nil if healthy, or an error if the health check fails.

func HealthCheckWithContext

func HealthCheckWithContext(
	ctx context.Context,
	out io.Writer,
	addr string,
) error

HealthCheckWithContext performs a health check against a running server with a context.

Summary: Checks the health of a running server using a context.

The function constructs the health check URL from the provided address and sends an HTTP GET request. It expects a 200 OK status code for a successful health check.

Parameters:

  • ctx: context.Context. The context for managing the health check's lifecycle.
  • out: io.Writer. The writer to which the success message will be written.
  • addr: string. The address (host:port) on which the server is running.

Returns:

  • error: nil if healthy, or an error if the health check fails.

Types

type Application

type Application struct {
	PromptManager   prompt.ManagerInterface
	ToolManager     tool.ManagerInterface
	ResourceManager resource.ManagerInterface
	ServiceRegistry serviceregistry.ServiceRegistryInterface
	TopologyManager *topology.Manager
	UpstreamFactory factory.Factory

	Storage         storage.Storage
	TemplateManager *TemplateManager

	// SkillManager manages agent skills
	SkillManager *skill.Manager

	// AlertsManager manages system alerts
	AlertsManager *alerts.Manager

	// DiscoveryManager manages auto-discovery providers
	DiscoveryManager *discovery.Manager

	// CatalogManager manages dynamic service catalog
	CatalogManager *catalog.Manager

	// Settings Manager for global settings (dynamic updates)
	SettingsManager *GlobalSettingsManager
	// Profile Manager for dynamic profile updates
	ProfileManager *profile.Manager
	// Auth Manager (stored here for access in runServerMode, though it is also passed to serviceregistry)
	// We need to keep a reference to update it on reload.
	AuthManager *auth.Manager

	// BoundHTTPPort stores the actual port the HTTP server is listening on.
	BoundHTTPPort atomic.Int32
	// BoundGRPCPort stores the actual port the gRPC server is listening on.
	BoundGRPCPort atomic.Int32

	// RegistrationRetryDelay allows configuring the retry delay for service registration.
	// If 0, it defaults to 5 seconds (in the worker).
	RegistrationRetryDelay time.Duration

	// MetricsGatherer is the interface for gathering metrics.
	// Defaults to prometheus.DefaultGatherer.
	MetricsGatherer prometheus.Gatherer
	// contains filtered or unexported fields
}

Application is the main application struct, holding the dependencies and logic for the MCP Any server.

Summary: The main application container.

Fields:

  • PromptManager: prompt.ManagerInterface. Manages AI prompts.
  • ToolManager: tool.ManagerInterface. Manages tools and execution.
  • ResourceManager: resource.ManagerInterface. Manages resources (files, data).
  • ServiceRegistry: serviceregistry.ServiceRegistryInterface. Manages upstream service connections.
  • TopologyManager: *topology.Manager. Manages the topology of the server.
  • UpstreamFactory: factory.Factory. Creates upstream service clients.
  • Storage: storage.Storage. Persistent storage interface.
  • TemplateManager: *TemplateManager. Manages templates.
  • SkillManager: *skill.Manager. Manages agent skills.
  • AlertsManager: *alerts.Manager. Manages system alerts.
  • DiscoveryManager: *discovery.Manager. Manages auto-discovery of services.
  • SettingsManager: *GlobalSettingsManager. Manages dynamic global settings.
  • ProfileManager: *profile.Manager. Manages user profiles.
  • AuthManager: *auth.Manager. Manages authentication and authorization.
  • RegistrationRetryDelay: time.Duration. Delay between service registration retries.
  • MetricsGatherer: prometheus.Gatherer. Interface for gathering metrics.
  • BoundHTTPPort: atomic.Int32. The actual bound HTTP port.
  • BoundGRPCPort: atomic.Int32. The actual bound gRPC port.

func NewApplication

func NewApplication() *Application

NewApplication creates a new Application with default dependencies.

Summary: Initializes a new Application instance.

Returns:

  • *Application: The initialized application.

func (*Application) HTTPRequestContextMiddleware

func (a *Application) HTTPRequestContextMiddleware(next http.Handler) http.Handler

HTTPRequestContextMiddleware injects the HTTP request into the context.

Summary: Middleware to add HTTP request to context.

Parameters:

  • next: http.Handler. The next handler.

Returns:

  • http.Handler: The wrapped handler.

func (*Application) ReloadConfig

func (a *Application) ReloadConfig(ctx context.Context, fs afero.Fs, configPaths []string) error

ReloadConfig reloads the configuration from the given paths and updates the services.

Summary: Reloads application configuration from disk/storage.

Parameters:

  • ctx: context.Context. The context for the reload operation.
  • fs: afero.Fs. The filesystem interface for reading configuration files.
  • configPaths: []string. A slice of paths to configuration files to reload.

Returns:

  • error: An error if the configuration reload fails.

func (*Application) Run

func (a *Application) Run(opts RunOptions) error

Run starts the MCP Any server and all its components.

Summary: Executes the application.

Parameters:

  • opts: RunOptions. The runtime options.

Returns:

  • error: An error if execution fails.

Side Effects:

  • Starts HTTP and gRPC servers.
  • Initializes background workers.
  • Loads configuration.

func (*Application) WaitForStartup

func (a *Application) WaitForStartup(ctx context.Context) error

WaitForStartup waits for the application to be fully initialized.

Summary: Waits for application startup completion.

It blocks until the startup process is complete or the context is canceled.

Parameters:

  • ctx: context.Context. The context to wait on.

Returns:

  • error: nil if startup completes successfully, or a context error if canceled.

type AuthTestRequest

type AuthTestRequest struct {
	CredentialID  string         `json:"credential_id"`
	ServiceType   string         `json:"service_type"`
	ServiceConfig map[string]any `json:"service_config"`
}

AuthTestRequest defines the structure for an authentication test request.

type AuthTestResponse

type AuthTestResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

AuthTestResponse defines the structure for an authentication test response.

type GlobalSettingsManager

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

GlobalSettingsManager manages the global settings of the application in a thread-safe manner. It allows for dynamic updates to configuration values that are used across the application.

func NewGlobalSettingsManager

func NewGlobalSettingsManager(apiKey string, allowedIPs []string, allowedOrigins []string) *GlobalSettingsManager

NewGlobalSettingsManager creates a new GlobalSettingsManager with initial values.

Summary: Initializes the global settings manager.

Parameters:

  • apiKey: string. The initial API key.
  • allowedIPs: []string. The initial list of allowed IP addresses.
  • allowedOrigins: []string. The initial list of allowed CORS origins.

Returns:

  • *GlobalSettingsManager: The initialized manager.

func (*GlobalSettingsManager) GetAPIKey

func (m *GlobalSettingsManager) GetAPIKey() string

GetAPIKey returns the current API key.

Summary: Retrieves the active API key.

Returns:

  • string: The API key.

func (*GlobalSettingsManager) GetAllowedIPs

func (m *GlobalSettingsManager) GetAllowedIPs() []string

GetAllowedIPs returns the current allowed IPs.

Summary: Retrieves the list of allowed IP addresses.

Returns:

  • []string: A list of allowed IP CIDRs or addresses.

func (*GlobalSettingsManager) GetAllowedOrigins

func (m *GlobalSettingsManager) GetAllowedOrigins() []string

GetAllowedOrigins returns the current allowed origins.

Summary: Retrieves the list of allowed CORS origins.

Returns:

  • []string: A list of allowed origins.

func (*GlobalSettingsManager) Update

func (m *GlobalSettingsManager) Update(settings *config_v1.GlobalSettings, explicitAPIKey string)

Update updates the settings from the provided GlobalSettings config.

Summary: Refreshes global settings from the configuration object.

Parameters:

  • settings: *config_v1.GlobalSettings. The new global settings configuration.
  • explicitAPIKey: string. An explicitly provided API key (e.g. from CLI flags) that overrides the config.

Returns:

None.

type LoginRequest

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

LoginRequest is the request body for login.

type LoginResponse

type LoginResponse struct {
	Token string `json:"token"`
}

LoginResponse is the response body for login.

type Metric

type Metric struct {
	// Label is the primary text description of the metric (e.g., "Total Requests").
	Label string `json:"label"`
	// Value is the current value of the metric to display (e.g., "1,234").
	Value string `json:"value"`
	// Change represents the change from a previous period (e.g., "+10%").
	Change string `json:"change"`
	// Trend indicates the direction of the change ("up", "down", or "neutral").
	Trend string `json:"trend"` // "up" | "down" | "neutral"
	// Icon is the name of the icon to display with the metric (e.g., "Activity").
	Icon string `json:"icon"`
	// SubLabel provides additional context or subtitle for the metric (e.g., "Since startup").
	SubLabel string `json:"subLabel"`
}

Metric represents a single dashboard metric to be displayed in the UI.

Summary: Data structure for dashboard metrics.

It contains the label, value, trend direction, and other visual metadata.

type RunOptions

type RunOptions struct {
	Ctx             context.Context
	Fs              afero.Fs
	Stdio           bool
	JSONRPCPort     string
	GRPCPort        string
	ConfigPaths     []string
	APIKey          string
	ShutdownTimeout time.Duration
	TLSCert         string
	TLSKey          string
	TLSClientCA     string
	DBPath          string
}

RunOptions configuration for starting the MCP Any application.

Summary: Options for configuring the application runtime.

Fields:

  • Ctx: context.Context. The context for the application.
  • Fs: afero.Fs. The filesystem interface.
  • Stdio: bool. Whether to run in stdio mode (for CLI/one-off usage).
  • JSONRPCPort: string. The port for the JSON-RPC/HTTP server.
  • GRPCPort: string. The port for the gRPC registration server.
  • ConfigPaths: []string. Paths to configuration files.
  • APIKey: string. The master API key for the server.
  • ShutdownTimeout: time.Duration. The timeout for graceful shutdown.
  • TLSCert: string. Path to the TLS certificate file.
  • TLSKey: string. Path to the TLS private key file.
  • TLSClientCA: string. Path to the TLS client CA certificate file (for mTLS).
  • DBPath: string. Path to the SQLite database file.

type Runner

type Runner interface {
	// Run starts the application with the given options.
	//
	// Summary: Starts the application.
	//
	// Parameters:
	//   - opts: RunOptions. The configuration for running.
	//
	// Returns:
	//   - error: An error if startup or execution fails.
	Run(opts RunOptions) error

	// ReloadConfig reloads the application configuration.
	//
	// Summary: Triggers a configuration reload.
	//
	// Parameters:
	//   - ctx: context.Context. The context for the operation.
	//   - fs: afero.Fs. The filesystem.
	//   - configPaths: []string. Paths to configuration files.
	//
	// Returns:
	//   - error: An error if reload fails.
	ReloadConfig(ctx context.Context, fs afero.Fs, configPaths []string) error
}

Runner defines the interface for running the application.

Summary: Interface for application execution and management.

type ServiceHealth

type ServiceHealth struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Status  string `json:"status"`
	Latency string `json:"latency"`
	Uptime  string `json:"uptime"`
	Message string `json:"message,omitempty"`
}

ServiceHealth represents the health status of a service.

type ServiceHealthResponse

type ServiceHealthResponse struct {
	Services []ServiceHealth                  `json:"services"`
	History  map[string][]health.HistoryPoint `json:"history"`
}

ServiceHealthResponse represents the response for the health dashboard.

type SkillServiceServer

type SkillServiceServer struct {
	pb.UnimplementedSkillServiceServer
	// contains filtered or unexported fields
}

SkillServiceServer implements the SkillService gRPC interface.

func NewSkillServiceServer

func NewSkillServiceServer(manager *skill.Manager) *SkillServiceServer

NewSkillServiceServer creates a new SkillServiceServer.

manager handles the resource management.

Returns the result.

func (*SkillServiceServer) CreateSkill

CreateSkill creates a new skill.

_ is an unused parameter. req is the request object.

Returns the response. Returns an error if the operation fails.

func (*SkillServiceServer) DeleteSkill

DeleteSkill deletes a skill.

_ is an unused parameter. req is the request object.

Returns the response. Returns an error if the operation fails.

func (*SkillServiceServer) GetSkill

GetSkill retrieves a specific skill by name.

_ is an unused parameter. req is the request object.

Returns the response. Returns an error if the operation fails.

func (*SkillServiceServer) ListSkills

ListSkills lists all available skills.

_ is an unused parameter. _ is an unused parameter.

Returns the response. Returns an error if the operation fails.

func (*SkillServiceServer) UpdateSkill

UpdateSkill updates an existing skill.

_ is an unused parameter. req is the request object.

Returns the response. Returns an error if the operation fails.

type Span

type Span struct {
	ID           string         `json:"id"`
	Name         string         `json:"name"`
	Type         string         `json:"type"`
	StartTime    int64          `json:"startTime"` // Unix millis
	EndTime      int64          `json:"endTime"`   // Unix millis
	Status       string         `json:"status"`    // success, error, pending
	Input        map[string]any `json:"input,omitempty"`
	Output       map[string]any `json:"output,omitempty"`
	ErrorMessage string         `json:"errorMessage,omitempty"`
}

Span represents a span in a trace.

type SystemStatusResponse

type SystemStatusResponse struct {
	UptimeSeconds     int64    `json:"uptime_seconds"`
	ActiveConnections int32    `json:"active_connections"`
	BoundHTTPPort     int      `json:"bound_http_port"`
	BoundGRPCPort     int      `json:"bound_grpc_port"`
	Version           string   `json:"version"`
	SecurityWarnings  []string `json:"security_warnings"`
}

SystemStatusResponse represents the response from the system status API.

type TemplateManager

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

TemplateManager manages the persistence and lifecycle of service templates.

func NewTemplateManager

func NewTemplateManager(dataDir string) *TemplateManager

NewTemplateManager creates a new instance of TemplateManager.

Summary: Initializes a new TemplateManager.

Parameters:

  • dataDir: string. The directory where template data is persisted.

Returns:

  • *TemplateManager: The initialized manager.

func (*TemplateManager) DeleteTemplate

func (tm *TemplateManager) DeleteTemplate(idOrName string) error

DeleteTemplate deletes a template by its ID or Name.

Summary: Removes a template.

Parameters:

  • idOrName: string. The ID or Name of the template to delete.

Returns:

  • error: An error if deletion or persistence fails.

func (*TemplateManager) ListTemplates

func (tm *TemplateManager) ListTemplates() []*configv1.UpstreamServiceConfig

ListTemplates returns a list of all stored templates.

Summary: Retrieves all managed templates.

Returns:

  • []*configv1.UpstreamServiceConfig: A list of templates.

func (*TemplateManager) SaveTemplate

func (tm *TemplateManager) SaveTemplate(template *configv1.UpstreamServiceConfig) error

SaveTemplate saves or updates a template.

Summary: Persists a template.

Parameters:

  • template: *configv1.UpstreamServiceConfig. The template to save.

Returns:

  • error: An error if persistence fails.

type TestAuthRequest

type TestAuthRequest struct {
	// The credential to use (can be a reference ID or inline Credential).
	CredentialID string `json:"credential_id"`
	// OR inline authentication config
	Authentication *configv1.Authentication `json:"authentication"`
	// OR inline user token (for ad-hoc testing)
	UserToken *configv1.UserToken `json:"user_token"`

	// The URL to test against.
	TargetURL string `json:"target_url"`
	// HTTP Method (GET, POST, etc.)
	Method string `json:"method"`
}

TestAuthRequest defines the payload for testing authentication.

Summary: Request payload for testing authentication configurations.

type TestAuthResponse

type TestAuthResponse struct {
	Status     int               `json:"status"`
	StatusText string            `json:"status_text"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
	Error      string            `json:"error,omitempty"`
}

TestAuthResponse defines the response for testing authentication.

Summary: Response payload for authentication tests.

type ToolAnalytics

type ToolAnalytics struct {
	Name        string  `json:"name"`
	ServiceID   string  `json:"serviceId"`
	TotalCalls  int64   `json:"totalCalls"`
	SuccessRate float64 `json:"successRate"`
}

ToolAnalytics represents detailed usage analytics for a tool.

type ToolFailureStats

type ToolFailureStats struct {
	Name        string  `json:"name"`
	ServiceID   string  `json:"serviceId"`
	FailureRate float64 `json:"failureRate"` // Percentage 0-100
	TotalCalls  int64   `json:"totalCalls"`
}

ToolFailureStats represents failure statistics for a tool.

type ToolUsageStats

type ToolUsageStats struct {
	Name      string `json:"name"`
	ServiceID string `json:"serviceId"`
	Count     int64  `json:"count"`
}

ToolUsageStats represents usage statistics for a tool.

type Trace

type Trace struct {
	ID            string `json:"id"`
	RootSpan      Span   `json:"rootSpan"`
	Timestamp     string `json:"timestamp"` // ISO 8601
	TotalDuration int64  `json:"totalDuration"`
	Status        string `json:"status"`
	Trigger       string `json:"trigger"`
}

Trace represents a full trace.

type ValidateRequest

type ValidateRequest struct {
	Content string `json:"content"`
	Format  string `json:"format"` // "json" or "yaml"
}

ValidateRequest represents the request body for the validation endpoint.

type ValidateResponse

type ValidateResponse struct {
	Valid   bool   `json:"valid"`
	Error   string `json:"error,omitempty"`
	Message string `json:"message,omitempty"`
}

ValidateResponse represents the response body for the validation endpoint.

Jump to

Keyboard shortcuts

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