storage

package
v0.71.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
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.

View Source
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).

View Source
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.

View Source
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"
)
View Source
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.

View Source
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"

	// ToolBaselineDecisionsBucket holds one marker per server stating that the
	// server's tool baseline has been decided (Spec 117 FR-020, #1567). Created
	// on first write; removed per server only together with its tool-approval
	// records.
	ToolBaselineDecisionsBucket = "tool_baseline_decisions"

	// Onboarding wizard bucket (Spec 046)
	OnboardingBucket = "onboarding"
)

Bucket names for bbolt database

View Source
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).

View Source
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

View Source
const (
	ToolApprovalStatusApproved = "approved"
	ToolApprovalStatusPending  = "pending"
	ToolApprovalStatusChanged  = "changed"
)

ToolApprovalStatus constants for tool-level quarantine

View Source
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.

View Source
const (
	// PurgeKeyToolCallBuckets counts the per-identity tool-call buckets
	// dropped for the server.
	PurgeKeyToolCallBuckets = "tool_call_buckets"
	// PurgeKeyServerIdentities counts the server identities dropped.
	PurgeKeyServerIdentities = serverIdentitiesBucket
)

Purge-set report keys that are not bucket names.

View Source
const (
	// ConfigCommitGenerationKey (meta bucket) holds the generation G of the
	// last config commit, as a decimal string.
	ConfigCommitGenerationKey = "config_commit_generation"
	// QuarantineEnabledMetaKey (meta bucket) holds the global
	// quarantine_enabled value of the last commit ("true"/"false"), so
	// approval decisions resolve their policy from storage (Spec 116 D16).
	QuarantineEnabledMetaKey = "quarantine_enabled"
)
View Source
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
)
View Source
const ActivityRecordsBucket = "activity_records"

ActivityRecordsBucket is the BBolt bucket name for activity records

View Source
const AgentTokenPendingBucket = "agent_token_pending" //nolint:gosec // bucket name, not a credential

AgentTokenPendingBucket indexes a staged rotation's NEW secret hash to the PRIMARY (current) hash key of the client-credential record it belongs to (FR-021a, data-model.md §3/§9): both the old and the pending secret must authenticate while a rotation is staged, and the primary record moves under the AgentTokensBucket key only at finalize.

View Source
const AnnotationHashSchemaVersion = 4

AnnotationHashSchemaVersion is the per-record HashSchemaVersion that starts folding the safety-relevant tool annotation hints (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) into the tool approval hash (red-team RT-03). Tools whose effective hints are the MCP defaults keep a byte-identical hash, so only tools with non-default hints get a new hash; records below this version are migrated by the formula-change path in runtime.checkToolApprovals without re-review when their stored contract still matches.

View Source
const CurrentSchemaVersion = 3

Current schema version

View Source
const DefaultMaxResponseSize = 64 * 1024

DefaultMaxResponseSize is the default maximum size for response truncation (64KB)

View Source
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.

View Source
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.

View Source
const (
	OnboardingStateKey = "wizard_state"
)

Onboarding state keys (Spec 046)

View Source
const OutputSchemaHashSchemaVersion = 3

OutputSchemaHashSchemaVersion is the schema version that starts including MCP outputSchema in the tool approval hash baseline.

View Source
const ScopeFilterUnattributed = "-"

ScopeFilterUnattributed is the sentinel filter value ("-") that selects records or sessions whose profile, client or token is EMPTY (Spec 108 FR-031, url-filter-contract.md). It is never a valid stored value.

View Source
const ToolApprovalHashSchemaVersion = UnambiguousHashSchemaVersion

ToolApprovalHashSchemaVersion is the HashSchemaVersion stamped on every tool approval record whose hashes this binary computes.

View Source
const UnambiguousHashSchemaVersion = 5

