Documentation
¶
Index ¶
- Constants
- Variables
- func CountsAsCall(rec *ActivityRecord) (counted, isError bool)
- func GenerateServerID(server *config.ServerConfig) string
- func GenerateServerIDFromAttributes(attrs ServerAttributes) string
- func IsManagementBuiltin(rec *ActivityRecord) bool
- func PromptApprovalKey(serverName, promptName string) string
- func ToolApprovalKey(serverName, toolName string) string
- func TruncateActivityResponse(response string, maxSize int) (string, bool)
- type ActivityFilter
- type ActivityRecord
- type ActivitySource
- type ActivityType
- type AsyncManager
- func (am *AsyncManager) DeleteServerAsync(name string)
- func (am *AsyncManager) EnableServerAsync(name string, enabled bool)
- func (am *AsyncManager) EnableServerSync(name string, enabled bool) error
- func (am *AsyncManager) QuarantineServerAsync(name string, quarantined bool)
- func (am *AsyncManager) QuarantineServerSync(name string, quarantined bool) error
- func (am *AsyncManager) SaveServerAsync(serverConfig *config.ServerConfig)
- func (am *AsyncManager) Start()
- func (am *AsyncManager) Stop()
- type BaselineSweepState
- type BoltDB
- func (b *BoltDB) Backup(destPath string) error
- func (s *BoltDB) CleanupOldOAuthCompletionEvents() error
- func (b *BoltDB) ClearOAuthClientCredentials(serverKey string) error
- func (b *BoltDB) Close() error
- func (b *BoltDB) DeleteIntegrityBaseline(serverName string) error
- func (b *BoltDB) DeleteOAuthToken(serverName string) error
- func (b *BoltDB) DeletePromptApproval(serverName, promptName string) error
- func (b *BoltDB) DeleteScanJob(id string) error
- func (b *BoltDB) DeleteScanReport(id string) error
- func (b *BoltDB) DeleteScanner(id string) error
- func (b *BoltDB) DeleteServerPromptApprovals(serverName string) error
- func (b *BoltDB) DeleteServerScanJobs(serverName string) error
- func (b *BoltDB) DeleteServerScanReports(serverName string) error
- func (b *BoltDB) DeleteServerToolApprovals(serverName string) error
- func (b *BoltDB) DeleteToolApproval(serverName, toolName string) error
- func (b *BoltDB) DeleteToolHash(toolName string) error
- func (b *BoltDB) DeleteUpstream(id string) error
- func (b *BoltDB) GetIntegrityBaseline(serverName string) (*scanner.IntegrityBaseline, error)
- func (b *BoltDB) GetLatestScanJob(serverName string) (*scanner.ScanJob, error)
- func (b *BoltDB) GetOAuthClientCredentials(serverKey string) (clientID, clientSecret string, callbackPort int, err error)
- func (b *BoltDB) GetOAuthToken(serverName string) (*OAuthTokenRecord, error)
- func (b *BoltDB) GetOnboardingState() (*OnboardingState, error)
- func (b *BoltDB) GetPromptApproval(serverName, promptName string) (*PromptApprovalRecord, error)
- func (b *BoltDB) GetScanJob(id string) (*scanner.ScanJob, error)
- func (b *BoltDB) GetScanReport(id string) (*scanner.ScanReport, error)
- func (b *BoltDB) GetScanner(id string) (*scanner.ScannerPlugin, error)
- func (b *BoltDB) GetSchemaVersion() (uint64, error)
- func (b *BoltDB) GetToolApproval(serverName, toolName string) (*ToolApprovalRecord, error)
- func (b *BoltDB) GetToolApprovals(serverName string, toolNames ...string) (map[string]*ToolApprovalRecord, error)
- func (b *BoltDB) GetToolHash(toolName string) (string, error)
- func (b *BoltDB) GetToolStats(toolName string) (*ToolStatRecord, error)
- func (s *BoltDB) GetUnprocessedOAuthCompletionEvents() ([]*OAuthCompletionEvent, error)
- func (b *BoltDB) GetUpstream(id string) (*UpstreamRecord, error)
- func (b *BoltDB) IncrementToolStats(toolName string) error
- func (b *BoltDB) ListIntegrityBaselines() ([]*scanner.IntegrityBaseline, error)
- func (b *BoltDB) ListOAuthTokens() ([]*OAuthTokenRecord, error)
- func (b *BoltDB) ListPromptApprovals(serverName string) ([]*PromptApprovalRecord, error)
- func (b *BoltDB) ListScanJobMetas(serverName string) ([]*scanner.ScanJobMeta, error)
- func (b *BoltDB) ListScanJobs(serverName string) ([]*scanner.ScanJob, error)
- func (b *BoltDB) ListScanReports(serverName string) ([]*scanner.ScanReport, error)
- func (b *BoltDB) ListScanReportsByJob(jobID string) ([]*scanner.ScanReport, error)
- func (b *BoltDB) ListScanners() ([]*scanner.ScannerPlugin, error)
- func (b *BoltDB) ListToolApprovals(serverName string) ([]*ToolApprovalRecord, error)
- func (b *BoltDB) ListToolStats() ([]*ToolStatRecord, error)
- func (b *BoltDB) ListUpstreams() ([]*UpstreamRecord, error)
- func (s *BoltDB) MarkOAuthCompletionEventProcessed(serverName string, completedAt time.Time) error
- func (b *BoltDB) PruneToolApprovalsNotIn(keep map[string]bool) (int, error)
- func (b *BoltDB) SaveIntegrityBaseline(baseline *scanner.IntegrityBaseline) error
- func (s *BoltDB) SaveOAuthCompletionEvent(event *OAuthCompletionEvent) error
- func (b *BoltDB) SaveOAuthToken(record *OAuthTokenRecord) error
- func (b *BoltDB) SaveOnboardingState(state *OnboardingState) error
- func (b *BoltDB) SavePromptApproval(record *PromptApprovalRecord) error
- func (b *BoltDB) SaveScanJob(job *scanner.ScanJob) error
- func (b *BoltDB) SaveScanReport(report *scanner.ScanReport) error
- func (b *BoltDB) SaveScanner(s *scanner.ScannerPlugin) error
- func (b *BoltDB) SaveToolApproval(record *ToolApprovalRecord) error
- func (b *BoltDB) SaveToolHash(toolName, hash string) error
- func (b *BoltDB) SaveUpstream(record *UpstreamRecord) error
- func (b *BoltDB) SetSchemaVersion(version uint64) error
- func (b *BoltDB) Stats() (*bbolt.Stats, error)
- func (b *BoltDB) UpdateOAuthClientCredentials(serverKey, clientID, clientSecret string, callbackPort int) error
- type DatabaseLockedError
- type DiagnosticRecord
- type DockerRecoveryState
- type EnableServerData
- type Manager
- func (m *Manager) AddUpstream(serverConfig *config.ServerConfig) (string, error)
- func (m *Manager) AggregateToolUsage(since time.Time) (map[string]ToolUsageStat, error)
- func (m *Manager) Backup(destPath string) error
- func (m *Manager) CleanupOrphanedOAuthTokens(validServerNames []string) (int, error)
- func (m *Manager) CleanupStaleServerData(threshold time.Duration) error
- func (m *Manager) ClearDockerRecoveryState() error
- func (m *Manager) ClearOAuthState(serverName string) error
- func (m *Manager) Close() error
- func (m *Manager) CloseAllActiveSessions() error
- func (m *Manager) CloseInactiveSessions(inactivityTimeout time.Duration) (int, error)
- func (m *Manager) CloseSession(sessionID string) error
- func (m *Manager) CountActivities() (int, error)
- func (m *Manager) CreateAgentToken(token auth.AgentToken, rawToken string, hmacKey []byte) error
- func (m *Manager) CreateSession(session *SessionRecord) error
- func (m *Manager) DeleteActivity(id string) error
- func (m *Manager) DeleteAgentToken(name string) error
- func (m *Manager) DeleteAgentTokenForOwner(userID, name string) error
- func (m *Manager) DeleteIntegrityBaseline(serverName string) error
- func (m *Manager) DeletePromptApproval(serverName, promptName string) error
- func (m *Manager) DeleteScanJob(id string) error
- func (m *Manager) DeleteScanReport(id string) error
- func (m *Manager) DeleteScanner(id string) error
- func (m *Manager) DeleteServerPromptApprovals(serverName string) error
- func (m *Manager) DeleteServerScanJobs(serverName string) error
- func (m *Manager) DeleteServerScanReports(serverName string) error
- func (m *Manager) DeleteServerToolApprovals(serverName string) error
- func (m *Manager) DeleteToolApproval(serverName, toolName string) error
- func (m *Manager) DeleteToolHash(toolName string) error
- func (m *Manager) DeleteUpstreamServer(name string) error
- func (m *Manager) EnableUpstreamServer(name string, enabled bool) error
- func (m *Manager) GetActivity(id string) (*ActivityRecord, error)
- func (m *Manager) GetActivityByIDScan(id string) (*ActivityRecord, error)
- func (m *Manager) GetAgentTokenByHash(hash string) (*auth.AgentToken, error)
- func (m *Manager) GetAgentTokenByName(name string) (*auth.AgentToken, error)
- func (m *Manager) GetAgentTokenByOwnerAndName(userID, name string) (*auth.AgentToken, error)
- func (m *Manager) GetAgentTokenCount() (int, error)
- func (m *Manager) GetBoltDB() *BoltDB
- func (m *Manager) GetDB() *bbolt.DB
- func (m *Manager) GetIntegrityBaseline(serverName string) (*scanner.IntegrityBaseline, error)
- func (m *Manager) GetLatestScanJob(serverName string) (*scanner.ScanJob, error)
- func (m *Manager) GetOAuthToken(serverName string) (*OAuthTokenRecord, error)
- func (m *Manager) GetOnboardingState() (*OnboardingState, error)
- func (m *Manager) GetPromptApproval(serverName, promptName string) (*PromptApprovalRecord, error)
- func (m *Manager) GetRecentSessions(limit int, status string) ([]*SessionRecord, int, error)
- func (m *Manager) GetScanJob(id string) (*scanner.ScanJob, error)
- func (m *Manager) GetScanReport(id string) (*scanner.ScanReport, error)
- func (m *Manager) GetScanner(id string) (*scanner.ScannerPlugin, error)
- func (m *Manager) GetSchemaVersion() (uint64, error)
- func (m *Manager) GetServerDiagnostics(serverID string, limit int) ([]*DiagnosticRecord, error)
- func (m *Manager) GetServerIdentity(server *config.ServerConfig) (*ServerIdentity, error)
- func (m *Manager) GetServerIdentityByID(serverID string) (*ServerIdentity, error)
- func (m *Manager) GetServerStatistics(serverID string) (*ServerStatistics, error)
- func (m *Manager) GetServerToolCalls(serverID string, limit int) ([]*ToolCallRecord, error)
- func (m *Manager) GetSessionByID(sessionID string) (*SessionRecord, error)
- func (m *Manager) GetStats() (map[string]interface{}, error)
- func (m *Manager) GetToolApproval(serverName, toolName string) (*ToolApprovalRecord, error)
- func (m *Manager) GetToolApprovals(serverName string, toolNames ...string) (map[string]*ToolApprovalRecord, error)
- func (m *Manager) GetToolCallsBySession(sessionID string, limit, offset int, scope ToolCallScope) ([]*ToolCallRecord, int, error)
- func (m *Manager) GetToolHash(toolName string) (string, error)
- func (m *Manager) GetToolStatistics(topN int) (*config.ToolStats, error)
- func (m *Manager) GetToolStats(topN int) ([]map[string]interface{}, error)
- func (m *Manager) GetToolUsage(toolName string) (*ToolStatRecord, error)
- func (m *Manager) GetUpstreamServer(name string) (*config.ServerConfig, error)
- func (m *Manager) HasToolChanged(toolName, currentHash string) (bool, error)
- func (m *Manager) IncrementToolUsage(toolName string) error
- func (m *Manager) ListActivities(filter ActivityFilter) ([]*ActivityRecord, int, error)
- func (m *Manager) ListAgentTokens() ([]auth.AgentToken, error)
- func (m *Manager) ListIntegrityBaselines() ([]*scanner.IntegrityBaseline, error)
- func (m *Manager) ListOAuthTokens() ([]*OAuthTokenRecord, error)
- func (m *Manager) ListPromptApprovals(serverName string) ([]*PromptApprovalRecord, error)
- func (m *Manager) ListQuarantinedTools(serverName string) ([]map[string]interface{}, error)
- func (m *Manager) ListQuarantinedUpstreamServers() ([]*config.ServerConfig, error)
- func (m *Manager) ListScanJobMetas(serverName string) ([]*scanner.ScanJobMeta, error)
- func (m *Manager) ListScanJobs(serverName string) ([]*scanner.ScanJob, error)
- func (m *Manager) ListScanReports(serverName string) ([]*scanner.ScanReport, error)
- func (m *Manager) ListScanReportsByJob(jobID string) ([]*scanner.ScanReport, error)
- func (m *Manager) ListScanners() ([]*scanner.ScannerPlugin, error)
- func (m *Manager) ListServerIdentities() ([]*ServerIdentity, error)
- func (m *Manager) ListToolApprovals(serverName string) ([]*ToolApprovalRecord, error)
- func (m *Manager) ListUpstreamServers() ([]*config.ServerConfig, error)
- func (m *Manager) ListUpstreams() ([]*config.ServerConfig, error)
- func (m *Manager) LoadBaselineSweepState() (*BaselineSweepState, error)
- func (m *Manager) LoadDockerRecoveryState() (*DockerRecoveryState, error)
- func (m *Manager) LoadUsageSnapshot() ([]byte, error)
- func (m *Manager) PruneActivitiesToSize(maxBytes int64) (int, error)
- func (m *Manager) PruneExcessActivities(maxRecords int, targetPercent float64) (int, error)
- func (m *Manager) PruneOldActivities(maxAge time.Duration) (int, error)
- func (m *Manager) PruneOrphanToolApprovals(configuredServers []string) (int, error)
- func (m *Manager) PruneOrphanToolCalls(configuredServers []string) (int, error)
- func (m *Manager) QuarantineUpstreamServer(name string, quarantined bool) error
- func (m *Manager) RecordServerDiagnostic(record *DiagnosticRecord) error
- func (m *Manager) RecordToolCall(record *ToolCallRecord) error
- func (m *Manager) RegenerateAgentToken(name string, newRawToken string, hmacKey []byte) (*auth.AgentToken, error)
- func (m *Manager) RegenerateAgentTokenForOwner(userID, name string, newRawToken string, hmacKey []byte, ...) (*auth.AgentToken, error)
- func (m *Manager) RegisterServerIdentity(server *config.ServerConfig, configPath string) (*ServerIdentity, error)
- func (m *Manager) RemoveUpstream(id string) error
- func (m *Manager) RevokeAgentToken(name string) error
- func (m *Manager) RevokeAgentTokenForOwner(userID, name string) error
- func (m *Manager) RevokeAgentTokensForOwner(userID string) (int, error)
- func (m *Manager) SaveActivity(record *ActivityRecord) error
- func (m *Manager) SaveActivityAsync(record *ActivityRecord)
- func (m *Manager) SaveBaselineSweepState(state *BaselineSweepState) error
- func (m *Manager) SaveDockerRecoveryState(state *DockerRecoveryState) error
- func (m *Manager) SaveIntegrityBaseline(baseline *scanner.IntegrityBaseline) error
- func (m *Manager) SaveOnboardingState(state *OnboardingState) error
- func (m *Manager) SavePromptApproval(record *PromptApprovalRecord) error
- func (m *Manager) SaveScanJob(job *scanner.ScanJob) error
- func (m *Manager) SaveScanReport(report *scanner.ScanReport) error
- func (m *Manager) SaveScanner(s *scanner.ScannerPlugin) error
- func (m *Manager) SaveToolApproval(record *ToolApprovalRecord) error
- func (m *Manager) SaveToolHash(toolName, hash string) error
- func (m *Manager) SaveUpstreamServer(serverConfig *config.ServerConfig) error
- func (m *Manager) SaveUsageSnapshot(data []byte) error
- func (m *Manager) ScanActivitiesAfter(since time.Time, visit func(*ActivityRecord)) error
- func (m *Manager) ScanAllActivities(visit func(*ActivityRecord)) error
- func (m *Manager) SetAgentTokenOwnerGate(gate agentTokenOwnerGate)
- func (m *Manager) SetAgentTokenScopeResolver(resolve agentTokenScopeResolver)
- func (m *Manager) SetSchemaVersion(version uint64) error
- func (m *Manager) SetSessionWorkspace(sessionID, workspaceRoot string) error
- func (m *Manager) SetToolCallLimits(maxResponseBytes, maxRecordsPerServer int)
- func (m *Manager) StopAsync()
- func (m *Manager) StreamActivities(filter ActivityFilter) <-chan *ActivityRecord
- func (m *Manager) UpdateActivityMetadata(id string, updates map[string]interface{}) error
- func (m *Manager) UpdateAgentTokenLastUsed(name string) errordeprecated
- func (m *Manager) UpdateAgentTokenLastUsedByHash(hash string) error
- func (m *Manager) UpdateServerStatistics(stats *ServerStatistics) error
- func (m *Manager) UpdateSessionActivity(sessionID string) error
- func (m *Manager) UpdateSessionStats(sessionID string, tokens int) error
- func (m *Manager) UpdateUpstream(id string, serverConfig *config.ServerConfig) error
- func (m *Manager) ValidateAgentToken(rawToken string, hmacKey []byte) (*auth.AgentToken, error)
- type OAuthAttributes
- type OAuthCompletionEvent
- type OAuthTokenRecord
- type OnboardingState
- type Operation
- type PromptApprovalRecord
- type QuarantineServerData
- type QueueFullError
- type Result
- type ServerAttributes
- type ServerIdentity
- type ServerStatistics
- type SessionRecord
- type TimeoutError
- type TokenMetrics
- type ToolApprovalRecord
- type ToolCallRecord
- type ToolCallScope
- type ToolHashRecord
- type ToolStatRecord
- type ToolUsageStat
- type UnsupportedOperationError
- type UpstreamRecord
Constants ¶
const ( // ActivityStatusSuccess is a call the upstream answered normally. ActivityStatusSuccess = "success" // ActivityStatusError is a call that failed (transport, upstream error, or // an isError:true answer). ActivityStatusError = "error" // ActivityStatusBlocked is a call a policy prevented from running. ActivityStatusBlocked = "blocked" // ActivityStatusRejected is a call shed by a concurrency limiter before it // ever reached the upstream (spec 093). Distinct from "error" on purpose: // nothing went wrong upstream, the proxy applied backpressure. The record's // metadata carries rejection_reason (queue_full | queue_timeout) and // rejection_scope (server | global). ActivityStatusRejected = "rejected" )
Activity status vocabulary. Activity status is a CLOSED vocabulary: every consumer (filters, summaries, usage aggregation, exports, Web UI badges) switches on these values, so a new status has to be threaded through all of them — see spec 093 FR-012.
const ( // MetadataKeyRejectionReason is "queue_full" or "queue_timeout". MetadataKeyRejectionReason = "rejection_reason" // MetadataKeyRejectionScope is "server" or "global". MetadataKeyRejectionScope = "rejection_scope" // MetadataKeyRejectionLimit is the cap that was in force in that scope. MetadataKeyRejectionLimit = "rejection_limit" // MetadataKeyRejectionRetryAfterMs is the Retry-After hint in milliseconds. MetadataKeyRejectionRetryAfterMs = "rejection_retry_after_ms" )
Metadata keys carried by an ActivityStatusRejected record (spec 093 FR-012).
const ( // MetadataKeyPreflightVerdict is the set-level verdict // (ready|degraded_retryable|blocked|unknown_ids). MetadataKeyPreflightVerdict = "verdict" // MetadataKeyPreflightIDsCount is the number of unique tool ids evaluated. MetadataKeyPreflightIDsCount = "ids_count" // MetadataKeyPreflightReasons is a {reason_code: count} rollup over the // unavailable results — the shape a dashboard or CLI summary reads. MetadataKeyPreflightReasons = "reasons" // MetadataKeyPreflightPerTool is the ordered per-tool detail: // [{id, status, reason?}] using the PreflightPerTool* keys below. MetadataKeyPreflightPerTool = "per_tool" // MetadataKeyPreflightSurface names the surface that ran the preflight when // it is not the REST endpoint — currently only "mcp-check", the in-band // describe_tool check mode (spec 099 FR-013). It is OMITTED for the REST // surface, whose records predate it and stay byte-identical. MetadataKeyPreflightSurface = "surface" // MetadataKeyPreflightArguments records the in-band caller's request AS // SENT, so the raw requested-id count stays recoverable from the record // even though MetadataKeyPreflightIDsCount is the UNIQUE count both // surfaces agree on (spec 099 FR-013). It carries the PreflightArgumentsKey* // members below: still ids and enum-valued filter names, never descriptions // or upstream arguments. OMITTED for the REST surface, whose records // predate it and stay byte-identical. MetadataKeyPreflightArguments = "arguments" // Keys inside MetadataKeyPreflightArguments. // // PreflightArgumentsKeyToolIDs is the raw tool_ids array: request order, // untrimmed, duplicates intact — len() is the raw requested count. PreflightArgumentsKeyToolIDs = "tool_ids" // PreflightArgumentsKeyFilters lists the annotation filters that were in // effect, in the order describe_tool declares them. Absent when none were. PreflightArgumentsKeyFilters = "filters" // PreflightSurfaceMCPCheck marks a record written by describe_tool check // mode. It matches the `surface` value the spec-099 sabotage-matrix rows // carry, so a matrix row and an activity record name the surface the same // way. PreflightSurfaceMCPCheck = "mcp-check" // Keys inside one MetadataKeyPreflightPerTool entry. PreflightPerToolKeyID = "id" PreflightPerToolKeyStatus = "status" PreflightPerToolKeyReason = "reason" )
Metadata keys carried by an ActivityTypePreflight record (spec 098 FR-014, data-model.md "Activity record"). The payload is deliberately small and enum-only: reason CODES and counts, never tool descriptions or arguments.
const ( // ActivityStatsBucket holds derived activity statistics (usage aggregate // snapshot). Separate from the raw ActivityRecordsBucket. ActivityStatsBucket = "activity_stats" // UsageSnapshotKey is the schema-versioned key for the persisted usage // aggregate. Bumping the version suffix forces a clean rebuild rather than // mis-decoding an incompatible older shape. UsageSnapshotKey = "usage_aggregate_v1" )
const ( AgentTokensBucket = "agent_tokens" //nolint:gosec // bucket name, not a credential // AgentTokenNamesBucket is a LEGACY, owner-blind name->hash index keyed by // the bare token name. It is maintained only for tokens with no owner // (UserID == ""), i.e. every personal-edition token, so the personal // edition is byte-identical on disk and a rollback sees exactly what it // wrote. Owner-scoped lookups never consult it — see // findAgentTokenHashLocked. // // Entries left behind by a pre-upgrade server-edition deployment are not // read, and are deliberately NOT swept: sweeping them would strand those // tokens on a rollback, while every by-name path on the old code already // re-checks ownership and can therefore only deny, never act on the wrong // tenant's token. // // For that rollback promise to be true, all THREE maintenance paths must // leave a foreign entry alone. Only delete already did, by requiring the // entry to point at the very record being removed. // // - Create used to Put unconditionally, overwriting whatever the name // pointed at — including a pre-upgrade tenant's entry, the very thing // the paragraph above promises to preserve. It now CLAIMS the slot: // taken when free, or when the entry it holds dangles (its hash is no // longer in agent_tokens); left alone when a live record holds it. // - Regenerate used to repoint unconditionally for any OWNERLESS // rotation (`userID == "" || …`), with the same stomp. It now follows // the entry only when the entry points at the record being rotated, and // otherwise applies create's claim rule. AgentTokenNamesBucket = "agent_token_names" //nolint:gosec // bucket name, not a credential )
Bucket names for agent token storage.
const ( UpstreamsBucket = "upstreams" ToolStatsBucket = "toolstats" ToolHashBucket = "toolhash" ToolApprovalBucket = "tool_approvals" PromptApprovalBucket = "prompt_approvals" // spec 100: per-prompt rug-pull baseline OAuthTokenBucket = "oauth_tokens" //nolint:gosec // bucket name, not a credential OAuthCompletionBucket = "oauth_completion" MetaBucket = "meta" CacheBucket = "cache" CacheStatsBucket = "cache_stats" // SessionsBucket holds MCP transport/work session records. // // It is NOT "sessions". The server edition stores USER LOGIN sessions in a // bucket of that name, on the same BBolt database, and the two were silently // destroying each other: // // - enforceSessionRetention (here) keeps the 100 newest keys and deletes the // rest by raw key order, with no type check — evicting user auth sessions // and logging people out at random. // - the server edition's CleanupExpiredSessions unmarshals every value as an // auth session; an MCP record has no expires_at, so its zero time reads as // long expired and the record is deleted. // // Namespacing the bucket is what makes each side's sweep safe. SessionsBucket = "mcp_sessions" // LegacySessionsBucket is the pre-namespacing bucket. In the personal edition // it holds only MCP records; in the server edition it holds a mix of those and // user login sessions. migrateLegacySessions moves the MCP records out and // leaves the auth sessions where they are, so nobody is logged out. LegacySessionsBucket = "sessions" // Security scanner buckets (Spec 039) ScannersBucket = "security_scanners" ScanJobsBucket = "security_scan_jobs" ScanJobIndexBucket = "security_scan_job_index" // lightweight ScanJobMeta index (MCP-2205) ScanReportsBucket = "security_reports" IntegrityBaselinesBucket = "integrity_baselines" // Onboarding wizard bucket (Spec 046) OnboardingBucket = "onboarding" )
Bucket names for bbolt database
const ( // StepStatusCompleted means the user completed the step inside the wizard. StepStatusCompleted = "completed" // StepStatusCompletedExternal means the wizard's connect step was never // advanced, but at dismissal time the install showed positive evidence of // a connection made outside the wizard (a supported client currently // connected, or an MCP client has ever handshaked). Connect step only // (Spec 080 FR-002). StepStatusCompletedExternal = "completed_external" // StepStatusSkipped means the wizard was dismissed with the step // untouched and no external-connection evidence was established. StepStatusSkipped = "skipped" )
Onboarding step-status values (Spec 046; enum widened by Spec 080 FR-001).
const ( SchemaVersionKey = "schema" DockerRecoveryStateKey = "docker_recovery_state" // BaselineSweepDoneKey marks that the one-shot informational baseline scan // sweep has already run on this installation. Presence of the record — not // its contents — is what suppresses a re-run, so the sweep stays one-shot // across restarts and upgrades. BaselineSweepDoneKey = "baseline_sweep_done" )
Meta keys
const ( ToolApprovalStatusApproved = "approved" ToolApprovalStatusPending = "pending" ToolApprovalStatusChanged = "changed" )
ToolApprovalStatus constants for tool-level quarantine
const ( // ToolHeldReasonScanFindings: the offline TPA scan returned a non-clean // verdict. HeldSignals names the matched check ids. ToolHeldReasonScanFindings = "scan_findings" // ToolHeldReasonScanCoverage: the scan itself could not be trusted (a check // failed, or the signature bundle was unavailable), so the gate failed closed // with no findings to show. ToolHeldReasonScanCoverage = "scan_coverage" )
Tool hold reasons (spec 086, FR-018). They explain why the trust_mode: scan gate refused to auto-approve a tool and left it for human review, so the tool-approval surfaces can show WHY a tool is held, not merely THAT it is. Empty on records held for any other reason (manual mode, plain quarantine) and on every record written before this field existed — back-compat by omission.
const ( // DefaultToolCallMaxResponseSize bounds the marshalled response persisted // on a single per-server tool-call record, in bytes. It matches the // activity log's DefaultMaxResponseSize so the two record types that // mirror the same call are bounded the same way. DefaultToolCallMaxResponseSize = 64 * 1024 // DefaultToolCallMaxRecordsPerServer bounds how many call records a single // server_<id>_tool_calls bucket retains. The store is a debugging history, // not an audit log — the activity log is the durable record — so it keeps // a recent window rather than everything. DefaultToolCallMaxRecordsPerServer = 1000 )
const ActivityRecordsBucket = "activity_records"
ActivityRecordsBucket is the BBolt bucket name for activity records
const CurrentSchemaVersion = 3
Current schema version
const DefaultMaxResponseSize = 64 * 1024
DefaultMaxResponseSize is the default maximum size for response truncation (64KB)
const InternalCallToolPrefix = "call_tool_"
InternalCallToolPrefix marks the internal_tool_call records that MIRROR a direct upstream dispatch (call_tool_read / _write / _destructive). Every one of them is paired with a tool_call record for the same dispatch, which is why both the list filter and the usage aggregate key off this prefix to avoid counting one call twice. Internal records WITHOUT it (retrieve_tools, describe_tool, code_execution, upstream_servers, quarantine_security …) are mcpproxy's own work and have no paired record.
const MaxToolHeldSignals = 16
MaxToolHeldSignals caps how many matched check ids are persisted on an approval record. The evidence is a review hint, not an audit log (the full finding set lives on the scan report), so a small deterministic prefix keeps records compact.
const (
OnboardingStateKey = "wizard_state"
)
Onboarding state keys (Spec 046)
const OutputSchemaHashSchemaVersion = 3
OutputSchemaHashSchemaVersion is the schema version that starts including MCP outputSchema in the tool approval hash baseline.
Variables ¶
var ( // ErrAgentTokenNameExists is returned when the OWNER already has a token // with that name. Names are scoped per owner, so this never fires because // of a different tenant's token. ErrAgentTokenNameExists = errors.New("agent token with this name already exists") // ErrAgentTokenLimitReached is returned when the deployment-wide token cap // is reached. ErrAgentTokenLimitReached = errors.New("maximum number of agent tokens reached") // ErrAgentTokenOwnerInactive is returned by ValidateAgentToken when a // token's OWNER is no longer allowed to authenticate — disabled, or gone // from the user store entirely. The token record itself may be perfectly // valid; the identity it speaks for is not. ErrAgentTokenOwnerInactive = errors.New("token owner is not active") // ErrAgentTokenNotFound is returned by the owner-scoped mutators when the // (owner, name) pair resolves to nothing. Callers MUST NOT distinguish // "absent" from "owned by someone else" in their response: the lookup is // owner-scoped, so both produce this same error. ErrAgentTokenNotFound = errors.New("agent token not found") // ErrAgentTokenRevoked is returned by RegenerateAgentTokenForOwner when the // named token has been revoked. Rotation refreshes a LIVE credential's // secret; it is not an un-revoke. // // It is safe to report to the token's owner: the lookup that produced it is // owner-scoped, so it can only ever describe a record the caller already // owns and can already see in their own token list. ErrAgentTokenRevoked = errors.New("agent token is revoked") )
Sentinel errors returned by CreateAgentToken so callers can classify the failure without matching on error strings (and without echoing a storage message that would disclose another tenant's token name).
var ErrPromptApprovalNotFound = errors.New("prompt approval not found")
ErrPromptApprovalNotFound is returned by GetPromptApproval when no record exists (wrapped so callers can errors.Is it). A real read/decode failure returns a different error and MUST NOT be treated as "missing".
var ErrToolApprovalNotFound = errors.New("tool approval not found")
ErrToolApprovalNotFound is returned by GetToolApproval when no record exists for the requested server+tool key. Callers that want to distinguish "first time we've seen this tool" from a real read error (corrupt JSON, closed DB, mmap remap during compaction) MUST use errors.Is, not a generic `err != nil` check — a transient decode error must not be misread as "missing", which would otherwise silently overwrite a pending/changed record with a synthesized approved one.
var ErrUpstreamNotFound = errors.New("upstream not found")
ErrUpstreamNotFound is returned by GetUpstream/GetUpstreamServer when no record exists for the requested server name. Callers that decide policy from the record MUST use errors.Is to tell it apart from a real read failure (corrupt record, closed DB, mmap remap): "no such server" is a verdict the caller can state, while an unreadable record means the caller knows nothing and must fail closed rather than answer "not configured".
var ValidActivityStatuses = []string{ ActivityStatusSuccess, ActivityStatusError, ActivityStatusBlocked, ActivityStatusRejected, }
ValidActivityStatuses is the closed status vocabulary, for filter validation and API documentation.
var ValidActivityTypes = []string{ string(ActivityTypeToolCall), string(ActivityTypePolicyDecision), string(ActivityTypeQuarantineChange), string(ActivityTypeServerChange), string(ActivityTypeSystemStart), string(ActivityTypeSystemStop), string(ActivityTypeInternalToolCall), string(ActivityTypeConfigChange), string(ActivityTypeToolQuarantineChange), string(ActivityTypeSecurityScan), string(ActivityTypeCredentialBroker), string(ActivityTypePreflight), string(ActivityTypePromptGet), }
ValidActivityTypes is the list of all valid activity types for filtering (Spec 024)
Functions ¶
func CountsAsCall ¶ added in v0.61.0
func CountsAsCall(rec *ActivityRecord) (counted, isError bool)
CountsAsCall reports whether a record is one of the calls the user made, and whether that call is a failure.
Admission, by record type:
- tool_call — an upstream dispatch. Counts, except when it was shed by a concurrency limiter (spec 093 "rejected"): a shed call never executed and never reached an upstream, so it is backpressure, not traffic. A "blocked" dispatch (a policy refused a code_execution sub-call) counts as a failed call: the user made it and did not get it.
- internal_tool_call — one of mcpproxy's own built-ins. The call_tool_* variants are excluded because every one of them duplicates a canonical record: a dispatched call — succeeded or failed — also emits its own tool_call record under the same request id, and a shed one is already written by the concurrency limiter. This is the same exclusion ActivityFilter.ExcludeCallToolSuccess applies to the list, so the counter and the rows it counts agree. Management built-ins never count. The rest count when they failed, and on success only for the discovery built-ins the user actually sees.
- policy_decision — counts only when a policy blocked or shed the attempt, as a failed call. An allow decision is bookkeeping about a call that is already counted through its own tool_call record.
Every other type — system_start, security_scan, quarantine and config changes, prompt fetches — is an EVENT. Those belong in the Activity Log, and the log's row count is a real number; it just is not a count of calls.
func GenerateServerID ¶
func GenerateServerID(server *config.ServerConfig) string
GenerateServerID creates a unique, stable identity for a server
func GenerateServerIDFromAttributes ¶
func GenerateServerIDFromAttributes(attrs ServerAttributes) string
GenerateServerIDFromAttributes creates ID from attributes directly
func IsManagementBuiltin ¶ added in v0.64.0
func IsManagementBuiltin(rec *ActivityRecord) bool
IsManagementBuiltin reports whether a record is one of mcpproxy's own management built-ins (upstream_servers / quarantine_security) rather than something a user asked an upstream for.
It is the same population CountsAsCall excludes above, exported because the per-server aggregation needs it too: issue #1146 gave these rows a target_server so the Activity Log could render a Server column and --server could filter on it, and without this predicate a burst of config edits would then read as traffic TO the server being configured — and "github: upstream_servers" would show up as one of github's busiest tools.
func PromptApprovalKey ¶ added in v0.59.0
PromptApprovalKey returns the storage key for a prompt approval record.
func ToolApprovalKey ¶ added in v0.21.0
ToolApprovalKey returns the storage key for a tool approval record.
Types ¶
type ActivityFilter ¶
type ActivityFilter struct {
Types []string // Filter by activity types (Spec 024: supports multiple types with OR logic)
Server string // Filter by server name
Tool string // Filter by tool name
SessionID string // Filter by MCP transport session
Status string // Filter by status (success/error/blocked/rejected)
StartTime time.Time // Activities after this time
EndTime time.Time // Activities before this time
Limit int // Max records to return (default 50, max 100)
Offset int // Pagination offset
IntentType string // Filter by intent operation type: read, write, destructive (Spec 018)
RequestID string // Filter by HTTP request ID for correlation (Spec 021)
// ParentID selects the CHILDREN of one parent call (exact match on
// ActivityRecord.ParentID) — the sub-calls a code_execution script issued.
ParentID string
// WorkSessionID filters by a unit of user work (Spec 082) — one client, one
// project, across reconnects. This is what the UI's "Session" filter means;
// SessionID above is the raw transport connection.
WorkSessionID string
// Sensitive data detection filters (Spec 026)
SensitiveData *bool // Filter by sensitive data detection (nil=no filter, true=has detections, false=no detections)
DetectionType string // Filter by specific detection type (e.g., "aws_access_key", "credit_card")
Severity string // Filter by severity level (critical, high, medium, low)
// Agent token identity filters (Spec 028)
AgentName string // Filter by agent token name in metadata
AuthType string // Filter by auth type: "admin" or "agent"
// AllowedServers is an AUTHORIZATION filter, not a user-facing one (#1166
// follow-up): nil means unrestricted, a non-nil slice restricts matches to
// records attributable to one of these server names ("*" is a wildcard, as
// in auth.AuthContext.AllowedServers).
//
// It lives HERE, in the predicate ListActivities and StreamActivities both
// run, rather than as a post-filter over a returned page. A post-filter
// shrinks the page while `total` keeps counting the records it removed —
// which is its own count oracle for exactly what was hidden, and breaks
// pagination for the caller besides.
//
// An empty non-nil slice matches NOTHING, deliberately: it is the shape a
// token allowed no servers produces, and treating it as unrestricted would
// open the door it exists to close. A record with no ServerName (system
// start/stop, config change) is likewise not matched — those are
// operator-plane events with no server to be entitled to.
AllowedServers []string
// ExcludeCallToolSuccess filters out call_tool_* internal tool calls, which
// are always paired with a canonical record carrying the same request_id:
// successful and failed ones with the upstream tool_call record
// (mcp.go emits both on every dispatched outcome), rejected ones with the
// concurrency limiter's shed record (spec 093). Pre-dispatch failures
// (arg validation, server not found) emit ONLY a tool_call record, so no
// call_tool_* row is ever the sole witness of a call.
// Default: true (to avoid duplicate entries in UI/CLI)
ExcludeCallToolSuccess bool
}
ActivityFilter represents query parameters for filtering activity records
func DefaultActivityFilter ¶
func DefaultActivityFilter() ActivityFilter
DefaultActivityFilter returns an ActivityFilter with sensible defaults
func (*ActivityFilter) Matches ¶
func (f *ActivityFilter) Matches(record *ActivityRecord) bool
Matches checks if an activity record matches the filter criteria.
func (*ActivityFilter) Validate ¶
func (f *ActivityFilter) Validate()
Validate validates and normalizes the filter for regular list queries.
func (*ActivityFilter) ValidateForExport ¶ added in v0.23.0
func (f *ActivityFilter) ValidateForExport()
ValidateForExport validates and normalizes the filter for export queries. Export allows larger limits than regular list queries. Default: 10000, Max: 50000.
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"` // 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", "rejected"
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 transport session ID (regenerated on every reconnect)
RequestID string `json:"request_id,omitempty"` // HTTP request ID for correlation
Metadata map[string]interface{} `json:"metadata,omitempty"` // Additional context-specific data
// ParentID is the correlation id of the record that CAUSED this one: today
// the code_execution call whose sandbox issued this sub-call. It equals the
// parent record's RequestID, so the two directions are one query each:
// parent → children: /api/v1/activity?parent_id=<parent request_id>
// child → parent: /api/v1/activity?request_id=<child parent_id>
//
// First-class rather than metadata for the same reason as WorkSessionID:
// ActivityFilter.Matches compares struct fields, so a value tucked into
// Metadata would be stored but not filterable. Empty for every top-level
// call and for every record written before this field existed.
ParentID string `json:"parent_id,omitempty"`
// WorkSessionID groups records into one unit of USER WORK (Spec 082): one
// client, in one project, under one principal, across reconnects. Unlike
// SessionID it survives the client re-initializing, which real clients do
// every few minutes.
//
// First-class rather than metadata on purpose: activity filtering compares
// struct fields (see ActivityFilter.Matches), so a value tucked into
// Metadata would be stored but not filterable.
//
// Empty on records written before Spec 082 — those stay viewable, just
// unattributed.
WorkSessionID string `json:"work_session_id,omitempty"`
// Byte sizes measured pre-truncation (Spec 069 A1). Zero means unknown (legacy records).
RequestBytes int `json:"request_bytes,omitempty"` // JSON-serialized request arguments size in bytes
ResponseBytes int `json:"response_bytes,omitempty"` // Raw upstream response size in bytes before truncation
// Multi-user identity fields (server edition). Empty/omitted for personal edition.
UserID string `json:"user_id,omitempty"` // User's unique identifier (set when server auth is active)
UserEmail string `json:"user_email,omitempty"` // User's email address (set when server auth is active)
}
ActivityRecord represents a single activity log entry stored in BBolt
func ActivityRecordFromJSON ¶
func ActivityRecordFromJSON(data []byte) (*ActivityRecord, error)
ActivityRecordFromJSON parses an activity record from JSON bytes.
func (*ActivityRecord) MarshalBinary ¶
func (a *ActivityRecord) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler for BBolt storage
func (*ActivityRecord) UnmarshalBinary ¶
func (a *ActivityRecord) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler for BBolt storage
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" // ActivitySourceInternal indicates the activity was triggered by an internal subsystem (Spec 039) ActivitySourceInternal ActivitySource = "internal" )
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" // ActivityTypeSystemStart represents MCPProxy server startup (Spec 024) ActivityTypeSystemStart ActivityType = "system_start" // ActivityTypeSystemStop represents MCPProxy server shutdown (Spec 024) ActivityTypeSystemStop ActivityType = "system_stop" // ActivityTypeInternalToolCall represents internal MCP tool calls like retrieve_tools, call_tool_* (Spec 024) ActivityTypeInternalToolCall ActivityType = "internal_tool_call" // ActivityTypeConfigChange represents configuration changes like server add/remove/update (Spec 024) ActivityTypeConfigChange ActivityType = "config_change" // ActivityTypeToolQuarantineChange represents a tool-level quarantine state change (Spec 032) ActivityTypeToolQuarantineChange ActivityType = "tool_quarantine_change" // ActivityTypeSecurityScan represents a security scan event (Spec 039) ActivityTypeSecurityScan ActivityType = "security_scan" // ActivityTypeCredentialBroker represents a per-user credential brokering // event: acquisition, refresh, injection, or connect (Spec 074 T10). It // carries attribution (UserID, ServerName) and never any token/secret value. ActivityTypeCredentialBroker ActivityType = "credential_broker" // ActivityTypePreflight represents one executed required-tools preflight // (Spec 098 FR-014). The record is written SYNCHRONOUSLY before the // preflight is answered — see runtime.ActivityService.RecordPreflight — so a // caller that got a verdict can always find the run that produced it. // // A preflight is set-scoped, not server-scoped: ServerName and ToolName stay // empty and the per-tool detail lives in Metadata under the MetadataKeyPreflight* // keys. RequestID is the correlation handle (`activity list --request-id`). ActivityTypePreflight ActivityType = "preflight" // ActivityTypePromptGet represents an upstream prompts/get fetch (Finding F10). // Mirrors the tool-call path: ServerName is the upstream server, ToolName is // the prompt name, Arguments are the prompt arguments (scanned for sensitive // data like tool args), RequestID is the correlation handle. ActivityTypePromptGet ActivityType = "prompt_get" )
type AsyncManager ¶
type AsyncManager struct {
// contains filtered or unexported fields
}
AsyncManager handles asynchronous storage operations to prevent deadlocks
func NewAsyncManager ¶
func NewAsyncManager(db *BoltDB, logger *zap.SugaredLogger) *AsyncManager
NewAsyncManager creates a new async storage manager
func (*AsyncManager) DeleteServerAsync ¶
func (am *AsyncManager) DeleteServerAsync(name string)
DeleteServerAsync queues a delete server operation
func (*AsyncManager) EnableServerAsync ¶
func (am *AsyncManager) EnableServerAsync(name string, enabled bool)
EnableServerAsync queues an enable/disable operation
func (*AsyncManager) EnableServerSync ¶
func (am *AsyncManager) EnableServerSync(name string, enabled bool) error
EnableServerSync queues an enable/disable operation and waits for confirmation
func (*AsyncManager) QuarantineServerAsync ¶
func (am *AsyncManager) QuarantineServerAsync(name string, quarantined bool)
QuarantineServerAsync queues a quarantine operation
func (*AsyncManager) QuarantineServerSync ¶
func (am *AsyncManager) QuarantineServerSync(name string, quarantined bool) error
QuarantineServerSync queues a quarantine operation and waits for confirmation
func (*AsyncManager) SaveServerAsync ¶
func (am *AsyncManager) SaveServerAsync(serverConfig *config.ServerConfig)
SaveServerAsync queues a save server operation
func (*AsyncManager) Start ¶
func (am *AsyncManager) Start()
Start begins processing storage operations in a dedicated goroutine
func (*AsyncManager) Stop ¶
func (am *AsyncManager) Stop()
Stop gracefully shuts down the async manager, draining any queued operations. Idempotent: subsequent calls are no-ops (no double-cancel, no DB work), so Manager.StopAsync followed by Manager.Close is safe.
type BaselineSweepState ¶ added in v0.61.0
type BaselineSweepState struct {
// Version is the mcpproxy build version that completed the sweep. Recorded
// for diagnostics; the sweep does not re-run on a version change.
Version string `json:"version,omitempty"`
// CompletedAt is when the sweep finished.
CompletedAt time.Time `json:"completed_at"`
// ServersScanned is how many servers the sweep actually scanned.
ServersScanned int `json:"servers_scanned"`
// Findings is the total number of findings the sweep's scans produced.
Findings int `json:"findings"`
}
BaselineSweepState records the outcome of the one-shot informational baseline scan sweep (the post-upgrade catch-up that scans pre-existing servers which have never been scanned). Stored in MetaBucket under BaselineSweepDoneKey. Absence of the record means "the sweep has never completed here".
type BoltDB ¶
type BoltDB struct {
// contains filtered or unexported fields
}
BoltDB wraps bolt database operations
func NewBoltDB ¶
func NewBoltDB(dataDir string, logger *zap.SugaredLogger) (*BoltDB, error)
NewBoltDB creates a new BoltDB instance
func (*BoltDB) CleanupOldOAuthCompletionEvents ¶
CleanupOldOAuthCompletionEvents removes OAuth completion events older than 24 hours
func (*BoltDB) ClearOAuthClientCredentials ¶
ClearOAuthClientCredentials clears only the DCR-related fields (ClientID, ClientSecret, CallbackPort) while preserving any existing token data. This is called when the callback port conflicts and fresh DCR is required (Spec 022: OAuth Redirect URI Port Persistence)
func (*BoltDB) DeleteIntegrityBaseline ¶ added in v0.24.0
DeleteIntegrityBaseline deletes an integrity baseline by server name
func (*BoltDB) DeleteOAuthToken ¶
DeleteOAuthToken deletes an OAuth token record
func (*BoltDB) DeletePromptApproval ¶ added in v0.59.0
DeletePromptApproval deletes a prompt approval record.
func (*BoltDB) DeleteScanJob ¶ added in v0.24.0
DeleteScanJob deletes a scan job by ID
func (*BoltDB) DeleteScanReport ¶ added in v0.24.0
DeleteScanReport deletes a scan report by ID
func (*BoltDB) DeleteScanner ¶ added in v0.24.0
DeleteScanner deletes a scanner plugin by ID
func (*BoltDB) DeleteServerPromptApprovals ¶ added in v0.59.0
DeleteServerPromptApprovals deletes all prompt approval records for a server.
func (*BoltDB) DeleteServerScanJobs ¶ added in v0.24.0
DeleteServerScanJobs deletes all scan jobs for a server
func (*BoltDB) DeleteServerScanReports ¶ added in v0.24.0
DeleteServerScanReports deletes all scan reports for a server
func (*BoltDB) DeleteServerToolApprovals ¶ added in v0.21.0
DeleteServerToolApprovals deletes all tool approval records for a server
func (*BoltDB) DeleteToolApproval ¶ added in v0.21.0
DeleteToolApproval deletes a tool approval record
func (*BoltDB) DeleteToolHash ¶
DeleteToolHash deletes a tool hash
func (*BoltDB) DeleteUpstream ¶
DeleteUpstream deletes an upstream server record
func (*BoltDB) GetIntegrityBaseline ¶ added in v0.24.0
func (b *BoltDB) GetIntegrityBaseline(serverName string) (*scanner.IntegrityBaseline, error)
GetIntegrityBaseline retrieves an integrity baseline by server name
func (*BoltDB) GetLatestScanJob ¶ added in v0.24.0
GetLatestScanJob returns the most recent scan job for a server
func (*BoltDB) GetOAuthClientCredentials ¶
func (b *BoltDB) GetOAuthClientCredentials(serverKey string) (clientID, clientSecret string, callbackPort int, err error)
GetOAuthClientCredentials retrieves the client credentials and callback port for token refresh callbackPort returns 0 if not stored (legacy records or fresh records without DCR)
func (*BoltDB) GetOAuthToken ¶
func (b *BoltDB) GetOAuthToken(serverName string) (*OAuthTokenRecord, error)
GetOAuthToken retrieves an OAuth token record by server name
func (*BoltDB) GetOnboardingState ¶ added in v0.29.0
func (b *BoltDB) GetOnboardingState() (*OnboardingState, error)
GetOnboardingState returns the current onboarding state. If no state has been recorded, returns a zero-value OnboardingState (i.e. Engaged=false) with nil error.
func (*BoltDB) GetPromptApproval ¶ added in v0.59.0
func (b *BoltDB) GetPromptApproval(serverName, promptName string) (*PromptApprovalRecord, error)
GetPromptApproval retrieves a prompt approval record by server and prompt name. Returns ErrPromptApprovalNotFound (wrapped) when no record exists; any other error is a real read failure and MUST NOT be treated as "missing".
func (*BoltDB) GetScanJob ¶ added in v0.24.0
GetScanJob retrieves a scan job by ID
func (*BoltDB) GetScanReport ¶ added in v0.24.0
func (b *BoltDB) GetScanReport(id string) (*scanner.ScanReport, error)
GetScanReport retrieves a scan report by ID
func (*BoltDB) GetScanner ¶ added in v0.24.0
func (b *BoltDB) GetScanner(id string) (*scanner.ScannerPlugin, error)
GetScanner retrieves a scanner plugin by ID
func (*BoltDB) GetSchemaVersion ¶
GetSchemaVersion returns the current schema version
func (*BoltDB) GetToolApproval ¶ added in v0.21.0
func (b *BoltDB) GetToolApproval(serverName, toolName string) (*ToolApprovalRecord, error)
GetToolApproval retrieves a tool approval record by server and tool name. Returns ErrToolApprovalNotFound (wrapped so callers can use errors.Is) when no record exists. Any other error indicates a real read failure (decode error, closed DB, etc.) and MUST NOT be treated as "missing" by callers.
func (*BoltDB) GetToolApprovals ¶ added in v0.66.0
func (b *BoltDB) GetToolApprovals(serverName string, toolNames ...string) (map[string]*ToolApprovalRecord, error)
GetToolApprovals reads the approval records for several tools of ONE server inside a single read transaction, so the result is a consistent snapshot: no write can land between the individual key reads the way it can between consecutive GetToolApproval calls. Tools without a record are simply absent from the returned map (there is no ErrToolApprovalNotFound for a partial miss); a decode failure on any key fails the whole read.
func (*BoltDB) GetToolHash ¶
GetToolHash retrieves a tool hash
func (*BoltDB) GetToolStats ¶
func (b *BoltDB) GetToolStats(toolName string) (*ToolStatRecord, error)
GetToolStats retrieves tool statistics
func (*BoltDB) GetUnprocessedOAuthCompletionEvents ¶
func (s *BoltDB) GetUnprocessedOAuthCompletionEvents() ([]*OAuthCompletionEvent, error)
GetUnprocessedOAuthCompletionEvents returns all unprocessed OAuth completion events
func (*BoltDB) GetUpstream ¶
func (b *BoltDB) GetUpstream(id string) (*UpstreamRecord, error)
GetUpstream retrieves an upstream server record by ID
func (*BoltDB) IncrementToolStats ¶
IncrementToolStats increments the usage count for a tool
func (*BoltDB) ListIntegrityBaselines ¶ added in v0.24.0
func (b *BoltDB) ListIntegrityBaselines() ([]*scanner.IntegrityBaseline, error)
ListIntegrityBaselines returns all integrity baseline records
func (*BoltDB) ListOAuthTokens ¶
func (b *BoltDB) ListOAuthTokens() ([]*OAuthTokenRecord, error)
ListOAuthTokens returns all OAuth token records
func (*BoltDB) ListPromptApprovals ¶ added in v0.59.0
func (b *BoltDB) ListPromptApprovals(serverName string) ([]*PromptApprovalRecord, error)
ListPromptApprovals returns all prompt approval records for a server. If serverName is empty, returns all records across all servers.
func (*BoltDB) ListScanJobMetas ¶ added in v0.39.0
func (b *BoltDB) ListScanJobMetas(serverName string) ([]*scanner.ScanJobMeta, error)
ListScanJobMetas returns lightweight scan-job metadata, optionally filtered by server name. Unlike ListScanJobs it reads from a dedicated index bucket and never deserializes the large per-job stdout/stderr payloads, so its cost is independent of scan-output size. See MCP-2205.
func (*BoltDB) ListScanJobs ¶ added in v0.24.0
ListScanJobs returns scan jobs, optionally filtered by server name. If serverName is empty, returns all jobs.
func (*BoltDB) ListScanReports ¶ added in v0.24.0
func (b *BoltDB) ListScanReports(serverName string) ([]*scanner.ScanReport, error)
ListScanReports returns scan reports, optionally filtered by server name. If serverName is empty, returns all reports.
func (*BoltDB) ListScanReportsByJob ¶ added in v0.24.0
func (b *BoltDB) ListScanReportsByJob(jobID string) ([]*scanner.ScanReport, error)
ListScanReportsByJob returns all scan reports for a specific scan job
func (*BoltDB) ListScanners ¶ added in v0.24.0
func (b *BoltDB) ListScanners() ([]*scanner.ScannerPlugin, error)
ListScanners returns all scanner plugin records
func (*BoltDB) ListToolApprovals ¶ added in v0.21.0
func (b *BoltDB) ListToolApprovals(serverName string) ([]*ToolApprovalRecord, error)
ListToolApprovals returns all tool approval records for a server. If serverName is empty, returns all records across all servers.
func (*BoltDB) ListToolStats ¶
func (b *BoltDB) ListToolStats() ([]*ToolStatRecord, error)
ListToolStats returns all tool statistics
func (*BoltDB) ListUpstreams ¶
func (b *BoltDB) ListUpstreams() ([]*UpstreamRecord, error)
ListUpstreams returns all upstream server records
func (*BoltDB) MarkOAuthCompletionEventProcessed ¶
MarkOAuthCompletionEventProcessed marks an OAuth completion event as processed
func (*BoltDB) PruneToolApprovalsNotIn ¶ added in v0.37.0
PruneToolApprovalsNotIn deletes tool-approval records whose ServerName is not present in keep, returning the number removed. This GCs orphaned approvals for servers that left the config without an explicit delete (e.g. the config file was hand-edited, or an old migration). Records for configured servers — including disabled ones — are kept so re-enabling a server doesn't re-trigger quarantine of its previously-approved tools (MCP-1002).
func (*BoltDB) SaveIntegrityBaseline ¶ added in v0.24.0
func (b *BoltDB) SaveIntegrityBaseline(baseline *scanner.IntegrityBaseline) error
SaveIntegrityBaseline saves an integrity baseline record
func (*BoltDB) SaveOAuthCompletionEvent ¶
func (s *BoltDB) SaveOAuthCompletionEvent(event *OAuthCompletionEvent) error
SaveOAuthCompletionEvent saves an OAuth completion event to the database
func (*BoltDB) SaveOAuthToken ¶
func (b *BoltDB) SaveOAuthToken(record *OAuthTokenRecord) error
SaveOAuthToken saves an OAuth token record
func (*BoltDB) SaveOnboardingState ¶ added in v0.29.0
func (b *BoltDB) SaveOnboardingState(state *OnboardingState) error
SaveOnboardingState persists the wizard state.
func (*BoltDB) SavePromptApproval ¶ added in v0.59.0
func (b *BoltDB) SavePromptApproval(record *PromptApprovalRecord) error
SavePromptApproval upserts a prompt approval record.
func (*BoltDB) SaveScanJob ¶ added in v0.24.0
SaveScanJob saves a scan job record
func (*BoltDB) SaveScanReport ¶ added in v0.24.0
func (b *BoltDB) SaveScanReport(report *scanner.ScanReport) error
SaveScanReport saves a scan report record
func (*BoltDB) SaveScanner ¶ added in v0.24.0
func (b *BoltDB) SaveScanner(s *scanner.ScannerPlugin) error
SaveScanner saves a scanner plugin record
func (*BoltDB) SaveToolApproval ¶ added in v0.21.0
func (b *BoltDB) SaveToolApproval(record *ToolApprovalRecord) error
SaveToolApproval saves a tool approval record
func (*BoltDB) SaveToolHash ¶
SaveToolHash saves a tool hash for change detection
func (*BoltDB) SaveUpstream ¶
func (b *BoltDB) SaveUpstream(record *UpstreamRecord) error
SaveUpstream saves an upstream server record
func (*BoltDB) SetSchemaVersion ¶ added in v0.33.4
SetSchemaVersion stores the current migration schema version.
func (*BoltDB) UpdateOAuthClientCredentials ¶
func (b *BoltDB) UpdateOAuthClientCredentials(serverKey, clientID, clientSecret string, callbackPort int) error
UpdateOAuthClientCredentials updates the client credentials (from DCR) and callback port on an existing token This is called after successful Dynamic Client Registration to persist the obtained client_id/secret and the callback port used for the redirect_uri (Spec 022: OAuth Redirect URI Port Persistence)
type DatabaseLockedError ¶
DatabaseLockedError indicates that the database is locked by another process
func (*DatabaseLockedError) Error ¶
func (e *DatabaseLockedError) Error() string
func (*DatabaseLockedError) Unwrap ¶
func (e *DatabaseLockedError) Unwrap() error
type DiagnosticRecord ¶
type DiagnosticRecord struct {
ServerID string `json:"server_id"`
ServerName string `json:"server_name"`
Type string `json:"type"` // error, warning, info
Category string `json:"category"` // oauth, connection, etc.
Message string `json:"message"`
Details map[string]interface{} `json:"details"`
Timestamp time.Time `json:"timestamp"`
ConfigPath string `json:"config_path"`
Resolved bool `json:"resolved"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
}
DiagnosticRecord represents a diagnostic event for a server
type DockerRecoveryState ¶
type DockerRecoveryState struct {
LastAttempt time.Time `json:"last_attempt"`
FailureCount int `json:"failure_count"`
DockerAvailable bool `json:"docker_available"`
RecoveryMode bool `json:"recovery_mode"`
LastError string `json:"last_error,omitempty"`
AttemptsSinceUp int `json:"attempts_since_up"` // Attempts since Docker was last available
LastSuccessfulAt time.Time `json:"last_successful_at,omitempty"`
}
DockerRecoveryState represents the persistent state of Docker recovery This allows recovery to resume after application restart
func (*DockerRecoveryState) MarshalBinary ¶
func (d *DockerRecoveryState) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*DockerRecoveryState) UnmarshalBinary ¶
func (d *DockerRecoveryState) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
type EnableServerData ¶
Data structures for different operation types
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager provides a unified interface for storage operations
func NewManager ¶
func NewManager(dataDir string, logger *zap.SugaredLogger) (*Manager, error)
NewManager creates a new storage manager
func (*Manager) AddUpstream ¶
func (m *Manager) AddUpstream(serverConfig *config.ServerConfig) (string, error)
AddUpstream adds an upstream server and returns its ID
func (*Manager) AggregateToolUsage ¶ added in v0.33.0
AggregateToolUsage performs a single pass over the activity bucket and returns per-(server,tool) call counts and last-used time for tool_call records with Timestamp >= since. Records outside the window and non tool_call records are skipped. An empty/absent bucket yields an empty map (not an error). This is the consolidated usage source for GET /api/v1/tools (spec 050) — read-only, no schema change.
func (*Manager) CleanupOrphanedOAuthTokens ¶ added in v0.16.8
CleanupOrphanedOAuthTokens removes OAuth tokens for servers that no longer exist in the configuration. This should be called during startup to clean up tokens left behind when servers were removed while mcpproxy was not running, or from older versions that didn't clean up properly.
func (*Manager) CleanupStaleServerData ¶
CleanupStaleServerData removes data for servers that haven't been seen for a threshold period
func (*Manager) ClearDockerRecoveryState ¶
ClearDockerRecoveryState removes the Docker recovery state from persistent storage
func (*Manager) ClearOAuthState ¶
ClearOAuthState clears all OAuth state for a server (tokens, client registration, etc.) This should be called when OAuth configuration changes to force re-authentication
func (*Manager) Close ¶
Close closes the storage manager: it stops the async manager (draining queued operations to the DB — a no-op if StopAsync already ran), then closes the underlying BBolt database.
func (*Manager) CloseAllActiveSessions ¶
CloseAllActiveSessions marks all active sessions as closed This should be called on startup to clean up stale sessions from previous runs
func (*Manager) CloseInactiveSessions ¶
CloseInactiveSessions closes sessions that haven't had activity for the specified duration
func (*Manager) CloseSession ¶
CloseSession marks a session as closed with end time
func (*Manager) CountActivities ¶
CountActivities returns the total number of activity records.
func (*Manager) CreateAgentToken ¶ added in v0.20.0
CreateAgentToken stores a new agent token. It hashes the raw token using the provided HMAC key and stores the AgentToken record keyed by hash in the "agent_tokens" bucket.
Token names are unique PER OWNER (token.UserID), not globally: two tenants can each hold a token called "ci". Ownerless tokens (UserID == "", every personal-edition token) additionally get a bare-name entry in the legacy "agent_token_names" index so the personal edition is unchanged on disk.
Returns ErrAgentTokenNameExists if the same owner already has that name, or ErrAgentTokenLimitReached if the deployment-wide cap is reached.
func (*Manager) CreateSession ¶
func (m *Manager) CreateSession(session *SessionRecord) error
CreateSession creates a new session record
func (*Manager) DeleteActivity ¶
DeleteActivity deletes an activity record by ID. Returns nil if the record doesn't exist.
func (*Manager) DeleteAgentToken ¶ added in v0.48.0
DeleteAgentToken permanently removes an agent token, deleting both the record in the "agent_tokens" bucket and the name->hash mapping in "agent_token_names". Unlike RevokeAgentToken (a soft delete that keeps the record), this frees the name so a new token can be created with the same name. Returns an error if the token does not exist.
func (*Manager) DeleteAgentTokenForOwner ¶ added in v0.64.0
DeleteAgentTokenForOwner permanently removes the token called name owned by userID. Returns ErrAgentTokenNotFound when the (owner, name) pair does not resolve, whether because it is absent or because it belongs to someone else.
func (*Manager) DeleteIntegrityBaseline ¶ added in v0.24.0
DeleteIntegrityBaseline deletes an integrity baseline by server name
func (*Manager) DeletePromptApproval ¶ added in v0.59.0
DeletePromptApproval deletes a prompt approval record.
func (*Manager) DeleteScanJob ¶ added in v0.24.0
DeleteScanJob deletes a scan job by ID
func (*Manager) DeleteScanReport ¶ added in v0.24.0
DeleteScanReport deletes a scan report by ID
func (*Manager) DeleteScanner ¶ added in v0.24.0
DeleteScanner deletes a scanner plugin by ID
func (*Manager) DeleteServerPromptApprovals ¶ added in v0.59.0
DeleteServerPromptApprovals deletes all prompt approval records for a server.
func (*Manager) DeleteServerScanJobs ¶ added in v0.24.0
DeleteServerScanJobs deletes all scan jobs for a server
func (*Manager) DeleteServerScanReports ¶ added in v0.24.0
DeleteServerScanReports deletes all scan reports for a server
func (*Manager) DeleteServerToolApprovals ¶ added in v0.21.0
DeleteServerToolApprovals deletes all tool approval records for a server
func (*Manager) DeleteToolApproval ¶ added in v0.21.0
DeleteToolApproval deletes a tool approval record
func (*Manager) DeleteToolHash ¶
DeleteToolHash deletes a tool hash
func (*Manager) DeleteUpstreamServer ¶
DeleteUpstreamServer deletes an upstream server
func (*Manager) EnableUpstreamServer ¶
EnableUpstreamServer enables/disables an upstream server using async operations
func (*Manager) GetActivity ¶
func (m *Manager) GetActivity(id string) (*ActivityRecord, error)
GetActivity retrieves an activity record by ID. Returns nil if the record is not found.
func (*Manager) GetActivityByIDScan ¶
func (m *Manager) GetActivityByIDScan(id string) (*ActivityRecord, error)
GetActivityByIDScan performs a full scan to find activity by ID. This is less efficient than GetActivity but works when the timestamp is unknown.
func (*Manager) GetAgentTokenByHash ¶ added in v0.20.0
func (m *Manager) GetAgentTokenByHash(hash string) (*auth.AgentToken, error)
GetAgentTokenByHash retrieves an agent token by its HMAC hash. Returns nil if not found.
func (*Manager) GetAgentTokenByName ¶ added in v0.20.0
func (m *Manager) GetAgentTokenByName(name string) (*auth.AgentToken, error)
GetAgentTokenByName retrieves an OWNERLESS agent token by its name — that is, GetAgentTokenByOwnerAndName("", name). Every personal-edition token is ownerless, so this is unchanged for the personal edition; it deliberately does NOT resolve a server-edition user's token, because token names are unique only within an owner and a bare name is therefore ambiguous. Returns nil if not found.
func (*Manager) GetAgentTokenByOwnerAndName ¶ added in v0.64.0
func (m *Manager) GetAgentTokenByOwnerAndName(userID, name string) (*auth.AgentToken, error)
GetAgentTokenByOwnerAndName retrieves the token called name owned by userID. Use "" as userID for ownerless (personal-edition) tokens.
Returns nil when the pair does not resolve — whether because no such token exists or because the name belongs to a different owner. Callers must not distinguish those two cases in a response: doing so turns the endpoint into an oracle for other tenants' token names.
func (*Manager) GetAgentTokenCount ¶ added in v0.20.0
GetAgentTokenCount returns the number of stored agent tokens.
func (*Manager) GetBoltDB ¶
GetBoltDB returns the wrapped BoltDB instance for higher-level operations
func (*Manager) GetIntegrityBaseline ¶ added in v0.24.0
func (m *Manager) GetIntegrityBaseline(serverName string) (*scanner.IntegrityBaseline, error)
GetIntegrityBaseline retrieves an integrity baseline by server name
func (*Manager) GetLatestScanJob ¶ added in v0.24.0
GetLatestScanJob returns the most recent scan job for a server
func (*Manager) GetOAuthToken ¶
func (m *Manager) GetOAuthToken(serverName string) (*OAuthTokenRecord, error)
GetOAuthToken retrieves an OAuth token for a server from storage
func (*Manager) GetOnboardingState ¶ added in v0.29.0
func (m *Manager) GetOnboardingState() (*OnboardingState, error)
GetOnboardingState returns the current wizard engagement state.
func (*Manager) GetPromptApproval ¶ added in v0.59.0
func (m *Manager) GetPromptApproval(serverName, promptName string) (*PromptApprovalRecord, error)
GetPromptApproval retrieves a prompt approval record by server and prompt name.
func (*Manager) GetRecentSessions ¶
GetRecentSessions returns the sessions that were active most recently.
"Recent" means LastActivity, not StartTime. Bucket keys are "{startUnixNano}_{id}", so a cursor walk is start-time order — and a client that connected this morning and is still calling tools sits at the very bottom of it, one reconnect-happy neighbour away from being truncated out of the page. The tray would then say the busiest client on the machine is gone.
So the walk collects every retained record first, sorts by LastActivity descending, and only then filters and truncates. Ordering before truncation is the whole guarantee (contracts/api-deltas.md §3); doing it in the caller can only reorder rows that already survived the cut. Session retention caps the bucket at 100 records (enforceSessionRetention), so the full scan and sort are bounded.
status filters on SessionRecord.Status ("active" / "closed"); an empty string means no filtering. It is applied after the sort and before the limit, so an old-but-active session is never dropped by a page full of newer ones. The returned total counts the whole bucket when unfiltered, and every matching record when filtered.
func (*Manager) GetScanJob ¶ added in v0.24.0
GetScanJob retrieves a scan job by ID
func (*Manager) GetScanReport ¶ added in v0.24.0
func (m *Manager) GetScanReport(id string) (*scanner.ScanReport, error)
GetScanReport retrieves a scan report by ID
func (*Manager) GetScanner ¶ added in v0.24.0
func (m *Manager) GetScanner(id string) (*scanner.ScannerPlugin, error)
GetScanner retrieves a scanner plugin by ID
func (*Manager) GetSchemaVersion ¶
GetSchemaVersion returns the current schema version
func (*Manager) GetServerDiagnostics ¶
func (m *Manager) GetServerDiagnostics(serverID string, limit int) ([]*DiagnosticRecord, error)
GetServerDiagnostics gets diagnostic records for a server
func (*Manager) GetServerIdentity ¶
func (m *Manager) GetServerIdentity(server *config.ServerConfig) (*ServerIdentity, error)
GetServerIdentity gets server identity by config
func (*Manager) GetServerIdentityByID ¶
func (m *Manager) GetServerIdentityByID(serverID string) (*ServerIdentity, error)
GetServerIdentityByID gets server identity by ID
func (*Manager) GetServerStatistics ¶
func (m *Manager) GetServerStatistics(serverID string) (*ServerStatistics, error)
GetServerStatistics gets statistics for a server
func (*Manager) GetServerToolCalls ¶
func (m *Manager) GetServerToolCalls(serverID string, limit int) ([]*ToolCallRecord, error)
GetServerToolCalls gets tool calls for a server
func (*Manager) GetSessionByID ¶
func (m *Manager) GetSessionByID(sessionID string) (*SessionRecord, error)
GetSessionByID retrieves a session by its ID
func (*Manager) GetToolApproval ¶ added in v0.21.0
func (m *Manager) GetToolApproval(serverName, toolName string) (*ToolApprovalRecord, error)
GetToolApproval retrieves a tool approval record by server and tool name
func (*Manager) GetToolApprovals ¶ added in v0.66.0
func (m *Manager) GetToolApprovals(serverName string, toolNames ...string) (map[string]*ToolApprovalRecord, error)
GetToolApprovals retrieves the approval records for several tools of one server as one consistent snapshot: a single manager read lock and a single storage read transaction cover every key, so no SaveToolApproval can interleave between them. Tools without a record are absent from the map.
func (*Manager) GetToolCallsBySession ¶
func (m *Manager) GetToolCallsBySession(sessionID string, limit, offset int, scope ToolCallScope) ([]*ToolCallRecord, int, error)
GetToolCallsBySession retrieves tool calls filtered by session ID scope restricts the read to a set of server names; nil is unrestricted. It is applied inside the same pass that computes `total`, so the page and the total never describe different record sets (#1166 follow-up).
func (*Manager) GetToolHash ¶
GetToolHash retrieves a tool hash
func (*Manager) GetToolStatistics ¶
GetToolStatistics returns aggregated tool statistics
func (*Manager) GetToolStats ¶
GetToolStats gets tool statistics formatted for MCP responses
func (*Manager) GetToolUsage ¶
func (m *Manager) GetToolUsage(toolName string) (*ToolStatRecord, error)
GetToolUsage retrieves usage statistics for a tool
func (*Manager) GetUpstreamServer ¶
func (m *Manager) GetUpstreamServer(name string) (*config.ServerConfig, error)
GetUpstreamServer retrieves an upstream server by name
func (*Manager) HasToolChanged ¶
HasToolChanged checks if a tool has changed based on its hash
func (*Manager) IncrementToolUsage ¶
IncrementToolUsage increments the usage count for a tool
func (*Manager) ListActivities ¶
func (m *Manager) ListActivities(filter ActivityFilter) ([]*ActivityRecord, int, error)
ListActivities returns paginated activity records matching the filter. Records are returned in reverse chronological order (newest first). Returns the records, total matching count, and any error.
func (*Manager) ListAgentTokens ¶ added in v0.20.0
func (m *Manager) ListAgentTokens() ([]auth.AgentToken, error)
ListAgentTokens returns all stored agent tokens.
A record that fails to unmarshal is SKIPPED, not fatal, for the same reason findAgentTokenHashLocked skips one: this walks the whole bucket, so aborting on the first bad row lets a single unparseable entry — a truncated write, a hand-edited DB, a record from a future schema — turn every listing into a 500 for EVERY tenant of the deployment, and for the operator's own `mcpproxy token list` with it. Skipping degrades the blast radius to "that one token is not listed". The skip is logged at WARN with the bucket key so an operator can find the row; that key is an HMAC hash, not a credential.
func (*Manager) ListIntegrityBaselines ¶ added in v0.24.0
func (m *Manager) ListIntegrityBaselines() ([]*scanner.IntegrityBaseline, error)
ListIntegrityBaselines returns all integrity baseline records
func (*Manager) ListOAuthTokens ¶
func (m *Manager) ListOAuthTokens() ([]*OAuthTokenRecord, error)
ListOAuthTokens returns all OAuth token records from storage. Used by RefreshManager to initialize proactive refresh schedules on startup.
func (*Manager) ListPromptApprovals ¶ added in v0.59.0
func (m *Manager) ListPromptApprovals(serverName string) ([]*PromptApprovalRecord, error)
ListPromptApprovals returns all prompt approval records for a server (all when empty).
func (*Manager) ListQuarantinedTools ¶
ListQuarantinedTools returns tools from quarantined servers with full descriptions for security analysis
func (*Manager) ListQuarantinedUpstreamServers ¶
func (m *Manager) ListQuarantinedUpstreamServers() ([]*config.ServerConfig, error)
ListQuarantinedUpstreamServers returns all quarantined upstream servers
func (*Manager) ListScanJobMetas ¶ added in v0.39.0
func (m *Manager) ListScanJobMetas(serverName string) ([]*scanner.ScanJobMeta, error)
ListScanJobMetas returns lightweight scan-job metadata, optionally filtered by server name (MCP-2205).
func (*Manager) ListScanJobs ¶ added in v0.24.0
ListScanJobs returns scan jobs, optionally filtered by server name
func (*Manager) ListScanReports ¶ added in v0.24.0
func (m *Manager) ListScanReports(serverName string) ([]*scanner.ScanReport, error)
ListScanReports returns scan reports, optionally filtered by server name
func (*Manager) ListScanReportsByJob ¶ added in v0.24.0
func (m *Manager) ListScanReportsByJob(jobID string) ([]*scanner.ScanReport, error)
ListScanReportsByJob returns all scan reports for a specific scan job
func (*Manager) ListScanners ¶ added in v0.24.0
func (m *Manager) ListScanners() ([]*scanner.ScannerPlugin, error)
ListScanners returns all scanner plugin records
func (*Manager) ListServerIdentities ¶
func (m *Manager) ListServerIdentities() ([]*ServerIdentity, error)
ListServerIdentities lists all server identities
func (*Manager) ListToolApprovals ¶ added in v0.21.0
func (m *Manager) ListToolApprovals(serverName string) ([]*ToolApprovalRecord, error)
ListToolApprovals returns all tool approval records for a server. If serverName is empty, returns all records across all servers.
func (*Manager) ListUpstreamServers ¶
func (m *Manager) ListUpstreamServers() ([]*config.ServerConfig, error)
ListUpstreamServers returns all upstream servers
func (*Manager) ListUpstreams ¶
func (m *Manager) ListUpstreams() ([]*config.ServerConfig, error)
ListUpstreams is an alias for ListUpstreamServers
func (*Manager) LoadBaselineSweepState ¶ added in v0.61.0
func (m *Manager) LoadBaselineSweepState() (*BaselineSweepState, error)
LoadBaselineSweepState returns the one-shot baseline sweep marker, or (nil, nil) when the sweep has never completed on this installation. A read error is returned as an error — callers must treat "unknown" as "do not sweep" rather than re-running the sweep on every start.
func (*Manager) LoadDockerRecoveryState ¶
func (m *Manager) LoadDockerRecoveryState() (*DockerRecoveryState, error)
LoadDockerRecoveryState loads the Docker recovery state from persistent storage
func (*Manager) LoadUsageSnapshot ¶ added in v0.35.0
LoadUsageSnapshot returns the persisted usage aggregate bytes, or (nil, nil) when no snapshot has been written yet (cold start). The returned slice is a copy safe to use outside the transaction.
func (*Manager) PruneActivitiesToSize ¶ added in v0.37.0
PruneActivitiesToSize deletes the oldest activity records until the activity log's stored data (sum of key+value bytes) is at or below maxBytes. Activity keys are timestamp-ordered, so a single forward cursor pass removes oldest-first. The newest record is ALWAYS retained — the log is never emptied while any record exists, even if that newest record alone exceeds the budget. maxBytes <= 0 disables size pruning (no-op). Returns the number deleted.
func (*Manager) PruneExcessActivities ¶
PruneExcessActivities deletes oldest records when count exceeds maxRecords. Deletes records until count is at targetPercent of maxRecords (default 90%). Returns the number of records deleted.
func (*Manager) PruneOldActivities ¶
PruneOldActivities deletes activity records older than the specified duration. Returns the number of records deleted.
func (*Manager) PruneOrphanToolApprovals ¶ added in v0.37.0
PruneOrphanToolApprovals removes tool-approval records for servers that are no longer in the configured set, returning the number removed. Configured servers (even disabled ones) are preserved so re-enabling never re-quarantines previously-approved tools (MCP-1002).
func (*Manager) PruneOrphanToolCalls ¶ added in v0.65.0
PruneOrphanToolCalls drops per-server tool-call history for servers that are no longer configured, mirroring PruneOrphanToolApprovals. It takes server NAMES, as its sibling does, and returns how many server histories it removed.
The translation in the middle is the whole point. These buckets are keyed by SERVER IDENTITY — the SHA-256 GenerateServerID computes from a server's stable attributes (mcp.go passes serverID, not serverName) — so comparing a bucket's key against configured NAMES marks every live history an orphan and deletes the lot. The names are resolved through server_identities first.
Two guards on top of that:
- the synthetic code_execution bucket is never an orphan; it holds the parent record of every code_execution run and has no identity at all;
- an empty server_identities bucket aborts the sweep. That state means the identity store has not been populated yet, not that every server is gone.
func (*Manager) QuarantineUpstreamServer ¶
QuarantineUpstreamServer sets the quarantine status of an upstream server using async operations
func (*Manager) RecordServerDiagnostic ¶
func (m *Manager) RecordServerDiagnostic(record *DiagnosticRecord) error
RecordServerDiagnostic records a diagnostic event for a server
func (*Manager) RecordToolCall ¶
func (m *Manager) RecordToolCall(record *ToolCallRecord) error
RecordToolCall records a tool call for a server
func (*Manager) RegenerateAgentToken ¶ added in v0.20.0
func (m *Manager) RegenerateAgentToken(name string, newRawToken string, hmacKey []byte) (*auth.AgentToken, error)
RegenerateAgentToken creates a new hash for an existing token, preserving configuration (name, permissions, allowed servers, expiry). It removes the old hash entry and creates a new one with the new raw token's hash. Returns the updated token record.
func (*Manager) RegenerateAgentTokenForOwner ¶ added in v0.64.0
func (m *Manager) RegenerateAgentTokenForOwner(userID, name string, newRawToken string, hmacKey []byte, narrowScope func([]string) []string) (*auth.AgentToken, error)
RegenerateAgentTokenForOwner regenerates the token called name owned by userID. Returns ErrAgentTokenNotFound when the (owner, name) pair does not resolve, whether because it is absent or because it belongs to someone else.
narrowScope, when non-nil, is applied to the stored AllowedServers inside the same transaction that rotates the hash, and its result is persisted. It exists because a token's server scope is decided once, at mint time, and nothing re-checks it afterwards: un-sharing a server does not revoke the grants already written into live tokens. Rotation is the one moment the owner's current entitlement is known, so the server edition passes a filter that drops anything they may no longer reach (see resolveTokenServerScope).
The hook can only ever NARROW, and that is ENFORCED here rather than merely documented: whatever it returns is intersected with the token's stored AllowedServers by intersectAllowedServers before anything is persisted. A future caller that returned a wider list — or a constant, or the entitled set itself — therefore cannot turn rotation, the one operation that is supposed to be scope-neutral, into a privilege escalation. Hooks are still expected to behave; the intersection is what makes misbehaving harmless instead of load-bearing on a comment.
The hook MUST NOT do I/O: it runs inside a write transaction while m.mu is held, so the caller computes the entitled set before the call and passes a pure filter.
func (*Manager) RegisterServerIdentity ¶
func (m *Manager) RegisterServerIdentity(server *config.ServerConfig, configPath string) (*ServerIdentity, error)
RegisterServerIdentity registers or updates a server identity
func (*Manager) RemoveUpstream ¶
RemoveUpstream removes an upstream server by ID/name
func (*Manager) RevokeAgentToken ¶ added in v0.20.0
RevokeAgentToken marks an OWNERLESS agent token as revoked by name. Equivalent to RevokeAgentTokenForOwner("", name).
func (*Manager) RevokeAgentTokenForOwner ¶ added in v0.64.0
RevokeAgentTokenForOwner marks the token called name owned by userID as revoked. Returns ErrAgentTokenNotFound when the (owner, name) pair does not resolve, whether because it is absent or because it belongs to someone else.
func (*Manager) RevokeAgentTokensForOwner ¶ added in v0.64.0
RevokeAgentTokensForOwner marks every token owned by userID as revoked and returns how many it changed. An owner with no tokens is not an error.
It is the credential half of disabling a user. The owner gate (SetAgentTokenOwnerGate) already stops a disabled user's tokens the moment they are disabled, but the gate is a live check: RE-ENABLING the account would hand every previously minted token straight back, including the one that caused the disable. Since disabling is the documented remediation for a compromised account, the credentials minted under it are burned outright. Revoked is a soft delete — the records stay, so the operator can still see what existed — and the owner mints new tokens after being re-enabled.
userID must not be empty: "" is the OWNERLESS namespace, i.e. every personal-edition token, and a bulk revoke of it would be an outage rather than a remediation.
func (*Manager) SaveActivity ¶
func (m *Manager) SaveActivity(record *ActivityRecord) error
SaveActivity stores an activity record in BBolt. The record is stored with a composite key for efficient time-based queries.
func (*Manager) SaveActivityAsync ¶
func (m *Manager) SaveActivityAsync(record *ActivityRecord)
SaveActivityAsync saves an activity record asynchronously. This is non-blocking and suitable for recording tool calls without impacting latency.
func (*Manager) SaveBaselineSweepState ¶ added in v0.61.0
func (m *Manager) SaveBaselineSweepState(state *BaselineSweepState) error
SaveBaselineSweepState persists the one-shot informational baseline sweep marker. Once this record exists the sweep never runs again on this installation, so it is written only after a sweep actually completed.
func (*Manager) SaveDockerRecoveryState ¶
func (m *Manager) SaveDockerRecoveryState(state *DockerRecoveryState) error
SaveDockerRecoveryState saves the Docker recovery state to persistent storage
func (*Manager) SaveIntegrityBaseline ¶ added in v0.24.0
func (m *Manager) SaveIntegrityBaseline(baseline *scanner.IntegrityBaseline) error
SaveIntegrityBaseline saves an integrity baseline record
func (*Manager) SaveOnboardingState ¶ added in v0.29.0
func (m *Manager) SaveOnboardingState(state *OnboardingState) error
SaveOnboardingState persists the wizard engagement state.
func (*Manager) SavePromptApproval ¶ added in v0.59.0
func (m *Manager) SavePromptApproval(record *PromptApprovalRecord) error
SavePromptApproval upserts a prompt approval record.
func (*Manager) SaveScanJob ¶ added in v0.24.0
SaveScanJob saves a scan job record
func (*Manager) SaveScanReport ¶ added in v0.24.0
func (m *Manager) SaveScanReport(report *scanner.ScanReport) error
SaveScanReport saves a scan report record
func (*Manager) SaveScanner ¶ added in v0.24.0
func (m *Manager) SaveScanner(s *scanner.ScannerPlugin) error
SaveScanner saves a scanner plugin record
func (*Manager) SaveToolApproval ¶ added in v0.21.0
func (m *Manager) SaveToolApproval(record *ToolApprovalRecord) error
SaveToolApproval saves a tool approval record
func (*Manager) SaveToolHash ¶
SaveToolHash saves a tool hash for change detection
func (*Manager) SaveUpstreamServer ¶
func (m *Manager) SaveUpstreamServer(serverConfig *config.ServerConfig) error
SaveUpstreamServer saves an upstream server configuration
func (*Manager) SaveUsageSnapshot ¶ added in v0.35.0
SaveUsageSnapshot persists the encoded usage aggregate under the versioned key, overwriting any previous snapshot.
func (*Manager) ScanActivitiesAfter ¶ added in v0.60.0
func (m *Manager) ScanActivitiesAfter(since time.Time, visit func(*ActivityRecord)) error
ScanActivitiesAfter visits every activity record STRICTLY newer than `since`, oldest first. It is the catch-up replay behind a persisted usage snapshot: a snapshot is flushed every 30s, so an unclean shutdown always leaves a tail of records that were saved but never folded in, and loading the snapshot alone left that tail permanently missing from the aggregate while the activity list showed it.
The bound is real work avoided, not a convenience: activity keys are "<20-digit unix nanos>_<id>", so seeking to the nanosecond after `since` skips the entire history in one cursor move instead of unmarshalling it.
Strictly-greater is what makes the replay safe to run every start: records are persisted BEFORE they are folded into the aggregate, so anything at or before the snapshot's stamp is already counted and re-applying it would double it.
A zero `since` is rejected rather than treated as "everything": the caller that cannot date its snapshot must rebuild from a full scan, not replay a history it may already contain.
func (*Manager) ScanAllActivities ¶ added in v0.35.0
func (m *Manager) ScanAllActivities(visit func(*ActivityRecord)) error
ScanAllActivities performs a single pass over every activity record and calls visit for each. Used to rebuild the usage aggregate on a cold start (reuses the same cursor pattern as AggregateToolUsage). An empty/absent bucket yields zero visits and no error. Filtering by record type is the caller's job.
func (*Manager) SetAgentTokenOwnerGate ¶ added in v0.64.0
func (m *Manager) SetAgentTokenOwnerGate(gate agentTokenOwnerGate)
SetAgentTokenOwnerGate installs the predicate ValidateAgentToken consults for every OWNED agent token. Passing nil removes it. Safe to call at any time.
It exists because a token's authorisation is decided once, when the token is minted, and nothing re-checks the identity behind it afterwards. Disabling a user is the documented remediation for a compromised account — it revokes their sessions and stops their JWTs — but the agent tokens they minted are separate records that kept authenticating, still carrying that user's UserID into every downstream authorisation and activity decision. The gate closes that: the token is only as live as its owner.
It FAILS CLOSED. A gate that errors denies the token rather than falling back to "valid", because the failure mode of the alternative is precisely the hole this closes. The personal edition installs no gate and is unaffected — its tokens are all ownerless.
func (*Manager) SetAgentTokenScopeResolver ¶ added in v0.66.1
func (m *Manager) SetAgentTokenScopeResolver(resolve agentTokenScopeResolver)
SetAgentTokenScopeResolver installs the live entitlement check used on each owned-token authentication. Its result can only narrow the persisted grant.
func (*Manager) SetSchemaVersion ¶ added in v0.33.4
SetSchemaVersion stores the current migration schema version.
func (*Manager) SetSessionWorkspace ¶ added in v0.49.0
SetSessionWorkspace backfills the workspace on an already-persisted session.
Needed because the workspace is discovered asynchronously (the client is asked for its roots only after the handshake completes — asking during it deadlocks), so a busy session can be persisted before the answer arrives.
func (*Manager) SetToolCallLimits ¶ added in v0.65.0
SetToolCallLimits configures the per-record response cap (in bytes of marshalled JSON) and the per-server record count for the tool-call history.
Non-positive values are ignored, leaving the current limit in place, so a config that omits the keys cannot silently restore the unbounded growth of #1176. This mirrors ActivityService.SetMaxResponseSize.
func (*Manager) StopAsync ¶ added in v0.47.0
func (m *Manager) StopAsync()
StopAsync stops the async operation manager, draining any queued operations to the database. It is idempotent: a second call (including the one inside Close) is a no-op, so callers may StopAsync then Close.
Use this when a final DB write must happen strictly AFTER all queued async operations have flushed but BEFORE the DB handle closes — e.g. the telemetry shutdown marker (Spec 080 FR-010): StopAsync, write the marker, then Close, which then closes the DB with no intervening work.
func (*Manager) StreamActivities ¶
func (m *Manager) StreamActivities(filter ActivityFilter) <-chan *ActivityRecord
StreamActivities returns a channel that yields activity records matching the filter. The channel is closed when all matching records have been sent. This is useful for streaming large exports without loading all records into memory. Respects filter.Limit and filter.Offset for bounded streaming.
func (*Manager) UpdateActivityMetadata ¶ added in v0.17.0
UpdateActivityMetadata updates the metadata of an existing activity record. This is used for async updates like sensitive data detection results. The updates map is merged into the existing metadata (existing keys are preserved unless overwritten).
func (*Manager) UpdateAgentTokenLastUsed
deprecated
added in
v0.20.0
UpdateAgentTokenLastUsed updates the LastUsedAt timestamp for an OWNERLESS token identified by name.
Deprecated: token names are unique only within an owner, so a bare name is ambiguous in the server edition. Authentication paths hold the validated record and must call UpdateAgentTokenLastUsedByHash instead.
func (*Manager) UpdateAgentTokenLastUsedByHash ¶ added in v0.64.0
UpdateAgentTokenLastUsedByHash updates the LastUsedAt timestamp for the token stored under the given HMAC hash. The hash is the authoritative, unambiguous key: unlike a name it is unique across owners, so this cannot stamp another tenant's token.
func (*Manager) UpdateServerStatistics ¶
func (m *Manager) UpdateServerStatistics(stats *ServerStatistics) error
UpdateServerStatistics updates server statistics
func (*Manager) UpdateSessionActivity ¶ added in v0.21.4
UpdateSessionActivity updates LastActivity without incrementing tool call counts. Call this on any MCP message to keep the session alive.
func (*Manager) UpdateSessionStats ¶
UpdateSessionStats increments tool call count and adds tokens
func (*Manager) UpdateUpstream ¶
func (m *Manager) UpdateUpstream(id string, serverConfig *config.ServerConfig) error
UpdateUpstream updates an upstream server configuration
func (*Manager) ValidateAgentToken ¶ added in v0.20.0
ValidateAgentToken hashes the raw token and looks it up in storage. Returns the token if found and valid (not expired, not revoked) and its owner is still allowed to authenticate. Returns an error describing why validation failed.
type OAuthAttributes ¶
type OAuthAttributes struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"` // Note: This might contain secrets
RedirectURI string `json:"redirect_uri"`
Scopes []string `json:"scopes"`
PKCEEnabled bool `json:"pkce_enabled"`
}
OAuthAttributes represents stable OAuth configuration attributes
type OAuthCompletionEvent ¶
type OAuthCompletionEvent struct {
ServerName string `json:"server_name"`
CompletedAt time.Time `json:"completed_at"`
ProcessedAt *time.Time `json:"processed_at,omitempty"` // Nil if not yet processed by server
}
OAuthCompletionEvent represents an OAuth completion event for cross-process notification
func (*OAuthCompletionEvent) MarshalBinary ¶
func (e *OAuthCompletionEvent) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*OAuthCompletionEvent) UnmarshalBinary ¶
func (e *OAuthCompletionEvent) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
type OAuthTokenRecord ¶
type OAuthTokenRecord struct {
ServerName string `json:"server_name"` // Storage key (serverName_hash format)
DisplayName string `json:"display_name,omitempty"` // Actual server name (for RefreshManager lookup)
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token,omitempty"`
TokenType string `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
Scopes []string `json:"scopes,omitempty"`
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
// ClientID and ClientSecret are persisted for DCR (Dynamic Client Registration)
// These are required for token refresh when using DCR-obtained credentials
ClientID string `json:"client_id,omitempty"`
ClientSecret string `json:"client_secret,omitempty"`
// CallbackPort and RedirectURI are persisted for OAuth redirect URI port persistence (Spec 022)
// These ensure re-authentication uses the same port registered during DCR
CallbackPort int `json:"callback_port,omitempty"` // Port used during DCR for redirect_uri
RedirectURI string `json:"redirect_uri,omitempty"` // Full redirect URI registered with DCR
}
OAuthTokenRecord represents stored OAuth tokens for a server
func (*OAuthTokenRecord) GetServerName ¶
func (r *OAuthTokenRecord) GetServerName() string
GetServerName returns the actual server name for RefreshManager lookup. Falls back to ServerName if DisplayName is not set (for backward compatibility).
func (*OAuthTokenRecord) MarshalBinary ¶
func (o *OAuthTokenRecord) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*OAuthTokenRecord) UnmarshalBinary ¶
func (o *OAuthTokenRecord) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
type OnboardingState ¶ added in v0.29.0
type OnboardingState struct {
// Engaged is true once the wizard was shown and the user completed or
// skipped it. Once true, the wizard does not auto-show again, even if
// state regresses (e.g. user disconnects all clients).
Engaged bool `json:"engaged"`
// FirstShownAt is the timestamp of first wizard render.
FirstShownAt *time.Time `json:"first_shown_at,omitempty"`
// EngagedAt is the timestamp of completion or explicit skip.
EngagedAt *time.Time `json:"engaged_at,omitempty"`
// ConnectStepStatus is one of: "", "completed", "completed_external",
// "skipped" (Spec 080 FR-001). "completed_external" records a dismissal
// where the connect step was untouched but the install was already
// connected outside the wizard (CLI, ConnectModal, manual config).
ConnectStepStatus string `json:"connect_step_status,omitempty"`
// ServerStepStatus is one of: "", "completed", "skipped".
ServerStepStatus string `json:"server_step_status,omitempty"`
}
OnboardingState records whether the user has engaged with the first-run wizard, and which steps they completed or skipped. Persisted under OnboardingBucket / OnboardingStateKey. Absence of the record means "wizard has never been shown to this installation".
type PromptApprovalRecord ¶ added in v0.59.0
type PromptApprovalRecord struct {
ServerName string `json:"server_name"`
PromptName string `json:"prompt_name"`
ApprovedHash string `json:"approved_hash"`
CurrentHash string `json:"current_hash"`
HashSchemaVersion uint64 `json:"hash_schema_version,omitempty"`
Status string `json:"status"` // "approved", "pending", "changed"
ApprovedAt time.Time `json:"approved_at"`
ApprovedBy string `json:"approved_by"`
PreviousDescription string `json:"previous_description,omitempty"`
CurrentDescription string `json:"current_description,omitempty"`
PreviousArguments string `json:"previous_arguments,omitempty"`
CurrentArguments string `json:"current_arguments,omitempty"`
Disabled bool `json:"disabled,omitempty"`
}
PromptApprovalRecord is the per-(server, prompt) rug-pull baseline for aggregated upstream prompts (spec 100). It is the prompt analogue of ToolApprovalRecord, deliberately parallel — NOT a shared bucket — because the server:tool and server:prompt key spaces would collide and the tool record carries schema/scan fields prompts never use.
It baselines ADVERTISED LIST METADATA ONLY (name + description + arguments); get-time prompts/get message content is out of scope and not baselineable here (spec 100 Non-Goals). Previous* fields are retained so a metadata revert is detectable (server swaps a description back → auto re-approve).
func (*PromptApprovalRecord) Key ¶ added in v0.59.0
func (r *PromptApprovalRecord) Key() string
Key returns the storage key for this prompt approval record.
func (*PromptApprovalRecord) MarshalBinary ¶ added in v0.59.0
func (r *PromptApprovalRecord) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*PromptApprovalRecord) UnmarshalBinary ¶ added in v0.59.0
func (r *PromptApprovalRecord) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
type QuarantineServerData ¶
type QueueFullError ¶
type QueueFullError struct {
Operation string
}
func (*QueueFullError) Error ¶
func (e *QueueFullError) Error() string
type Result ¶
type Result struct {
Error error
Data interface{}
}
Result contains the result of a storage operation
type ServerAttributes ¶
type ServerAttributes struct {
Name string `json:"name"` // Server name (required)
Protocol string `json:"protocol"` // http, stdio, etc.
URL string `json:"url"` // For HTTP servers
Command string `json:"command"` // For stdio servers
Args []string `json:"args"` // For stdio servers
WorkingDir string `json:"working_dir"` // Working directory
Env map[string]string `json:"env"` // Environment variables (sorted)
Headers map[string]string `json:"headers"` // HTTP headers (sorted)
OAuth *OAuthAttributes `json:"oauth"` // OAuth configuration (if present)
}
ServerAttributes represents the stable attributes that define a server's identity
type ServerIdentity ¶
type ServerIdentity struct {
ID string `json:"id"` // SHA256 hash of stable attributes
ServerName string `json:"server_name"` // Human-readable name
Fingerprint string `json:"fingerprint"` // Short hash (first 12 chars) for display
Attributes ServerAttributes `json:"attributes"` // Stable configuration attributes
FirstSeen time.Time `json:"first_seen"` // When first encountered
LastSeen time.Time `json:"last_seen"` // When last active
ConfigPaths []string `json:"config_paths"` // All configs that have included this server
Metadata map[string]string `json:"metadata"` // Additional metadata
}
ServerIdentity represents a unique server identity based on stable configuration
func NewServerIdentity ¶
func NewServerIdentity(server *config.ServerConfig, configPath string) *ServerIdentity
NewServerIdentity creates a new ServerIdentity from config
func (*ServerIdentity) GetShortID ¶
func (si *ServerIdentity) GetShortID() string
GetShortID returns a shortened version of the ID for display
func (*ServerIdentity) IsStale ¶
func (si *ServerIdentity) IsStale(threshold time.Duration) bool
IsStale returns true if the server hasn't been seen for a long time
func (*ServerIdentity) UpdateLastSeen ¶
func (si *ServerIdentity) UpdateLastSeen(configPath string)
UpdateLastSeen updates the last seen timestamp and adds config path if new
type ServerStatistics ¶
type ServerStatistics struct {
ServerID string `json:"server_id"`
ServerName string `json:"server_name"`
TotalCalls int `json:"total_calls"`
SuccessfulCalls int `json:"successful_calls"`
ErrorCalls int `json:"error_calls"`
AverageResponseTime int64 `json:"avg_response_time"` // nanoseconds
LastCallTime *time.Time `json:"last_call_time,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
ServerStatistics represents statistical data for a server
type SessionRecord ¶
type SessionRecord 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"` // Whether client supports roots
HasSampling bool `json:"has_sampling,omitempty"` // Whether client supports sampling
Experimental []string `json:"experimental,omitempty"` // Experimental capability names
// Workspace / work session (Spec 082).
//
// WorkspaceRoot is the project the client is working in, fetched once from
// the client's MCP roots. It is a LOCAL FILESYSTEM PATH: it stays on this
// machine and is never sent to telemetry. WorkspaceName is its basename, and
// is what the UI shows.
//
// WorkSessionID groups this connection with the other connections that make
// up the same stretch of user work (see internal/runtime/worksession.go).
// A client reconnecting every few minutes produces many session records that
// all share one WorkSessionID.
WorkspaceRoot string `json:"workspace_root,omitempty"`
WorkspaceName string `json:"workspace_name,omitempty"`
WorkSessionID string `json:"work_session_id,omitempty"`
}
SessionRecord represents a stored MCP session
type TimeoutError ¶
type TimeoutError struct {
Operation string
}
Error types for async operations
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
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 ToolApprovalRecord ¶ added in v0.21.0
type ToolApprovalRecord struct {
ServerName string `json:"server_name"`
ToolName string `json:"tool_name"`
ApprovedHash string `json:"approved_hash"`
CurrentHash string `json:"current_hash"`
HashSchemaVersion uint64 `json:"hash_schema_version,omitempty"`
Status string `json:"status"` // "approved", "pending", "changed"
ApprovedAt time.Time `json:"approved_at"`
ApprovedBy string `json:"approved_by"`
PreviousDescription string `json:"previous_description,omitempty"`
CurrentDescription string `json:"current_description,omitempty"`
PreviousSchema string `json:"previous_schema,omitempty"`
CurrentSchema string `json:"current_schema,omitempty"`
PreviousOutputSchema string `json:"previous_output_schema,omitempty"`
CurrentOutputSchema string `json:"current_output_schema,omitempty"`
Disabled bool `json:"disabled,omitempty"`
// HeldReason, HeldVerdict and HeldSignals carry the scan evidence that made
// the trust_mode: scan gate hold this tool for human review (spec 086
// FR-018). They are set ONLY on the pass that performs the hold and cleared
// whenever the record leaves the held state, so they always describe the
// CURRENT hold. All three are additive and omitempty: records written before
// this field existed (and every record held for a non-scan reason) decode
// with them empty and render as they always did.
//
// HeldReason is one of the ToolHeldReason* constants.
HeldReason string `json:"held_reason,omitempty"`
// HeldVerdict is the offline scanner's baseline verdict at hold time
// ("dangerous" / "warnings"; "clean" when only coverage failed).
HeldVerdict string `json:"held_verdict,omitempty"`
// HeldSignals lists the deterministic check ids that matched, e.g.
// "tpa.TPA-2026-0001.hidden_instruction" or "phrase.injection". Deduplicated,
// order-stable, capped at MaxToolHeldSignals.
HeldSignals []string `json:"held_signals,omitempty"`
}
ToolApprovalRecord represents a tool's approval status for tool-level quarantine. When a tool is first discovered, it starts as "pending". Once approved, it becomes "approved". If the tool's description or schema changes after approval, it becomes "changed".
func (*ToolApprovalRecord) ClearScanHold ¶ added in v0.53.0
func (r *ToolApprovalRecord) ClearScanHold()
ClearScanHold drops any scan-hold evidence. Called on every transition out of the held state so an approved record never renders a stale TPA badge.
func (*ToolApprovalRecord) Key ¶ added in v0.21.0
func (r *ToolApprovalRecord) Key() string
Key returns the storage key for this tool approval record.
func (*ToolApprovalRecord) MarshalBinary ¶ added in v0.21.0
func (r *ToolApprovalRecord) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*ToolApprovalRecord) SetScanHold ¶ added in v0.53.0
func (r *ToolApprovalRecord) SetScanHold(reason, verdict string, signals []string)
SetScanHold records the evidence of a trust_mode: scan hold on the record. Signals are deduplicated in first-seen order and capped at MaxToolHeldSignals.
func (*ToolApprovalRecord) UnmarshalBinary ¶ added in v0.21.0
func (r *ToolApprovalRecord) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
type ToolCallRecord ¶
type ToolCallRecord struct {
ID string `json:"id"` // UUID
ServerID string `json:"server_id"` // Server identity
ServerName string `json:"server_name"` // For quick reference
ToolName string `json:"tool_name"` // Original tool name (without server prefix)
Arguments map[string]interface{} `json:"arguments"` // Tool arguments
Response interface{} `json:"response"` // Tool response
Error string `json:"error"` // Error if failed
Duration int64 `json:"duration"` // Duration in nanoseconds
Timestamp time.Time `json:"timestamp"` // When the call was made
ConfigPath string `json:"config_path"` // Which config was active
RequestID string `json:"request_id"` // For correlation
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 *config.ToolAnnotations `json:"annotations,omitempty"` // Tool behavior hints snapshot
// ResponseTruncated and ResponseBytes describe a STORAGE-side cut (#1176):
// the caller received the response whole, and only this persisted copy was
// shortened to tool_call_max_response_size. ResponseBytes is the size of
// the marshalled response before the cut, so a consumer can tell a
// shortened record from a small one.
ResponseTruncated bool `json:"response_truncated,omitempty"`
ResponseBytes int64 `json:"response_bytes,omitempty"`
// ArgumentsTruncated says the stored Arguments are a placeholder, not the
// arguments the tool was called with. Replay MUST refuse to reuse them:
// re-dispatching the placeholder would call the upstream tool with
// nonsense, and call_tool_write / destructive variants reach real systems.
ArgumentsTruncated bool `json:"arguments_truncated,omitempty"`
}
ToolCallRecord represents a tool call with server context
type ToolCallScope ¶ added in v0.64.0
type ToolCallScope []string
ToolCallScope restricts a tool-call read to a set of upstream server names (#1166 follow-up).
nil means UNRESTRICTED — an admin caller, or an internal caller with no identity to check. A non-nil value restricts, and an EMPTY non-nil value restricts to nothing: that is the shape an agent token allowed no servers produces, and reading it as "unrestricted" would open the door it exists to close. "*" is a wildcard, matching auth.AuthContext.CanAccessServer.
It is threaded into the read itself rather than applied to a returned page because the reads it guards also report a `total`: post-filtering shrinks the page while the total keeps counting the records it removed, which is both a broken pager and a precise count oracle for what was hidden.
func (ToolCallScope) Allows ¶ added in v0.64.0
func (s ToolCallScope) Allows(serverName string) bool
Allows reports whether records attributed to serverName are in scope.
type ToolHashRecord ¶
type ToolHashRecord struct {
ToolName string `json:"tool_name"`
Hash string `json:"hash"`
Updated time.Time `json:"updated"`
}
ToolHashRecord represents a tool hash for change detection
func (*ToolHashRecord) MarshalBinary ¶
func (h *ToolHashRecord) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*ToolHashRecord) UnmarshalBinary ¶
func (h *ToolHashRecord) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
type ToolStatRecord ¶
type ToolStatRecord struct {
ToolName string `json:"tool_name"`
Count uint64 `json:"count"`
LastUsed time.Time `json:"last_used"`
}
ToolStatRecord represents tool usage statistics
func (*ToolStatRecord) MarshalBinary ¶
func (t *ToolStatRecord) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*ToolStatRecord) UnmarshalBinary ¶
func (t *ToolStatRecord) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
type ToolUsageStat ¶ added in v0.33.0
ToolUsageStat is a per-tool rollup of activity over a bounded window. Used by the global tools view (spec 050). A zero LastUsed means the tool was never used within the window.
type UnsupportedOperationError ¶
type UnsupportedOperationError struct {
Operation string
}
UnsupportedOperationError is returned for unknown operation types
func (*UnsupportedOperationError) Error ¶
func (e *UnsupportedOperationError) Error() string
type UpstreamRecord ¶
type UpstreamRecord struct {
ID string `json:"id"`
Name string `json:"name"`
URL string `json:"url,omitempty"`
Protocol string `json:"protocol,omitempty"` // stdio, http, sse, streamable-http, auto
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
WorkingDir string `json:"working_dir,omitempty"` // Working directory for stdio servers
Env map[string]string `json:"env,omitempty"`
Headers map[string]string `json:"headers,omitempty"` // For HTTP authentication
OAuth *config.OAuthConfig `json:"oauth,omitempty"` // OAuth configuration
Enabled bool `json:"enabled"`
Quarantined bool `json:"quarantined"` // Security quarantine status
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
Isolation *config.IsolationConfig `json:"isolation,omitempty"` // Per-server isolation settings
ReconnectOnUse bool `json:"reconnect_on_use,omitempty"` // Attempt reconnection on tool call
// AutoApproveToolChanges (MCP-2930/MCP-2940) is the per-server intent to
// auto-approve new/changed tools past the trust baseline. Tri-state *bool.
// Persisted to BBolt because SaveConfiguration rebuilds the JSON config's
// server list from these records — a field absent here is wiped on the
// next mutation, so REST/UI toggling (MCP-2932) and runtime enforcement
// (MCP-2931) would not survive a save/restart without it.
AutoApproveToolChanges *bool `json:"auto_approve_tool_changes,omitempty"`
// TrustMode (spec 086) is the per-server trust tier (auto|scan|manual) that
// governs new-server admission and tool-change approval. Persisted to BBolt
// for the same reason as AutoApproveToolChanges: SaveConfiguration rebuilds
// the JSON server list from these records, so a REST/UI/MCP-set trust_mode
// would be wiped on the next save without it.
TrustMode string `json:"trust_mode,omitempty"`
LauncherWaitTimeout config.Duration `json:"launcher_wait_timeout,omitempty"` // Spec 046: max wait for locally-launched HTTP/SSE upstream URL to become reachable
EnabledTools []string `json:"enabled_tools,omitempty"` // Allowlist: only these tools are exposed
DisabledTools []string `json:"disabled_tools,omitempty"` // Denylist: these tools are hidden
// MCP-866: persist a server's registry origin + provenance so the
// approval/quarantine view and the custom-origin skip_quarantine guard
// survive a restart.
SourceRegistryID string `json:"source_registry_id,omitempty"`
SourceRegistryProvenance string `json:"source_registry_provenance,omitempty"`
// Spec 074: per-server discovery/health-check interval overrides, persisted
// so REST-API/UI-set overrides survive a restart. *Duration tri-state:
// nil = inherit, pointer-to-0s = disabled, positive = interval.
HealthCheckInterval *config.Duration `json:"health_check_interval,omitempty"`
ToolDiscoveryInterval *config.Duration `json:"tool_discovery_interval,omitempty"`
// MCP-3322: per-server MCP `initialize` handshake deadline override,
// persisted so a REST/UI/CLI-set init_timeout survives a restart.
InitTimeout *config.Duration `json:"init_timeout,omitempty"`
// Spec 084: per-server toon_output override ("" = inherit global),
// persisted so the override survives a restart and a SaveConfiguration
// rebuild of the JSON server list.
ToonOutput string `json:"toon_output,omitempty"`
// Spec 093: per-server concurrency-limit overrides, persisted for the same
// reason as the interval overrides above — SaveConfiguration rebuilds the
// JSON server list from these records, so a REST/UI-set limit would be
// wiped on the next save without them. Tri-state: nil = inherit the
// per-server default set, 0 = opt out, positive = override.
MaxConcurrentRequests *int `json:"max_concurrent_requests,omitempty"`
QueueSize *int `json:"queue_size,omitempty"`
QueueTimeout *config.Duration `json:"queue_timeout,omitempty"`
// ExposePrompts is the per-server override for exposing upstream prompts
// through mcpproxy's aggregated prompts/list and prompts/get.
ExposePrompts *bool `json:"expose_prompts,omitempty"`
}
UpstreamRecord represents an upstream server record in storage
func (*UpstreamRecord) MarshalBinary ¶
func (u *UpstreamRecord) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (*UpstreamRecord) UnmarshalBinary ¶
func (u *UpstreamRecord) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler