Documentation
¶
Overview ¶
Package contracts defines typed data transfer objects for API communication
Index ¶
- Constants
- Variables
- func AssertType[T any](data interface{}, fieldName string) (T, error)
- func ConvertConfigToContract(cfg *config.Config) interface{}
- func DeriveCallWith(annotations *config.ToolAnnotations) string
- type APIResponse
- type ActivityDetailResponse
- type ActivityExportFormat
- type ActivityListResponse
- type ActivityRecord
- type ActivitySSEEvent
- type ActivitySource
- type ActivitySummaryResponse
- type ActivityTopServer
- type ActivityTopTool
- type ActivityType
- type ApplyConfigRequest
- type AuthStatus
- type ConfigApplyResult
- type DCRStatus
- type DiagnosticIssue
- type Diagnostics
- type DiagnosticsResponse
- type DockerStatus
- type ErrorResponse
- type Event
- type GetConfigResponse
- type GetMigrationAnalysisResponse
- type GetRefsResponse
- type GetRegistriesResponse
- type GetServerLogsResponse
- type GetServerToolCallsResponse
- type GetServerToolsResponse
- type GetServersResponse
- type GetSessionDetailResponse
- type GetSessionsResponse
- type GetToolCallDetailResponse
- type GetToolCallsResponse
- type HealthStatus
- type InfoEndpoints
- type InfoResponse
- type IntentDeclaration
- func (i *IntentDeclaration) ToMap() map[string]interface{}
- func (i *IntentDeclaration) Validate() *IntentValidationError
- func (i *IntentDeclaration) ValidateAgainstServerAnnotations(toolVariant, serverTool string, annotations *config.ToolAnnotations, ...) *IntentValidationError
- func (i *IntentDeclaration) ValidateForToolVariant(toolVariant string) *IntentValidationError
- type IntentValidationError
- type IsolationConfig
- type LogEntry
- type MCPSession
- type MetadataStatus
- type MigrationAnalysis
- type MigrationCandidate
- type MissingSecret
- type MissingSecretInfo
- type NPMPackageInfo
- type OAuthConfig
- type OAuthErrorDetails
- type OAuthFlowError
- type OAuthIssue
- type OAuthRequirement
- type OAuthStartResponse
- type OAuthValidationError
- type QuarantinedServersResponse
- type Ref
- type Registry
- type ReplayToolCallRequest
- type ReplayToolCallResponse
- type RepositoryInfo
- type RepositoryServer
- type RuntimeStatus
- type SearchRegistryServersResponse
- type SearchResult
- type SearchToolsResponse
- type Server
- type ServerActionResponse
- type ServerStats
- type ServerTokenMetrics
- type SuccessResponse
- type SystemStatus
- type TokenMetrics
- type Tool
- type ToolAnnotation
- type ToolCallRecord
- type ToolCallRequest
- type ToolCallResponse
- type UpdateInfo
- type UpstreamError
- type ValidateConfigRequest
- type ValidateConfigResponse
- type ValidationError
Constants ¶
const ( OperationTypeRead = "read" OperationTypeWrite = "write" OperationTypeDestructive = "destructive" )
Operation type constants for intent declaration
const ( DataSensitivityPublic = "public" DataSensitivityInternal = "internal" DataSensitivityPrivate = "private" DataSensitivityUnknown = "unknown" )
Data sensitivity constants for intent declaration
const ( ToolVariantRead = "call_tool_read" ToolVariantWrite = "call_tool_write" ToolVariantDestructive = "call_tool_destructive" )
Tool variant constants for intent-based tool calling
const ( IntentErrorCodeMissing = "MISSING_INTENT" IntentErrorCodeMissingOperationType = "MISSING_OPERATION_TYPE" IntentErrorCodeInvalidOperationType = "INVALID_OPERATION_TYPE" IntentErrorCodeMismatch = "INTENT_MISMATCH" IntentErrorCodeServerMismatch = "SERVER_MISMATCH" IntentErrorCodeInvalidSensitivity = "INVALID_SENSITIVITY" IntentErrorCodeReasonTooLong = "REASON_TOO_LONG" )
Error codes for intent validation
const ( OAuthValidationServerNotFound = "server_not_found" OAuthValidationServerDisabled = "server_disabled" OAuthValidationServerQuarantined = "server_quarantined" OAuthValidationNotSupported = "oauth_not_supported" OAuthValidationFlowInProgress = "flow_in_progress" )
OAuth validation error type constants
const ( OAuthErrorMetadataMissing = "oauth_metadata_missing" OAuthErrorMetadataInvalid = "oauth_metadata_invalid" OAuthErrorResourceMismatch = "oauth_resource_mismatch" OAuthErrorClientIDRequired = "oauth_client_id_required" OAuthErrorDCRFailed = "oauth_dcr_failed" OAuthErrorFlowFailed = "oauth_flow_failed" )
OAuth flow error type constants
const ( OAuthCodeNoMetadata = "OAUTH_NO_METADATA" OAuthCodeBadMetadata = "OAUTH_BAD_METADATA" OAuthCodeResourceMismatch = "OAUTH_RESOURCE_MISMATCH" OAuthCodeNoClientID = "OAUTH_NO_CLIENT_ID" OAuthCodeDCRFailed = "OAUTH_DCR_FAILED" OAuthCodeFlowFailed = "OAUTH_FLOW_FAILED" )
OAuth flow error code constants (machine-readable)
const ( AuthStateAuthenticated = "authenticated" AuthStateUnauthenticated = "unauthenticated" AuthStateExpired = "expired" AuthStateRefreshing = "refreshing" )
OAuth Authentication State Constants
const MaxReasonLength = 1000
MaxReasonLength is the maximum allowed length for the reason field
Variables ¶
var ToolVariantToOperationType = map[string]string{ ToolVariantRead: OperationTypeRead, ToolVariantWrite: OperationTypeWrite, ToolVariantDestructive: OperationTypeDestructive, }
ToolVariantToOperationType maps tool variants to their expected operation types
var ValidDataSensitivities = []string{ DataSensitivityPublic, DataSensitivityInternal, DataSensitivityPrivate, DataSensitivityUnknown, }
ValidDataSensitivities contains all valid data_sensitivity values
var ValidOperationTypes = []string{ OperationTypeRead, OperationTypeWrite, OperationTypeDestructive, }
ValidOperationTypes contains all valid operation_type values
Functions ¶
func AssertType ¶
Type assertion helper with better error messages
func ConvertConfigToContract ¶
ConvertConfigToContract converts config.Config to a map for API response
func DeriveCallWith ¶
func DeriveCallWith(annotations *config.ToolAnnotations) string
DeriveCallWith derives the recommended tool variant from server annotations. Defaults to call_tool_read as the safest option when intent is unclear. LLMs should analyze the tool description to override this default when appropriate.
Priority:
- destructiveHint=true → call_tool_destructive
- readOnlyHint=false (explicitly NOT read-only) → call_tool_write
- readOnlyHint=true → call_tool_read
- No hints / nil annotations → call_tool_read (safe default)
Types ¶
type APIResponse ¶
type APIResponse struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty" swaggertype:"object"`
Error string `json:"error,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
APIResponse is the standard wrapper for all API responses
func NewErrorResponse ¶
func NewErrorResponse(errorMsg string) APIResponse
NewErrorResponse creates an error response without request ID (for backward compatibility)
func NewErrorResponseWithRequestID ¶
func NewErrorResponseWithRequestID(errorMsg, requestID string) APIResponse
NewErrorResponseWithRequestID creates an error response with request ID for log correlation
func NewSuccessResponse ¶
func NewSuccessResponse(data interface{}) APIResponse
Helper function to create typed API responses
type ActivityDetailResponse ¶
type ActivityDetailResponse struct {
Activity ActivityRecord `json:"activity"`
}
ActivityDetailResponse is the response for GET /api/v1/activity/{id}
type ActivityExportFormat ¶
type ActivityExportFormat string
ActivityExportFormat represents the format for exporting activities
const ( // ActivityExportFormatJSON exports as JSON Lines (JSONL) ActivityExportFormatJSON ActivityExportFormat = "json" // ActivityExportFormatCSV exports as CSV ActivityExportFormatCSV ActivityExportFormat = "csv" )
type ActivityListResponse ¶
type ActivityListResponse struct {
Activities []ActivityRecord `json:"activities"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
ActivityListResponse is the response for GET /api/v1/activity
type ActivityRecord ¶
type ActivityRecord struct {
ID string `json:"id"` // Unique identifier (ULID format)
Type ActivityType `json:"type"` // Type of activity
Source ActivitySource `json:"source,omitempty"` // How activity was triggered: "mcp", "cli", "api"
ServerName string `json:"server_name,omitempty"` // Name of upstream MCP server
ToolName string `json:"tool_name,omitempty"` // Name of tool called
Arguments map[string]interface{} `json:"arguments,omitempty" swaggertype:"object"` // Tool call arguments
Response string `json:"response,omitempty"` // Tool response (potentially truncated)
ResponseTruncated bool `json:"response_truncated,omitempty"` // True if response was truncated
Status string `json:"status"` // Result status: "success", "error", "blocked"
ErrorMessage string `json:"error_message,omitempty"` // Error details if status is "error"
DurationMs int64 `json:"duration_ms,omitempty"` // Execution duration in milliseconds
Timestamp time.Time `json:"timestamp"` // When activity occurred
SessionID string `json:"session_id,omitempty"` // MCP session ID for correlation
RequestID string `json:"request_id,omitempty"` // HTTP request ID for correlation
Metadata map[string]interface{} `json:"metadata,omitempty" swaggertype:"object"` // Additional context-specific data
}
ActivityRecord represents an activity record in API responses
type ActivitySSEEvent ¶
type ActivitySSEEvent struct {
EventType string `json:"event_type"` // SSE event name
ActivityID string `json:"activity_id"` // Reference to ActivityRecord
Timestamp int64 `json:"timestamp"` // Unix timestamp
Payload map[string]interface{} `json:"payload" swaggertype:"object"` // Event-specific data
}
ActivitySSEEvent represents an activity event for SSE streaming
type ActivitySource ¶
type ActivitySource string
ActivitySource indicates how the activity was triggered
const ( // ActivitySourceMCP indicates the activity was triggered via MCP protocol (AI agent) ActivitySourceMCP ActivitySource = "mcp" // ActivitySourceCLI indicates the activity was triggered via CLI command ActivitySourceCLI ActivitySource = "cli" // ActivitySourceAPI indicates the activity was triggered via REST API ActivitySourceAPI ActivitySource = "api" )
type ActivitySummaryResponse ¶
type ActivitySummaryResponse struct {
Period string `json:"period"` // Time period (1h, 24h, 7d, 30d)
TotalCount int `json:"total_count"` // Total activity count
SuccessCount int `json:"success_count"` // Count of successful activities
ErrorCount int `json:"error_count"` // Count of error activities
BlockedCount int `json:"blocked_count"` // Count of blocked activities
TopServers []ActivityTopServer `json:"top_servers,omitempty"` // Top servers by activity count
TopTools []ActivityTopTool `json:"top_tools,omitempty"` // Top tools by activity count
StartTime string `json:"start_time"` // Start of the period (RFC3339)
EndTime string `json:"end_time"` // End of the period (RFC3339)
}
ActivitySummaryResponse is the response for GET /api/v1/activity/summary
type ActivityTopServer ¶
type ActivityTopServer struct {
Name string `json:"name"` // Server name
Count int `json:"count"` // Activity count
}
ActivityTopServer represents a server's activity count in the summary
type ActivityTopTool ¶
type ActivityTopTool struct {
Server string `json:"server"` // Server name
Tool string `json:"tool"` // Tool name
Count int `json:"count"` // Activity count
}
ActivityTopTool represents a tool's activity count in the summary
type ActivityType ¶
type ActivityType string
ActivityType represents the type of activity being recorded
const ( // ActivityTypeToolCall represents a tool execution event ActivityTypeToolCall ActivityType = "tool_call" // ActivityTypePolicyDecision represents a policy blocking a tool call ActivityTypePolicyDecision ActivityType = "policy_decision" // ActivityTypeQuarantineChange represents a server quarantine state change ActivityTypeQuarantineChange ActivityType = "quarantine_change" // ActivityTypeServerChange represents a server configuration change ActivityTypeServerChange ActivityType = "server_change" )
type ApplyConfigRequest ¶
type ApplyConfigRequest struct {
Config interface{} `json:"config" swaggertype:"object"` // The new configuration to apply
}
ApplyConfigRequest is the request for POST /api/v1/config/apply
type AuthStatus ¶
type AuthStatus struct {
ServerName string `json:"server_name"`
State string `json:"state"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
TokenType string `json:"token_type,omitempty"`
Scopes []string `json:"scopes,omitempty"`
Message string `json:"message"`
}
AuthStatus represents detailed OAuth authentication status for a single server.
type ConfigApplyResult ¶
type ConfigApplyResult struct {
Success bool `json:"success"`
AppliedImmediately bool `json:"applied_immediately"`
RequiresRestart bool `json:"requires_restart"`
RestartReason string `json:"restart_reason,omitempty"`
ValidationErrors []ValidationError `json:"validation_errors,omitempty"`
ChangedFields []string `json:"changed_fields,omitempty"`
}
ConfigApplyResult represents the result of applying a configuration change
type DCRStatus ¶
type DCRStatus struct {
Attempted bool `json:"attempted"`
Success bool `json:"success"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
}
DCRStatus represents the status of Dynamic Client Registration.
type DiagnosticIssue ¶
type DiagnosticIssue struct {
Type string `json:"type"` // error, warning, info
Category string `json:"category"` // oauth, connection, secrets, config
Server string `json:"server,omitempty"` // Associated server (if any)
Title string `json:"title"` // Short title
Message string `json:"message"` // Detailed message
Timestamp time.Time `json:"timestamp"` // When detected
Severity string `json:"severity"` // critical, high, medium, low
Metadata map[string]interface{} `json:"metadata,omitempty" swaggertype:"object"` // Additional context
}
DiagnosticIssue represents a single diagnostic issue
type Diagnostics ¶
type Diagnostics struct {
TotalIssues int `json:"total_issues"`
UpstreamErrors []UpstreamError `json:"upstream_errors"`
OAuthRequired []OAuthRequirement `json:"oauth_required"`
OAuthIssues []OAuthIssue `json:"oauth_issues"` // OAuth parameter mismatches
MissingSecrets []MissingSecretInfo `json:"missing_secrets"` // Renamed to avoid conflict
RuntimeWarnings []string `json:"runtime_warnings"`
DockerStatus *DockerStatus `json:"docker_status,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
Diagnostics represents aggregated health information from all MCPProxy components. This is the new unified diagnostics format for the management service.
type DiagnosticsResponse ¶
type DiagnosticsResponse struct {
UpstreamErrors []DiagnosticIssue `json:"upstream_errors"`
OAuthRequired []string `json:"oauth_required"` // Server names
MissingSecrets []MissingSecret `json:"missing_secrets"`
RuntimeWarnings []DiagnosticIssue `json:"runtime_warnings"`
TotalIssues int `json:"total_issues"`
LastUpdated time.Time `json:"last_updated"`
}
DiagnosticsResponse represents the aggregated diagnostics
type DockerStatus ¶
type DockerStatus struct {
Available bool `json:"available"`
Version string `json:"version,omitempty"`
Error string `json:"error,omitempty"`
}
DockerStatus represents the availability of Docker daemon for stdio server isolation.
type ErrorResponse ¶
type ErrorResponse struct {
Success bool `json:"success"`
Error string `json:"error"`
RequestID string `json:"request_id,omitempty"`
}
ErrorResponse is the standard error response for API endpoints. All error responses include a request_id for log correlation.
type Event ¶
type Event struct {
Type string `json:"type"`
Data interface{} `json:"data" swaggertype:"object"`
Server string `json:"server,omitempty"`
Timestamp time.Time `json:"timestamp"`
Metadata map[string]interface{} `json:"metadata,omitempty" swaggertype:"object"`
}
Event represents a system event for SSE streaming
type GetConfigResponse ¶
type GetConfigResponse struct {
Config interface{} `json:"config" swaggertype:"object"` // The configuration object
ConfigPath string `json:"config_path"` // Path to config file
}
GetConfigResponse is the response for GET /api/v1/config
type GetMigrationAnalysisResponse ¶
type GetMigrationAnalysisResponse struct {
Analysis MigrationAnalysis `json:"analysis"`
}
GetMigrationAnalysisResponse is the response for POST /api/v1/secrets/migrate
type GetRefsResponse ¶
type GetRefsResponse struct {
Refs []Ref `json:"refs"`
}
GetRefsResponse is the response for GET /api/v1/secrets/refs
type GetRegistriesResponse ¶
type GetRegistriesResponse struct {
Registries []Registry `json:"registries"`
Total int `json:"total"`
}
GetRegistriesResponse is the response for GET /api/v1/registries
type GetServerLogsResponse ¶
type GetServerLogsResponse struct {
ServerName string `json:"server_name"`
Logs []LogEntry `json:"logs"`
Count int `json:"count"`
}
GetServerLogsResponse is the response for GET /api/v1/servers/{id}/logs
type GetServerToolCallsResponse ¶
type GetServerToolCallsResponse struct {
ServerName string `json:"server_name"`
ToolCalls []ToolCallRecord `json:"tool_calls"`
Total int `json:"total"`
}
GetServerToolCallsResponse is the response for GET /api/v1/servers/{name}/tool-calls
type GetServerToolsResponse ¶
type GetServerToolsResponse struct {
ServerName string `json:"server_name"`
Tools []Tool `json:"tools"`
Count int `json:"count"`
}
GetServerToolsResponse is the response for GET /api/v1/servers/{id}/tools
type GetServersResponse ¶
type GetServersResponse struct {
Servers []Server `json:"servers"`
Stats ServerStats `json:"stats"`
}
GetServersResponse is the response for GET /api/v1/servers
type GetSessionDetailResponse ¶
type GetSessionDetailResponse struct {
Session MCPSession `json:"session"`
}
GetSessionDetailResponse is the response for GET /api/v1/sessions/{id}
type GetSessionsResponse ¶
type GetSessionsResponse struct {
Sessions []MCPSession `json:"sessions"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
GetSessionsResponse is the response for GET /api/v1/sessions
type GetToolCallDetailResponse ¶
type GetToolCallDetailResponse struct {
ToolCall ToolCallRecord `json:"tool_call"`
}
GetToolCallDetailResponse is the response for GET /api/v1/tool-calls/{id}
type GetToolCallsResponse ¶
type GetToolCallsResponse struct {
ToolCalls []ToolCallRecord `json:"tool_calls"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
GetToolCallsResponse is the response for GET /api/v1/tool-calls
type HealthStatus ¶
type HealthStatus struct {
// Level indicates the health level: "healthy", "degraded", or "unhealthy"
Level string `json:"level"`
// AdminState indicates the admin state: "enabled", "disabled", or "quarantined"
AdminState string `json:"admin_state"`
// Summary is a human-readable status message (e.g., "Connected (5 tools)")
Summary string `json:"summary"`
// Detail is an optional longer explanation of the status
Detail string `json:"detail,omitempty"`
// Action is the suggested fix action: "login", "restart", "enable", "approve", "view_logs", "set_secret", "configure", or "" (none)
Action string `json:"action,omitempty"`
}
HealthStatus represents the unified health status of an upstream MCP server. Calculated once in the backend and rendered identically by all interfaces.
type InfoEndpoints ¶
type InfoEndpoints struct {
HTTP string `json:"http"` // HTTP endpoint address (e.g., "127.0.0.1:8080")
Socket string `json:"socket"` // Unix socket path (empty if disabled)
}
InfoEndpoints represents the available API endpoints
type InfoResponse ¶
type InfoResponse struct {
Version string `json:"version"` // Current MCPProxy version
WebUIURL string `json:"web_ui_url"` // URL to access the web control panel
ListenAddr string `json:"listen_addr"` // Listen address (e.g., "127.0.0.1:8080")
Endpoints InfoEndpoints `json:"endpoints"` // Available API endpoints
Update *UpdateInfo `json:"update,omitempty"` // Update information (if available)
}
InfoResponse is the response for GET /api/v1/info
type IntentDeclaration ¶
type IntentDeclaration struct {
// OperationType is automatically inferred from the tool variant.
// Valid values: "read", "write", "destructive"
// This field is populated by the server based on which tool variant is called.
OperationType string `json:"operation_type"`
// DataSensitivity is optional classification of data being accessed/modified.
// Valid values: "public", "internal", "private", "unknown"
// Default: "unknown" if not provided
DataSensitivity string `json:"data_sensitivity,omitempty"`
// Reason is optional human-readable explanation for the operation.
// Max length: 1000 characters
Reason string `json:"reason,omitempty"`
}
IntentDeclaration represents the agent's declared intent for a tool call. The operation_type is automatically inferred from the tool variant used (call_tool_read/write/destructive), so agents only need to provide optional metadata fields for audit and compliance purposes.
func IntentFromMap ¶
func IntentFromMap(m map[string]interface{}) *IntentDeclaration
IntentFromMap creates an IntentDeclaration from a map
func (*IntentDeclaration) ToMap ¶
func (i *IntentDeclaration) ToMap() map[string]interface{}
ToMap converts IntentDeclaration to a map for storage in metadata
func (*IntentDeclaration) Validate ¶
func (i *IntentDeclaration) Validate() *IntentValidationError
Validate validates the IntentDeclaration optional fields. Note: operation_type is not validated here as it's inferred from tool variant.
func (*IntentDeclaration) ValidateAgainstServerAnnotations ¶
func (i *IntentDeclaration) ValidateAgainstServerAnnotations(toolVariant, serverTool string, annotations *config.ToolAnnotations, strict bool) *IntentValidationError
ValidateAgainstServerAnnotations validates intent against server-provided annotations
func (*IntentDeclaration) ValidateForToolVariant ¶
func (i *IntentDeclaration) ValidateForToolVariant(toolVariant string) *IntentValidationError
ValidateForToolVariant validates the intent and sets operation_type from tool variant. The operation_type is automatically inferred from the tool variant, so agents don't need to provide it explicitly.
type IntentValidationError ¶
type IntentValidationError struct {
Code string `json:"code"` // Error code for programmatic handling
Message string `json:"message"` // Human-readable error message
Details map[string]interface{} `json:"details" swaggertype:"object"` // Additional context
}
IntentValidationError represents intent validation failures
func NewIntentValidationError ¶
func NewIntentValidationError(code, message string, details map[string]interface{}) *IntentValidationError
NewIntentValidationError creates a new IntentValidationError
func (*IntentValidationError) Error ¶
func (e *IntentValidationError) Error() string
Error implements the error interface
type IsolationConfig ¶
type IsolationConfig struct {
Enabled bool `json:"enabled"`
Image string `json:"image,omitempty"`
MemoryLimit string `json:"memory_limit,omitempty"`
CPULimit string `json:"cpu_limit,omitempty"`
WorkingDir string `json:"working_dir,omitempty"`
Timeout string `json:"timeout,omitempty"`
}
IsolationConfig represents Docker isolation configuration
type LogEntry ¶
type LogEntry struct {
Timestamp time.Time `json:"timestamp"`
Level string `json:"level"`
Message string `json:"message"`
Server string `json:"server,omitempty"`
Fields map[string]interface{} `json:"fields,omitempty" swaggertype:"object"`
}
LogEntry represents a single log entry
func ConvertLogEntry ¶
ConvertLogEntry converts a string log line to a contracts.LogEntry This is a simplified conversion - in a real implementation you'd parse structured logs
type MCPSession ¶
type MCPSession struct {
ID string `json:"id"`
ClientName string `json:"client_name,omitempty"`
ClientVersion string `json:"client_version,omitempty"`
Status string `json:"status"`
StartTime time.Time `json:"start_time"`
EndTime *time.Time `json:"end_time,omitempty"`
LastActivity time.Time `json:"last_activity"`
ToolCallCount int `json:"tool_call_count"`
TotalTokens int `json:"total_tokens"`
// MCP Client Capabilities
HasRoots bool `json:"has_roots,omitempty"`
HasSampling bool `json:"has_sampling,omitempty"`
Experimental []string `json:"experimental,omitempty"`
}
MCPSession represents a client session with MCPProxy
type MetadataStatus ¶
type MetadataStatus struct {
Found bool `json:"found"`
URLChecked string `json:"url_checked"`
Error string `json:"error,omitempty"`
AuthorizationServers []string `json:"authorization_servers,omitempty"`
}
MetadataStatus represents the status of OAuth metadata discovery.
type MigrationAnalysis ¶
type MigrationAnalysis struct {
Candidates []MigrationCandidate `json:"candidates"`
TotalFound int `json:"total_found"`
}
MigrationAnalysis represents the result of analyzing configuration for potential secrets
type MigrationCandidate ¶
type MigrationCandidate struct {
Field string `json:"field"` // Field path in configuration
Value string `json:"value"` // Masked value for display
Suggested string `json:"suggested"` // Suggested secret reference
Confidence float64 `json:"confidence"` // Confidence score (0.0 to 1.0)
}
MigrationCandidate represents a potential secret that could be migrated to secure storage
type MissingSecret ¶
type MissingSecret struct {
Name string `json:"name"` // Variable/secret name
Reference string `json:"reference"` // Original reference (e.g., "${env:API_KEY}")
Server string `json:"server"` // Which server needs it
Type string `json:"type"` // env, keyring, etc.
}
MissingSecret represents an unresolved secret reference
type MissingSecretInfo ¶
type MissingSecretInfo struct {
SecretName string `json:"secret_name"`
UsedBy []string `json:"used_by"`
}
MissingSecretInfo represents a secret referenced in configuration but not found. This is used by the new Diagnostics type to avoid field name conflicts.
type NPMPackageInfo ¶
NPMPackageInfo represents NPM package information
type OAuthConfig ¶
type OAuthConfig struct {
AuthURL string `json:"auth_url"`
TokenURL string `json:"token_url"`
ClientID string `json:"client_id"`
Scopes []string `json:"scopes,omitempty"`
ExtraParams map[string]string `json:"extra_params,omitempty"`
RedirectPort int `json:"redirect_port,omitempty"`
PKCEEnabled bool `json:"pkce_enabled,omitempty"`
TokenExpiresAt *time.Time `json:"token_expires_at,omitempty"` // When the OAuth token expires
TokenValid bool `json:"token_valid,omitempty"` // Whether token is currently valid
}
OAuthConfig represents OAuth configuration for a server
type OAuthErrorDetails ¶
type OAuthErrorDetails struct {
ServerURL string `json:"server_url"`
ProtectedResourceMetadata *MetadataStatus `json:"protected_resource_metadata,omitempty"`
AuthorizationServerMetadata *MetadataStatus `json:"authorization_server_metadata,omitempty"`
DCRStatus *DCRStatus `json:"dcr_status,omitempty"`
}
OAuthErrorDetails contains structured discovery/failure details for OAuth errors.
type OAuthFlowError ¶
type OAuthFlowError struct {
Success bool `json:"success"` // Always false
ErrorType string `json:"error_type"` // Category of OAuth runtime failure
ErrorCode string `json:"error_code"` // Machine-readable error code (e.g., OAUTH_NO_METADATA)
ServerName string `json:"server_name"` // Server that failed OAuth
CorrelationID string `json:"correlation_id"` // Flow tracking ID for log correlation
RequestID string `json:"request_id"` // HTTP request ID (from PR #237)
Message string `json:"message"` // Human-readable error description
Details *OAuthErrorDetails `json:"details,omitempty"` // Structured discovery/failure details
Suggestion string `json:"suggestion"` // Actionable remediation hint
DebugHint string `json:"debug_hint"` // CLI command for log lookup
}
OAuthFlowError is returned for OAuth runtime failures (after validation passes but before browser opens). Examples: metadata discovery failure, DCR failure, authorization URL construction failure. Implements the error interface so it can be returned as an error while carrying structured data. Spec 020: OAuth Login Error Feedback
func NewOAuthFlowError ¶
func NewOAuthFlowError(serverName, errorType, errorCode, message, suggestion string) *OAuthFlowError
NewOAuthFlowError creates a new OAuthFlowError with the given parameters.
func (*OAuthFlowError) Error ¶
func (e *OAuthFlowError) Error() string
Error implements the error interface for OAuthFlowError.
type OAuthIssue ¶
type OAuthIssue struct {
ServerName string `json:"server_name"`
Issue string `json:"issue"`
Error string `json:"error"`
MissingParams []string `json:"missing_params,omitempty"`
Resolution string `json:"resolution"`
DocumentationURL string `json:"documentation_url,omitempty"`
}
OAuthIssue represents an OAuth configuration issue (e.g., missing parameters).
type OAuthRequirement ¶
type OAuthRequirement struct {
ServerName string `json:"server_name"`
State string `json:"state"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Message string `json:"message"`
}
OAuthRequirement represents an OAuth authentication requirement for a server.
type OAuthStartResponse ¶
type OAuthStartResponse struct {
Success bool `json:"success"` // Always true for successful start
ServerName string `json:"server_name"` // Name of the server being authenticated
CorrelationID string `json:"correlation_id"` // UUID for tracking this flow
AuthURL string `json:"auth_url,omitempty"` // Authorization URL (always included for manual use)
BrowserOpened bool `json:"browser_opened"` // Whether browser launch succeeded
BrowserError string `json:"browser_error,omitempty"` // Error message if browser launch failed
Message string `json:"message"` // Human-readable status message
}
OAuthStartResponse is returned by POST /api/v1/servers/{id}/login when OAuth flow starts successfully. Spec 020: OAuth Login Error Feedback
type OAuthValidationError ¶
type OAuthValidationError struct {
Success bool `json:"success"` // Always false
ErrorType string `json:"error_type"` // Category of validation failure
ServerName string `json:"server_name"` // Requested server name
Message string `json:"message"` // Human-readable error description
Suggestion string `json:"suggestion"` // Actionable remediation hint
AvailableServers []string `json:"available_servers,omitempty"` // List of valid server names (for server_not_found)
CorrelationID string `json:"correlation_id,omitempty"` // Existing flow ID (for flow_in_progress)
}
OAuthValidationError is returned for pre-flight validation failures before OAuth is attempted. Returned with HTTP 400. Implements the error interface so it can be returned as an error while carrying structured data. Spec 020: OAuth Login Error Feedback
func NewOAuthValidationError ¶
func NewOAuthValidationError(serverName, errorType, message, suggestion string) *OAuthValidationError
NewOAuthValidationError creates a new OAuthValidationError with the given parameters.
func (*OAuthValidationError) Error ¶
func (e *OAuthValidationError) Error() string
Error implements the error interface for OAuthValidationError.
type QuarantinedServersResponse ¶
type QuarantinedServersResponse struct {
Servers []Server `json:"servers"`
Count int `json:"count"`
}
QuarantinedServersResponse is the response for quarantined servers
type Ref ¶
type Ref struct {
Type string `json:"type"` // "env", "keyring", etc.
Name string `json:"name"` // The secret name/key
Original string `json:"original"` // Original reference string like "${env:API_KEY}"
}
Ref represents a reference to a secret value
type Registry ¶
type Registry struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
URL string `json:"url"`
ServersURL string `json:"servers_url,omitempty"`
Tags []string `json:"tags,omitempty"`
Protocol string `json:"protocol,omitempty"`
Count interface{} `json:"count,omitempty" swaggertype:"primitive,string"` // number or string
}
Registry represents an MCP server registry
type ReplayToolCallRequest ¶
type ReplayToolCallRequest struct {
Arguments map[string]interface{} `json:"arguments" swaggertype:"object"` // Modified arguments for replay
}
ReplayToolCallRequest is the request for POST /api/v1/tool-calls/{id}/replay
type ReplayToolCallResponse ¶
type ReplayToolCallResponse struct {
Success bool `json:"success"`
NewCallID string `json:"new_call_id"` // ID of the newly created call
NewToolCall ToolCallRecord `json:"new_tool_call"` // The new tool call record
ReplayedFrom string `json:"replayed_from"` // Original call ID
Error string `json:"error,omitempty"` // Error if replay failed
}
ReplayToolCallResponse is the response for POST /api/v1/tool-calls/{id}/replay
type RepositoryInfo ¶
type RepositoryInfo struct {
NPM *NPMPackageInfo `json:"npm,omitempty"`
}
RepositoryInfo represents detected repository type information
type RepositoryServer ¶
type RepositoryServer struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
URL string `json:"url,omitempty"` // MCP endpoint for remote servers only
SourceCodeURL string `json:"source_code_url,omitempty"` // Source repository URL
InstallCmd string `json:"install_cmd,omitempty"` // Installation command
ConnectURL string `json:"connect_url,omitempty"` // Alternative connection URL
UpdatedAt string `json:"updated_at,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
Registry string `json:"registry,omitempty"` // Which registry this came from
RepositoryInfo *RepositoryInfo `json:"repository_info,omitempty"` // Detected package info
}
RepositoryServer represents an MCP server from a registry
type RuntimeStatus ¶
type RuntimeStatus struct {
Version string `json:"version"`
GoVersion string `json:"go_version"`
BuildTime string `json:"build_time,omitempty"`
IndexStatus string `json:"index_status"`
StorageStatus string `json:"storage_status"`
LastConfigLoad time.Time `json:"last_config_load"`
}
RuntimeStatus represents runtime-specific status information
type SearchRegistryServersResponse ¶
type SearchRegistryServersResponse struct {
RegistryID string `json:"registry_id"`
Servers []RepositoryServer `json:"servers"`
Total int `json:"total"`
Query string `json:"query,omitempty"`
Tag string `json:"tag,omitempty"`
}
SearchRegistryServersResponse is the response for GET /api/v1/registries/{id}/servers
type SearchResult ¶
type SearchResult struct {
Tool Tool `json:"tool"`
Score float64 `json:"score"`
Snippet string `json:"snippet,omitempty"`
Matches int `json:"matches"`
}
SearchResult represents a search result for tools
func ConvertGenericSearchResultsToTyped ¶
func ConvertGenericSearchResultsToTyped(genericResults []map[string]interface{}) []SearchResult
ConvertGenericSearchResultsToTyped converts []map[string]interface{} to []SearchResult
func ConvertSearchResult ¶
func ConvertSearchResult(result *config.SearchResult) *SearchResult
ConvertSearchResult converts a config.SearchResult to a contracts.SearchResult
type SearchToolsResponse ¶
type SearchToolsResponse struct {
Query string `json:"query"`
Results []SearchResult `json:"results"`
Total int `json:"total"`
Took string `json:"took"`
}
SearchToolsResponse is the response for GET /api/v1/index/search
type Server ¶
type Server struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url,omitempty"`
Protocol string `json:"protocol"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
WorkingDir string `json:"working_dir,omitempty"`
Env map[string]string `json:"env,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
OAuth *OAuthConfig `json:"oauth,omitempty"`
Enabled bool `json:"enabled"`
Quarantined bool `json:"quarantined"`
Connected bool `json:"connected"`
Connecting bool `json:"connecting"`
Status string `json:"status"`
LastError string `json:"last_error,omitempty"`
ConnectedAt *time.Time `json:"connected_at,omitempty"`
LastReconnectAt *time.Time `json:"last_reconnect_at,omitempty"`
ReconnectCount int `json:"reconnect_count"`
ToolCount int `json:"tool_count"`
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
Isolation *IsolationConfig `json:"isolation,omitempty"`
Authenticated bool `json:"authenticated"` // OAuth authentication status
OAuthStatus string `json:"oauth_status,omitempty"` // OAuth status: "authenticated", "expired", "error", "none"
TokenExpiresAt *time.Time `json:"token_expires_at,omitempty"` // When the OAuth token expires (ISO 8601)
ToolListTokenSize int `json:"tool_list_token_size,omitempty"` // Token size for this server's tools
ShouldRetry bool `json:"should_retry,omitempty"`
RetryCount int `json:"retry_count,omitempty"`
LastRetryTime *time.Time `json:"last_retry_time,omitempty"`
UserLoggedOut bool `json:"user_logged_out,omitempty"` // True if user explicitly logged out (prevents auto-reconnection)
Health *HealthStatus `json:"health,omitempty"` // Unified health status calculated by the backend
}
Server represents an upstream MCP server configuration and status
func ConvertGenericServersToTyped ¶
ConvertGenericServersToTyped converts []map[string]interface{} to []Server
func ConvertServerConfig ¶
func ConvertServerConfig(cfg *config.ServerConfig, status string, connected bool, toolCount int, authenticated bool) *Server
ConvertServerConfig converts a config.ServerConfig to a contracts.Server
type ServerActionResponse ¶
type ServerActionResponse struct {
Server string `json:"server"`
Action string `json:"action"`
Success bool `json:"success"`
Async bool `json:"async,omitempty"`
}
ServerActionResponse is the response for server enable/disable/restart actions
type ServerStats ¶
type ServerStats struct {
TotalServers int `json:"total_servers"`
ConnectedServers int `json:"connected_servers"`
QuarantinedServers int `json:"quarantined_servers"`
TotalTools int `json:"total_tools"`
DockerContainers int `json:"docker_containers"`
TokenMetrics *ServerTokenMetrics `json:"token_metrics,omitempty"`
}
ServerStats represents aggregated statistics about servers
func ConvertUpstreamStatsToServerStats ¶
func ConvertUpstreamStatsToServerStats(stats map[string]interface{}) ServerStats
ConvertUpstreamStatsToServerStats converts upstream stats map to typed ServerStats
type ServerTokenMetrics ¶
type ServerTokenMetrics struct {
TotalServerToolListSize int `json:"total_server_tool_list_size"` // All upstream tools combined (tokens)
AverageQueryResultSize int `json:"average_query_result_size"` // Typical retrieve_tools output (tokens)
SavedTokens int `json:"saved_tokens"` // Difference
SavedTokensPercentage float64 `json:"saved_tokens_percentage"` // Percentage saved
PerServerToolListSizes map[string]int `json:"per_server_tool_list_sizes"` // Token size per server
}
ServerTokenMetrics represents token usage and savings metrics
type SuccessResponse ¶
type SuccessResponse struct {
Success bool `json:"success"`
Data interface{} `json:"data" swaggertype:"object"`
}
SuccessResponse is the standard success response wrapper for API endpoints.
type SystemStatus ¶
type SystemStatus struct {
Phase string `json:"phase"`
Message string `json:"message"`
Uptime time.Duration `json:"uptime"`
StartedAt time.Time `json:"started_at"`
ConfigPath string `json:"config_path"`
LogDir string `json:"log_dir"`
Runtime RuntimeStatus `json:"runtime"`
Servers ServerStats `json:"servers"`
}
SystemStatus represents the overall system status
type TokenMetrics ¶
type TokenMetrics struct {
InputTokens int `json:"input_tokens"` // Tokens in the request
OutputTokens int `json:"output_tokens"` // Tokens in the response
TotalTokens int `json:"total_tokens"` // Total tokens (input + output)
Model string `json:"model"` // Model used for tokenization
Encoding string `json:"encoding"` // Encoding used (e.g., cl100k_base)
EstimatedCost float64 `json:"estimated_cost,omitempty"` // Optional cost estimate
TruncatedTokens int `json:"truncated_tokens,omitempty"` // Tokens removed by truncation
WasTruncated bool `json:"was_truncated"` // Whether response was truncated
}
TokenMetrics represents token usage statistics for a tool call
type Tool ¶
type Tool struct {
Name string `json:"name"`
ServerName string `json:"server_name"`
Description string `json:"description"`
Schema map[string]interface{} `json:"schema,omitempty" swaggertype:"object"`
Usage int `json:"usage"`
LastUsed *time.Time `json:"last_used,omitempty"`
Annotations *ToolAnnotation `json:"annotations,omitempty"`
}
Tool represents an MCP tool with its metadata
func ConvertGenericToolsToTyped ¶
ConvertGenericToolsToTyped converts []map[string]interface{} to []Tool
func ConvertToolMetadata ¶
func ConvertToolMetadata(meta *config.ToolMetadata) *Tool
ConvertToolMetadata converts a config.ToolMetadata to a contracts.Tool
type ToolAnnotation ¶
type ToolAnnotation struct {
Title string `json:"title,omitempty"`
ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
DestructiveHint *bool `json:"destructiveHint,omitempty"`
IdempotentHint *bool `json:"idempotentHint,omitempty"`
OpenWorldHint *bool `json:"openWorldHint,omitempty"`
}
ToolAnnotation represents MCP tool behavior hints
type ToolCallRecord ¶
type ToolCallRecord struct {
ID string `json:"id"` // Unique identifier
ServerID string `json:"server_id"` // Server identity hash
ServerName string `json:"server_name"` // Human-readable server name
ToolName string `json:"tool_name"` // Tool name (without server prefix)
Arguments map[string]interface{} `json:"arguments" swaggertype:"object"` // Tool arguments
Response interface{} `json:"response,omitempty" swaggertype:"object"` // Tool response (success only)
Error string `json:"error,omitempty"` // Error message (failure only)
Duration int64 `json:"duration"` // Duration in nanoseconds
Timestamp time.Time `json:"timestamp"` // When the call was made
ConfigPath string `json:"config_path"` // Active config file path
RequestID string `json:"request_id,omitempty"` // Request correlation ID
Metrics *TokenMetrics `json:"metrics,omitempty"` // Token usage metrics (nil for older records)
ParentCallID string `json:"parent_call_id,omitempty"` // Links nested calls to parent code_execution
ExecutionType string `json:"execution_type,omitempty"` // "direct" or "code_execution"
MCPSessionID string `json:"mcp_session_id,omitempty"` // MCP session identifier
MCPClientName string `json:"mcp_client_name,omitempty"` // MCP client name from InitializeRequest
MCPClientVersion string `json:"mcp_client_version,omitempty"` // MCP client version
Annotations *ToolAnnotation `json:"annotations,omitempty"` // Tool behavior hints snapshot
}
ToolCallRecord represents a single recorded tool call with full context
func ConvertStorageToolCallToContract ¶
func ConvertStorageToolCallToContract(storageRecord interface{}) *ToolCallRecord
ConvertStorageToolCallToContract converts storage.ToolCallRecord to contracts.ToolCallRecord
type ToolCallRequest ¶
type ToolCallRequest struct {
ToolName string `json:"tool_name"`
Args map[string]interface{} `json:"args" swaggertype:"object"`
}
ToolCallRequest represents a request to call a tool
type ToolCallResponse ¶
type ToolCallResponse struct {
ToolName string `json:"tool_name"`
ServerName string `json:"server_name"`
Result interface{} `json:"result" swaggertype:"object"`
Error string `json:"error,omitempty"`
Duration string `json:"duration"`
Timestamp time.Time `json:"timestamp"`
}
ToolCallResponse represents the response from a tool call
type UpdateInfo ¶
type UpdateInfo struct {
Available bool `json:"available"` // Whether an update is available
LatestVersion string `json:"latest_version,omitempty"` // Latest version available (e.g., "v1.2.3")
ReleaseURL string `json:"release_url,omitempty"` // URL to the release page
CheckedAt *time.Time `json:"checked_at,omitempty"` // When the update check was performed
IsPrerelease bool `json:"is_prerelease,omitempty"` // Whether the latest version is a prerelease
CheckError string `json:"check_error,omitempty"` // Error message if update check failed
}
UpdateInfo represents version update check information
type UpstreamError ¶
type UpstreamError struct {
ServerName string `json:"server_name"`
ErrorMessage string `json:"error_message"`
Timestamp time.Time `json:"timestamp"`
}
UpstreamError represents a connection or runtime error from an upstream MCP server.
type ValidateConfigRequest ¶
type ValidateConfigRequest struct {
Config interface{} `json:"config" swaggertype:"object"` // The configuration to validate
}
ValidateConfigRequest is the request for POST /api/v1/config/validate
type ValidateConfigResponse ¶
type ValidateConfigResponse struct {
Valid bool `json:"valid"`
Errors []ValidationError `json:"errors,omitempty"`
}
ValidateConfigResponse is the response for POST /api/v1/config/validate
type ValidationError ¶
ValidationError represents a single configuration validation error
func ConvertValidationErrors ¶
func ConvertValidationErrors(configErrors []config.ValidationError) []ValidationError
ConvertValidationErrors converts config.ValidationError slice to contracts.ValidationError slice