UnambiguousHashSchemaVersion is the per-record HashSchemaVersion whose tool approval hash encodes every field length-prefixed, with an explicit marker for an absent output schema (issue #1606). The v4 formula joined the fields with an unescaped '|' and left an absent output schema out, so (D, I, O) and (D+"|"+I, O, none) shared one hash. Records below this version are re-baselined by the formula-migration path in runtime.checkToolApprovals only when their v4 ApprovedHash covers the stored contract and that contract is still the one the server serves; any other contract is marked changed.

Variables

View Source
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")

	// ErrAgentTokenOwnerLimitReached is returned when one owner reaches the
	// server edition's per-owner quota. It is distinct from the deployment cap
	// because the caller can remedy this condition by permanently deleting one
	// of their own unused tokens.
	ErrAgentTokenOwnerLimitReached = errors.New("maximum number of agent tokens for this owner 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")
	ErrAgentTokenScopeUnavailable = errors.New("token entitlement unavailable")

	// 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).

View Source
var (
	// ErrClientCredentialConflict is returned when the token name
	// "client-<id>" is already held by a GRANDFATHERED kind=agent token
	// (research D8). Minting never touches such a record.
	ErrClientCredentialConflict = errors.New("token name is held by a regular agent token")

	// ErrClientCredentialActive is returned by MintClientCredential when an
	// ACTIVE (non-revoked, non-expired) kind=client record already holds the
	// name: minting over an active credential is a staged rotation
	// (StageClientCredentialRotation), never an immediate replace.
	ErrClientCredentialActive = errors.New("client credential is active; use rotation instead of mint")

	// ErrClientCredentialNotActive is returned by StageClientCredentialRotation
	// when the kind=client record exists but is revoked or expired: there is
	// no active credential to rotate, so the caller must mint a fresh one.
	ErrClientCredentialNotActive = errors.New("client credential is revoked or expired; mint a new one")

	// ErrClientCredentialNotFound is returned by rotation/forget operations
	// when no client-<id> record exists at all.
	ErrClientCredentialNotFound = errors.New("client credential not found")

	// ErrClientCredentialNotRotating is returned by FinalizeClientCredentialRotation
	// when no rotation is staged. Callers treat this as an idempotent no-op
	// success (a second finalize is a 200 no-op), not a hard error.
	ErrClientCredentialNotRotating = errors.New("client credential has no rotation in progress")

	// ErrClientCredentialRegenerateRefused is returned by
	// RegenerateAgentTokenForOwner when the resolved record is a kind=client
	// credential. The generic regenerate path mints a fresh mcp_agt_ secret
	// and leaves Kind/ClientID/ProfileMode untouched, which would permanently
	// brick the credential: ValidateTokenInvariants requires the presented
	// secret's prefix to match the stored record's kind on every subsequent
	// authentication, so the new mcp_agt_ secret would fail closed forever
	// while the record stays non-revoked (MintClientCredential also refuses
	// to replace an active record with ErrClientCredentialActive). Client
	// credentials rotate only through StageClientCredentialRotation /
	// FinalizeClientCredentialRotation, never through the generic name-based
	// regenerate used by admin token management.
	ErrClientCredentialRegenerateRefused = errors.New("client credential cannot be regenerated via this endpoint; use client-credential rotation instead")
)

Sentinel errors for the client-credential mint/rotation surface (FR-021, FR-021a).

View Source
var ErrInvariant = stderrors.New("config commit invariant violated")

ErrInvariant marks a commit batch that violates a Spec 116 invariant. It indicates a bug in the caller, never a user error.

View Source
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".

View Source
var ErrSkipOAuthTokenUpdate = stderrors.New("skip oauth token update")

ErrSkipOAuthTokenUpdate may be returned by an UpdateOAuthToken mutate function to leave the record untouched without reporting an error (e.g. a compare-and-swap whose expected generation no longer matches).

View Source
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.

View Source
var ErrUpstreamExists = stderrors.New("upstream server already exists")

ErrUpstreamExists is returned by CreateUpstream when a record with the same ID is already stored.

View Source
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".

ValidActivityStatuses is the closed status vocabulary, for filter validation and API documentation.

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 DisableSyncForTesting added in v0.71.0

func DisableSyncForTesting()

DisableSyncForTesting makes every database opened afterwards in this process skip the fsync on commit (bbolt Options.NoSync). Committed data is still visible to every reader of the open database; only crash durability is lost, which no unit test exercises. Call it from TestMain in packages whose tests open many databases or commit heavily: an fsync per commit on the Windows CI runner dominated internal/runtime's test time. Never call it from production code.

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 OAuthRecordVisible added in v0.71.0

func OAuthRecordVisible(rec *OAuthTokenRecord, b commitview.CredentialBinding) bool

OAuthRecordVisible reports whether a reader bound to b may use rec: a bound reader sees only records written under its epoch (a record written before PR2b carries epoch 0 and is read only by a binding with epoch 0); an unbound reader sees every record.

func PromptApprovalKey added in v0.59.0

func PromptApprovalKey(serverName, promptName string) string

PromptApprovalKey returns the storage key for a prompt approval record.

func ServerRowMatches added in v0.71.0

func ServerRowMatches(cfg, stored *config.ServerConfig) bool

ServerRowMatches reports whether a stored row describes the same projection of a server as cfg: the persisted fields compared, Created and Updated and the stamps ignored. Config-only fields (Shared, AuthBroker, the explicit quarantine bit) are not part of the projection.

func ToolApprovalKey added in v0.21.0

func ToolApprovalKey(serverName, toolName string) string

ToolApprovalKey returns the storage key for a tool approval record.

func TruncateActivityResponse

func TruncateActivityResponse(response string, maxSize int) (string, bool)

TruncateActivityResponse is a helper to truncate responses for storage.

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

	// ErrorClass and FaultDomain filter by the call-error taxonomy (Spec 113-c
	// FR-046): exact match on ActivityRecord.ErrorClass / FaultDomain. Records
	// written before Spec 113 carry neither and never match a set filter.
	ErrorClass  string
	FaultDomain 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"

	// Scope attribution filters (Spec 108 FR-031). Each is exact-match, or "-"
	// (ScopeFilterUnattributed) for "no value". Profile, TokenName and
	// ClientName fall back to the legacy record shapes (see the effective*
	// helpers); ClientID reads the first-class field only.
	Profile    string // Effective profile name
	ClientID   string // Client id (the binding), NOT the self-reported name
	ClientName string // Advisory clientInfo.name; only /activity and /activity/export expose it
	TokenName  string // Token name (REST "agent" is an alias)

	// IdentityOwner is set for scoped (non-admin) callers: a row the owner did
	// not make reads as unattributed to the Profile/ClientID/TokenName filters.
	IdentityOwner *ActivityIdentityOwner

	// 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

	// UserID is an AUTHORIZATION filter (Spec 107 FR-002, T086), evaluated
	// beside AllowedServers: empty means unrestricted (every existing caller
	// of ListActivities/StreamActivities), a non-empty value restricts
	// matches to records whose UserID equals this exactly. It exists so
	// GET /api/v1/user/activity can select "my own records on servers I am
	// entitled to" inside ONE storage query, rather than fetching a page and
	// post-filtering it — which shrinks the returned page while `total` keeps
	// counting the records that were dropped.
	UserID 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 ActivityIdentityOwner added in v0.70.0

type ActivityIdentityOwner struct {
	TokenName   string
	TokenPrefix string
}

ActivityIdentityOwner is the caller identity of a SCOPED (non-admin) reader. When set on an ActivityFilter, Matches evaluates the profile/client/token filters against the view that caller is allowed to see: a record the caller did not make reads as unattributed. Without it a scoped caller could probe "?token=<someone else>" and use total/the row set as an oracle for another token's activity (Spec 108 FR-031 disclosure rule).

"Own" needs the stored token prefix AND name to match (names are unique per owner only; the 12-char prefix carries few random bits), the same rule as httpapi.redactForeignIdentity.

func (*ActivityIdentityOwner) Owns added in v0.70.0

Owns reports whether the record was made by this caller.

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

	// Call-error taxonomy (Spec 113-c FR-043): what failed and whose fault it
	// is, stamped by internal/callerr at the dispatch site. All omitempty: a
	// success record, and every record written before Spec 113, carries none
	// of them and round-trips byte-identical. Display/filter only; Status is
	// unchanged (an isError result keeps status "error" and is told apart by
	// ErrorClass "tool_error", FR-048).
	ErrorClass         string `json:"error_class,omitempty"`          // network|timeout|http|jsonrpc|tool_error|session_terminated|auth|proxy_policy|proxy_internal|cancelled
	FaultDomain        string `json:"fault_domain,omitempty"`         // upstream|proxy|client
	UpstreamHTTPStatus int    `json:"upstream_http_status,omitempty"` // upstream HTTP status when known

	// 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"`

	// Scope attribution (Spec 108 FR-029): the profile, client and token IN
	// EFFECT when the call ran, stamped once at write time and never rewritten
	// (a later reassignment does not touch history). First-class rather than
	// metadata because ActivityFilter.Matches compares struct fields.
	//
	// All omitempty: a record written before Spec 108, or one with no MCP/REST
	// request context (system_*, config_change, limiter sheds), carries none of
	// them and round-trips byte-identical. Legacy records keep matching the
	// profile/client_name/token filters through the fallbacks on the effective*
	// helpers below.
	Profile       string `json:"profile,omitempty"`        // Effective profile name (profile_change: the NEW profile)
	ProfileSource string `json:"profile_source,omitempty"` // pin|binding|url|session|anonymous|none
	ClientID      string `json:"client_id,omitempty"`      // Client id from the client-credential binding
	ClientName    string `json:"client_name,omitempty"`    // Self-reported clientInfo.name (advisory, never authoritative)
	TokenName     string `json:"token_name,omitempty"`     // Agent/client token name
	// TokenPrefix is the calling token's 12-char display prefix, persisted as
	// the INTERNAL ownership proof (FR-029/FR-031): a policy_decision or
	// prompt_get row carries no _auth_token_prefix argument, so this is how a
	// scoped caller recognises its own rows. It is never projected: no REST,
	// export or SSE shape maps it. Empty on records written before it existed
	// (those fall back to the _auth_token_prefix argument, else read as foreign).
	TokenPrefix string `json:"token_prefix,omitempty"`
	// BlockReason is the typed cause of a profile policy refusal. It is also
	// written to Metadata[MetadataKeyBlockReason] for one release so existing
	// readers keep working. Display only: no filter reads it.
	BlockReason string `json:"block_reason,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) EffectiveBlockReason added in v0.70.0

func (a *ActivityRecord) EffectiveBlockReason() string

EffectiveBlockReason is the first-class block reason, else the metadata key 108-d wrote before the field existed.

func (*ActivityRecord) EffectiveClientName added in v0.70.0

func (a *ActivityRecord) EffectiveClientName() string

EffectiveClientName is the first-class client name, else metadata.client_name.

func (*ActivityRecord) EffectiveProfile added in v0.70.0

func (a *ActivityRecord) EffectiveProfile() string

EffectiveProfile is the first-class profile, else the legacy metadata.profile (Spec 057) that every record with a resolved profile has carried.

func (*ActivityRecord) EffectiveTokenName added in v0.70.0

func (a *ActivityRecord) EffectiveTokenName() string

EffectiveTokenName is the first-class token name, else the Spec 028 _auth_agent_name argument older records carry.

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 (
	// MetadataKeyBlockReason is the typed cause of a profile policy refusal.
	MetadataKeyBlockReason = "block_reason"

	// 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"
	// ActivityTypeProfileChange represents a Profiles v3 change: a client
	// binding, credential rotation or forget (Spec 108, FR-030). Metadata:
	// actor_kind, actor_name, surface, change, profile, previous_profile,
	// client_id, token_name, diff.
	ActivityTypeProfileChange ActivityType = "profile_change"
)

type AgentTokenOwnerResolver added in v0.68.0

type AgentTokenOwnerResolver func(userID string, granted []string) (OwnerResolution, error)

AgentTokenOwnerResolver answers OwnerResolution for the owner of a token whose stored grant is `granted`. It is consulted on the authentication hot path — exactly ONCE per ValidateAgentToken — so it must be one keyed store read and the entitlement computation, no more. It is called ONLY for owned tokens (UserID != ""), never for the personal edition's ownerless ones.

Errors fail CLOSED: a resolver that cannot answer denies the token (ErrAgentTokenScopeUnavailable), or ErrAgentTokenOwnerInactive when the error wraps that sentinel (the resolver's own owner-store read failed — "cannot read the owner" and "owner is gone" refuse the same way).

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) Backup

func (b *BoltDB) Backup(destPath string) error

Backup creates a backup of the database. The copy carries the same secrets as the live database and the destination is caller-chosen (potentially outside the 0700 data directory), so it is written owner-only.

func (*BoltDB) CleanupOldOAuthCompletionEvents

func (s *BoltDB) CleanupOldOAuthCompletionEvents() error

CleanupOldOAuthCompletionEvents removes OAuth completion events older than 24 hours

func (*BoltDB) ClearOAuthClientCredentials

func (b *BoltDB) ClearOAuthClientCredentials(serverKey string) error

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) ClearOAuthClientCredentialsIf added in v0.71.0

func (b *BoltDB) ClearOAuthClientCredentialsIf(serverKey, expectedClientID, expectedRefreshToken string) (bool, error)

ClearOAuthClientCredentialsIf clears the DCR fields like ClearOAuthClientCredentials, but only while the stored ClientID still equals expectedClientID and the stored RefreshToken still equals expectedRefreshToken, the grant the failed request used (compare-and-clear in one transaction, Spec 113 FR-006a/FR-009). A stale refresh failure therefore cannot clear a registration that a concurrent login just saved, even when the login reused the same client id. It reports whether it cleared.

func (*BoltDB) ClearOAuthClientCredentialsIfClientID added in v0.71.0

func (b *BoltDB) ClearOAuthClientCredentialsIfClientID(serverKey, expectedClientID string) (bool, error)

ClearOAuthClientCredentialsIfClientID clears the DCR fields like ClearOAuthClientCredentials, but only while the stored ClientID still equals expectedClientID (compare-and-clear in one transaction). It is the login path's counterpart of ClearOAuthClientCredentialsIf: a login whose authorization request is rejected because the persisted DCR client no longer exists has no grant to compare, and DCR issues a new id per registration, so a concurrent login that already saved a fresh registration is never wiped. Token fields are left untouched. It reports whether it cleared.

func (*BoltDB) ClearOAuthClientIfBound added in v0.71.0

func (b *BoltDB) ClearOAuthClientIfBound(serverKey, server string, binding commitview.CredentialBinding, observedRev uint64) (bool, error)

ClearOAuthClientIfBound clears only the DCR registration fields (client id and secret, callback port, redirect URI) of the record at serverKey, keeping its tokens, expiry and epoch, under the same checks as DeleteOAuthTokenIfBound (review R9.4): a DCR clear forces a fresh registration on the next login; it does not sign the server out. The rewrite takes a new revision, so a second parked clear that observed the old one is dropped. It reports whether it cleared.

func (*BoltDB) ClearOAuthClientIfBoundAndClientID added in v0.71.0

func (b *BoltDB) ClearOAuthClientIfBoundAndClientID(serverKey, server string, binding commitview.CredentialBinding, expectedClientID string) (bool, error)

ClearOAuthClientIfBoundAndClientID clears the DCR registration fields of the record at serverKey like ClearOAuthClientIfBound, but decides on the client id instead of a revision: it acts only while server's row carries binding, the record was written under it, and the record still holds expectedClientID, all in one transaction. It is the login path's clear of a registration the authorization server rejected: that login holds the client id it sent, not the record it was read from, and DCR issues a new id per registration, so a concurrent login that stored a fresh registration is never wiped. It reports whether it cleared.

func (*BoltDB) ClearOAuthTokenForStandaloneLogout added in v0.71.0

func (b *BoltDB) ClearOAuthTokenForStandaloneLogout(serverKey string) error

ClearOAuthTokenForStandaloneLogout deletes the token record at exactly serverKey (oauth.GenerateServerKey(name, url)) for `mcpproxy auth logout` without a daemon (review R8.3). It is an operator action on the current state, not stale-instance cleanup, so it is not binding-conditional: the standalone CLI opens config.db itself, and bbolt's exclusive file lock means no daemon (and so no live instance) shares the database meanwhile. scripts/check-upstream-write-sites.sh allows it in exactly one file, internal/upstream/cli/client.go.

func (*BoltDB) Close

func (b *BoltDB) Close() error

Close closes the database

func (*BoltDB) CreateUpstream added in v0.71.0

func (b *BoltDB) CreateUpstream(record *UpstreamRecord) error

CreateUpstream stores a new upstream record, failing with ErrUpstreamExists if the ID is taken. The existence check and the Put run in one Update transaction, which bbolt serializes, so the create is atomic.

func (*BoltDB) DeleteIntegrityBaseline added in v0.24.0

func (b *BoltDB) DeleteIntegrityBaseline(serverName string) error

DeleteIntegrityBaseline deletes an integrity baseline by server name

func (*BoltDB) DeleteOAuthToken

func (b *BoltDB) DeleteOAuthToken(serverName string) error

DeleteOAuthToken deletes an OAuth token record

func (*BoltDB) DeleteOAuthTokenIfBound added in v0.71.0

func (b *BoltDB) DeleteOAuthTokenIfBound(serverKey, server string, binding commitview.CredentialBinding, observedRev uint64) (bool, error)

DeleteOAuthTokenIfBound deletes the record at serverKey (tokens and DCR client) only while server's row carries binding and the record is still at revision observedRev, the one the caller inspected (the 5xx token clear, review R6.2). It reports whether it deleted.

func (*BoltDB) DeletePromptApproval added in v0.59.0

func (b *BoltDB) DeletePromptApproval(serverName, promptName string) error

DeletePromptApproval deletes a prompt approval record.

func (*BoltDB) DeleteScanJob added in v0.24.0

func (b *BoltDB) DeleteScanJob(id string) error

DeleteScanJob deletes a scan job by ID

func (*BoltDB) DeleteScanReport added in v0.24.0

func (b *BoltDB) DeleteScanReport(id string) error

DeleteScanReport deletes a scan report by ID

func (*BoltDB) DeleteScanner added in v0.24.0

func (b *BoltDB) DeleteScanner(id string) error

DeleteScanner deletes a scanner plugin by ID

func (*BoltDB) DeleteServerPromptApprovals added in v0.59.0

func (b *BoltDB) DeleteServerPromptApprovals(serverName string) error

DeleteServerPromptApprovals deletes all prompt approval records for a server.

func (*BoltDB) DeleteServerScanJobs added in v0.24.0

func (b *BoltDB) DeleteServerScanJobs(serverName string) error

DeleteServerScanJobs deletes all scan jobs for a server

func (*BoltDB) DeleteServerScanReports added in v0.24.0

func (b *BoltDB) DeleteServerScanReports(serverName string) error

DeleteServerScanReports deletes all scan reports for a server

func (*BoltDB) DeleteServerToolApprovals added in v0.21.0

func (b *BoltDB) DeleteServerToolApprovals(serverName string) error

DeleteServerToolApprovals deletes all tool approval records for a server

func (*BoltDB) DeleteToolApproval added in v0.21.0

func (b *BoltDB) DeleteToolApproval(serverName, toolName string) error

DeleteToolApproval deletes a tool approval record

func (*BoltDB) DeleteToolApprovalIf added in v0.71.0

func (b *BoltDB) DeleteToolApprovalIf(serverName, toolName string, eligible func(*ToolApprovalRecord) bool) (bool, error)

DeleteToolApprovalIf deletes the record only when it still exists and eligible returns true for its CURRENT stored value, evaluated in the same write transaction as the delete. It reports whether a record was removed.

func (*BoltDB) DeleteToolHash

func (b *BoltDB) DeleteToolHash(toolName string) error

DeleteToolHash deletes a tool hash

func (*BoltDB) DeleteUpstream

func (b *BoltDB) DeleteUpstream(id string) error

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

func (b *BoltDB) GetLatestScanJob(serverName string) (*scanner.ScanJob, error)

GetLatestScanJob returns the most recent scan job for a server

func (*BoltDB) GetOAuthClientCredentials

func (b *BoltDB) GetOAuthClientCredentials(serverKey string) (clientID, clientSecret string, callbackPort int, redirectURI string, err error)

GetOAuthClientCredentials retrieves the client credentials, callback port and redirect URI for token refresh. callbackPort returns 0 and redirectURI returns "" if not stored (legacy records or fresh records without DCR).

func (*BoltDB) GetOAuthClientCredentialsBound added in v0.71.0

func (b *BoltDB) GetOAuthClientCredentialsBound(serverKey string, binding commitview.CredentialBinding) (clientID, clientSecret string, callbackPort int, redirectURI string, revision uint64, err error)

GetOAuthClientCredentialsBound is GetOAuthClientCredentials for a reader bound to binding; it also returns the revision of the record it read (0 when none), which a later ClearOAuthClientIfBound passes back.

func (*BoltDB) GetOAuthToken

func (b *BoltDB) GetOAuthToken(serverName string) (*OAuthTokenRecord, error)

GetOAuthToken retrieves an OAuth token record by server name

func (*BoltDB) GetOAuthTokenBound added in v0.71.0

func (b *BoltDB) GetOAuthTokenBound(serverKey string, binding commitview.CredentialBinding) (*OAuthTokenRecord, error)

GetOAuthTokenBound is GetOAuthToken for a reader bound to binding: a record written under another binding reads as absent ("oauth token not found").

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

func (b *BoltDB) GetScanJob(id string) (*scanner.ScanJob, error)

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

func (b *BoltDB) GetSchemaVersion() (uint64, error)

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) GetToolBaselineDecision added in v0.71.0

func (b *BoltDB) GetToolBaselineDecision(serverName string) (d toolreview.BaselineDecision, ok bool, err error)

GetToolBaselineDecision is the BoltDB form of Manager.GetToolBaselineDecision.

func (*BoltDB) GetToolHash

func (b *BoltDB) GetToolHash(toolName string) (string, error)

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

func (b *BoltDB) IncrementToolStats(toolName string) error

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

func (b *BoltDB) ListScanJobs(serverName string) ([]*scanner.ScanJob, error)

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

func (s *BoltDB) MarkOAuthCompletionEventProcessed(serverName string, completedAt time.Time) error

MarkOAuthCompletionEventProcessed marks an OAuth completion event as processed

func (*BoltDB) MarkToolBaselineDecided added in v0.71.0

func (b *BoltDB) MarkToolBaselineDecided(serverName string, d toolreview.BaselineDecision) error

MarkToolBaselineDecided is the BoltDB form of Manager.MarkToolBaselineDecided.

func (*BoltDB) PruneToolApprovalsNotIn added in v0.37.0

func (b *BoltDB) PruneToolApprovalsNotIn(keep map[string]bool) (int, error)

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) SaveIntegrityBaselineWithBlocks added in v0.70.0

func (b *BoltDB) SaveIntegrityBaselineWithBlocks(baseline *scanner.IntegrityBaseline, blocks []scanner.ToolApprovalBlock) error

SaveIntegrityBaselineWithBlocks writes the approval baseline and tool blocks in one bbolt transaction. If any named tool has no captured approval record, the entire update rolls back and the server remains quarantined.

func (*BoltDB) SaveOAuthClientCredentialsIfSameOrEmpty added in v0.71.0

func (b *BoltDB) SaveOAuthClientCredentialsIfSameOrEmpty(serverKey, clientID, clientSecret string, callbackPort int, redirectURI string) (bool, error)

SaveOAuthClientCredentialsIfSameOrEmpty stores a DCR registration like UpdateOAuthClientCredentials, but only while the record already holds this same client id, or holds neither a client id nor a refresh token. It reports whether it saved. Unlike SaveOAuthClientCredentialsIfUnsetOrSame it refuses a record whose DCR fields were cleared but which still holds a refresh token: that token came from another login, and pairing it with this client would make the next refresh fail.

func (*BoltDB) SaveOAuthClientCredentialsIfUnsetOrSame added in v0.71.0

func (b *BoltDB) SaveOAuthClientCredentialsIfUnsetOrSame(serverKey, clientID, clientSecret string, callbackPort int, redirectURI string) (bool, error)

SaveOAuthClientCredentialsIfUnsetOrSame stores a DCR registration like UpdateOAuthClientCredentials, but only while the record holds no client id (missing record, or DCR fields cleared) or already holds this same client id. It reports whether it saved. A login must never write its registration over a different one another login stored in the meantime: that login's token would end up next to this login's client_id.

func (*BoltDB) SaveOAuthClientIfBound added in v0.71.0

func (b *BoltDB) SaveOAuthClientIfBound(serverKey, server string, binding commitview.CredentialBinding, mode OAuthClientSaveMode, clientID, clientSecret string, callbackPort int, redirectURI string) (bool, error)

SaveOAuthClientIfBound persists a DCR client registration (client id and secret, callback port, redirect URI) bound to the credential binding of server: it writes only while server's row carries binding and mode's precondition holds on the record, in one transaction. It reports whether it wrote.

func (*BoltDB) SaveOAuthCompletionEvent

func (s *BoltDB) SaveOAuthCompletionEvent(event *OAuthCompletionEvent) error

SaveOAuthCompletionEvent saves an OAuth completion event to the database

func (*BoltDB) SaveOAuthCompletionEventIfBound added in v0.71.0

func (b *BoltDB) SaveOAuthCompletionEventIfBound(event *OAuthCompletionEvent, binding commitview.CredentialBinding) (bool, error)

SaveOAuthCompletionEventIfBound records an OAuth completion event bound to binding (Spec 116 PR2b, T055c): it writes only while the server's row carries the binding (an unbound caller: while the row exists, or no commit was ever recorded) and stamps the event with the binding, so the consumer can drop an event that a superseded instance wrote. It reports whether it wrote.

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

func (b *BoltDB) SaveScanJob(job *scanner.ScanJob) error

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

It stamps DefinitionChangedAt: when a prior record exists and its current definition content differs from the incoming one the stamp is set to now, otherwise the prior value is carried over. The stamp is also written back to the caller's record. PendingSince is stamped the same way (see its field doc).

func (*BoltDB) SaveToolHash

func (b *BoltDB) SaveToolHash(toolName, hash string) error

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) SaveUpstreamKeepingQuarantine added in v0.70.0

func (b *BoltDB) SaveUpstreamKeepingQuarantine(record *UpstreamRecord, explicit bool) (kept bool, err error)

SaveUpstreamKeepingQuarantine is SaveUpstream with the quarantine-lowering guard: if a record already exists with Quarantined=true and the incoming record would clear it without an explicit decision (explicit=false), the stored quarantine is kept. The read-check-write runs in one bbolt Update transaction so a concurrent QuarantineUpstreamServer cannot be lost between the read and the write. It reports whether the guard kept the quarantine. An undecodable previous record is overwritten, as SaveUpstream would.

func (*BoltDB) SetSchemaVersion added in v0.33.4

func (b *BoltDB) SetSchemaVersion(version uint64) error

SetSchemaVersion stores the current migration schema version.

func (*BoltDB) StampToolApprovalsIdentityKeyed added in v0.67.0

func (b *BoltDB) StampToolApprovalsIdentityKeyed(serverName string, toolNames []string) ([]string, error)

StampToolApprovalsIdentityKeyed marks the named records of one server identity-keyed (Spec 105 FR-009) in ONE update transaction, re-reading each record INSIDE the transaction and stamping it only if it is still unstamped and still does not Restricts() at write time. Used by the discovery producer to end the legacy consults for a server's remaining pre-105 records after its first pass. The in-transaction re-read is what makes the sweep safe against an operator write (SetToolEnabled / BlockTools) that lands between the caller's listing and this stamp (astra r1 P4): a stale listed copy is never written back, so the operator's Disabled=true is neither discarded nor stamped over — only the IdentityKeyed bit is ever touched. Returns the names actually stamped.

func (*BoltDB) Stats

func (b *BoltDB) Stats() (*bbolt.Stats, error)

Stats returns database statistics

func (*BoltDB) UpdateOAuthClientCredentials

func (b *BoltDB) UpdateOAuthClientCredentials(serverKey, clientID, clientSecret string, callbackPort int, redirectURI string) error

UpdateOAuthClientCredentials updates the client credentials (from DCR), callback port and the exact redirect URI used, on an existing token record. This is called after successful Dynamic Client Registration to persist the obtained client_id/secret, the callback port used for the redirect_uri (Spec 022: OAuth Redirect URI Port Persistence), and the redirect URI itself so a later change to `oauth.redirect_uri` that keeps the same port but changes the path (issue #1304) can still be detected as stale (comparing port alone would miss it).

func (*BoltDB) UpdateOAuthToken added in v0.71.0

func (b *BoltDB) UpdateOAuthToken(serverKey string, mutate func(rec *OAuthTokenRecord) error) error

UpdateOAuthToken applies mutate to the record stored under serverKey inside one read-modify-write transaction (Spec 113 FR-006). Fields the mutate function does not touch — the DCR client credentials, callback port, redirect URI, Created and DisplayName — keep the values they have inside that transaction, so a concurrent UpdateOAuthClientCredentials or ClearOAuthClientCredentials is never lost. A missing record is created with ServerName=serverKey. If mutate returns an error nothing is written; ErrSkipOAuthTokenUpdate is swallowed.

func (*BoltDB) UpdateOAuthTokenIfBound added in v0.71.0

func (b *BoltDB) UpdateOAuthTokenIfBound(serverKey, server string, binding commitview.CredentialBinding, mutate func(rec *OAuthTokenRecord) error) (bool, error)

UpdateOAuthTokenIfBound is UpdateOAuthToken bound to the credential binding of server (Spec 116 PR2b): mutate runs and the record is written only while server's row carries binding, in the same transaction. A record of another epoch under the key is a leftover the bound writer does not build on: mutate starts from an empty record. The written record carries the binding's epoch. It reports whether it wrote; mutate returning ErrSkipOAuthTokenUpdate leaves the record alone and reports false. On a write, the record passed to mutate carries the written Revision afterwards (a refresh flight reports it as the revision it serves).

func (*BoltDB) UpdateOnboardingState added in v0.70.0

func (b *BoltDB) UpdateOnboardingState(fn func(*OnboardingState) error) error

UpdateOnboardingState reads the current onboarding state, applies fn to it, and persists the result — all inside ONE bbolt update transaction (Spec 109-b, T035). Every writer of the record (the mark-state handler, the connect success path, the `initialize` hook) MUST go through this instead of a separate GetOnboardingState + SaveOnboardingState pair: bbolt's b.db.Update transactions are serialized against each other, but two separate Get/Save calls are two separate transactions, so a second writer's change made in the gap between them is silently overwritten by the first writer's stale snapshot on Save. Wrapping both steps in one Update closes that window entirely.

A nil fn is a caller error (bbolt would otherwise persist an unmodified read as a no-op write); it returns an error rather than panicking.

Callback constraint: fn executes inside the open bbolt write transaction (and, when reached through Manager.UpdateOnboardingState, with Manager.mu held). It must be a short, pure mutation of the state it is given, and MUST NOT call any BoltDB or Manager method or block on I/O: bbolt allows a single writer, so a nested b.db.Update (or a re-acquired Manager.mu) self-deadlocks. If fn returns an error the transaction is rolled back and nothing is persisted.

type ClientCredentialObservation added in v0.70.0

type ClientCredentialObservation struct {
	State string    `json:"state"`
	At    time.Time `json:"at"`
}

ClientCredentialObservation is one on-demand credential classification of a client's config (see OnboardingState.ClientCredentialObserved).

type ClientMintOptions added in v0.71.0

type ClientMintOptions struct {
	Mode        string
	Pin         string
	ExpiresAt   time.Time
	DisplayName string
	Issuer      *auth.CredentialIssuer
	Purpose     string
}

ClientMintOptions are the fields of a client credential mint. Issuer and Purpose are the Spec 115 issuance fields (data-model §1); a connect mint leaves them empty.

type DatabaseLockedError

type DatabaseLockedError struct {
	Path string
	Err  error
}

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

type EnableServerData struct {
	Name    string
	Enabled bool
}

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

func (m *Manager) AggregateToolUsage(since time.Time) (map[string]ToolUsageStat, error)

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) ApplyServerCommit added in v0.71.0

func (m *Manager) ApplyServerCommit(b *ServerCommitBatch) error

ApplyServerCommit is ApplyServerCommitWithReport without the purge report.

func (*Manager) ApplyServerCommitWithReport added in v0.71.0

func (m *Manager) ApplyServerCommitWithReport(b *ServerCommitBatch) (map[string]PurgeReport, error)

ApplyServerCommitWithReport writes one commit's batch in a single bbolt Update transaction: the purges of Removes and Replaces first, then the OAuth clears, then the saves with their stamps, then the meta keys. Any invariant violation or write error aborts the whole transaction and nothing changes. It returns one PurgeReport per removed or replaced name.

func (*Manager) Backup

func (m *Manager) Backup(destPath string) error

Backup creates a backup of the database

func (*Manager) CheckCommittedView added in v0.71.0

func (m *Manager) CheckCommittedView(server string, sg commitview.ServerGen) error

CheckCommittedView is the construction-time check of an upstream instance (Spec 116 PR2b, review R6.1): in one bbolt View, server's row must exist and carry exactly sg (generation, incarnation and OAuth epoch). Otherwise it returns commitview.ErrStaleGeneration and the caller builds nothing: a newer commit already wrote the row, and that commit's own worker builds the instance for it. A failed check is not an error to report.

func (*Manager) CleanupOrphanedOAuthTokens added in v0.16.8

func (m *Manager) CleanupOrphanedOAuthTokens(validServerNames []string) (int, error)

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

func (m *Manager) CleanupStaleServerData(threshold time.Duration) error

CleanupStaleServerData removes data for servers that haven't been seen for a threshold period

func (*Manager) ClearDockerRecoveryState

func (m *Manager) ClearDockerRecoveryState() error

ClearDockerRecoveryState removes the Docker recovery state from persistent storage

func (*Manager) ClearOAuthState

func (m *Manager) ClearOAuthState(serverName string) error

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

func (m *Manager) Close() error

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

func (m *Manager) CloseAllActiveSessions() error

CloseAllActiveSessions marks all active sessions as closed This should be called on startup to clean up stale sessions from previous runs

func (*Manager) CloseInactiveSessions

func (m *Manager) CloseInactiveSessions(inactivityTimeout time.Duration) (int, error)

CloseInactiveSessions closes sessions that haven't had activity for the specified duration

func (*Manager) CloseSession

func (m *Manager) CloseSession(sessionID string) error

CloseSession marks a session as closed with end time

func (*Manager) ConfigCommitState added in v0.71.0

func (m *Manager) ConfigCommitState() (seed int64, committed bool, err error)

ConfigCommitState reports the generation to seed the config service with (the larger of meta.config_commit_generation and every row's Generation) and whether a Spec 116 commit has ever written this database.

func (*Manager) ConfigCommitted added in v0.71.0

func (m *Manager) ConfigCommitted() (bool, error)

ConfigCommitted reports whether a Spec 116 config commit has written this database (meta.config_commit_generation is present). One key read; callers on hot paths use it instead of ConfigCommitState.

func (*Manager) CountActivities

func (m *Manager) CountActivities() (int, error)

CountActivities returns the total number of activity records.

func (*Manager) CreateAgentToken added in v0.20.0

func (m *Manager) CreateAgentToken(token auth.AgentToken, rawToken string, hmacKey []byte) error

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) CreateUpstreamServer added in v0.71.0

func (m *Manager) CreateUpstreamServer(serverConfig *config.ServerConfig) error

CreateUpstreamServer persists a NEW server and fails with ErrUpstreamExists when a record with that name is already stored. The existence check and the write share one bbolt transaction, so concurrent creates of the same name yield exactly one success. Unlike SaveUpstreamServer it never overwrites.

func (*Manager) DeleteActivity

func (m *Manager) DeleteActivity(id string) error

DeleteActivity deletes an activity record by ID. Returns nil if the record doesn't exist.

func (*Manager) DeleteAgentToken added in v0.48.0

func (m *Manager) DeleteAgentToken(name string) error

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

func (m *Manager) DeleteAgentTokenForOwner(userID, name string) error

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

func (m *Manager) DeleteIntegrityBaseline(serverName string) error

DeleteIntegrityBaseline deletes an integrity baseline by server name

func (*Manager) DeletePromptApproval added in v0.59.0

func (m *Manager) DeletePromptApproval(serverName, promptName string) error

DeletePromptApproval deletes a prompt approval record.

func (*Manager) DeleteScanJob added in v0.24.0

func (m *Manager) DeleteScanJob(id string) error

DeleteScanJob deletes a scan job by ID

func (*Manager) DeleteScanReport added in v0.24.0

func (m *Manager) DeleteScanReport(id string) error

DeleteScanReport deletes a scan report by ID

func (*Manager) DeleteScanner added in v0.24.0

func (m *Manager) DeleteScanner(id string) error

DeleteScanner deletes a scanner plugin by ID

func (*Manager) DeleteServerPromptApprovals added in v0.59.0

func (m *Manager) DeleteServerPromptApprovals(serverName string) error

DeleteServerPromptApprovals deletes all prompt approval records for a server.

func (*Manager) DeleteServerScanJobs added in v0.24.0

func (m *Manager) DeleteServerScanJobs(serverName string) error

DeleteServerScanJobs deletes all scan jobs for a server

func (*Manager) DeleteServerScanReports added in v0.24.0

func (m *Manager) DeleteServerScanReports(serverName string) error

DeleteServerScanReports deletes all scan reports for a server

func (*Manager) DeleteServerToolApprovals added in v0.21.0

func (m *Manager) DeleteServerToolApprovals(serverName string) error

DeleteServerToolApprovals deletes all tool approval records for a server

func (*Manager) DeleteToolApproval added in v0.21.0

func (m *Manager) DeleteToolApproval(serverName, toolName string) error

DeleteToolApproval deletes a tool approval record

func (*Manager) DeleteToolApprovalIf added in v0.71.0

func (m *Manager) DeleteToolApprovalIf(serverName, toolName string, eligible func(*ToolApprovalRecord) bool) (bool, error)

DeleteToolApprovalIf is the conditional, atomic form of DeleteToolApproval.

func (*Manager) DeleteToolHash

func (m *Manager) DeleteToolHash(toolName string) error

DeleteToolHash deletes a tool hash

func (*Manager) DeleteUpstreamServer

func (m *Manager) DeleteUpstreamServer(name string) error

DeleteUpstreamServer deletes an upstream server

func (*Manager) EnableUpstreamServer

func (m *Manager) EnableUpstreamServer(name string, enabled bool) error

EnableUpstreamServer enables/disables an upstream server using async operations

func (*Manager) FinalizeClientCredentialRotation added in v0.70.0

func (m *Manager) FinalizeClientCredentialRotation(clientID string) (*auth.AgentToken, error)

FinalizeClientCredentialRotation promotes the staged pending secret to primary and drops the old one. Idempotent: a second finalize (no rotation in progress) returns the current record and ErrClientCredentialNotRotating, which callers MUST treat as a 200 no-op, never a hard failure.

func (*Manager) ForgetClientCredential added in v0.70.0

func (m *Manager) ForgetClientCredential(clientID string) (*auth.AgentToken, error)

ForgetClientCredential revokes the client credential named "client-"+clientID (disconnect, FR-030 change=forget). Returns ErrClientCredentialNotFound when no such record exists.

func (*Manager) ForgetClientCredentialRestoringPrior added in v0.71.0

func (m *Manager) ForgetClientCredentialRestoringPrior(clientID string) (*auth.AgentToken, error)

ForgetClientCredentialRestoringPrior revokes like ForgetClientCredential and, when the record replaced a revoked/expired tombstone, puts that tombstone's binding back. It is for rolling back a connect that never took effect (abort, undo): a plain forget would leave the tombstone with the aborted connect's binding and a later profileless reconnect could re-mint with it.

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

func (m *Manager) GetAgentTokenCount() (int, error)

GetAgentTokenCount returns the number of stored agent tokens.

func (*Manager) GetBoltDB

func (m *Manager) GetBoltDB() *BoltDB

GetBoltDB returns the wrapped BoltDB instance for higher-level operations

func (*Manager) GetDB

func (m *Manager) GetDB() *bbolt.DB

GetDB returns the underlying BBolt database for direct access

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

func (m *Manager) GetLatestScanJob(serverName string) (*scanner.ScanJob, error)

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

func (m *Manager) GetRecentSessions(limit int, status string) ([]*SessionRecord, int, error)

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) GetRecentSessionsFiltered added in v0.70.0

func (m *Manager) GetRecentSessionsFiltered(f SessionFilter) ([]*SessionRecord, int, error)

GetRecentSessionsFiltered is GetRecentSessions with the Spec 108 scope filters. Every filter is applied after the LastActivity sort and BEFORE the limit, so total is the filtered count and an old-but-matching session is never truncated out by a page of newer non-matching ones.

func (*Manager) GetScanJob added in v0.24.0

func (m *Manager) GetScanJob(id string) (*scanner.ScanJob, error)

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

func (m *Manager) GetSchemaVersion() (uint64, error)

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) GetStats

func (m *Manager) GetStats() (map[string]interface{}, error)

GetStats returns storage statistics

func (*Manager) GetStoredServer added in v0.71.0

func (m *Manager) GetStoredServer(name string) (*StoredServer, error)

GetStoredServer returns one row with its stamp, or ErrUpstreamNotFound.

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) GetToolBaselineDecision added in v0.71.0

func (m *Manager) GetToolBaselineDecision(serverName string) (d toolreview.BaselineDecision, ok bool, err error)

GetToolBaselineDecision returns serverName's marker. ok is true when a value is stored, including one that cannot be decoded (then d carries only Source "inferred").

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

func (m *Manager) GetToolHash(toolName string) (string, error)

GetToolHash retrieves a tool hash

func (*Manager) GetToolStatistics

func (m *Manager) GetToolStatistics(topN int) (*config.ToolStats, error)

GetToolStatistics returns aggregated tool statistics

func (*Manager) GetToolStats

func (m *Manager) GetToolStats(topN int) ([]map[string]interface{}, error)

GetToolStats gets tool statistics formatted for MCP responses

func (*Manager) GetToolStatsFiltered added in v0.68.0

func (m *Manager) GetToolStatsFiltered(keep func(toolName string) bool, topN int) ([]map[string]interface{}, error)

GetToolStatsFiltered is GetToolStats restricted to records keep admits (Spec 105 FR-005 G2): the sort-then-cut-to-topN happens AFTER filtering, unlike GetToolStatistics/GetToolStats which cut first — a caller whose authorized population excludes some records must never let a hidden or unapproved tool's usage count evict an authorized tool from the topN window. keep receives the full "server:tool" name exactly as recorded by IncrementToolUsage. A nil keep behaves like GetToolStats (nothing filtered).

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

func (m *Manager) HasToolChanged(toolName, currentHash string) (bool, error)

HasToolChanged checks if a tool has changed based on its hash

func (*Manager) IncrementToolUsage

func (m *Manager) IncrementToolUsage(toolName string) error

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

func (m *Manager) ListQuarantinedTools(serverName string) ([]map[string]interface{}, error)

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

func (m *Manager) ListScanJobs(serverName string) ([]*scanner.ScanJob, error)

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) ListStoredServers added in v0.71.0

func (m *Manager) ListStoredServers() (map[string]*StoredServer, error)

ListStoredServers returns every upstreams row with its stamp, keyed by name.

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

func (m *Manager) LoadUsageSnapshot() ([]byte, error)

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) MarkToolBaselineDecided added in v0.71.0

func (m *Manager) MarkToolBaselineDecided(serverName string, d toolreview.BaselineDecision) error

MarkToolBaselineDecided records that serverName's tool baseline was decided. It is idempotent: the first DecidedAt is kept, and the source (and by) of an existing marker are replaced only when the stored one was inferred and the new one is explicit. A zero DecidedAt is stamped with the current time.

func (*Manager) MintClientCredential added in v0.70.0

func (m *Manager) MintClientCredential(clientID, rawToken string, hmacKey []byte, mode, pin string, expiresAt time.Time) (*auth.AgentToken, error)

MintClientCredential mints a fresh mcp_cli_ credential for clientID bound to (mode, pin) with the given expiry (FR-021). It replaces an existing revoked/expired kind=client record for the same clientID IN THE SAME TRANSACTION (names stay reserved by soft-revoked records); it never touches a kind=agent record (ErrClientCredentialConflict); minting over an ACTIVE client record is refused with ErrClientCredentialActive — the caller must use StageClientCredentialRotation/FinalizeClientCredentialRotation instead.

func (*Manager) MintClientCredentialNamed added in v0.70.0

func (m *Manager) MintClientCredentialNamed(clientID, rawToken string, hmacKey []byte, mode, pin string, expiresAt time.Time, displayName string) (*auth.AgentToken, error)

MintClientCredentialNamed is MintClientCredential for a CUSTOM client that also carries a display name (Spec 108-f FR-021). The name is validated with the rest of the record's invariants.

func (*Manager) MintClientCredentialWith added in v0.71.0

func (m *Manager) MintClientCredentialWith(clientID, rawToken string, hmacKey []byte, opts ClientMintOptions) (*auth.AgentToken, error)

MintClientCredentialWith is MintClientCredentialNamed with the Spec 115 issuance fields. It returns the committed record (the caller projects its view from it, never from a second store read).

func (*Manager) PruneActivitiesToSize added in v0.37.0

func (m *Manager) PruneActivitiesToSize(maxBytes int64) (int, error)

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

func (m *Manager) PruneExcessActivities(maxRecords int, targetPercent float64) (int, error)

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

func (m *Manager) PruneOldActivities(maxAge time.Duration) (int, error)

PruneOldActivities deletes activity records older than the specified duration. Returns the number of records deleted.

func (*Manager) PruneOrphanToolApprovals added in v0.37.0

func (m *Manager) PruneOrphanToolApprovals(configuredServers []string) (int, error)

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

func (m *Manager) PruneOrphanToolCalls(configuredServers []string) (int, error)

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) PurgeSetCounts added in v0.71.0

func (m *Manager) PurgeSetCounts(name string) (map[string]int, error)

PurgeSetCounts reports, per purge-set bucket, how many keys still belong to name, with the same key matching as the purge. It is read-only; the debug purge-report command and the live checks use it (quickstart L2).

func (*Manager) QuarantineUpstreamServer

func (m *Manager) QuarantineUpstreamServer(name string, quarantined bool) error

QuarantineUpstreamServer sets the quarantine status of an upstream server using async operations

func (*Manager) RecordReplayedToolCallIfIncarnation added in v0.71.0

func (m *Manager) RecordReplayedToolCallIfIncarnation(record *ToolCallRecord, inc int64, originalCallID string) (bool, error)

RecordReplayedToolCallIfIncarnation is RecordToolCallIfIncarnation for an activity replay (Spec 116 PR2 review rounds 5-6, FR-014c). The replayed call carries the identity of the ORIGINAL call, read from that identity's history bucket before the incarnation was captured. A removal purges that identity and its history; a same-name replacement then carries a new incarnation the replay may have captured. The identity alone does not prove the call still belongs to the server: GenerateServerID hashes the configuration and not the incarnation, so a same-config replacement registers the SAME identity id (review round 6). The write is therefore conditional, in its own transaction, on the original call record originalCallID itself still being in that identity's history bucket. A removal purged it, and nothing recreates it, so a replay never records a removed server's call under the replacement nor recreates a purged identity or its history.

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) RecordToolCallIfIncarnation added in v0.71.0

func (m *Manager) RecordToolCallIfIncarnation(record *ToolCallRecord, inc int64) (bool, error)

RecordToolCallIfIncarnation is RecordToolCall conditional on the row of record.ServerName carrying incarnation inc (code_execution parent records are exempt: they belong to no upstream and are recorded unconditionally).

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) RegisterServerIdentityIfIncarnation added in v0.71.0

func (m *Manager) RegisterServerIdentityIfIncarnation(server *config.ServerConfig, configPath string, inc int64) (identity *ServerIdentity, written bool, err error)

RegisterServerIdentityIfIncarnation is RegisterServerIdentity conditional on the server's row carrying incarnation inc. written is false (and nothing is stored) when the server was removed or replaced.

func (*Manager) RemoveUpstream

func (m *Manager) RemoveUpstream(id string) error

RemoveUpstream removes an upstream server by ID/name

func (*Manager) ReopenSession added in v0.71.0

func (m *Manager) ReopenSession(sessionID string) error

ReopenSession marks a closed session active again and clears its end time. It is a no-op for an unknown or already-active session (no duplicate record).

func (*Manager) RepinProfile added in v0.70.0

func (m *Manager) RepinProfile(from, to string) (before []auth.AgentToken, err error)

RepinProfile rewrites ProfilePin from -> to on EVERY stored ownerless token naming `from` — regular agent tokens and client credentials alike, revoked and expired ones included — in one transaction (Spec 108 D19). It is the token half of a profile rename or delete-with-reassign: doing it in one tx means a failure part-way leaves every record unchanged. Owned (server-edition) tokens are never touched: a profile is not tenant state.

It returns the records as they were BEFORE the rewrite, so the caller can restore exactly those pins with RestorePins. An empty source or target is refused before anything is written (a locked client credential cannot hold an empty pin).

func (*Manager) RestorePins added in v0.70.0

func (m *Manager) RestorePins(before []auth.AgentToken) error

RestorePins puts back the ProfilePin of each record RepinProfile returned, in one transaction (the rollback of a repin whose config write failed). A record that no longer exists is left alone.

func (*Manager) RevokeAgentToken added in v0.20.0

func (m *Manager) RevokeAgentToken(name string) error

RevokeAgentToken marks an OWNERLESS agent token as revoked by name. Equivalent to RevokeAgentTokenForOwner("", name).

func (*Manager) RevokeAgentTokenForOwner added in v0.64.0

func (m *Manager) RevokeAgentTokenForOwner(userID, name string) error

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) RevokeAgentTokenReport added in v0.71.0

func (m *Manager) RevokeAgentTokenReport(userID, name string) (before, after *auth.AgentToken, err error)

RevokeAgentTokenReport is RevokeAgentTokenForOwner that also returns the record as it was and as it is now, so a caller can tell whether the revoke changed anything (Spec 115: revoking an already-revoked token is changed: false). RevokedAt is stamped (UTC) the first time the token is revoked and is never overwritten by a later revoke.

func (*Manager) RevokeAgentTokensForOwner added in v0.64.0

func (m *Manager) RevokeAgentTokensForOwner(userID string) (int, error)

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) RollbackClientCredentialRotation added in v0.70.0

func (m *Manager) RollbackClientCredentialRotation(clientID string) (*auth.AgentToken, error)

RollbackClientCredentialRotation discards a staged pending secret, keeping the old one valid — the reconciler path for "config write failed, old secret still in the client's config" (FR-021a). Idempotent: a no-op when no rotation is in progress.

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) SaveIntegrityBaselineWithBlocks added in v0.70.0

func (m *Manager) SaveIntegrityBaselineWithBlocks(baseline *scanner.IntegrityBaseline, blocks []scanner.ToolApprovalBlock) error

SaveIntegrityBaselineWithBlocks commits the scan approval and the selected disabled tool records atomically in the underlying bbolt database.

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

func (m *Manager) SaveScanJob(job *scanner.ScanJob) error

SaveScanJob saves a scan job record

func (*Manager) SaveScanJobIfIncarnation added in v0.71.0

func (m *Manager) SaveScanJobIfIncarnation(job *scanner.ScanJob, inc int64) (bool, error)

SaveScanJobIfIncarnation saves job only while the scanned server's row carries incarnation inc (FR-014a): a scan that outlives a remove and re-add leaves no job under the replacement.

func (*Manager) SaveScanReport added in v0.24.0

func (m *Manager) SaveScanReport(report *scanner.ScanReport) error

SaveScanReport saves a scan report record

func (*Manager) SaveScanReportIfIncarnation added in v0.71.0

func (m *Manager) SaveScanReportIfIncarnation(report *scanner.ScanReport, inc int64) (bool, error)

SaveScanReportIfIncarnation saves report only while the scanned server's row carries incarnation inc (FR-014a).

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

func (m *Manager) SaveToolHash(toolName, hash string) error

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.

Invariant: it never lowers a recorded Quarantined=true. Only QuarantineUpstreamServer (the review/approve door) or a config that carries an explicit operator decision (QuarantineExplicitlySet) may clear it. A Go-built or file-decoded ServerConfig that merely says Quarantined=false is indistinguishable from "never stated", so it must not erase a quarantine the admission gate recorded. The guard changes only the persisted record, never the caller's struct.

func (*Manager) SaveUsageSnapshot added in v0.35.0

func (m *Manager) SaveUsageSnapshot(data []byte) error

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) ServerIncarnation added in v0.71.0

func (m *Manager) ServerIncarnation(name string) (inc int64, ok bool, err error)

ServerIncarnation returns the incarnation stamped on name's row. ok is false when no row exists.

func (*Manager) SetAgentTokenOwnerResolver added in v0.68.0

func (m *Manager) SetAgentTokenOwnerResolver(resolve AgentTokenOwnerResolver)

SetAgentTokenOwnerResolver installs the single owner resolution 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-checked 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. The resolver closes that (the token is only as live as its owner) and, in the same read, re-derives the owner's current entitlement so every authentication receives a fresh, narrow-only intersection (Spec 106 FR-004).

It FAILS CLOSED. The personal edition installs no resolver and is unaffected — its tokens are all ownerless.

func (*Manager) SetSchemaVersion added in v0.33.4

func (m *Manager) SetSchemaVersion(version uint64) error

SetSchemaVersion stores the current migration schema version.

func (*Manager) SetSessionProfile added in v0.70.0

func (m *Manager) SetSessionProfile(sessionID, profile, source string) error

SetSessionProfile writes a session's latest profile resolution through to its persisted row (Spec 108 FR-033). A session that is not persisted yet is a no-op: EnsurePersisted copies the in-memory resolution when it persists.

func (*Manager) SetSessionWorkspace added in v0.49.0

func (m *Manager) SetSessionWorkspace(sessionID, workspaceRoot string) error

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

func (m *Manager) SetToolCallLimits(maxResponseBytes, maxRecordsPerServer int)

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) StageClientCredentialRotation added in v0.70.0

func (m *Manager) StageClientCredentialRotation(clientID, newRawToken string, hmacKey []byte) (*auth.AgentToken, error)

StageClientCredentialRotation begins a staged rotation (FR-021a) over the ACTIVE client credential named "client-"+clientID: it adds a pending secret while leaving the current one valid, so an in-flight config write on the client side is never invalidated mid-flight. Both the old and the new secret authenticate until FinalizeClientCredentialRotation (or a caller-driven rollback) resolves it.

func (*Manager) StampToolApprovalsIdentityKeyed added in v0.67.0

func (m *Manager) StampToolApprovalsIdentityKeyed(serverName string, toolNames []string) ([]string, error)

StampToolApprovalsIdentityKeyed stamps the named records identity-keyed in one storage transaction under one manager write lock — the same lock every SaveToolApproval takes, so an operator write is either fully before the stamp (and seen by its in-transaction re-read) or fully after it (see BoltDB.StampToolApprovalsIdentityKeyed).

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) StoredQuarantineEnabled added in v0.71.0

func (m *Manager) StoredQuarantineEnabled() (enabled, ok bool, err error)

StoredQuarantineEnabled returns meta.quarantine_enabled. ok is false when no commit has recorded it.

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) ToolBaselineDecided added in v0.71.0

func (m *Manager) ToolBaselineDecided(serverName string) (bool, error)

ToolBaselineDecided reports whether serverName has a baseline marker. A stored value that cannot be decoded counts as decided (fail closed). A store without the bucket (written by an older binary) reads false.

func (*Manager) ToolCallRecordExists added in v0.71.0

func (m *Manager) ToolCallRecordExists(serverID, callID string) (bool, error)

ToolCallRecordExists reports whether the history bucket of server identity serverID still holds the call callID (Spec 116 PR2 review round 6). Replay checks it before dispatch: a removal purged the bucket, and a same-config replacement's bucket under the same identity id never holds the removed server's calls.

func (*Manager) UpdateActivityMetadata added in v0.17.0

func (m *Manager) UpdateActivityMetadata(id string, updates map[string]interface{}) error

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

func (m *Manager) UpdateAgentTokenLastUsed(name string) error

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

func (m *Manager) UpdateAgentTokenLastUsedByHash(hash string) error

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) UpdateClientCredentialBinding added in v0.70.0

func (m *Manager) UpdateClientCredentialBinding(clientID, pin, mode string) (before, after *auth.AgentToken, err error)

UpdateClientCredentialBinding rewrites the (profile pin, mode) of the ACTIVE kind=client credential named "client-"+clientID in one transaction and returns the record as it was and as it is now. The secret is untouched, so the client's config never changes (FR-026: a binding is server-side state). The result must still satisfy ValidateTokenInvariants (a locked binding needs a non-empty pin); otherwise nothing is written.

func (*Manager) UpdateOnboardingState added in v0.70.0

func (m *Manager) UpdateOnboardingState(fn func(*OnboardingState) error) error

UpdateOnboardingState runs fn against the current onboarding state and persists the result in one bbolt transaction (Spec 109-b, T035). Every writer of the record must use this instead of a separate Get/SaveOnboardingState pair — see BoltDB.UpdateOnboardingState.

Callback constraint: fn runs while m.mu is write-locked AND inside a bbolt write transaction. It must be a short, pure mutation of the *OnboardingState it is handed. It MUST NOT call any Manager or BoltDB method (Get/Save/ UpdateOnboardingState, or anything else that takes m.mu or opens a bbolt transaction) and must not block on I/O or other goroutines: re-entering either lock deadlocks, and slow work stalls every other storage operation.

func (*Manager) UpdateServerStatistics

func (m *Manager) UpdateServerStatistics(stats *ServerStatistics) error

UpdateServerStatistics updates server statistics

func (*Manager) UpdateSessionActivity added in v0.21.4

func (m *Manager) UpdateSessionActivity(sessionID string) error

UpdateSessionActivity updates LastActivity without incrementing tool call counts. Call this on any MCP message to keep the session alive.

func (*Manager) UpdateSessionStats

func (m *Manager) UpdateSessionStats(sessionID string, tokens int) error

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

func (m *Manager) ValidateAgentToken(rawToken string, hmacKey []byte) (*auth.AgentToken, error)

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 OAuthClientSaveMode added in v0.71.0

type OAuthClientSaveMode int

OAuthClientSaveMode selects the precondition of SaveOAuthClientIfBound.

const (
	// OAuthClientSaveAlways writes the registration whatever the record
	// holds (the operator's static client; UpdateOAuthClientCredentials).
	OAuthClientSaveAlways OAuthClientSaveMode = iota
	// OAuthClientSaveIfUnsetOrSame writes only while the record holds no
	// client id or this same one (SaveOAuthClientCredentialsIfUnsetOrSame).
	OAuthClientSaveIfUnsetOrSame
	// OAuthClientSaveIfSameOrEmpty writes only while the record holds this
	// same client id, or neither a client id nor a refresh token
	// (SaveOAuthClientCredentialsIfSameOrEmpty).
	OAuthClientSaveIfSameOrEmpty
)

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
	// Incarnation and OAuthEpoch are the credential binding of the instance
	// that completed the login (Spec 116 PR2b, T055c). The consumer drops
	// an event whose binding is not the registered instance's. Zero on an
	// event written by an unbound caller or before PR2b.
	Incarnation int64 `json:"incarnation,omitempty"`
	OAuthEpoch  int64 `json:"oauth_epoch,omitempty"`
}

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
	// OAuthEpoch is the credential binding epoch the record was written
	// under (Spec 116 PR2b, #1607): the OAuthEpoch of the server's row when a
	// bound writer saved it. A bound reader ignores a record of another
	// epoch. 0 on a record written before PR2b, which only a binding with
	// epoch 0 reads.
	OAuthEpoch int64 `json:"oauth_epoch,omitempty"`
	// Revision is set from the oauth_tokens bucket's sequence on every write
	// of the record (review R7.3). A binding-conditional clear acts only on
	// the exact revision its caller inspected, so a parked clear never
	// erases a record somebody rewrote meanwhile.
	Revision uint64 `json:"revision,omitempty"`
}

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"`

	// ClientConnectedAt records, per client id from the fixed connect client
	// registry (internal/connect.GetAllClients — never user input), the last
	// time a connect write succeeded for that client (Spec 109-b FR-042).
	// Written by the connect success path through UpdateOnboardingState so a
	// concurrent onboarding/mark write can never drop it. Consumed by the
	// Verify step / presence layer to tell "connected, never seen" apart from
	// "connected seconds ago, hasn't reconnected yet".
	ClientConnectedAt map[string]time.Time `json:"client_connected_at,omitempty"`

	// ClientLastSeen records the latest MCP initialize for a recognised client
	// alias. It is intentionally kept with onboarding state: presence is a
	// local UI concern and must still work when telemetry is disabled.
	ClientLastSeen       map[string]time.Time `json:"client_last_seen,omitempty"`
	ClientDisconnectedAt map[string]time.Time `json:"client_disconnected_at,omitempty"`

	// ClientCredentialObserved records, per client id, the LAST credential
	// classification an on-demand read produced (Spec 108-f FR-025, F11): what
	// the client's config held (client | admin_key | none | revoked | expired)
	// and when it was read. The stat-only GET /clients listing never reads a
	// config (Spec 075: no macOS App-Data prompt from a list), so this is how
	// it still reports a client that holds the admin key across restarts. It is
	// written only when the classification CHANGES, by every on-demand read
	// (GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,
	// a connect write) and deleted on disconnect. Additive: an older binary
	// ignores it, and a record without it reads as "unknown".
	ClientCredentialObserved map[string]ClientCredentialObservation `json:"client_credential_observed,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 Operation

type Operation struct {
	Type     string
	Data     interface{}
	ResultCh chan Result
}

Operation represents a queued storage operation

type OwnerResolution added in v0.68.0

type OwnerResolution struct {
	// Active is false when the owner record is missing or disabled — the
	// token is refused with ErrAgentTokenOwnerInactive.
	Active bool
	// UserID, Email, Provider and Role describe the owner as of now; Role is
	// derived live from admin_emails. They are stamped on the returned
	// token's non-persisted Owner* fields, never written to the store.
	UserID, Email  string
	Provider, Role string
	// Entitled is the ALREADY NARROWED grant: narrowScopeToEntitled(granted,
	// entitledServerNamesFor(user, isAdmin), isAdmin). Non-nil. ["*"] stays
	// literal for an administrator, is materialised into the entitlement set
	// for a tenant, and is [] when nothing survives. It MUST NOT be the raw
	// whole-configuration list: intersectAllowedServers treats a stored "*"
	// as "take every entry of proposed", so an administrator's literal star
	// would be frozen into a snapshot of the current configuration (FR-009).
	Entitled []string
}

OwnerResolution is the single answer the server edition gives about an owned token's owner on every authentication (Spec 107 FR-004, contracts/entitlement-predicate.md §2, data-model.md §6). It replaces the two callbacks that used to run in sequence (an owner gate returning only `active`, then a scope resolver that loaded the same user record again): one store read now yields the owner's liveness, identity, live role and the NARROWED grant together.

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 PurgeReport added in v0.71.0

type PurgeReport struct {
	Server  string         `json:"server"`
	Deleted map[string]int `json:"deleted"`
}

PurgeReport lists what one server's purge deleted, per bucket.

func (PurgeReport) Total added in v0.71.0

func (r PurgeReport) Total() int

Total returns the number of keys the purge deleted.

type QuarantineServerData

type QuarantineServerData struct {
	Name        string
	Quarantined bool
}

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 ServerCommitBatch added in v0.71.0

type ServerCommitBatch struct {
	// Generation is G; it is written to meta.config_commit_generation only.
	Generation int64
	// Saves are the rows the commit creates, changes or repairs.
	Saves []ServerSave
	// Removes are names whose row and whole purge set (purge.go, Spec 116
	// PR2) are deleted in this transaction.
	Removes []string
	// Replaces are names removed and re-created in this commit (review
	// R8.2): the old row and its whole purge set are deleted before the new
	// row is saved.
	Replaces []string
	// QuarantineEnabled, when non-nil, is written to
	// meta.quarantine_enabled in the same transaction (D16).
	QuarantineEnabled *bool
	// OAuthClears are names whose cached OAuth state (tokens and DCR client
	// credentials, the ClearOAuthState key set) is deleted in this
	// transaction because their OAuth configuration changed (data-model §1,
	// review round 3): the new OAuth config and the removal of the old
	// credentials commit or roll back together.
	OAuthClears []string
	// RowOnlyRemoves limits Removes to the row and its tool-call history,
	// keeping the rest of the purge set. The startup commits set it when the
	// configuration they load lists no server at all: the same guard as the
	// boot-time orphan GC (a config that came up empty must not wipe every
	// approval and credential). Replaces always purge.
	RowOnlyRemoves bool
}

ServerCommitBatch is everything one commit writes to the upstreams bucket.

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 ServerSave added in v0.71.0

type ServerSave struct {
	Config *config.ServerConfig
	Stamp  commitview.ServerGen
}

ServerSave is one row write. Stamp is the ServerGen that the commit's Prepare computed for this name. Storage writes it verbatim and never derives a stamp from the batch generation or from the row it replaces (review R9.3).

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 SessionFilter added in v0.70.0

type SessionFilter struct {
	Limit     int
	Status    string
	Profile   string
	ClientID  string
	TokenName string
}

SessionFilter selects sessions for GetRecentSessionsFiltered. Empty string fields are unfiltered; "-" (ScopeFilterUnattributed) selects sessions with no value. Profile is the session's latest effective profile; ClientID and TokenName are the credential at initialize.

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"`

	// Scope attribution (Spec 108 FR-028/FR-033). TokenName and ClientID are the
	// credential the session initialized with; Profile/ProfileSource are the
	// session's LATEST resolution (written through on change by
	// SetSessionProfile). Legacy rows decode empty and read as unattributed.
	TokenName     string `json:"token_name,omitempty"`
	ClientID      string `json:"client_id,omitempty"`
	Profile       string `json:"profile,omitempty"`
	ProfileSource string `json:"profile_source,omitempty"`
}

