Documentation
¶
Index ¶
- Constants
- Variables
- func PreflightActivityStatus(verdict string) string
- func WorkspaceName(root string) string
- type ActivityService
- func (s *ActivityService) RecordPreflight(rec PreflightActivity) error
- func (s *ActivityService) RecordToolCallRejected(evt Event)
- func (s *ActivityService) SetDetector(detector *security.Detector)
- func (s *ActivityService) SetEventEmitter(emitter SensitiveDataEventEmitter)
- func (s *ActivityService) SetMaxResponseSize(maxResponseSize int)
- func (s *ActivityService) SetRetentionConfig(maxAge time.Duration, maxRecords int, checkInterval time.Duration, ...)
- func (s *ActivityService) SetSessionClientResolver(r SessionClientResolver)
- func (s *ActivityService) SetUsagePersistInterval(d time.Duration)
- func (s *ActivityService) SetWorkSessionReaper(f func(time.Duration) int)
- func (s *ActivityService) SetWorkSessionResolver(r SessionWorkSessionResolver)
- func (s *ActivityService) Start(ctx context.Context, rt *Runtime)
- func (s *ActivityService) Stop()
- func (s *ActivityService) UsageSnapshot() *UsageAggregate
- type ConfigApplyResult
- type Event
- type EventType
- type Phase
- type PreflightActivity
- type PreflightArguments
- type PreflightToolOutcome
- type RejectionMetricSink
- type Runtime
- func (r *Runtime) ActivityService() *ActivityService
- func (r *Runtime) AggregateToolUsage(since time.Time) (map[string]storage.ToolUsageStat, error)
- func (r *Runtime) AppContext() context.Context
- func (r *Runtime) ApplyConfig(newCfg *config.Config, cfgPath string) (*ConfigApplyResult, error)
- func (r *Runtime) ApproveAllTools(serverName string, approvedBy string) (int, error)
- func (r *Runtime) ApproveTools(serverName string, toolNames []string, approvedBy string) error
- func (r *Runtime) BlockAllTools(serverName string, blockedBy string) (int, error)
- func (r *Runtime) BlockTools(serverName string, toolNames []string, blockedBy string) (int, error)
- func (r *Runtime) BulkEnableServers(serverNames []string, enabled bool) (map[string]error, error)
- func (r *Runtime) CacheManager() *cache.Manager
- func (r *Runtime) CalculateTokenSavings() (*contracts.ServerTokenMetrics, error)
- func (r *Runtime) ClassifyDisabledTool(serverName, toolName string) contracts.DisabledToolStatus
- func (r *Runtime) Close() error
- func (r *Runtime) ConcurrencyStats() (global limiter.Stats, servers map[string]limiter.Stats)
- func (r *Runtime) Config() *config.Config
- func (r *Runtime) ConfigPath() string
- func (r *Runtime) ConfigService() *configsvc.Service
- func (r *Runtime) ConfigSnapshot() *configsvc.Snapshot
- func (r *Runtime) CurrentPhase() Phase
- func (r *Runtime) CurrentStatus() Status
- func (r *Runtime) DiscoverAndIndexTools(ctx context.Context) error
- func (r *Runtime) DiscoverAndIndexToolsForServer(ctx context.Context, serverName string) error
- func (r *Runtime) EmitActiveProfileChanged(profile string)
- func (r *Runtime) EmitActivityConfigChange(action, affectedEntity, source string, changedFields []string, ...)
- func (r *Runtime) EmitActivityInternalToolCall(...)
- func (r *Runtime) EmitActivityInternalToolCallTruncated(...)
- func (r *Runtime) EmitActivityPolicyDecision(serverName, toolName, sessionID, requestID, decision, reason string)
- func (r *Runtime) EmitActivityPromptGet(serverName, promptName, sessionID, requestID, status, errorMsg string, ...)
- func (r *Runtime) EmitActivityQuarantineChange(serverName string, quarantined bool, reason string)
- func (r *Runtime) EmitActivitySystemStart(version, listenAddress string, startupDurationMs int64, configPath string)
- func (r *Runtime) EmitActivitySystemStop(reason, signal string, uptimeSeconds int64, errorMsg string)
- func (r *Runtime) EmitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg string, ...)
- func (r *Runtime) EmitActivityToolCallRejected(serverName, toolName, source, requestID, reason, scope, message string, ...)
- func (r *Runtime) EmitActivityToolCallStarted(serverName, toolName, sessionID, requestID, source string, args map[string]any)
- func (r *Runtime) EmitOAuthRefreshFailed(serverName string, errorMsg string)
- func (r *Runtime) EmitOAuthTokenRefreshed(serverName string, expiresAt time.Time)
- func (r *Runtime) EmitSecurityIntegrityAlert(serverName, alertType, action string)
- func (r *Runtime) EmitSecurityScanCompleted(serverName string, findingsSummary map[string]int)
- func (r *Runtime) EmitSecurityScanFailed(serverName, _, errMsg string)
- func (r *Runtime) EmitSecurityScanProgress(_, _, _ string, _ int)
- func (r *Runtime) EmitSecurityScanStarted(serverName string, _ []string, _ string)
- func (r *Runtime) EmitSecurityScanTelemetry(completed bool, findingsBySeverity map[string]int)
- func (r *Runtime) EmitSecurityScannerChanged(scannerID, status, errMsg string)
- func (r *Runtime) EmitSensitiveDataDetected(activityID string, detectionCount int, maxSeverity string, ...)
- func (r *Runtime) EmitServersChanged(reason string, extra map[string]any)
- func (r *Runtime) EnableServer(serverName string, enabled bool) error
- func (r *Runtime) ForceReconnectAllServers(reason string) error
- func (r *Runtime) GetActivationFirstMCPClient() (bool, []string)
- func (r *Runtime) GetActivity(id string) (*storage.ActivityRecord, error)
- func (r *Runtime) GetAllServers() ([]map[string]interface{}, error)
- func (r *Runtime) GetConfig() (*config.Config, error)
- func (r *Runtime) GetConnectedServerCount() int
- func (r *Runtime) GetCurrentConfig() *config.Config
- func (r *Runtime) GetDesiredConfig() (*config.Config, error)
- func (r *Runtime) GetDirectToolResponseMode() string
- func (r *Runtime) GetDockerCLISource() string
- func (r *Runtime) GetDockerIsolatedServerCount() int
- func (r *Runtime) GetDockerRecoveryStatus() *storage.DockerRecoveryState
- func (r *Runtime) GetManagementService() management.Service
- func (r *Runtime) GetOnboardingState() (*storage.OnboardingState, error)
- func (r *Runtime) GetRecentSessions(limit int, status string) ([]*contracts.MCPSession, int, error)
- func (r *Runtime) GetRoutingMode() string
- func (r *Runtime) GetSecretResolver() *secret.Resolver
- func (r *Runtime) GetServerCount() int
- func (r *Runtime) GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)
- func (r *Runtime) GetServerTools(serverName string) ([]map[string]interface{}, error)
- func (r *Runtime) GetSessionByID(sessionID string) (*contracts.MCPSession, error)
- func (r *Runtime) GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)
- func (r *Runtime) GetToolCallByID(id string) (*contracts.ToolCallRecord, error)
- func (r *Runtime) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
- func (r *Runtime) GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
- func (r *Runtime) GetToolCount() int
- func (r *Runtime) GetToolResponseMode() string
- func (r *Runtime) GetVersionInfo() *updatecheck.VersionInfo
- func (r *Runtime) HandleUpstreamServerChange(ctx context.Context)
- func (r *Runtime) HealthRefreshState(name string, cfg *config.ServerConfig) *oauth.RefreshStateInfo
- func (r *Runtime) IndexManager() *index.Manager
- func (r *Runtime) IsDockerAvailable() bool
- func (r *Runtime) IsQuarantineEnabled() bool
- func (r *Runtime) IsRunning() bool
- func (r *Runtime) IsToolConfigDenied(serverName, toolName string) bool
- func (r *Runtime) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)
- func (r *Runtime) ListRegistries() ([]interface{}, error)
- func (r *Runtime) ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error)
- func (r *Runtime) LoadConfiguredServers(cfg *config.Config) error
- func (r *Runtime) Logger() *zap.Logger
- func (r *Runtime) MarkFirstConnectedServerForActivation()
- func (r *Runtime) NotifySecretsChanged(ctx context.Context, operation, secretName string) error
- func (r *Runtime) QuarantineServer(serverName string, quarantined bool) error
- func (r *Runtime) ReapWorkSessions(maxIdle time.Duration) int
- func (r *Runtime) RecordAvailabilityBlock(reason string)
- func (r *Runtime) RecordDiscoveryOmission()
- func (r *Runtime) RecordFilterDiagnosticsEmitted(missingAnnotation, explicit int)
- func (r *Runtime) RecordFilterDiagnosticsFollowed()
- func (r *Runtime) RecordMCPClientForActivation(rawClientName string)
- func (r *Runtime) RecordPreflight(rec PreflightActivity) error
- func (r *Runtime) RecordRealToolCallForActivation()
- func (r *Runtime) RecordRetrieveToolsCallForActivation()
- func (r *Runtime) RecordTokensSavedForActivation(n int)
- func (r *Runtime) RefreshManager() *oauth.RefreshManager
- func (r *Runtime) RefreshOAuthToken(serverName string) error
- func (r *Runtime) RefreshRegistryCache(registryID string) (int, error)
- func (r *Runtime) RefreshServerTools(ctx context.Context, serverName string) error
- func (r *Runtime) RefreshVersionInfo() *updatecheck.VersionInfo
- func (r *Runtime) ReloadConfiguration() error
- func (r *Runtime) ReplayToolCall(ctx context.Context, id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)
- func (r *Runtime) ResolveWorkSession(id WorkSessionIdentity) string
- func (r *Runtime) RestartServer(serverName string) error
- func (r *Runtime) SaveConfiguration() error
- func (r *Runtime) SaveOnboardingState(state *storage.OnboardingState) error
- func (r *Runtime) SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, *contracts.RegistryCacheInfo, error)
- func (r *Runtime) ServedRoutingMode() string
- func (r *Runtime) SetAllToolsEnabled(serverName string, enabled bool, updatedBy string) (int, error)
- func (r *Runtime) SetManagementService(svc management.Service)
- func (r *Runtime) SetRefreshMetricsRecorder(recorder oauth.RefreshMetricsRecorder)
- func (r *Runtime) SetRejectionMetricSink(sink RejectionMetricSink)
- func (r *Runtime) SetRunning(running bool)
- func (r *Runtime) SetServedRoutingMode(mode string)
- func (r *Runtime) SetServerShared(name string, shared bool) (*config.ServerConfig, error)
- func (r *Runtime) SetSessionClientResolver(resolver SessionClientResolver)
- func (r *Runtime) SetTelemetry(version, edition string)
- func (r *Runtime) SetToolEnabled(serverName, toolName string, enabled bool, updatedBy string) error
- func (r *Runtime) SetVersion(version string)
- func (r *Runtime) SetWorkSessionResolver(resolver SessionWorkSessionResolver)
- func (r *Runtime) SignatureCache() *toolsig.Cache
- func (r *Runtime) StartBackgroundInitialization()
- func (r *Runtime) StatusChannel() <-chan Status
- func (r *Runtime) StatusSnapshot(serverRunning bool) map[string]interface{}
- func (r *Runtime) StorageManager() *storage.Manager
- func (r *Runtime) StoredOAuthTokenInPlay(name string, cfg *config.ServerConfig) bool
- func (r *Runtime) StreamActivities(filter storage.ActivityFilter) <-chan *storage.ActivityRecord
- func (r *Runtime) SubscribeEvents() chan Event
- func (r *Runtime) Supervisor() *supervisor.Supervisor
- func (r *Runtime) TelemetryRegistry() *telemetry.CounterRegistry
- func (r *Runtime) TelemetryService() *telemetry.Service
- func (r *Runtime) Tokenizer() tokens.Tokenizer
- func (r *Runtime) TriggerOAuthLogin(serverName string) error
- func (r *Runtime) TriggerOAuthLoginQuick(serverName string) (*core.OAuthStartResult, error)
- func (r *Runtime) TriggerOAuthLogout(serverName string) error
- func (r *Runtime) Truncator() *truncate.Truncator
- func (r *Runtime) UnsubscribeEvents(ch chan Event)
- func (r *Runtime) UpdateConfig(cfg *config.Config, cfgPath string)
- func (r *Runtime) UpdateListenAddress(addr string) error
- func (r *Runtime) UpdatePhase(phase Phase, message string)
- func (r *Runtime) UpdatePhaseMessage(message string)
- func (r *Runtime) UpdatePolicy() updatecheck.Policy
- func (r *Runtime) UpdateStatus(phase Phase, message string, stats map[string]interface{}, toolsIndexed int)
- func (r *Runtime) UpstreamManager() *upstream.Manager
- func (r *Runtime) UsageSnapshot() *UsageAggregate
- func (r *Runtime) ValidateConfig(cfg *config.Config) ([]config.ValidationError, error)
- type SensitiveDataEventEmitter
- type SessionClientResolver
- type SessionWorkSessionResolver
- type Status
- type TimeBucket
- type ToolApprovalResult
- type ToolUsage
- type TransitionReason
- type UsageAggregate
- type UsageStore
- type WorkSessionIdentity
- type WorkSessionTracker
Constants ¶
const ( // DefaultRetentionMaxAge is the default max age for activity records (7 days) DefaultRetentionMaxAge = 7 * 24 * time.Hour // DefaultRetentionMaxRecords is the default max number of records (10000) DefaultRetentionMaxRecords = 10000 // DefaultRetentionCheckInterval is the default interval between retention checks (1 hour) DefaultRetentionCheckInterval = 1 * time.Hour // DefaultRetentionMaxSizeBytes is the default total activity-log size cap (256MB) DefaultRetentionMaxSizeBytes int64 = 256 * 1024 * 1024 // DefaultActivityMaxResponseSize is the default per-record response cap (64KB). // Aliased here because NewActivityService's first parameter shadows the // storage package inside that function body. DefaultActivityMaxResponseSize = storage.DefaultMaxResponseSize )
Default retention configuration
const DefaultUsagePersistInterval = 30 * time.Second
DefaultUsagePersistInterval is the default snapshot flush cadence.
const DefaultWorkSessionIdleWindow = 30 * time.Minute
DefaultWorkSessionIdleWindow is how long a work session may sit idle before the next activity is considered a new one.
30 minutes is a natural break in human work: long enough to survive a pause inside a task, short enough that yesterday's work does not merge into today's.
Variables ¶
var ( ErrActivityUnavailable = errors.New("activity service unavailable") // ErrActivityShuttingDown means the service already closed its write // barrier; the DB may be closing, so nothing new may be written. ErrActivityShuttingDown = errors.New("activity service is shutting down") )
Errors a preflight activity write can fail with. They are sentinels because the served preflight surface must answer 503 when the record could not be persisted (spec 098 FR-008/FR-014: a 200 without its activity record would break the transparency guarantee), and it should be able to tell "the proxy is shutting down" from "the write failed".
Functions ¶
func PreflightActivityStatus ¶ added in v0.58.0
PreflightActivityStatus maps a set verdict onto the CLOSED activity status vocabulary (see storage.ValidActivityStatuses): an all-ready preflight is a success, anything else is a policy/state block the operator has to act on. No new status value is introduced — spec 093 FR-012 makes that a cross-surface change, and preflight does not need one.
func WorkspaceName ¶ added in v0.49.0
WorkspaceName is the display name of the project — the final path element.
Only the basename is ever shown or stored for display: the full path is a local filesystem path and is nobody's business but the user's. It is never sent to telemetry.
Types ¶
type ActivityService ¶
type ActivityService struct {
// contains filtered or unexported fields
}
ActivityService subscribes to activity events and persists them to storage. It runs as a background goroutine and handles activity recording non-blocking.
func NewActivityService ¶
func NewActivityService(storage *storage.Manager, logger *zap.Logger) *ActivityService
NewActivityService creates a new activity service.
func (*ActivityService) RecordPreflight ¶ added in v0.58.0
func (s *ActivityService) RecordPreflight(rec PreflightActivity) error
RecordPreflight persists one preflight run SYNCHRONOUSLY and returns the write error (spec 098 FR-014).
It deliberately bypasses the bounded async event channel every other activity path uses: that channel drops events for a subscriber that falls behind, and FR-014 requires the record to be durable BEFORE the caller is answered. This is the same trade RecordToolCallRejected makes — one BBolt write on the caller's goroutine, joined to the shutdown barrier via enterWrite so it can never straddle a DB close (Spec 080 FR-010).
func (*ActivityService) RecordToolCallRejected ¶ added in v0.54.0
func (s *ActivityService) RecordToolCallRejected(evt Event)
RecordToolCallRejected persists a concurrency-limiter shed as a tool_call record with the dedicated "rejected" status (spec 093 FR-012). It is a separate path from handleToolCallCompleted because a shed has no upstream response, no token metrics and no intent envelope — only the rejection metadata an operator needs to right-size the limits.
It runs SYNCHRONOUSLY on the rejecting goroutine rather than on the activity event loop: the event bus drops events for a subscriber that falls behind, and a shed burst is exactly when it does. The cost is one BBolt write on an error path that is already returning without calling the upstream.
Spec 080 FR-010: because the write lives on someone else's goroutine, it must join the same shutdown barrier as every other BBolt writer this service owns. enterWrite registers it in workersWG under the lock Stop coordinates with, so a write either happens entirely before Stop returns or does not happen at all — it can never straddle the DB close.
func (*ActivityService) SetDetector ¶ added in v0.17.0
func (s *ActivityService) SetDetector(detector *security.Detector)
SetDetector sets the sensitive data detector for async scanning (Spec 026). If set, tool call arguments and responses will be scanned for sensitive data.
func (*ActivityService) SetEventEmitter ¶ added in v0.17.0
func (s *ActivityService) SetEventEmitter(emitter SensitiveDataEventEmitter)
SetEventEmitter sets the event emitter for sensitive data detection events (Spec 026). If set, events will be emitted when sensitive data is detected in tool calls.
func (*ActivityService) SetMaxResponseSize ¶ added in v0.65.0
func (s *ActivityService) SetMaxResponseSize(maxResponseSize int)
SetMaxResponseSize sets the per-record response size cap in bytes. Values <= 0 are ignored, leaving the current cap in place; truncateForStorage falls back to storage.DefaultMaxResponseSize if it is ever unset.
func (*ActivityService) SetRetentionConfig ¶
func (s *ActivityService) SetRetentionConfig(maxAge time.Duration, maxRecords int, checkInterval time.Duration, maxSizeBytes int64)
SetRetentionConfig updates the retention configuration. maxAge: maximum age for records (0 = no age limit) maxRecords: maximum number of records (0 = no count limit) checkInterval: how often to run retention cleanup
func (*ActivityService) SetSessionClientResolver ¶ added in v0.49.0
func (s *ActivityService) SetSessionClientResolver(r SessionClientResolver)
SetSessionClientResolver wires the session -> MCP client lookup. Safe to leave unset (records then carry no client name).
func (*ActivityService) SetUsagePersistInterval ¶ added in v0.35.0
func (s *ActivityService) SetUsagePersistInterval(d time.Duration)
SetUsagePersistInterval updates the snapshot flush cadence. Hot-reloadable: the flush loop re-reads this value each cycle.
func (*ActivityService) SetWorkSessionReaper ¶ added in v0.49.0
func (s *ActivityService) SetWorkSessionReaper(f func(time.Duration) int)
SetWorkSessionReaper wires the idle-work-session sweep into the retention loop.
func (*ActivityService) SetWorkSessionResolver ¶ added in v0.49.0
func (s *ActivityService) SetWorkSessionResolver(r SessionWorkSessionResolver)
SetWorkSessionResolver wires the session -> work-session lookup (Spec 082).
func (*ActivityService) Start ¶
func (s *ActivityService) Start(ctx context.Context, rt *Runtime)
Start begins listening for activity events and persisting them. It should be called as a goroutine: go svc.Start(ctx, runtime)
func (*ActivityService) Stop ¶
func (s *ActivityService) Stop()
Stop gracefully shuts down the activity service, waiting for every BBolt writer it owns to finish: the main event loop (including its final flush-on-shutdown of the usage snapshot), the retention and usage-flush loops, and any in-flight async detection goroutines (Spec 080 FR-010: no activity write may land after Runtime.Close resolves the clean-shutdown marker or closes the DB).
Callers must cancel the context passed to Start FIRST — the final usage flush runs on ctx.Done inside the event loop, and Stop waits for it, so the flush is captured before the marker resolves. Idempotent, and returns immediately when Start never ran.
Stop is also terminal (Spec 080, review round 5): it marks stopped under startMu, so a Start that has not yet registered (production starts the service via `go` in lifecycle.go) becomes a no-op instead of launching retention/usage/persist loops after the shutdown-marker path began. If Start is mid-registration, acquiring startMu here blocks until every workersWG.Add has happened, so the Wait below cannot miss a worker.
func (*ActivityService) UsageSnapshot ¶ added in v0.35.0
func (s *ActivityService) UsageSnapshot() *UsageAggregate
UsageSnapshot returns the latest immutable usage aggregate snapshot. Safe for concurrent readers (the A3 endpoint); never blocks. Returns nil if usage tracking was never initialized.
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"`
ChangedFields []string `json:"changed_fields,omitempty"`
ValidationErrors []config.ValidationError `json:"validation_errors,omitempty"`
}
ConfigApplyResult represents the result of applying a configuration
func DetectConfigChanges ¶
func DetectConfigChanges(oldCfg, newCfg *config.Config) *ConfigApplyResult
func (*ConfigApplyResult) FormatChangedFields ¶
func (r *ConfigApplyResult) FormatChangedFields() string
FormatChangedFields returns a human-readable string of changed fields
type Event ¶
type Event struct {
Type EventType `json:"type"`
Timestamp time.Time `json:"timestamp"`
Payload map[string]any `json:"payload,omitempty"`
}
Event is a typed notification published by the runtime event bus.
type EventType ¶
type EventType string
EventType represents a runtime event category broadcast to subscribers.
const ( // EventTypeServersChanged is emitted whenever the set of servers or their state changes. EventTypeServersChanged EventType = "servers.changed" // EventTypeConfigReloaded is emitted after configuration reload completes. EventTypeConfigReloaded EventType = "config.reloaded" // EventTypeConfigSaved is emitted after configuration is successfully saved to disk. EventTypeConfigSaved EventType = "config.saved" // EventTypeSecretsChanged is emitted when secrets are added, updated, or deleted. EventTypeSecretsChanged EventType = "secrets.changed" // EventTypeActiveProfileChanged is emitted when the server-level default // active profile changes (Profiles v2). UI surfaces (Web UI, tray) refetch // GET /api/v1/profiles/active to reflect a switch made by another client. EventTypeActiveProfileChanged EventType = "active_profile.changed" // EventTypeOAuthTokenRefreshed is emitted when proactive token refresh succeeds. EventTypeOAuthTokenRefreshed EventType = "oauth.token_refreshed" // EventTypeOAuthRefreshFailed is emitted when proactive token refresh fails after retries. EventTypeOAuthRefreshFailed EventType = "oauth.refresh_failed" // Activity logging events (RFC-003) // EventTypeActivityToolCallStarted is emitted when a tool execution begins. EventTypeActivityToolCallStarted EventType = "activity.tool_call.started" // EventTypeActivityToolCallCompleted is emitted when a tool execution finishes. EventTypeActivityToolCallCompleted EventType = "activity.tool_call.completed" // EventTypeActivityToolCallRejected is emitted when a concurrency limiter // sheds a tool call before it reaches the upstream (spec 093 FR-012). It is // published from the limiter's origin-independent seam, so it also covers // the dispatch paths that never pass through the MCP layer (sandboxed code // execution, activity replay). EventTypeActivityToolCallRejected EventType = "activity.tool_call.rejected" // EventTypeActivityPolicyDecision is emitted when a policy blocks a tool call. EventTypeActivityPolicyDecision EventType = "activity.policy_decision" // EventTypeActivityQuarantineChange is emitted when a server's quarantine state changes. EventTypeActivityQuarantineChange EventType = "activity.quarantine_change" // Spec 024: Expanded Activity Log events // EventTypeActivitySystemStart is emitted when MCPProxy server starts. EventTypeActivitySystemStart EventType = "activity.system.start" // EventTypeActivitySystemStop is emitted when MCPProxy server stops. EventTypeActivitySystemStop EventType = "activity.system.stop" // EventTypeActivityInternalToolCall is emitted when an internal tool (retrieve_tools, call_tool_*, etc.) completes. EventTypeActivityInternalToolCall EventType = "activity.internal_tool_call.completed" // EventTypeActivityConfigChange is emitted when configuration changes (server add/remove/update). EventTypeActivityConfigChange EventType = "activity.config_change" // EventTypeActivityPromptGet is emitted when an upstream prompts/get completes (Finding F10). EventTypeActivityPromptGet EventType = "activity.prompt_get.completed" // EventTypeUpstreamPromptsChanged is emitted (debounced) when a connected // upstream sends notifications/prompts/list_changed, so the aggregated prompt // set is rebuilt without waiting for an unrelated servers.changed (F13). // Carries no payload — RefreshPrompts re-aggregates from live state. EventTypeUpstreamPromptsChanged EventType = "upstream.prompts_changed" // Spec 026: Sensitive data detection event // EventTypeSensitiveDataDetected is emitted when sensitive data is detected in a tool call. EventTypeSensitiveDataDetected EventType = "sensitive_data.detected" // Spec 032: Tool-level quarantine events // EventTypeActivityToolQuarantineChange is emitted when a tool's quarantine status changes. EventTypeActivityToolQuarantineChange EventType = "activity.tool_quarantine_change" // Spec 039: Security scanner events // EventTypeSecurityScanStarted is emitted when a security scan begins. EventTypeSecurityScanStarted EventType = "security.scan_started" // EventTypeSecurityScanProgress is emitted for scanner progress updates. EventTypeSecurityScanProgress EventType = "security.scan_progress" // EventTypeSecurityScanCompleted is emitted when a security scan completes. EventTypeSecurityScanCompleted EventType = "security.scan_completed" // EventTypeSecurityScanFailed is emitted when a scanner fails. EventTypeSecurityScanFailed EventType = "security.scan_failed" // EventTypeSecurityScanSettled is the single, debounced terminal event that // Spec 077 US4 (MCP-2207) emits per server per scan. It collapses the // per-scanner scan_started/progress/completed/failed storm — including // repeats from reconnect storms — into one settled result. EventTypeSecurityScanSettled EventType = "security.scan_settled" // EventTypeSecurityIntegrityAlert is emitted for integrity violations. EventTypeSecurityIntegrityAlert EventType = "security.integrity_alert" // EventTypeSecurityScannerChanged is emitted when a scanner plugin's state // changes (e.g., background image pull started, completed, or failed). EventTypeSecurityScannerChanged EventType = "security.scanner_changed" )
type PreflightActivity ¶ added in v0.58.0
type PreflightActivity struct {
// RequestID correlates the record with the response's X-Request-Id and with
// every tool call the same workflow makes afterwards.
RequestID string
SessionID string
Source storage.ActivitySource
// Verdict is the set-level verdict (preflight.Verdict*).
Verdict string
// Status overrides the derived activity status. Leave empty to derive it
// from Verdict via PreflightActivityStatus.
Status string
// Surface names the surface that ran the preflight, for surfaces the
// Source alone does not identify (spec 099 FR-013:
// storage.PreflightSurfaceMCPCheck). Empty for the REST endpoint, whose
// metadata then stays exactly as spec 098 shipped it.
Surface string
// Arguments is the request as the caller sent it (spec 099 FR-013). Set by
// the in-band check surface; nil for the REST endpoint, whose metadata then
// stays exactly as spec 098 shipped it.
Arguments *PreflightArguments
// Timestamp defaults to time.Now() when zero.
Timestamp time.Time
Tools []PreflightToolOutcome
// Multi-user identity (server edition); empty in the personal edition.
UserID string
UserEmail string
}
PreflightActivity is one executed preflight, as the served surface hands it to the activity log. Everything here is either an enum value, a count or a tool ID — never a description, argument or hash (FR-014: local activity log only, nothing that could leak to a telemetry surface).
type PreflightArguments ¶ added in v0.58.0
type PreflightArguments struct {
// ToolIDs is the RAW array: request order, untrimmed, duplicates intact.
// len(ToolIDs) is the raw requested count.
ToolIDs []string
// Filters names the annotation filters in effect, in declared order. Empty
// when the call carried none.
Filters []string
}
PreflightArguments is one in-band caller's request AS SENT, before trimming and dedup (spec 099 FR-013).
It exists because ids_count is the count of UNIQUE ids — the definition the REST record already uses, and the one that makes the two records mean the same thing — which on its own would make "the agent asked for 12 ids, three of them duplicates" unrecoverable from the log. Nothing here is new data: the ids already appear per-tool, and the filter names are the closed enum describe_tool declares.
type PreflightToolOutcome ¶ added in v0.58.0
PreflightToolOutcome is one per-tool line of a preflight activity record. Reason is empty for a ready tool.
type RejectionMetricSink ¶ added in v0.54.0
type RejectionMetricSink func(server, reason, scope string)
RejectionMetricSink counts one shed call. It runs on the caller's goroutine at the moment of rejection, so implementations must be non-blocking (a Prometheus counter increment is).
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime owns the non-HTTP lifecycle for the proxy process.
func (*Runtime) ActivityService ¶ added in v0.17.0
func (r *Runtime) ActivityService() *ActivityService
ActivityService exposes the activity service for testing.
func (*Runtime) AggregateToolUsage ¶ added in v0.33.0
AggregateToolUsage rolls up tool_call activity per (server,tool) since the given time (spec 050). Returns an empty map when storage is unavailable.
func (*Runtime) AppContext ¶
AppContext returns the long-lived runtime context.
func (*Runtime) ApplyConfig ¶
ApplyConfig applies a new configuration with hot-reload support
func (*Runtime) ApproveAllTools ¶ added in v0.21.0
ApproveAllTools approves all pending/changed tools for a server.
func (*Runtime) ApproveTools ¶ added in v0.21.0
ApproveTools approves specific tools for a server, updating their status to approved.
func (*Runtime) BlockAllTools ¶ added in v0.39.0
BlockAllTools blocks (approve+disable) every pending/changed tool for a server. Mirrors ApproveAllTools' selection set so the two bulk operations dismiss the same quarantine queue — approve keeps tools visible, block hides them. Returns the number of tools blocked.
func (*Runtime) BlockTools ¶ added in v0.39.0
BlockTools atomically "blocks" the named tools for a server. A block is an approve+disable performed as a single, all-or-nothing record write per tool: the tool's quarantine status is promoted to approved (clearing any pending / changed flag, exactly like ApproveTools) AND its Disabled flag is set so it is hidden from MCP clients. Because both mutations land in one SaveToolApproval, a tool is never observably left in the approved+enabled state — that is the invariant this endpoint exists to guarantee.
Why a single combined write instead of ApproveTools followed by SetToolEnabled(disabled): two sequential saves leave a window where a crash or I/O error after the approve but before the disable yields an approved+enabled tool — the exact state callers want to avoid. Folding both into one write removes that window.
Config-denied tools (enabled_tools / disabled_tools) need no special handling: block only ever disables, so it can never enable a tool the operator forbids.
Returns the number of tools actually blocked. Missing approval records are skipped with a warning (mirrors ApproveTools), not treated as a hard error.
func (*Runtime) BulkEnableServers ¶
BulkEnableServers toggles the enabled state for multiple servers in a single storage/config save to avoid repeated file writes. Returns a map of per-server errors for operations that could not be applied.
func (*Runtime) CacheManager ¶
CacheManager exposes the cache manager.
func (*Runtime) CalculateTokenSavings ¶
func (r *Runtime) CalculateTokenSavings() (*contracts.ServerTokenMetrics, error)
CalculateTokenSavings calculates token savings from using MCPProxy
func (*Runtime) ClassifyDisabledTool ¶ added in v0.32.0
func (r *Runtime) ClassifyDisabledTool(serverName, toolName string) contracts.DisabledToolStatus
ClassifyDisabledTool returns the single machine-branchable reason a tool is not callable, by fixed first-match precedence (Spec 049). Pure, request-time, read-only — nothing is written to BBolt. Only meaningful for tools that are already known non-callable; it never lies (indeterminate → unknown).
func (*Runtime) ConcurrencyStats ¶ added in v0.54.0
ConcurrencyStats reports the live occupancy of the global aggregate limiter and of every per-server limiter (spec 093 FR-013). Sampled by the metrics bridge to publish the queue-depth gauges.
func (*Runtime) Config ¶
Config returns the underlying configuration pointer. Deprecated: Use ConfigSnapshot() for lock-free reads. This method exists for backward compatibility.
func (*Runtime) ConfigPath ¶
ConfigPath returns the tracked config path.
func (*Runtime) ConfigService ¶
ConfigService returns the configuration service for advanced access patterns.
func (*Runtime) ConfigSnapshot ¶
ConfigSnapshot returns an immutable configuration snapshot. This is the preferred way to read configuration - it's lock-free and non-blocking.
func (*Runtime) CurrentPhase ¶
CurrentPhase returns the current lifecycle phase.
func (*Runtime) CurrentStatus ¶
CurrentStatus returns a copy of the underlying status struct.
func (*Runtime) DiscoverAndIndexTools ¶
DiscoverAndIndexTools discovers tools from ALL connected upstream servers and indexes them. Used by event-driven callers (boot, server reload, manual refresh) that want a full sweep regardless of per-server cadence.
func (*Runtime) DiscoverAndIndexToolsForServer ¶
DiscoverAndIndexToolsForServer discovers and indexes tools for a single server. This is the LENIENT entry point used by reactive tool discovery (server connect, notifications/tools/list_changed): a successful ListTools that returns zero tools is treated as a transient blip and leaves the existing index untouched (see the authoritative variant for the explicit-refresh path). Implements retry logic with exponential backoff for robustness.
func (*Runtime) EmitActiveProfileChanged ¶ added in v0.46.0
EmitActiveProfileChanged emits an event when the server-level default active profile changes (Profiles v2). UI surfaces subscribe and refetch GET /api/v1/profiles/active so a switch made by one client (Web UI, tray, CLI) is reflected everywhere. An empty profile means "all servers".
func (*Runtime) EmitActivityConfigChange ¶
func (r *Runtime) EmitActivityConfigChange(action, affectedEntity, source string, changedFields []string, previousValues, newValues map[string]interface{})
EmitActivityConfigChange emits an event when configuration changes (Spec 024). action is one of: server_added, server_removed, server_updated, settings_changed source indicates how the change was triggered: "mcp", "cli", or "api"
func (*Runtime) EmitActivityInternalToolCall ¶
func (r *Runtime) EmitActivityInternalToolCall(internalToolName, targetServer, targetTool, toolVariant, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{}, intent map[string]interface{}, contentTrust string)
EmitActivityInternalToolCall emits an event when an internal tool is called (Spec 024). internalToolName is the name of the internal tool (retrieve_tools, call_tool_read, etc.) targetServer and targetTool are used for call_tool_* handlers arguments contains the input parameters, response contains the output intent is the intent declaration metadata
func (*Runtime) EmitActivityInternalToolCallTruncated ¶ added in v0.64.0
func (r *Runtime) EmitActivityInternalToolCallTruncated(internalToolName, targetServer, targetTool, toolVariant, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{}, intent map[string]interface{}, contentTrust string, responseTruncated bool)
EmitActivityInternalToolCallTruncated is EmitActivityInternalToolCall for a built-in whose RECORDED response is larger than the one the agent received.
The non-internal path has carried this since Spec 024 (see the "response_truncated" key in EmitActivityToolCallCompleted); the internal path did not, and that asymmetry is a correctness problem rather than a cosmetic one. retrieve_tools deliberately writes its FULL pre-truncation response to the activity log while the agent consumed only the cut text, so a record that does not say it was truncated is indistinguishable from a complete one. Anything recomputing cost from the log then tokenizes text the agent never paid for and OVERSTATES what mcpproxy cost — the one direction of error the Spec 103 token benchmark exists to prevent, and one that cannot be detected after the fact.
func (*Runtime) EmitActivityPolicyDecision ¶
func (r *Runtime) EmitActivityPolicyDecision(serverName, toolName, sessionID, requestID, decision, reason string)
EmitActivityPolicyDecision emits an event when a policy blocks a tool call.
requestID is the dispatch's correlation id, and it is what lets a consumer recognise the live event and the record persisted from it as one thing rather than two. Every other activity event already carries it; policy decisions gained it in spec 090, so records written before then have none and must not be correlated at all (FR-015) rather than correlated by an empty key.
func (*Runtime) EmitActivityPromptGet ¶ added in v0.59.0
func (r *Runtime) EmitActivityPromptGet(serverName, promptName, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{})
EmitActivityPromptGet emits an event when an upstream prompts/get completes (Finding F10). serverName/promptName identify the prompt, arguments are the prompt inputs, response is the *mcp.GetPromptResult (marshaled by the handler).
func (*Runtime) EmitActivityQuarantineChange ¶
EmitActivityQuarantineChange emits an event when a server's quarantine state changes.
func (*Runtime) EmitActivitySystemStart ¶
func (r *Runtime) EmitActivitySystemStart(version, listenAddress string, startupDurationMs int64, configPath string)
EmitActivitySystemStart emits an event when MCPProxy server starts (Spec 024).
func (*Runtime) EmitActivitySystemStop ¶
func (r *Runtime) EmitActivitySystemStop(reason, signal string, uptimeSeconds int64, errorMsg string)
EmitActivitySystemStop emits an event when MCPProxy server stops (Spec 024).
func (*Runtime) EmitActivityToolCallCompleted ¶
func (r *Runtime) EmitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response string, responseTruncated bool, toolVariant string, intent map[string]interface{}, contentTrust, profile string, requestBytes, responseBytes int, detectionText string, toonOutput map[string]interface{}, parentID string)
EmitActivityToolCallCompleted emits an event when a tool execution finishes. This is used to track activity for observability and debugging. source indicates how the call was triggered: "mcp", "cli", or "api" arguments is the input parameters passed to the tool call toolVariant is the MCP tool variant used (call_tool_read/write/destructive) - optional intent is the intent declaration metadata - optional detectionText is the spec-084 pre-encoding sensitive-data scan input (FR-007b); empty means "scan response as before" (feature off / non-call_tool_* paths) toonOutput is the spec-084 per-block encoding decision metadata (FR-010) - optional parentID is the correlation id of the parent code_execution call for a sandbox sub-call; empty for every top-level dispatch
func (*Runtime) EmitActivityToolCallRejected ¶ added in v0.54.0
func (r *Runtime) EmitActivityToolCallRejected(serverName, toolName, source, requestID, reason, scope, message string, limit int, retryAfterMs, waitedMs int64)
EmitActivityToolCallRejected emits an event when a concurrency limiter shed a tool call (spec 093 FR-012). This is the ORIGIN-INDEPENDENT rejection seam: it is invoked from the limiter observer inside the managed client, so a shed is recorded identically whether the call came from an MCP tool-call variant, the REST endpoint, a sandboxed code-execution script or an activity replay.
reason is queue_full | queue_timeout; scope is server | global. Unlike every other activity emission, the RECORD is written synchronously here rather than by the activity service's bus subscriber: publishEvent drops events for any subscriber whose channel is full, and a burst of sheds is precisely the load that fills it. The bus copy is still published, but only so live subscribers (SSE, tray) see the rejection — the durable row no longer depends on it.
func (*Runtime) EmitActivityToolCallStarted ¶
func (r *Runtime) EmitActivityToolCallStarted(serverName, toolName, sessionID, requestID, source string, args map[string]any)
EmitActivityToolCallStarted emits an event when a tool execution begins. This is used to track activity for observability and debugging. source indicates how the call was triggered: "mcp", "cli", or "api"
func (*Runtime) EmitOAuthRefreshFailed ¶
EmitOAuthRefreshFailed emits an event when proactive token refresh fails after retries. This is used by the RefreshManager to notify subscribers that re-authentication is needed.
func (*Runtime) EmitOAuthTokenRefreshed ¶
EmitOAuthTokenRefreshed emits an event when proactive token refresh succeeds. This is used by the RefreshManager to notify subscribers of successful token refresh.
func (*Runtime) EmitSecurityIntegrityAlert ¶ added in v0.24.0
EmitSecurityIntegrityAlert emits an event for integrity violations (Spec 039).
func (*Runtime) EmitSecurityScanCompleted ¶ added in v0.24.0
EmitSecurityScanCompleted records a terminal scan result for the debouncer, which publishes exactly one settled event per server per scan (Spec 077 US4).
func (*Runtime) EmitSecurityScanFailed ¶ added in v0.24.0
EmitSecurityScanFailed records a terminal failure for the debouncer. Under Spec 077 the baseline verdict is derived elsewhere; here we only ensure the storm still collapses to a single settled event (Spec 077 US4).
func (*Runtime) EmitSecurityScanProgress ¶ added in v0.24.0
EmitSecurityScanProgress is dropped: intermediate per-scanner progress is the noise the settled-event model eliminates (Spec 077 US4).
func (*Runtime) EmitSecurityScanStarted ¶ added in v0.24.0
EmitSecurityScanStarted feeds the scan-notification debouncer (Spec 077 US4, MCP-2207). The started signal is intentionally dropped: it is part of the per-scanner storm the debouncer collapses. The service still invalidates its summary cache independently so the UI shows "scanning" while the scan runs.
func (*Runtime) EmitSecurityScanTelemetry ¶ added in v0.53.0
EmitSecurityScanTelemetry is the sole producer of the schema-v8 TPA scanner counters. The scanner package calls it exactly once per terminal, real (non-dry-run) Pass-1 scan JOB — never per scanner and never for the Pass-2 deep supply-chain audit — so scans_completed/scans_failed count scans, not scanner invocations or passes. See scanCallbackAdapter.countsForTelemetry.
Only counts cross this boundary: the server name, the scanner id, and the error text are not parameters at all, and the registry drops any severity key outside the fixed enum. Nil-safe: telemetry may be disabled or not yet initialized.
func (*Runtime) EmitSecurityScannerChanged ¶ added in v0.24.0
EmitSecurityScannerChanged emits an event when a scanner plugin's state changes — notably while a Docker image is being pulled in the background (Spec 039). The UI listens for this and refreshes its scanner list.
func (*Runtime) EmitSensitiveDataDetected ¶ added in v0.17.0
func (r *Runtime) EmitSensitiveDataDetected(activityID string, detectionCount int, maxSeverity string, detectionTypes []string, serverName string)
EmitSensitiveDataDetected emits an event when sensitive data is detected in a tool call (Spec 026). activityID is the ID of the activity record where sensitive data was detected. detectionCount is the number of sensitive data detections found. maxSeverity is the highest severity level among detections (e.g., "high", "medium", "low"). detectionTypes is a list of detection type names (e.g., "credit_card", "api_key").
func (*Runtime) EmitServersChanged ¶
EmitServersChanged implements the EventEmitter interface for the management service. This delegates to the runtime's internal event emission mechanism.
func (*Runtime) EnableServer ¶
EnableServer enables or disables a server and persists the change.
func (*Runtime) ForceReconnectAllServers ¶
ForceReconnectAllServers triggers reconnection attempts for all managed servers.
func (*Runtime) GetActivationFirstMCPClient ¶ added in v0.29.0
GetActivationFirstMCPClient returns Spec 044's FirstMCPClientEver flag and the capped list of recognized client names from the activation bucket. Used by the v2 onboarding wizard (Spec 046 v2) Verify tab. Nil-safe: when telemetry/activation isn't wired (CI/test or telemetry disabled) returns (false, nil).
func (*Runtime) GetActivity ¶
func (r *Runtime) GetActivity(id string) (*storage.ActivityRecord, error)
GetActivity returns a single activity record by ID.
func (*Runtime) GetAllServers ¶
GetAllServers implements RuntimeOperations interface for management service. Returns all servers with their current status using the Supervisor's StateView.
func (*Runtime) GetConnectedServerCount ¶ added in v0.22.0
GetConnectedServerCount returns the number of connected upstream servers (implements telemetry.RuntimeStats).
func (*Runtime) GetCurrentConfig ¶
GetCurrentConfig returns the current configuration. It may be nil only before the config is installed; New rejects a nil config outright.
func (*Runtime) GetDesiredConfig ¶ added in v0.63.0
GetDesiredConfig returns the configuration as persisted on disk — what the next start will use. Identical to GetConfig() unless a restart-gated field is pending; callers that read-modify-write the configuration MUST merge onto this one, or they silently revert whatever is waiting for a restart.
Shares the same aliasing caveat as GetConfig: the caller must not mutate the returned value in place.
func (*Runtime) GetDirectToolResponseMode ¶ added in v0.63.0
GetDirectToolResponseMode returns the direct-surface serialization mode as a closed enum (implements telemetry.RuntimeStats, schema v10). Live-snapshot read, for the same reason as above.
func (*Runtime) GetDockerCLISource ¶ added in v0.40.0
GetDockerCLISource returns the coarse, fixed-enum branch that resolved the docker CLI — "path" | "bundled" | "login_shell" | "absent" (implements telemetry.RuntimeStats, schema v5 / MCP-2745). This is the direct #696 fleet signal (docker installed but not on the spawn PATH). It delegates to shellwrap.ResolveDockerSource, which shares the process-wide docker-path cache, so this is cheap on the heartbeat path. NEVER returns the path itself.
func (*Runtime) GetDockerIsolatedServerCount ¶ added in v0.24.4
GetDockerIsolatedServerCount returns how many currently-configured servers the runtime actually wraps in a Docker container (implements telemetry.RuntimeStats, schema v3).
Implementation note: we reuse core.IsolationManager.ShouldIsolate — the same function the stdio connection path consults — so the count matches the runtime's real behavior rather than a config-only approximation. When DockerIsolation is nil or disabled globally, ShouldIsolate returns false for every server, giving a count of 0.
func (*Runtime) GetDockerRecoveryStatus ¶
func (r *Runtime) GetDockerRecoveryStatus() *storage.DockerRecoveryState
GetDockerRecoveryStatus returns the current Docker recovery status from the upstream manager
func (*Runtime) GetManagementService ¶
func (r *Runtime) GetManagementService() management.Service
GetManagementService returns the management service instance. Returns nil if service hasn't been set yet.
func (*Runtime) GetOnboardingState ¶ added in v0.29.0
func (r *Runtime) GetOnboardingState() (*storage.OnboardingState, error)
GetOnboardingState returns the current wizard engagement state (Spec 046).
func (*Runtime) GetRecentSessions ¶
GetRecentSessions returns recent MCP sessions.
status filters on the session status ("active" / "closed"); an empty string means no filtering. Both the filter and the last-activity ordering are pushed down into storage, so they are applied before truncation to limit.
func (*Runtime) GetRoutingMode ¶ added in v0.22.0
GetRoutingMode returns the current routing mode (implements telemetry.RuntimeStats).
func (*Runtime) GetSecretResolver ¶
GetSecretResolver returns the secret resolver instance
func (*Runtime) GetServerCount ¶ added in v0.22.0
GetServerCount returns the total number of configured servers (implements telemetry.RuntimeStats).
func (*Runtime) GetServerToolCalls ¶
func (r *Runtime) GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)
GetServerToolCalls retrieves tool call history for a specific server
func (*Runtime) GetServerTools ¶
GetServerTools implements RuntimeOperations interface for management service. Returns all tools for a specific upstream server from StateView cache (lock-free read).
func (*Runtime) GetSessionByID ¶
func (r *Runtime) GetSessionByID(sessionID string) (*contracts.MCPSession, error)
GetSessionByID returns a session by its ID
func (*Runtime) GetToolApproval ¶ added in v0.21.0
func (r *Runtime) GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)
GetToolApproval returns a single tool approval record (Spec 032).
func (*Runtime) GetToolCallByID ¶
func (r *Runtime) GetToolCallByID(id string) (*contracts.ToolCallRecord, error)
GetToolCallByID retrieves a single tool call by ID
func (*Runtime) GetToolCalls ¶
func (r *Runtime) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
GetToolCalls retrieves tool call history with pagination.
scope restricts the result to a set of server names (nil = unrestricted, #1166 follow-up). It is applied BEFORE pagination so `total`, the page and the offset all describe the same record set — a post-filter in the handler would shrink the page while the total kept counting the hidden records, which is both a broken pager and an exact oracle for what was hidden.
func (*Runtime) GetToolCallsBySession ¶
func (r *Runtime) GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
GetToolCallsBySession returns tool calls filtered by session ID.
scope restricts the result to a set of server names (nil = unrestricted). It is pushed down into storage so it lands in the same pass that computes `total` (#1166 follow-up).
func (*Runtime) GetToolCount ¶ added in v0.22.0
GetToolCount returns the total number of indexed tools (implements telemetry.RuntimeStats).
This reads the Bleve index document count — one document per tool, durable across restarts — rather than the upstream manager's per-client tool-count cache. Reading that cache made the telemetry heartbeat report tool_count=0 for installs that held a fully populated index: every indexing pass calls InvalidateAllToolCountCaches() as its LAST step (see lifecycle.go), and the only paths that refill the cache without re-zeroing it are UI/API-triggered ListTools calls. The field metric was therefore biased toward installs whose owner had opened the dashboard, which is not what "indexed tools" means.
Per-profile indexes are not double-counted: RebuildProfileFromShared derives each of them from this shared index, so the shared count is the superset.
When the index CANNOT answer — it is closed, mid-reopen, or returned an error — the last successful POSITIVE count is reported instead of falling through to the upstream cache. That matters most at shutdown: Close() performs a final graceful heartbeat flush (telemetryService.Stop), and the upstream clients are disconnected by then, so the cache path would answer 0 for an install with a fully populated durable index — reintroducing the exact structural zero this function was changed to remove. Close() also now closes the index AFTER that flush, so this is defence in depth rather than the only guard.
A memoised ZERO is deliberately not preferred over the cache. Zero is only ever memoised when the index genuinely held no tools at the last successful read, and in that state the cache cannot produce the structural zero this guard exists for — it can only report MORE (tools held by live clients that the index has not caught up with yet), which is the closer answer. So the guard protects the one value that is expensive to lose and lets the cache arbitrate the empty case.
The upstream cache is otherwise the fallback only for the case it is actually right for: no index manager wired at all (unit tests, early startup).
func (*Runtime) GetToolResponseMode ¶ added in v0.63.0
GetToolResponseMode returns the retrieve_tools serialization mode as a closed enum (implements telemetry.RuntimeStats, schema v10).
Reads the LIVE snapshot via Config() rather than the legacy r.cfg field the older getters use: these are hot-reloadable settings, and a heartbeat that reported the value an operator had at startup would be measuring the wrong thing precisely for the installs that experimented with the mode.
func (*Runtime) GetVersionInfo ¶
func (r *Runtime) GetVersionInfo() *updatecheck.VersionInfo
GetVersionInfo returns the current version information from the update checker. Returns nil if the update checker has not been initialized.
func (*Runtime) HandleUpstreamServerChange ¶
HandleUpstreamServerChange should be called when upstream servers change.
func (*Runtime) HealthRefreshState ¶ added in v0.66.0
func (r *Runtime) HealthRefreshState(name string, cfg *config.ServerConfig) *oauth.RefreshStateInfo
HealthRefreshState returns the RefreshManager state to feed into the health calculator for the named server, or nil when there is none or when the token it rides on is not in play for this server (StoredOAuthTokenInPlay). Every CalculateHealth call site must read refresh state through this, or the REST, MCP and tray surfaces disagree about a header-authenticated server.
func (*Runtime) IndexManager ¶
IndexManager exposes the index manager.
func (*Runtime) IsDockerAvailable ¶ added in v0.24.4
IsDockerAvailable reports whether the host has a reachable Docker daemon (implements telemetry.RuntimeStats, schema v3). Uses a time-based cache — see dockerProbeTTLPositive / dockerProbeTTLNegative for reasoning.
func (*Runtime) IsQuarantineEnabled ¶ added in v0.22.0
IsQuarantineEnabled returns whether tool-level quarantine is enabled (implements telemetry.RuntimeStats).
func (*Runtime) IsToolConfigDenied ¶ added in v0.32.0
IsToolConfigDenied reports whether toolName is denied by the server's static enabled_tools / disabled_tools config. Evaluated at call time — nothing is written to BBolt. Returns false (allow) when the server is unknown or has no filter configured.
func (*Runtime) ListActivities ¶
func (r *Runtime) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)
ListActivities returns activity records matching the filter.
func (*Runtime) ListRegistries ¶
ListRegistries returns the list of available MCP server registries (Phase 7).
It routes through the SAME merged source (built-in defaults + user-configured registries, keyed by ID) that search/add use via SetRegistriesFromConfig, so `mcpproxy registry list` / the Web UI never omit a built-in that is still searchable/addable and never show the legacy hard-coded Smithery entry instead of the shipped defaults (FR-006 / MCP-800 finding 2).
func (*Runtime) ListToolApprovals ¶ added in v0.21.0
func (r *Runtime) ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error)
ListToolApprovals returns all tool approval records for a server (Spec 032).
func (*Runtime) LoadConfiguredServers ¶
LoadConfiguredServers synchronizes storage and upstream manager from the given or current config. If cfg is nil, it will use the current runtime configuration.
func (*Runtime) MarkFirstConnectedServerForActivation ¶ added in v0.25.0
func (r *Runtime) MarkFirstConnectedServerForActivation()
MarkFirstConnectedServerForActivation sets the first_connected_server_ever flag. Called from the supervisor's connect-success callback. Spec 044 US2.
func (*Runtime) NotifySecretsChanged ¶
NotifySecretsChanged notifies the runtime that secrets have changed and restarts affected servers. This method should be called by the HTTP API when secrets are added, updated, or deleted.
func (*Runtime) QuarantineServer ¶
QuarantineServer updates the quarantine state and persists the change. Security: When quarantining a server, all its tools are removed from the index to prevent Tool Poisoning Attacks (TPA) from exposing potentially malicious tool descriptions.
func (*Runtime) ReapWorkSessions ¶ added in v0.49.0
ReapWorkSessions drops work sessions idle past maxIdle, so a long-lived daemon does not accumulate one map entry per identity forever.
func (*Runtime) RecordAvailabilityBlock ¶ added in v0.58.0
RecordAvailabilityBlock counts one policy block by its structured reason key (closed enum; see telemetry.BlockReason*).
func (*Runtime) RecordDiscoveryOmission ¶ added in v0.58.0
func (r *Runtime) RecordDiscoveryOmission()
RecordDiscoveryOmission counts one retrieve_tools response that withheld locked/quarantined matches the caller could not see.
func (*Runtime) RecordFilterDiagnosticsEmitted ¶ added in v0.58.0
RecordFilterDiagnosticsEmitted counts one retrieve_tools response that attached a spec-094 filter_diagnostics block, plus that block's summed per-reason-class counts.
func (*Runtime) RecordFilterDiagnosticsFollowed ¶ added in v0.58.0
func (r *Runtime) RecordFilterDiagnosticsFollowed()
RecordFilterDiagnosticsFollowed counts one diagnostics block the agent acted on within the same MCP session.
func (*Runtime) RecordMCPClientForActivation ¶ added in v0.25.0
RecordMCPClientForActivation records a sanitized MCP client name and marks the first-ever-client flag (Spec 044 US2). No-op if activation store not wired or if the raw name cannot be plumbed through (nil-safe all the way down). Intentionally takes the raw name; sanitization happens inside the store.
func (*Runtime) RecordPreflight ¶ added in v0.58.0
func (r *Runtime) RecordPreflight(rec PreflightActivity) error
RecordPreflight is the Runtime-level passthrough onto the activity service's synchronous preflight write, so a served surface holding only the runtime can satisfy FR-014 without reaching for the service directly.
func (*Runtime) RecordRealToolCallForActivation ¶ added in v0.49.0
func (r *Runtime) RecordRealToolCallForActivation()
RecordRealToolCallForActivation marks the first-ever real (upstream) tool call. "Real" means a call proxied to an upstream server, as opposed to a built-in tool such as retrieve_tools.
This is the lifetime counterpart of RecordRetrieveToolsCallForActivation. Until it existed, the retrieve step had a lifetime flag while the call step had only a windowed counter, so the retrieve→call funnel compared a lifetime value against a 24h one and understated conversion badly.
No-op if the activation store is not wired.
func (*Runtime) RecordRetrieveToolsCallForActivation ¶ added in v0.25.0
func (r *Runtime) RecordRetrieveToolsCallForActivation()
RecordRetrieveToolsCallForActivation bumps the 24h retrieve_tools counter and marks the first-ever-call flag (Spec 044 US2). No-op if the activation store is not wired.
func (*Runtime) RecordTokensSavedForActivation ¶ added in v0.25.0
RecordTokensSavedForActivation adds n to the 24h tokens-saved estimator. n <= 0 is a no-op. Spec 044 US2.
func (*Runtime) RefreshManager ¶ added in v0.16.0
func (r *Runtime) RefreshManager() *oauth.RefreshManager
RefreshManager returns the OAuth refresh manager for health status integration. Returns nil if refresh manager hasn't been initialized.
func (*Runtime) RefreshOAuthToken ¶
RefreshOAuthToken implements RuntimeOperations interface for management service. Triggers token refresh for a specific server.
func (*Runtime) RefreshRegistryCache ¶ added in v0.35.0
RefreshRegistryCache invalidates all cached server lists for a registry, forcing the next search to re-fetch from the source (FR-007). Returns the number of cache entries dropped.
func (*Runtime) RefreshServerTools ¶ added in v0.52.0
RefreshServerTools re-discovers and re-indexes a single server AUTHORITATIVELY (issue #873): a successful ListTools that returns zero tools is taken as the truth — the server's stale index entries are removed and its last-good snapshot is cleared, so a later approval-driven reindex cannot resurface tools that no longer exist upstream. This is the explicit operator refresh/discover path; the reactive callbacks keep the lenient behavior above.
func (*Runtime) RefreshVersionInfo ¶
func (r *Runtime) RefreshVersionInfo() *updatecheck.VersionInfo
RefreshVersionInfo performs an immediate update check and returns the result. Returns nil if the update checker has not been initialized.
func (*Runtime) ReloadConfiguration ¶
ReloadConfiguration reloads the configuration from disk and resyncs state.
func (*Runtime) ReplayToolCall ¶
func (r *Runtime) ReplayToolCall(ctx context.Context, id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)
ReplayToolCall replays a tool call with modified arguments.
ctx is the CALLER's context (the HTTP request's). It governs the whole replay, including the wait for a concurrency slot: a client that disconnects mid-queue releases the slot immediately instead of leaving a call queued for a caller that is gone (FR-005).
func (*Runtime) ResolveWorkSession ¶ added in v0.49.0
func (r *Runtime) ResolveWorkSession(id WorkSessionIdentity) string
ResolveWorkSession derives the work session for an identity, opening a new one when it has been idle past the window. Called once per connection.
func (*Runtime) RestartServer ¶
RestartServer restarts an upstream server by disconnecting and reconnecting it. Validation and disconnect are synchronous; reconnection and reindexing happen asynchronously so the caller (HTTP handler) returns immediately.
func (*Runtime) SaveConfiguration ¶
SaveConfiguration persists the runtime configuration to disk.
func (*Runtime) SaveOnboardingState ¶ added in v0.29.0
func (r *Runtime) SaveOnboardingState(state *storage.OnboardingState) error
SaveOnboardingState persists the wizard engagement state (Spec 046).
func (*Runtime) SearchRegistryServers ¶
func (r *Runtime) SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, *contracts.RegistryCacheInfo, error)
SearchRegistryServers searches for servers in a specific registry (Phase 7). Results are cached per (registry, tag, query, limit) via the cache manager; a cached list is served while flagging its freshness (FR-007), and the returned *contracts.RegistryCacheInfo carries the age/stale indicator. A registry that requires an unconfigured API key surfaces as a wrapped registries.ErrRegistryKeyMissing so the caller can mark it unavailable without failing the overall search (FR-008).
func (*Runtime) ServedRoutingMode ¶ added in v0.63.0
ServedRoutingMode returns the mode /mcp is actually serving, or "" before the server has bound one.
func (*Runtime) SetAllToolsEnabled ¶ added in v0.31.0
func (r *Runtime) SetAllToolsEnabled(serverName string, enabled bool, updatedBy string) (int, error)
SetAllToolsEnabled bulk-toggles every tool currently known for a server to the given enabled state. Returns the count of tools whose state was changed (i.e. excluding tools already in the desired state).
Tool inventory comes from the StateView when available (so it covers tools the user has seen even if not yet indexed) and falls back to the search index. Tools without an approval record get one synthesized — see setToolEnabledNoEmit for the rationale.
SSE emission: the loop calls setToolEnabledNoEmit (no per-tool servers.changed). A single trailing emitServersChanged fires after the loop when at least one tool actually flipped, mirroring the ApproveAllTools pattern. With the lazy-build coalescer (Spec 047 §B2 + PR #463) the bulk operation pays exactly one payload build no matter how many tools changed.
func (*Runtime) SetManagementService ¶
func (r *Runtime) SetManagementService(svc management.Service)
SetManagementService stores the management service instance. It is called after runtime initialization because the service is CONSTRUCTED on top of the Runtime (it takes one as its RuntimeOperations), not because of an import cycle — internal/management does not import internal/runtime.
func (*Runtime) SetRefreshMetricsRecorder ¶ added in v0.16.0
func (r *Runtime) SetRefreshMetricsRecorder(recorder oauth.RefreshMetricsRecorder)
SetRefreshMetricsRecorder sets the metrics recorder for OAuth token refresh operations. This enables FR-011: OAuth refresh metrics emission.
func (*Runtime) SetRejectionMetricSink ¶ added in v0.54.0
func (r *Runtime) SetRejectionMetricSink(sink RejectionMetricSink)
SetRejectionMetricSink installs the synchronous rejection counter (spec 093 FR-013). Passing nil detaches it.
func (*Runtime) SetRunning ¶
SetRunning records whether the server HTTP layer is active.
func (*Runtime) SetServedRoutingMode ¶ added in v0.63.0
SetServedRoutingMode records the routing mode /mcp bound at startup. Called once, from the server as it registers the handler.
func (*Runtime) SetServerShared ¶ added in v0.66.1
SetServerShared commits sharing against the current configuration and publishes it before returning. A successful unshare must not leave a file watcher delay in which existing credentials can still reach the server.
func (*Runtime) SetSessionClientResolver ¶ added in v0.49.0
func (r *Runtime) SetSessionClientResolver(resolver SessionClientResolver)
SetSessionClientResolver wires the session -> MCP client lookup that stamps client_name / client_version onto every activity record at write time. No-op if the activity service is not wired.
func (*Runtime) SetTelemetry ¶ added in v0.22.0
SetTelemetry initializes the telemetry service with the given version and edition. This should be called once during server startup.
func (*Runtime) SetToolEnabled ¶ added in v0.29.3
SetToolEnabled sets whether a tool is enabled for exposure to MCP clients. Thin wrapper over setToolEnabledNoEmit that adds the per-toggle SSE servers.changed emit so single-tool consumers (CLI, REST) see the state transition without polling. The emit is skipped when the call was a no-op (already in the desired state) to avoid wasted SSE traffic.
func (*Runtime) SetVersion ¶
SetVersion initializes the update checker with the given version. This should be called once during server startup with the build version.
func (*Runtime) SetWorkSessionResolver ¶ added in v0.49.0
func (r *Runtime) SetWorkSessionResolver(resolver SessionWorkSessionResolver)
SetWorkSessionResolver wires the session -> work-session lookup used to stamp every activity record (Spec 082).
The resolver reads the id CACHED on the connection rather than re-deriving it. Re-deriving per record would let one connection's records disagree: the first resolves before the client's project has arrived, the second after.
func (*Runtime) SignatureCache ¶ added in v0.51.0
SignatureCache exposes the process-wide compact-signature cache (Spec 085 FR-008). Exactly one instance exists: the indexing path warms it and the MCP request path (via NewMCPProxyServer) reads it. Never construct a second cache — warming a cache the request path does not hold is a silent no-op.
func (*Runtime) StartBackgroundInitialization ¶
func (r *Runtime) StartBackgroundInitialization()
StartBackgroundInitialization kicks off configuration sync and background loops.
func (*Runtime) StatusChannel ¶
StatusChannel exposes the status updates stream.
func (*Runtime) StatusSnapshot ¶
StatusSnapshot returns the latest status as a map for API responses. The serverRunning parameter should come from the authoritative server running state.
func (*Runtime) StorageManager ¶
StorageManager exposes the storage manager.
func (*Runtime) StoredOAuthTokenInPlay ¶ added in v0.66.0
func (r *Runtime) StoredOAuthTokenInPlay(name string, cfg *config.ServerConfig) bool
StoredOAuthTokenInPlay reports whether a record in the oauth_tokens bucket (and the RefreshManager schedule built from it) is evidence about the named server's authentication state (GH #1172).
It is not when the server has no `oauth` block and carries a static Authorization header: the headers-auth strategy runs first and OAuth is never attempted while it works, and OAuth would populate that very header, so a token left behind by an earlier OAuth login (autodiscovery servers have no `oauth` block whose removal could have cleared it) is stale. Consulting it used to report a connected, tool-serving upstream as unhealthy / "Token expired" / login for as long as the record existed, and its failed refresh schedule as "Refresh token expired". The record is left alone (logout still removes it); it is simply not consulted.
The live connection has the final say: if the configured header was rejected and the OAuth strategy rescued the connection with that very token, the token IS in play and is reported as for any other OAuth server. A nil config (server known only to the state view) keeps the historical behaviour of consulting the record.
func (*Runtime) StreamActivities ¶
func (r *Runtime) StreamActivities(filter storage.ActivityFilter) <-chan *storage.ActivityRecord
StreamActivities returns a channel that yields activity records matching the filter.
func (*Runtime) SubscribeEvents ¶
SubscribeEvents registers a new subscriber and returns a channel that will receive runtime events. Callers must not close the returned channel; use UnsubscribeEvents when finished.
func (*Runtime) Supervisor ¶
func (r *Runtime) Supervisor() *supervisor.Supervisor
Supervisor returns the supervisor instance for lock-free state reads via StateView. Phase 6: Provides access to fast server status without storage queries.
func (*Runtime) TelemetryRegistry ¶ added in v0.24.0
func (r *Runtime) TelemetryRegistry() *telemetry.CounterRegistry
TelemetryRegistry returns the Tier 2 counter registry, or nil if telemetry has not been initialized yet. Callers can record events without nil-checking — use telemetry.RecordSurfaceOn(reg, ...) which is nil-safe.
func (*Runtime) TelemetryService ¶ added in v0.22.0
TelemetryService returns the telemetry service instance.
func (*Runtime) TriggerOAuthLogin ¶
TriggerOAuthLogin implements RuntimeOperations interface for management service. Initiates OAuth 2.x authentication flow for a specific server.
func (*Runtime) TriggerOAuthLoginQuick ¶
func (r *Runtime) TriggerOAuthLoginQuick(serverName string) (*core.OAuthStartResult, error)
TriggerOAuthLoginQuick implements RuntimeOperations interface for management service. Returns OAuthStartResult with actual browser status, auth URL, and any errors. This is the synchronous version that provides immediate feedback about browser opening.
func (*Runtime) TriggerOAuthLogout ¶
TriggerOAuthLogout implements RuntimeOperations interface for management service. Clears OAuth token and disconnects a specific server.
func (*Runtime) Truncator ¶
Truncator exposes the current tool-response truncator. It is safe to call concurrently with a config hot-reload that swaps the truncator (#861): the field is an atomic.Pointer, so the read never tears against the swap. Callers on the serving path MUST call this at use time rather than caching the returned pointer, so a hot-reloaded tool_response_limit takes effect.
func (*Runtime) UnsubscribeEvents ¶
UnsubscribeEvents removes the subscriber and closes the channel.
func (*Runtime) UpdateConfig ¶
UpdateConfig replaces the runtime configuration in-place. This now updates both the legacy field and the ConfigService.
func (*Runtime) UpdateListenAddress ¶
UpdateListenAddress mutates the in-memory listen address used by the runtime.
func (*Runtime) UpdatePhase ¶
UpdatePhase gathers runtime metrics and broadcasts a status update.
func (*Runtime) UpdatePhaseMessage ¶
UpdatePhaseMessage refreshes the status message without moving to a new phase.
func (*Runtime) UpdatePolicy ¶ added in v0.54.0
func (r *Runtime) UpdatePolicy() updatecheck.Policy
UpdatePolicy returns the effective update policy (Spec 092 FR-015): the kill-switch state, the release channel, and whether UI nudges are suppressed. Without an update checker automatic checking cannot happen at all, which is reported as an explicit disabled policy rather than as missing data.
func (*Runtime) UpdateStatus ¶
func (r *Runtime) UpdateStatus(phase Phase, message string, stats map[string]interface{}, toolsIndexed int)
UpdateStatus mutates the status object and notifies subscribers.
func (*Runtime) UpstreamManager ¶
UpstreamManager exposes the upstream manager.
func (*Runtime) UsageSnapshot ¶ added in v0.36.0
func (r *Runtime) UsageSnapshot() *UsageAggregate
UsageSnapshot returns the actor-owned in-memory usage aggregate snapshot (spec 069 A2/A3). Reads are lock-free; the returned value is immutable and must be treated as read-only. Returns nil when the activity service is unavailable.
func (*Runtime) ValidateConfig ¶
ValidateConfig validates a configuration without applying it
type SensitiveDataEventEmitter ¶ added in v0.17.0
type SensitiveDataEventEmitter interface {
// EmitSensitiveDataDetected emits an event when sensitive data is detected.
EmitSensitiveDataDetected(activityID string, detectionCount int, maxSeverity string, detectionTypes []string, serverName string)
}
SensitiveDataEventEmitter provides the ability to emit sensitive data detection events. This interface is implemented by Runtime to enable event emission from ActivityService.
type SessionClientResolver ¶ added in v0.49.0
SessionClientResolver maps an MCP session id to the client that opened it (clientInfo.name / clientInfo.version from the initialize handshake). Returns empty strings when the session is unknown.
type SessionWorkSessionResolver ¶ added in v0.49.0
SessionWorkSessionResolver maps an MCP session id to the WORK session it belongs to (Spec 082): one client, one project, across reconnects.
It returns the id cached on the connection — deliberately not a fresh derivation, so every record from one connection agrees on its work session.
type Status ¶
type Status struct {
Phase Phase `json:"phase"`
Message string `json:"message"`
UpstreamStats map[string]interface{} `json:"upstream_stats"`
ToolsIndexed int `json:"tools_indexed"`
LastUpdated time.Time `json:"last_updated"`
}
Status captures high-level state for API consumers.
type TimeBucket ¶ added in v0.35.0
type TimeBucket struct {
Start time.Time `json:"start"`
Calls int64 `json:"calls"`
Errors int64 `json:"errors"`
RespBytesSum int64 `json:"resp_bytes_sum"`
}
TimeBucket is a pre-bucketed slice of call volume over time for the timeline.
type ToolApprovalResult ¶ added in v0.21.0
type ToolApprovalResult struct {
// BlockedTools is the set of tool names that should not be indexed (pending, changed, or disabled).
BlockedTools map[string]bool
// PendingCount is the number of newly discovered tools awaiting approval.
PendingCount int
// ChangedCount is the number of tools whose description/schema changed since approval.
ChangedCount int
}
ToolApprovalResult contains the result of checking tool approvals for a server.
type ToolUsage ¶ added in v0.35.0
type ToolUsage struct {
Server string `json:"server"`
Tool string `json:"tool"`
Calls int64 `json:"calls"`
Errors int64 `json:"errors"`
Blocked int64 `json:"blocked"`
Rejected int64 `json:"rejected"` // spec 093: shed by a concurrency limit, never executed
ReqBytesSum int64 `json:"req_bytes_sum"`
RespBytesSum int64 `json:"resp_bytes_sum"`
SizedReqCalls int64 `json:"sized_req_calls"` // calls with RequestBytes>0
SizedRespCalls int64 `json:"sized_resp_calls"` // calls with ResponseBytes>0
LatencyBuckets []int64 `json:"latency_buckets"` // len == numLatencyBuckets()
LastUsed time.Time `json:"last_used"`
}
ToolUsage is a per-(server,tool) incremental rollup.
func (*ToolUsage) AvgReqBytes ¶ added in v0.35.0
AvgReqBytes returns the average request size over sized calls only (records with RequestBytes>0). ok is false when there are no sized calls.
func (*ToolUsage) AvgRespBytes ¶ added in v0.35.0
AvgRespBytes returns the average response size over sized calls only (records with ResponseBytes>0). ok is false when there are no sized calls.
func (*ToolUsage) ErrorRate ¶ added in v0.35.0
ErrorRate returns Errors/Calls (0 when there are no calls).
func (*ToolUsage) Percentile ¶ added in v0.35.0
Percentile returns an approximate latency percentile (in ms) derived from the fixed latency histogram. p is in [0,1].
ms is the upper BOUND of the bucket the percentile falls in, never a measured duration — the true value is somewhere at or below it. exceeds reports the one case where that reading inverts: the overflow bucket has no upper bound, so its ms is the last bound and the true value is ABOVE it. Callers must render the two differently ("≤ 5 ms" vs "> 10 s"); printing the number bare is how a bucketed estimate came to be read as a measurement (F22, #1046).
An empty histogram returns (0, false): no calls, nothing to bound.
type TransitionReason ¶ added in v0.23.1
type TransitionReason string
TransitionReason explains why a tool approval state transition is occurring.
const ( ReasonHashMatch TransitionReason = "hash_match" ReasonDescriptionRevert TransitionReason = "description_revert" ReasonFormulaMigration TransitionReason = "formula_migration" ReasonContentMatch TransitionReason = "content_match" ReasonDescriptionMatch TransitionReason = "description_match" ReasonUserApprove TransitionReason = "user_approve" ReasonAutoApprove TransitionReason = "auto_approve" // ReasonBaselineTrust marks promotion of a never-reviewed (pending) tool to // approved because the server is trusted (non-quarantined) and has no prior // approved baseline yet — the current toolset IS the baseline (MCP-2931). ReasonBaselineTrust TransitionReason = "baseline_trust" // ReasonAutoApproveChanges marks promotion driven by the explicit per-server // auto_approve_tool_changes flag (MCP-2931/MCP-2930). It is the ONLY reason, // besides explicit user action, that may clear a changed (rug-pull) record — // because the operator opted into auto-approving changes for that server. ReasonAutoApproveChanges TransitionReason = "auto_approve_changes" // ReasonScanApproved marks a change/addition auto-approved because the server // runs in trust_mode: scan AND a synchronous, offline TPA scan of the changed // tool returned a green (clean) verdict (spec 086 stage 2). Like // ReasonAutoApproveChanges it may clear a changed (rug-pull) record, but only // with the scanner's positive attestation — a non-green or degraded/absent // verdict never reaches this reason (the gate fails closed before it). ReasonScanApproved TransitionReason = "scan_approved" )
type UsageAggregate ¶ added in v0.35.0
type UsageAggregate struct {
Tools map[string]*ToolUsage `json:"tools"`
Buckets map[int64]*TimeBucket `json:"buckets"` // key = bucket start unix seconds
UpdatedAt time.Time `json:"updated_at"`
// AdmissionVersion stamps which population rule built this aggregate. A
// persisted snapshot whose stamp differs from usageAdmissionVersion was
// counted under a different rule and cannot be patched incrementally —
// the loader discards it and rebuilds from a full activity scan instead.
AdmissionVersion int `json:"admission_version,omitempty"`
}
UsageAggregate is the actor-owned rollup. Exported fields are JSON-serialized for persistence; unexported config fields are restored on construction.
func (*UsageAggregate) Apply ¶ added in v0.35.0
func (a *UsageAggregate) Apply(rec *storage.ActivityRecord)
Apply folds a single activity record into the aggregate. Apply is not safe for concurrent use; it is called only by the owning goroutine (see UsageStore).
Two populations live in here and they are NOT the same:
- the per-tool rollup (ToolUsage) describes UPSTREAM TOOLS: calls, latency percentiles, byte averages, blocked and shed attempts. Only records that name an upstream tool belong in it.
- the timeline (TimeBucket) describes WHAT THE USER SAW. It must match the glance row-for-row, or the bars under the list disagree with the list above them — the single most confusing thing a dashboard can do.
Which records reach the timeline is NOT decided here: it is storage.CountsAsCall, the one definition of "a call the user made", shared with the Activity Log's own counters so the two surfaces cannot drift apart (audit finding F1, #1046). Apply only decides what each admitted record does to the PER-TOOL rollup, which is a narrower population — upstream tools only.
func (*UsageAggregate) Timeline ¶ added in v0.35.0
func (a *UsageAggregate) Timeline() []TimeBucket
Timeline returns the time buckets in chronological order.
type UsageStore ¶ added in v0.35.0
type UsageStore struct {
// contains filtered or unexported fields
}
UsageStore owns the working aggregate and publishes immutable snapshots via an atomic pointer (copy-on-write).
Spec 069 / MCP-835: the activity write path must stay O(1) and must not block. Apply therefore folds the record into the working aggregate under a short writer lock and only marks the published snapshot stale — it does NOT clone. The O(tools×buckets) clone is deferred to Snapshot (publish-on-read): the first reader after a burst of writes materializes one fresh snapshot; the owning activity goroutine never pays the clone cost on the hot path. Reads with no pending writes are lock-free (atomic load); the A3 endpoint and the 30s persist flush are the only readers, so clones are rare relative to writes.
func (*UsageStore) Apply ¶ added in v0.35.0
func (s *UsageStore) Apply(rec *storage.ActivityRecord)
Apply folds a record into the working aggregate. O(1): it mutates under the writer lock and marks the snapshot stale, but never clones on the hot path.
func (*UsageStore) Replace ¶ added in v0.35.0
func (s *UsageStore) Replace(agg *UsageAggregate)
Replace swaps in a freshly built aggregate (cold-start load or rebuild). The new snapshot is materialized lazily on the next read, like Apply.
func (*UsageStore) Snapshot ¶ added in v0.35.0
func (s *UsageStore) Snapshot() *UsageAggregate
Snapshot returns the latest immutable aggregate snapshot reflecting all writes applied so far. When writes have occurred since the last publish it materializes one fresh snapshot here (the clone runs off the activity hot path); otherwise it is a lock-free atomic load. The returned value must be treated as read-only.
type WorkSessionIdentity ¶ added in v0.49.0
type WorkSessionIdentity struct {
// Principal is the authenticated identity (agent token subject / API key).
// Empty when the proxy is used unauthenticated.
Principal string
// ClientName / ClientVersion come from the MCP clientInfo.
ClientName string
ClientVersion string
// WorkspaceRoot is the project the client is working in, as it disclosed
// via MCP roots. Empty for clients that do not disclose it — measured:
// Claude Code, Gemini and opencode do; Codex does not.
WorkspaceRoot string
// CorrelationID is a client-supplied conversation id. No MCP client offers
// one today (Claude Code has a conversation UUID but does not send it), so
// this is always empty for now. When a client finally does, it OVERRIDES the
// derivation below and the grouping stops being a heuristic.
CorrelationID string
}
WorkSessionIdentity is everything we know about who is doing the work. Every field is optional — the derivation degrades rather than failing.
type WorkSessionTracker ¶ added in v0.49.0
type WorkSessionTracker struct {
// contains filtered or unexported fields
}
WorkSessionTracker maps an identity to a stable work-session id, opening a new one when the idle window lapses. Safe for concurrent use.
func NewWorkSessionTracker ¶ added in v0.49.0
func NewWorkSessionTracker(idleWindow time.Duration) *WorkSessionTracker
NewWorkSessionTracker returns a tracker with the given idle window. A zero or negative window falls back to the default.
func (*WorkSessionTracker) Reap ¶ added in v0.49.0
func (t *WorkSessionTracker) Reap(maxIdle time.Duration) int
Reap drops work sessions idle for more than maxIdle, so the tracker cannot grow without bound on a long-lived proxy.
func (*WorkSessionTracker) Resolve ¶ added in v0.49.0
func (t *WorkSessionTracker) Resolve(id WorkSessionIdentity) string
Resolve returns the work-session id for this activity, opening a new one when the identity is unseen or its previous activity is older than the idle window.
Returns "" when we know nothing about the caller: an unattributable record is better left unattributed than grouped into a bucket that means nothing.
func (*WorkSessionTracker) SetIdleWindow ¶ added in v0.49.0
func (t *WorkSessionTracker) SetIdleWindow(d time.Duration)
SetIdleWindow updates the idle window (hot-reloadable config).
Source Files
¶
- activity_preflight.go
- activity_service.go
- concurrency_rejections.go
- config_hotreload.go
- config_load_admission_gate.go
- config_watcher.go
- event_bus.go
- events.go
- isolation_projection.go
- lifecycle.go
- phase.go
- profile_index.go
- prompts_refresh.go
- restart_gated.go
- runtime.go
- scan_notify.go
- server_sharing.go
- tool_quarantine.go
- usage_aggregate.go
- usage_service.go
- worksession.go