SessionRecord represents a stored MCP session

type StoredServer added in v0.71.0

type StoredServer struct {
	Config *config.ServerConfig
	Stamp  commitview.ServerGen
}

StoredServer is one upstreams row as a config entry plus its stamp.

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"`
	// CurrentHashSchemaVersion is the hash formula version CurrentHash was
	// computed with, stamped by every runtime write that recomputes
	// CurrentHash. Zero means unknown (a record written before this field
	// existed). ApproveCurrentHash uses it so an approval that copies
	// CurrentHash into ApprovedHash carries the version of the hash it copied
	// (red-team RT-03, Sol r4 P1). Additive and omitted when zero.
	CurrentHashSchemaVersion uint64                  `json:"current_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"`
	PreviousAnnotations      *config.ToolAnnotations `json:"previous_annotations,omitempty"`
	CurrentAnnotations       *config.ToolAnnotations `json:"current_annotations,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"`

	// DefinitionChangedAt is when the stored CurrentDescription,
	// CurrentSchema or CurrentOutputSchema last differed from the prior
	// record. BoltDB.SaveToolApproval stamps it inside its write transaction
	// (one seam for every writer) and carries the prior value otherwise. A
	// brand-new record stays zero: first capture is not a change, so a scan
	// that preceded capture is not made stale by it. Annotations are
	// excluded, like the approval hash. It is never part of the hash. The
	// review composer compares it with the scan start to decide whether a
	// scan covers the current definition. Additive and omitted when zero.
	DefinitionChangedAt time.Time `json:"definition_changed_at,omitzero"`

	// PendingSince is when the tool began waiting as pending. BoltDB.
	// SaveToolApproval stamps it (one seam for every writer): a pending record
	// with no prior pending record gets now, a prior pending record's value is
	// carried, and any other status clears it. Records filed before this field
	// existed stay zero: their age is unknown and the review queue reports
	// them undated. Additive and omitted when zero.
	PendingSince time.Time `json:"pending_since,omitzero"`

	// 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"`

	// IdentityKeyed marks a record written by a Spec 105 (FR-009) binary,
	// which keys every record by the tool's exact RAW upstream name. Every
	// post-105 writer stamps it (internal/runtime/tool_quarantine.go
	// saveToolApproval: the discovery producer, ApproveTools, BlockTools, the
	// user toggle). A record WITHOUT the stamp was written by a pre-105
	// binary, whose discovery producer filed a raw "ns:erase" under the
	// COLLAPSED key "erase" — so only an unstamped record can be the collapsed
	// sibling of a namespaced tool, and only unstamped siblings are consulted
	// by the legacy carry-over in checkToolApprovals and the legacy
	// re-admission in internal/server/tool_gate.go readToolApprovalRecord.
	// The stamp bounds that migration logic to the upgrade: once a store has
	// been rewritten by a post-105 binary, a sibling record is a genuine
	// sibling and lends nothing to another raw name (FR-009: a record can
	// neither inherit nor disturb the record of a sibling). Additive and
	// omitempty: pre-105 records decode with it false.
	IdentityKeyed bool `json:"identity_keyed,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) ApproveCurrentHash added in v0.71.0

func (r *ToolApprovalRecord) ApproveCurrentHash()

ApproveCurrentHash copies CurrentHash into ApprovedHash. HashSchemaVersion follows the copied hash: it takes CurrentHashSchemaVersion when that is known and is kept otherwise. A legacy hint-free CurrentHash must not be stamped as the hint-aware version (Sol r2 P1), and a CurrentHash this binary recomputed must not keep a legacy version whose unknown-hints wildcard would let a later annotation flip match it unchecked (Sol r4 P1).

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) Restricts added in v0.67.0

func (r *ToolApprovalRecord) Restricts() bool

Restricts reports whether the record carries a fact that binds the tool beyond a plain approval: a quarantine lock (pending / changed) or the user's Disabled block. It is the shared reader rule for a pre-Spec-105 COLLAPSED record — a raw "ns:erase" that an older binary filed under "erase": such a record may approve only the exact raw name it stores, but its lock or block must keep binding the namespaced name it may have been filed for while no exact record exists (internal/server/tool_gate.go readToolApprovalRecord). The discovery producer (internal/runtime/tool_quarantine.go checkToolApprovals) carries the user's Disabled block onto the new exact record and, under an active gate, adopts the lock with its evidence — only from an unstamped sibling (IdentityKeyed) — and its end-of-pass stamping leaves a restricting orphan unstamped so it can be consulted once when its tool reappears.

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

type ToolUsageStat struct {
	Count    int
	LastUsed time.Time
}

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"`
	// ForwardHeaders (Spec 112) is the per-server allowlist of inbound MCP
	// client header NAMES to forward on tools/call. Names only, never values.
	// Persisted here because SaveConfiguration rebuilds the JSON server list
	// from these records: a field absent here is wiped on the next mutation.
	ForwardHeaders []string `json:"forward_headers,omitempty"`

	// Generation and Incarnation are the committed ServerGen of the config
	// commit that last wrote this row (Spec 116). A row written before Spec
	// 116 reads as zero; the next commit that writes it stamps it.
	Generation  int64 `json:"generation,omitempty"`
	Incarnation int64 `json:"incarnation,omitempty"`
	// OAuthEpoch is the generation of the commit that created the row or
	// last cleared its OAuth state (Spec 116 PR2b, #1607). OAuth token,
	// client and completion writes bound to {Incarnation, OAuthEpoch} land
	// only while the row still carries both. 0 on a row written before PR2b.
	OAuthEpoch int64 `json:"oauth_epoch,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

Directories

Path Synopsis
Package purgetest seeds and inspects the Spec 116 removal purge set (data-model.md §PurgeSet) for tests.
Package purgetest seeds and inspects the Spec 116 removal purge set (data-model.md §PurgeSet) for tests.

Jump to

Keyboard shortcuts

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