runtime

package
v0.73.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 69 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultRetentionMaxAge is the default max age for activity records (7 days)
	DefaultRetentionMaxAge = 7 * 24 * time.Hour
	// DefaultRetentionMaxRecords is the default max number of records (10000)
	DefaultRetentionMaxRecords = 10000
	// DefaultRetentionCheckInterval is the default interval between retention checks (1 hour)
	DefaultRetentionCheckInterval = 1 * time.Hour
	// DefaultRetentionMaxSizeBytes is the default total activity-log size cap (256MB)
	DefaultRetentionMaxSizeBytes int64 = 256 * 1024 * 1024
	// DefaultActivityMaxResponseSize is the default per-record response cap (64KB).
	// Aliased here because NewActivityService's first parameter shadows the
	// storage package inside that function body.
	DefaultActivityMaxResponseSize = storage.DefaultMaxResponseSize
)

Default retention configuration

View Source
const (
	AttentionKindSignInRequired  = "sign_in_required"
	AttentionKindMissingSecret   = "missing_secret"
	AttentionKindConfigError     = "config_error"
	AttentionKindServerError     = "server_error"
	AttentionKindServerReview    = "server_review"
	AttentionKindToolReview      = "tool_review"
	AttentionKindClientNeverSeen = "client_never_seen"
)

Attention item kinds (Spec 109 FR-002). Kept as plain strings (not a typed enum) because they cross the wire verbatim in AttentionItem.Kind and in the CLI/Web/macOS fixtures generated from contracts/health-vocabulary.md's derivation table.

View Source
const (
	AttentionKindAnonymousDeniedByBindingGuard = "anonymous_denied_by_binding_guard"
	AttentionKindClientHoldsAdminKey           = "client_holds_admin_key"
	AttentionKindClientTokenNameConflict       = "client_token_name_conflict"
	AttentionKindProfileMissing                = "profile_missing"
	AttentionKindClientRotationPending         = "client_rotation_pending"
	AttentionKindClientCredentialExpiring      = "client_credential_expiring"
)

Spec 108 warning kinds surfaced as attention items (Spec 109-l FR-093). The values equal the profile.Warning* codes verbatim: one name per condition on every surface (a test asserts the equality).

View Source
const (
	// Spec 108 warnings (109-l) outrank every server item: they are
	// security-relevant and instance-level.
	AttentionRankAnonymousDenied          = 4
	AttentionRankClientHoldsAdminKey      = 5
	AttentionRankClientTokenNameConflict  = 6
	AttentionRankProfileMissing           = 7
	AttentionRankClientRotationPending    = 8
	AttentionRankClientCredentialExpiring = 9
	AttentionRankSignInRequired           = 10
	AttentionRankMissingSecret            = 20
	AttentionRankConfigError              = 30
	AttentionRankServerError              = 40
	AttentionRankServerReview             = 50
	AttentionRankToolReviewChanged        = 60
	AttentionRankToolReviewPending        = 61
	AttentionRankClientNeverSeen          = 70
)

Attention ranks (contracts/rest-api.md#attention). Ascending: lower rank sorts first. tool_review has two ranks depending on which approval state drove the item (a server with both states yields two items).

View Source
const (
	AttentionFixLogin      = "login"
	AttentionFixSetSecret  = "set_secret"
	AttentionFixRestart    = "restart"
	AttentionFixReview     = "review"
	AttentionFixReloadHint = "reload_hint"

	// Spec 108 warning fix verbs (109-l); they equal the WarningAction kinds.
	AttentionFixChangeSetting          = "change_setting"
	AttentionFixUpgradeAdminKeyHolders = "upgrade_admin_key_holders"
	AttentionFixEditToken              = "edit_token"
	AttentionFixMoveClient             = "move_client"
	AttentionFixReconnectClient        = "reconnect_client"
)

Attention fix verbs. Most are the health.Action* verbs re-used verbatim (config_error and sign_in_required fixes run the same action the health vocabulary already names); review/reload_hint are attention-only.

View Source
const (
	// AttentionServerErrorThreshold is how long a server must stay in
	// "error" or "connecting" (measured from AttentionServer.StateSince)
	// before it becomes a server_error item.
	AttentionServerErrorThreshold = 60 * time.Second
	// AttentionClientNeverSeenThreshold is how long a client must have been
	// connected (AttentionClient.ConnectedAt) with no session observed
	// since, before it becomes a client_never_seen item.
	AttentionClientNeverSeenThreshold = 5 * time.Minute
	// AttentionTimerCap bounds the threshold-recompute timer the subscriber
	// arms after every recompute (never longer than this, so a clock jump
	// cannot stall a time-based item past its threshold indefinitely).
	AttentionTimerCap = 30 * time.Second
)

Time-based thresholds (FR-002, research D2).

View Source
const (
	CredentialKindClient = "client"
	CredentialKindToken  = "token"
)

Credential kinds in the MCP vocabulary (data-model §2).

View Source
const (
	CredentialStateActive  = "active"
	CredentialStateExpired = "expired"
	CredentialStateRevoked = "revoked"
)

Credential states (data-model §2): revoked takes precedence over expired.

View Source
const (
	ProfileStateOK       = "ok"
	ProfileStateDangling = "dangling"
	ProfileStateNone     = "none"
)

Profile states of a credential's binding (data-model §2).

View Source
const (
	// ReviewScanCoverageCurrent: the latest completed scan analysed every
	// captured definition as it is now.
	ReviewScanCoverageCurrent = "current"
	// ReviewScanCoverageStale: at least one captured definition was added or
	// changed after that scan.
	ReviewScanCoverageStale = "stale"
	// ReviewScanCoverageNotCaptured: no definitions are captured for review.
	ReviewScanCoverageNotCaptured = "not_captured"
	// ReviewScanCoverageToolsNotScanned: the scan completed but exported no
	// tool definitions (a source-only or URL scan).
	ReviewScanCoverageToolsNotScanned = "tools_not_scanned"
	// ReviewScanCoverageScanning: the newest scan job is pending or running.
	ReviewScanCoverageScanning = "scanning"
	// ReviewScanCoverageNone: there is no completed scan (never scanned, or
	// the newest job failed or was cancelled).
	ReviewScanCoverageNone = "none"
)

Review scan coverage values (ReviewScan.Coverage). They say whether the latest scan verdict describes the definitions an operator is looking at. Precedence when several apply: not_captured > scanning > none > tools_not_scanned > stale > current.

View Source
const BindingPinned = "pinned"

BindingPinned is the binding of a profile-pinned agent token.

View Source
const DefaultSuggestWindow = 24 * time.Hour

DefaultSuggestWindow is the look-back window when the caller names none. The audit-log retention is the only upper limit.

View Source
const DefaultUsagePersistInterval = 30 * time.Second

DefaultUsagePersistInterval is the default snapshot flush cadence.

View Source
const DefaultWorkSessionIdleWindow = 30 * time.Minute

DefaultWorkSessionIdleWindow is how long a work session may sit idle before the next activity is considered a new one.

30 minutes is a natural break in human work: long enough to survive a pause inside a task, short enough that yesterday's work does not merge into today's.

View Source
const MaxCredentialArgumentsBytes = 16 * 1024

MaxCredentialArgumentsBytes caps the canonical JSON of a `credentials` call's arguments (A17). The largest legitimate call is a 500-character purpose plus a few ids, well under 2 KiB; capping at 16 KiB guarantees every screened string is scanned whole by the forced detector below.

View Source
const NextStepRotateAdminKey = "rotate_admin_api_key"

NextStepRotateAdminKey is the follow-up once no client holds the admin key.

View Source
const SignalHintSaferFlip = contracts.HoldSignalHintSaferFlip

SignalHintSaferFlip is kept for the spec-119 callers and tests: the safer-direction hint flip is one of the gate's signals (FR-003).

View Source
const UnknownArgumentField = "(unknown argument)"

UnknownArgumentField is the fixed placeholder a refusal names instead of a caller-supplied key (FR-020a): a key is never echoed.

Variables

View Source
var (
	// ErrActivityUnavailable means there is no activity store to write to.
	ErrActivityUnavailable = errors.New("activity service unavailable")
	// ErrActivityShuttingDown means the service already closed its write
	// barrier; the DB may be closing, so nothing new may be written.
	ErrActivityShuttingDown = errors.New("activity service is shutting down")
)

Errors a preflight activity write can fail with. They are sentinels because the served preflight surface must answer 503 when the record could not be persisted (spec 098 FR-008/FR-014: a 200 without its activity record would break the transparency guarantee), and it should be able to tell "the proxy is shutting down" from "the write failed".

View Source
var ErrCommitInvariant = errors.New("config commit invariant violated")

ErrCommitInvariant marks a commit that violated a Spec 116 invariant: a bug, never a user error.

View Source
var ErrConfigUnavailable = errors.New("configuration unavailable")

ErrConfigUnavailable is returned by MutateConfig when the desired configuration cannot be read; REST answers 500.

View Source
var ErrCredentialsUnavailable = &CredentialError{ErrCode: profile.CredentialErrorCodeCredentialsUnavailable, Msg: "credential service not available", Status: 503}

ErrCredentialsUnavailable answers when the store is not wired (startup).

View Source
var ErrEvaluatorUnavailable = errors.New("profile evaluator unavailable")

ErrEvaluatorUnavailable is returned when no ProfileEvaluator is installed.

View Source
var ErrReviewServerNotFound = errors.New("review server not found")
View Source
var ErrServerNotFound = errors.New("server not found")

ErrServerNotFound matches every *ServerNotFoundError.

View Source
var ErrServerReplaced = commitview.ErrServerReplaced

ErrServerReplaced reports that the server a caller bound to (by generation or incarnation) was removed or replaced before its commit ran. It is commitview.ErrServerReplaced, so the scanner and the HTTP layer match it without importing the runtime.

Functions

func ActiveGuardedBinding added in v0.71.0

func ActiveGuardedBinding(t *auth.AgentToken, now time.Time) bool

ActiveGuardedBinding is THE "counts as a binding" predicate of every FR-008a path (Spec 115 data-model §5): an active named client binding (ActiveNamedBinding), or an active guard-bound agent token — one minted through the MCP credentials path, which stays confined to its pin for its whole life (FR-012a). A guard-bound token is evaluated as a binding LOCKED to its pin. Legacy and REST/CLI tokens carry no guard_bound and never count (A13), so their behaviour is unchanged.

func ActiveNamedBinding added in v0.70.0

func ActiveNamedBinding(t *auth.AgentToken, now time.Time) bool

ActiveNamedBinding reports whether t is an active client credential bound to a named profile (locked or switchable).

func AttentionKinds added in v0.70.0

func AttentionKinds() []string

AttentionKinds lists every attention kind the core can emit, in rank order. The generated TypeScript union and the parity test are checked against it.

func CanonicalArgumentsSize added in v0.71.0

func CanonicalArgumentsSize(args map[string]any) int

CanonicalArgumentsSize is the byte length of the canonical JSON of args (encoding/json sorts map keys). An unserializable payload reports a size above the cap so it is refused (fail closed).

func CheckBindingGuard added in v0.70.0

func CheckBindingGuard(g BindingGuard, current, candidate GuardState) error

CheckBindingGuard runs the guard over (current -> candidate) and returns a *BindingGuardError when the delta is non-empty, nil otherwise. A nil guard is replaced by ConservativeBindingGuard, so an unwired runtime can never silently skip the check.

func Compute added in v0.70.0

Compute derives the needs-attention list from an in-memory snapshot. Pure: no I/O, no clock reads beyond in.Now (defaulted to time.Now() so production callers may omit it). Sorted by rank ascending, then subject.name (contracts/rest-api.md#attention).

func CredentialStateOf added in v0.71.0

func CredentialStateOf(t *auth.AgentToken, now time.Time) string

CredentialStateOf classifies a record: revoked over expired over active.

func IsGuardedRecord added in v0.71.0

func IsGuardedRecord(t *auth.AgentToken) bool

IsGuardedRecord reports whether t is a record kind the guard tracks at all (a client credential of any state, or a guard-bound token of any state). The snapshots keep such records so a delta can compare current and candidate.

func ParseSuggestWindow added in v0.72.0

func ParseSuggestWindow(v string) (time.Duration, error)

func PreflightActivityStatus added in v0.58.0

func PreflightActivityStatus(verdict string) string

PreflightActivityStatus maps a set verdict onto the CLOSED activity status vocabulary (see storage.ValidActivityStatuses): an all-ready preflight is a success, anything else is a policy/state block the operator has to act on. No new status value is introduced — spec 093 FR-012 makes that a cross-surface change, and preflight does not need one.

func ProfileStateOf added in v0.71.0

func ProfileStateOf(pin string, cfg *config.Config) string

ProfileStateOf reports whether the record's profile still exists.

func SortBindingRefs added in v0.70.0

func SortBindingRefs(refs []BindingRef)

SortBindingRefs orders refs by client id, then token name (the refusal's stable order; guard-bound tokens have no client id).

func TokenLegacyScope added in v0.71.0

func TokenLegacyScope(t *auth.AgentToken) bool

TokenLegacyScope reports whether a regular token's scope is its own allowed_servers/permissions rather than a profile's (data-model §3 of 108).

func ValidTokenName added in v0.71.0

func ValidTokenName(name string) bool

ValidTokenName reports whether name has the agent-token name syntax (letters, digits, '_' or '-', starting with a letter or digit, at most 64).

func WorkspaceName added in v0.49.0

func WorkspaceName(root string) string

WorkspaceName is the display name of the project — the final path element.

Only the basename is ever shown or stored for display: the full path is a local filesystem path and is nobody's business but the user's. It is never sent to telemetry.

Types

type AccessExplanation added in v0.70.0

type AccessExplanation struct {
	Subject      ExplainSubjectView     `json:"subject"`
	Tool         string                 `json:"tool"`
	Profile      ExplainProfileView     `json:"profile"`
	Steps        []ExplainStepView      `json:"steps"`
	Verdict      profile.ExplainVerdict `json:"verdict"`
	FirstFailure profile.ExplainStep    `json:"first_failure"`
	Fixes        []Fix                  `json:"fixes"`
}

AccessExplanation is GET /access/explain (FR-035, data-model §7).

type AccessSuggestion added in v0.72.0

type AccessSuggestion struct {
	Profile     string              `json:"profile"`
	Tool        string              `json:"tool"` // "server:tool", or the built-in name
	Server      string              `json:"server,omitempty"`
	BlockReason profile.BlockReason `json:"block_reason"`
	Count       int                 `json:"count"`
	Tokens      []string            `json:"tokens"`
	Clients     []string            `json:"clients"`
	FirstSeen   time.Time           `json:"first_seen"`
	LastSeen    time.Time           `json:"last_seen"`
	Suggestion  SuggestionKind      `json:"suggestion"`
	// Fixes are the access explainer's remediations of the first failing step,
	// in preference order. Empty for a deny rule and for the built-in tools.
	Fixes []Fix `json:"fixes"`
	// NeedsInput names what a person must supply before a change is
	// apply-ready (classify: "tier").
	NeedsInput []string `json:"needs_input,omitempty"`
	// Warning is set for profile_code_execution and profile_management: both
	// change what a profile can do beyond tool access.
	Warning string `json:"warning,omitempty"`
	Note    string `json:"note,omitempty"`
}

AccessSuggestion is one group of identical refusals: the same profile, server, tool and block reason.

type AccessSuggestions added in v0.72.0

type AccessSuggestions struct {
	Since       time.Time          `json:"since"`
	Until       time.Time          `json:"until"`
	Window      string             `json:"window"`
	Suggestions []AccessSuggestion `json:"suggestions"`
	Patches     []ProfilePatch     `json:"patches,omitempty"`

	// BlockedCalls counts every profile-refused call in the window.
	BlockedCalls int `json:"blocked_calls"`
	// AlreadyFixed counts groups the explainer now allows (they drop out).
	AlreadyFixed int `json:"already_fixed"`
	// ProfileRemoved counts groups whose profile no longer exists (they drop out).
	ProfileRemoved int `json:"profile_removed"`
	// NonProfileBlocked counts blocked calls with a cause outside profiles.
	NonProfileBlocked int `json:"non_profile_blocked"`
	// Unattributed counts profile refusals whose record names no profile.
	Unattributed int `json:"unattributed"`
}

AccessSuggestions is the whole answer.

type ActivityAttribution added in v0.70.0

type ActivityAttribution struct {
	Profile       string
	ProfileSource string
	ClientID      string
	// ClientName is the self-reported clientInfo.name: advisory, never
	// authoritative (a client can claim any name).
	ClientName string
	// ClientVersion is the self-reported clientInfo.version that travelled
	// with ClientName when the identity was read off the REQUEST rather than
	// a session (Spec 058 US3: a 2026-07-28 request never ran initialize, so
	// the session store cannot supply it). Empty when the session resolver
	// already stamped metadata.client_version.
	ClientVersion string
	TokenName     string
	// TokenPrefix is the 12-char display prefix of the calling token. It is
	// INTERNAL: persisted on the storage record as the ownership proof (so a
	// scoped caller recognises its own policy_decision and prompt_get rows),
	// never in any API shape, export or SSE frame for another caller.
	TokenPrefix string
}

ActivityAttribution is the Spec 108 FR-029 scope attribution of one call: the profile, client and token IN EFFECT when it ran. It is computed once at emit time by the dispatch path (never re-resolved later, so a reassignment does not rewrite history), travels in the event payload under "attribution", and the activity service copies it onto the first-class record fields.

The zero value means "no attribution" (system events, limiter sheds, callers with no MCP/REST request context).

func (ActivityAttribution) IsZero added in v0.70.0

func (a ActivityAttribution) IsZero() bool

IsZero reports whether no field is set.

type ActivityCallOutcome added in v0.71.0

type ActivityCallOutcome struct {
	ErrorClass         string
	FaultDomain        string
	UpstreamHTTPStatus int
}

ActivityCallOutcome is the call-error taxonomy of one failed tool call (Spec 113-c FR-044/FR-045): the classifier's error_class, fault_domain and, when known, the upstream HTTP status. The zero value (a success, or a path that has no classification) leaves the payload exactly as it was before Spec 113.

type ActivityService

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

ActivityService subscribes to activity events and persists them to storage. It runs as a background goroutine and handles activity recording non-blocking.

func NewActivityService

func NewActivityService(storage *storage.Manager, logger *zap.Logger) *ActivityService

NewActivityService creates a new activity service.

func (*ActivityService) RecordPreflight added in v0.58.0

func (s *ActivityService) RecordPreflight(rec PreflightActivity) error

RecordPreflight persists one preflight run SYNCHRONOUSLY and returns the write error (spec 098 FR-014).

It deliberately bypasses the bounded async event channel every other activity path uses: that channel drops events for a subscriber that falls behind, and FR-014 requires the record to be durable BEFORE the caller is answered. This is the same trade RecordToolCallRejected makes — one BBolt write on the caller's goroutine, joined to the shutdown barrier via enterWrite so it can never straddle a DB close (Spec 080 FR-010).

func (*ActivityService) RecordToolCallRejected added in v0.54.0

func (s *ActivityService) RecordToolCallRejected(evt Event)

RecordToolCallRejected persists a concurrency-limiter shed as a tool_call record with the dedicated "rejected" status (spec 093 FR-012). It is a separate path from handleToolCallCompleted because a shed has no upstream response, no token metrics and no intent envelope — only the rejection metadata an operator needs to right-size the limits.

It runs SYNCHRONOUSLY on the rejecting goroutine rather than on the activity event loop: the event bus drops events for a subscriber that falls behind, and a shed burst is exactly when it does. The cost is one BBolt write on an error path that is already returning without calling the upstream.

Spec 080 FR-010: because the write lives on someone else's goroutine, it must join the same shutdown barrier as every other BBolt writer this service owns. enterWrite registers it in workersWG under the lock Stop coordinates with, so a write either happens entirely before Stop returns or does not happen at all — it can never straddle the DB close.

func (*ActivityService) SetDetector added in v0.17.0

func (s *ActivityService) SetDetector(detector *security.Detector)

SetDetector sets the sensitive data detector for async scanning (Spec 026). If set, tool call arguments and responses will be scanned for sensitive data.

func (*ActivityService) SetEventEmitter added in v0.17.0

func (s *ActivityService) SetEventEmitter(emitter SensitiveDataEventEmitter)

SetEventEmitter sets the event emitter for sensitive data detection events (Spec 026). If set, events will be emitted when sensitive data is detected in tool calls.

func (*ActivityService) SetMaxResponseSize added in v0.65.0

func (s *ActivityService) SetMaxResponseSize(maxResponseSize int)

SetMaxResponseSize sets the per-record response size cap in bytes. Values <= 0 are ignored, leaving the current cap in place; truncateForStorage falls back to storage.DefaultMaxResponseSize if it is ever unset.

func (*ActivityService) SetRetentionConfig

func (s *ActivityService) SetRetentionConfig(maxAge time.Duration, maxRecords int, checkInterval time.Duration, maxSizeBytes int64)

SetRetentionConfig updates the retention configuration. maxAge: maximum age for records (0 = no age limit) maxRecords: maximum number of records (0 = no count limit) checkInterval: how often to run retention cleanup

func (*ActivityService) SetSessionClientResolver added in v0.49.0

func (s *ActivityService) SetSessionClientResolver(r SessionClientResolver)

SetSessionClientResolver wires the session -> MCP client lookup. Safe to leave unset (records then carry no client name).

func (*ActivityService) SetUsagePersistInterval added in v0.35.0

func (s *ActivityService) SetUsagePersistInterval(d time.Duration)

SetUsagePersistInterval updates the snapshot flush cadence. Hot-reloadable: the flush loop re-reads this value each cycle.

func (*ActivityService) SetWorkSessionReaper added in v0.49.0

func (s *ActivityService) SetWorkSessionReaper(f func(time.Duration) int)

SetWorkSessionReaper wires the idle-work-session sweep into the retention loop.

func (*ActivityService) SetWorkSessionResolver added in v0.49.0

func (s *ActivityService) SetWorkSessionResolver(r SessionWorkSessionResolver)

SetWorkSessionResolver wires the session -> work-session lookup (Spec 082).

func (*ActivityService) Start

func (s *ActivityService) Start(ctx context.Context, rt *Runtime)

Start begins listening for activity events and persisting them. It should be called as a goroutine: go svc.Start(ctx, runtime)

func (*ActivityService) Started added in v0.70.0

func (s *ActivityService) Started() bool

Started reports whether the activity service has registered its runtime event subscription. It is safe to call while Start is running.

func (*ActivityService) Stop

func (s *ActivityService) Stop()

Stop gracefully shuts down the activity service, waiting for every BBolt writer it owns to finish: the main event loop (including its final flush-on-shutdown of the usage snapshot), the retention and usage-flush loops, and any in-flight async detection goroutines (Spec 080 FR-010: no activity write may land after Runtime.Close resolves the clean-shutdown marker or closes the DB).

Callers must cancel the context passed to Start FIRST — the final usage flush runs on ctx.Done inside the event loop, and Stop waits for it, so the flush is captured before the marker resolves. Idempotent, and returns immediately when Start never ran.

Stop is also terminal (Spec 080, review round 5): it marks stopped under startMu, so a Start that has not yet registered (production starts the service via `go` in lifecycle.go) becomes a no-op instead of launching retention/usage/persist loops after the shutdown-marker path began. If Start is mid-registration, acquiring startMu here blocks until every workersWG.Add has happened, so the Wait below cannot miss a worker.

func (*ActivityService) UsageSnapshot added in v0.35.0

func (s *ActivityService) UsageSnapshot() *UsageAggregate

UsageSnapshot returns the latest immutable usage aggregate snapshot. Safe for concurrent readers (the A3 endpoint); never blocks. Returns nil if usage tracking was never initialized.

type ActivityStats24h added in v0.70.0

type ActivityStats24h struct {
	ByProfile map[string]Counter
	ByClient  map[string]Counter
}

ActivityStats24h is the last-24 h rollup of tool calls and blocked calls by profile and by client (F27).

type Actor added in v0.70.0

type Actor struct {
	Kind    string          // actor_kind: api_key, socket, agent_token, cookie, cli_offline, ...
	Name    string          // actor_name: token name / user email, "" otherwise
	Surface profile.Surface // web, macos, cli, mcp, api
}

Actor attributes a mutation on the profile_change record (FR-030).

func ActorFromContext added in v0.70.0

func ActorFromContext(ctx context.Context, surface profile.Surface) Actor

ActorFromContext derives the actor from the request's AuthContext (D21).

type AddRequest added in v0.70.0

type AddRequest struct {
	ID          string
	DisplayName string
	Profile     string
	Mode        *string
	ExpiresAt   time.Time
	// Purpose is the stated, unenforced task brief (Spec 115).
	Purpose string
}

AddRequest creates a credential for a custom (non-connect-registry) client. ExpiresAt zero means the 365-day default; DisplayName is at most auth.MaxClientDisplayName characters.

type AdminKeyUpgradePort added in v0.70.0

type AdminKeyUpgradePort interface {
	GetStatus(clientID string) (connect.ClientStatus, error)
	PreviewWithIntent(clientID, serverName string, intent connect.CredentialIntent) (*connect.ConnectPreview, error)
	ConnectWithOptions(clientID, serverName string, opts connect.ConnectOptions) (*connect.ConnectResult, error)
}

AdminKeyUpgradePort is the slice of connect.Service the upgrade uses (*connect.Service implements it).

type ArgumentsTooLargeError added in v0.71.0

type ArgumentsTooLargeError struct{ Size int }

ArgumentsTooLargeError is the `arguments_too_large` refusal (A17).

func (*ArgumentsTooLargeError) Code added in v0.71.0

func (e *ArgumentsTooLargeError) Code() string

Code is the wire `code`.

func (*ArgumentsTooLargeError) Error added in v0.71.0

func (e *ArgumentsTooLargeError) Error() string

type AttentionClient added in v0.70.0

type AttentionClient struct {
	ID          string
	DisplayName string
	ConnectedAt *time.Time // last successful connect write
	LastSeen    *time.Time // last MCP session mapped to this client
}

AttentionClient is the only client data Compute needs. 109-d defines it so attention.go compiles and is testable without 109-h's client presence service; 109-h feeds it from ClientPresence.

type AttentionClientWarning added in v0.70.0

type AttentionClientWarning struct {
	Code         string // a profile.Warning* value
	ClientID     string
	DisplayName  string
	Profile      string     // profile_missing: the missing profile slug
	ExpiresAt    *time.Time // client_credential_expiring
	BindingCount int        // anonymous_denied_by_binding_guard
	BindingNames []string   // display names of the bound clients, for the guard detail
	// Since is when the subscriber first saw this warning. Ignored for
	// client_credential_expiring, whose since is ExpiresAt minus the warning
	// window. Zero means "now".
	Since time.Time
}

AttentionClientWarning is the only Spec 108 warning data Compute needs.

type AttentionEventItem added in v0.70.0

type AttentionEventItem struct {
	ID          string `json:"id"`
	SubjectType string `json:"subject_type"`
	SubjectID   string `json:"subject_id"`
}

AttentionEventItem is the minimal, wire-stable shape the runtime attention.changed event carries per item (data-model.md §4): just enough for internal/httpapi to narrow the id set per subscriber (FR-006) without re-deriving summaries/fixes on the SSE hot path.

func AttentionEventItems added in v0.70.0

func AttentionEventItems(items []contracts.AttentionItem) []AttentionEventItem

type AttentionInput added in v0.70.0

type AttentionInput struct {
	Servers []AttentionServer
	Clients []AttentionClient
	// ClientWarnings are the Spec 108 warnings (109-l). Empty in the server
	// edition, which has no clients service.
	ClientWarnings []AttentionClientWarning
	Now            time.Time

	// ServerErrorThreshold and ClientNeverSeenThreshold override the package
	// defaults (AttentionServerErrorThreshold, AttentionClientNeverSeenThreshold)
	// when non-zero. Production callers leave these zero; tests use them to
	// exercise the threshold-crossing behaviour without waiting real minutes.
	ServerErrorThreshold     time.Duration
	ClientNeverSeenThreshold time.Duration
}

AttentionInput is the pure snapshot Compute derives the list from.

type AttentionServer added in v0.70.0

type AttentionServer struct {
	Name        string
	Enabled     bool
	Quarantined bool
	Health      contracts.HealthStatus
	Pending     int
	Changed     int
	StateSince  time.Time
	Detail      string // e.g. "OAuth · api.githubcopilot.com" — never a secret, path, query or header
}

AttentionServer is the only server data Compute needs (data-model.md §4). The subscriber builds it from the same []contracts.Server rows the servers.changed payload is built from.

type BindingGuard added in v0.70.0

type BindingGuard interface {
	// BindingGuardDelta returns the bindings that are bypassable in candidate
	// and were not already bypassable in current, sorted by client id.
	BindingGuardDelta(current, candidate GuardState) []BindingRef
	// BindingGuardFixes returns the fixes that would make delta empty for
	// candidate: require_mcp_auth always, plus set_anonymous_profile (with a
	// target when one is available).
	BindingGuardFixes(candidate GuardState, delta []BindingRef) []GuardFix
	// BindingGuardActiveBindings returns the bindings that are bypassable
	// right now (config and token store as they stand). It drives the
	// anonymous_denied_by_binding_guard warning.
	BindingGuardActiveBindings() []BindingRef
}

BindingGuard evaluates FR-008a. Implementations must be safe for concurrent use and must fail closed: when the condition cannot be evaluated they report the binding as bypassable.

type BindingGuardError added in v0.70.0

type BindingGuardError struct {
	Bindings []BindingRef
	Fixes    []GuardFix
}

BindingGuardError is the refusal returned when a write would leave a named client binding bypassable without auth. REST maps it to `409 binding_bypassable_without_auth`, the CLI prints it and exits 1.

func (*BindingGuardError) Code added in v0.70.0

func (e *BindingGuardError) Code() string

Code is the wire `code` of the refusal.

func (*BindingGuardError) Error added in v0.70.0

func (e *BindingGuardError) Error() string

Error returns the byte-stable refusal text (contracts/refusals.md).

type BindingNotifier added in v0.70.0

type BindingNotifier interface {
	NotifyBindingChanged(tokenName string)
}

BindingNotifier delivers FR-026's live effects for a token whose binding changed: clear the stored set_profile selection of every session it authenticated and send notifications/tools/list_changed to each. The server implements it; it is called synchronously so clearing is complete before the mutation returns.

type BindingRef added in v0.70.0

type BindingRef struct {
	ClientID  string `json:"client_id"`
	TokenName string `json:"token_name"`
	Profile   string `json:"profile"`
	Mode      string `json:"mode"`
}

BindingRef names one client binding in a guard refusal (the `bindings[]` of the 409 body).

func BindingRefOf added in v0.70.0

func BindingRefOf(t *auth.AgentToken) BindingRef

BindingRefOf projects a guarded record to its BindingRef. A guard-bound token has no client id and is reported as locked to its pin.

type ChangeHint added in v0.70.0

type ChangeHint struct {
	Kind            profile.ChangeKind
	Profile         string
	PreviousProfile string
	Diff            map[string]interface{}
}

ChangeHint lets a service that performs ONE named operation (rename, delete with reassign, classify, set anonymous) say so, so the write yields exactly that operation's single record instead of the create+delete pair (and the cascaded switchable_to edits) a plain snapshot diff would show (F8). A zero Kind means "derive the records from the diff".

type ClientConfigReader added in v0.70.0

type ClientConfigReader interface {
	ClientSecret(clientID string) (secret string, found bool, err error)
}

ClientConfigReader reads the credential a supported client's config holds (the reconciler's view of FR-021a). found is false when the config has no mcpproxy entry. connect.Service implements it.

type ClientCredentialStore added in v0.70.0

type ClientCredentialStore interface {
	MintClientCredential(clientID, rawToken string, hmacKey []byte, mode, pin string, expiresAt time.Time) (*auth.AgentToken, error)
	MintClientCredentialNamed(clientID, rawToken string, hmacKey []byte, mode, pin string, expiresAt time.Time, displayName string) (*auth.AgentToken, error)
	MintClientCredentialWith(clientID, rawToken string, hmacKey []byte, opts storage.ClientMintOptions) (*auth.AgentToken, error)
	StageClientCredentialRotation(clientID, newRawToken string, hmacKey []byte) (*auth.AgentToken, error)
	FinalizeClientCredentialRotation(clientID string) (*auth.AgentToken, error)
	RollbackClientCredentialRotation(clientID string) (*auth.AgentToken, error)
	ForgetClientCredential(clientID string) (*auth.AgentToken, error)
	ForgetClientCredentialRestoringPrior(clientID string) (*auth.AgentToken, error)
	UpdateClientCredentialBinding(clientID, pin, mode string) (before, after *auth.AgentToken, err error)
	ListAgentTokens() ([]auth.AgentToken, error)
}

ClientCredentialStore is the token-store surface the service needs; *storage.Manager implements it.

type ClientCredentialView added in v0.70.0

type ClientCredentialView struct {
	ID              string                  `json:"id"`
	DisplayName     string                  `json:"display_name,omitempty"`
	TokenName       string                  `json:"token_name"`
	Profile         string                  `json:"profile"`
	Mode            string                  `json:"mode"`
	CredentialState profile.CredentialState `json:"credential_state"`
	ExpiresAt       *time.Time              `json:"expires_at,omitempty"`
	ConnectedAt     *time.Time              `json:"connected_at,omitempty"`
	RotationPending bool                    `json:"rotation_pending,omitempty"`
}

ClientCredentialView is a client's credential as the surfaces show it.

type ClientsService added in v0.70.0

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

ClientsService is THE service behind every client-credential operation (Spec 108, FR-026): assign, lock, unlock, bulk, rotate, forget, add, list, plus the connect credential minter and the staged-rotation reconciler. REST, CLI, MCP, Web UI and macOS all call it, so records, notifications and the FR-008a guard cannot drift between surfaces.

Every mutation holds one mutex across "guard check + write" (plan D3). The mutex is the runtime's bindingWriteMu, shared with the guarded config apply, so a config write and a binding write can never combine into a bypassable state.

func NewClientsService added in v0.70.0

func NewClientsService(d ClientsServiceDeps) *ClientsService

NewClientsService builds the service from its dependencies.

func (*ClientsService) Add added in v0.70.0

Add mints a credential for a custom client and returns the secret once. Id rules are FR-021: the pattern, and never a supported-client id. It is the REST-mode credentials issue path (Spec 115 FR-010): the secret-shaped input screen runs first, the record is `issue`, and the view is projected from the committed record, so nothing after the mint can fail the call.

func (*ClientsService) ApplyAdminKeyUpgrade added in v0.70.0

func (s *ClientsService) ApplyAdminKeyUpgrade(ctx context.Context, a Actor, req UpgradeRequest) (*UpgradeResult, error)

ApplyAdminKeyUpgrade upgrades every holder. The precondition token, when sent, must match a fresh preview (*PreconditionFailedError otherwise); the FR-008a guard runs over the whole request first (*BindingGuardError: nothing minted, no file written); then each client is connected with force, bound to its own row token, so one client's drift fails that client only.

func (*ClientsService) BulkAssign added in v0.70.0

func (s *ClientsService) BulkAssign(ctx context.Context, a Actor, from, to string, modeArg *string) (moved []string, skipped []Skipped, err error)

BulkAssign moves every active client credential bound to profile `from` to profile `to` (mode as in SetBinding). The guard and the credential precondition apply per client: refused clients are reported in skipped[] with the same code the single operation returns, the others are moved and each writes its own record.

func (*ClientsService) ConnectMinter added in v0.70.0

func (s *ClientsService) ConnectMinter() connect.CredentialMinter

ConnectMinter adapts the service to connect.CredentialMinter.

func (*ClientsService) CredentialsServiceOver added in v0.71.0

func (s *ClientsService) CredentialsServiceOver(tokens CredentialTokenStore) *CredentialsService

CredentialsServiceOver builds a CredentialsService that shares this service's store wiring, clock, guard, mutex, activity sink and publisher, with tokens as its token store (the REST server's fallback when the runtime's own service is not wired, e.g. in unit tests).

func (*ClientsService) FinalizeRotation added in v0.70.0

func (s *ClientsService) FinalizeRotation(ctx context.Context, a Actor, clientID string) (*ClientCredentialView, error)

FinalizeRotation promotes a staged secret. Idempotent: no rotation in progress is a no-op success. A finalize that did promote writes the single `rotate` record (outcome finalized).

func (*ClientsService) Forget added in v0.70.0

func (s *ClientsService) Forget(ctx context.Context, a Actor, clientID string, disconnected bool) (*ClientCredentialView, error)

Forget revokes a client's credential (change=forget). disconnected records whether the config entry was removed with it.

func (*ClientsService) Get added in v0.70.0

func (s *ClientsService) Get(clientID string) (*ClientCredentialView, error)

Get returns one client's credential view, or nil when it has none.

func (*ClientsService) List added in v0.70.0

func (s *ClientsService) List() ([]ClientCredentialView, error)

List returns every client credential (any state), sorted by client id.

func (*ClientsService) Now added in v0.70.0

func (s *ClientsService) Now() time.Time

Now is the service's clock (tests inject one); REST uses it so "expiring" and "last observed" agree with the service.

func (*ClientsService) ObservedCredentialStates added in v0.70.0

func (s *ClientsService) ObservedCredentialStates(observed map[string]storage.ClientCredentialObservation) (map[string]profile.CredentialState, error)

ObservedCredentialStates returns the credential states Warnings needs for the admin-key warning: the persisted last observation (Spec 108-f F11) of every connect-registry client that has no client credential record of its own. It reads the credential store only, never a client config (Spec 075). Both GET /clients and the needs-attention list call it, so they cannot disagree.

func (*ClientsService) PreviewAdminKeyUpgrade added in v0.70.0

func (s *ClientsService) PreviewAdminKeyUpgrade(ctx context.Context, a Actor, req UpgradeRequest) (*UpgradePreview, error)

PreviewAdminKeyUpgrade classifies every supported client that holds the admin key and shows what upgrading each would change. It writes nothing and mints nothing; when a named profile would make the request's bindings bypassable, the refusal the apply would return is reported as `guard`.

func (*ClientsService) Reconcile added in v0.70.0

func (s *ClientsService) Reconcile(ctx context.Context) error

Reconcile resolves every staged rotation it can (FR-021a), at startup. Only records mid-rotation are examined, so it reads at most the configs of clients whose rotation was interrupted.

func (*ClientsService) ReconcileClient added in v0.70.0

func (s *ClientsService) ReconcileClient(ctx context.Context, clientID string) error

ReconcileClient resolves one client's staged rotation, if any:

  • supported client whose config holds the new secret -> finalize;
  • holds the old secret -> roll back (drop the pending one);
  • unreadable, no entry, or neither -> keep both (client_rotation_pending);
  • custom client (no readable config) -> finalize after the 24 h overlap.

A crash or write failure at any point therefore never leaves a client holding an invalidated secret.

func (*ClientsService) ReconcileTimeOnly added in v0.70.0

func (s *ClientsService) ReconcileTimeOnly(ctx context.Context) error

ReconcileTimeOnly is the half of the FR-021a reconciler that needs no config read: a custom client's staged rotation finalizes once the 24 h overlap has passed. The clients LIST runs only this half (Spec 075 keeps a list free of content reads); the detail read runs the full ReconcileClient.

func (*ClientsService) Records added in v0.70.0

func (s *ClientsService) Records() ([]auth.AgentToken, error)

Records returns every ownerless token record that concerns a client credential: the kind=client records (any state) and any regular token that holds a client-<id> name (the FR-021 conflict). The REST clients list reads it once to decorate its rows.

func (*ClientsService) Rotate added in v0.70.0

func (s *ClientsService) Rotate(ctx context.Context, a Actor, clientID string) (secret string, view *ClientCredentialView, err error)

Rotate stages a rotation over an active credential and returns the new secret ONCE (custom clients paste it into their own config; supported clients go through connect). Both secrets authenticate until FinalizeRotation.

func (*ClientsService) SetBinding added in v0.70.0

func (s *ClientsService) SetBinding(ctx context.Context, a Actor, clientID, profileName string, modeArg *string) (*ClientCredentialView, error)

SetBinding reassigns a client's profile and/or mode (assign|lock|unlock). It applies only to an active client credential (FR-026), refuses a binding the FR-008a guard would leave bypassable, clears the stored selection of every live session of the token, emits client.binding_changed, notifies the sessions, writes one profile_change record and never touches the client's config file. modeArg nil keeps the current mode, except profile "" which means All servers (switchable).

func (*ClientsService) SetConfigReader added in v0.70.0

func (s *ClientsService) SetConfigReader(r ClientConfigReader)

SetConfigReader installs the client-config reader used by the reconciler.

func (*ClientsService) SetNotifier added in v0.70.0

func (s *ClientsService) SetNotifier(n BindingNotifier)

SetNotifier installs the live-session notifier (the server).

func (*ClientsService) SetObserver added in v0.70.0

func (s *ClientsService) SetObserver(fn func(clientID string, state profile.CredentialState))

SetObserver installs the sink for on-demand credential classifications (Spec 108-f F11): REST persists the last observation per client so the stat-only list can still report who holds the admin key across restarts.

func (*ClientsService) SetUpgradePort added in v0.70.0

func (s *ClientsService) SetUpgradePort(p AdminKeyUpgradePort)

SetUpgradePort installs the connect port behind the admin-key upgrade.

func (*ClientsService) StateOf added in v0.70.0

StateOf classifies a credential record (client | revoked | expired | none).

func (*ClientsService) Warnings added in v0.70.0

func (s *ClientsService) Warnings(states map[string]profile.CredentialState) []Warning

Warnings derives the credential and guard warnings. states maps client id to its classified credential_state where the caller has it (an on-demand classification or the persisted last observation); rows not in the map contribute no admin-key warning.

type ClientsServiceDeps added in v0.70.0

type ClientsServiceDeps struct {
	Store    ClientCredentialStore
	HMACKey  func() ([]byte, error)
	Config   func() *config.Config
	Guard    func() BindingGuard
	Activity func(*storage.ActivityRecord) error
	Publish  func(Event)
	Now      func() time.Time
	Mu       *sync.Mutex
	Logger   *zap.Logger
}

ClientsServiceDeps wires a ClientsService. Zero values are safe in tests: Now defaults to time.Now, Mu to a private mutex, Guard to the conservative evaluator, Logger to a no-op.

type CommitResult added in v0.71.0

type CommitResult struct {
	// Generation is the commit generation G, or 0 when nothing was published.
	Generation int64
	// Snapshot is the published snapshot (nil when nothing was published).
	Snapshot *configsvc.Snapshot
	// Changes is the per-server change set.
	Changes map[string]ServerChange
	// Published reports whether the commit published a configuration.
	Published bool
	// DiskWritten reports whether the commit wrote the config file.
	DiskWritten bool
	// Restamped lists the retained instances step 7 updated in place.
	Restamped []string
	// Purged reports, per removed or replaced server, what the storage step
	// deleted from the purge set (Spec 116 PR2, data-model §PurgeSet).
	Purged map[string]storage.PurgeReport
	// contains filtered or unexported fields
}

CommitResult describes a commit that returned without error.

type CommitTx added in v0.71.0

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

CommitTx is the working copy a commit's fn mutates. It is only valid inside fn. Its methods never touch storage, disk or the manager; the pipeline does.

func (*CommitTx) Base added in v0.71.0

func (tx *CommitTx) Base() *config.Config

Base returns the live configuration the commit started from. Read-only.

func (*CommitTx) Bootstrap added in v0.71.0

func (tx *CommitTx) Bootstrap()

Bootstrap is for the boot reconcile only, always with ReconcileLive: it forces the pipeline to run and schedules a connect for every enabled server. Anywhere else it is an invariant error (review R9.6).

func (*CommitTx) Config added in v0.71.0

func (tx *CommitTx) Config() *config.Config

Config returns the working configuration. Callers may read it; they change it only through the CommitTx operations (or MutateGlobal for global fields).

func (*CommitTx) CreateServer added in v0.71.0

func (tx *CommitTx) CreateServer(sc *config.ServerConfig) error

CreateServer adds a new server. It fails with *ServerExistsError when the name is in the working copy, or when a row is still stored for a name that is not in the live configuration (#1570: an add never overwrites).

func (*CommitTx) EventExtra added in v0.71.0

func (tx *CommitTx) EventExtra(extra map[string]any)

EventExtra adds caller fields (for example {"server", "quarantined"}) to the commit's one servers.changed event, so a caller never sends a second, same-reason copy of it (FR-028: at most once per commit and reason). The commit's own "servers" and "generation" fields win on a clash.

func (*CommitTx) ExpectGeneration added in v0.71.0

func (tx *CommitTx) ExpectGeneration(name string, gen int64) error

ExpectGeneration fails the commit with ErrServerReplaced unless name's committed generation is gen.

func (*CommitTx) ExpectIncarnation added in v0.71.0

func (tx *CommitTx) ExpectIncarnation(name string, inc int64) error

ExpectIncarnation fails the commit with ErrServerReplaced unless name's committed incarnation is inc.

func (*CommitTx) ForceDisk added in v0.71.0

func (tx *CommitTx) ForceDisk()

ForceDisk makes the commit write the config file even when nothing changed (SaveConfiguration).

func (*CommitTx) Generation added in v0.71.0

func (tx *CommitTx) Generation(name string) (configsvc.ServerGen, bool)

Generation returns name's committed generation in the base snapshot.

func (*CommitTx) MutateGlobal added in v0.71.0

func (tx *CommitTx) MutateGlobal(fn func(cfg *config.Config) error) error

MutateGlobal runs fn on the working configuration for global fields (listen, registries, profiles, …). Servers must be changed through the server operations, which keep the replacement bookkeeping.

func (*CommitTx) ReconcileLive added in v0.71.0

func (tx *CommitTx) ReconcileLive()

ReconcileLive reconciles storage with the live configuration (projection repair). It takes no argument: the base is the config read inside the lock.

func (*CommitTx) RemoveServer added in v0.71.0

func (tx *CommitTx) RemoveServer(name string) error

RemoveServer removes a server. Unknown names fail with *ServerNotFoundError.

func (*CommitTx) ReplaceConfig added in v0.71.0

func (tx *CommitTx) ReplaceConfig(cfg *config.Config)

ReplaceConfig makes cfg the new configuration. cfg must be a configuration the caller submitted in this call, or the file read inside the commit (D14); never a snapshot captured earlier. It cannot express a same-name replacement: an entry that keeps its name is an update.

func (*CommitTx) Server added in v0.71.0

func (tx *CommitTx) Server(name string) (*config.ServerConfig, bool)

Server returns a deep copy of the working entry for name.

func (*CommitTx) SetEnabled added in v0.71.0

func (tx *CommitTx) SetEnabled(name string, enabled bool) error

SetEnabled sets a server's enabled flag.

func (*CommitTx) SetQuarantined added in v0.71.0

func (tx *CommitTx) SetQuarantined(name string, quarantined bool) error

SetQuarantined sets a server's quarantine flag and records it as an explicit decision (#937), so the admission gate and the next file load obey it.

func (*CommitTx) UnderApprovalLock added in v0.71.0

func (tx *CommitTx) UnderApprovalLock(name string, fn func() error) error

UnderApprovalLock registers fn to run in step 4 while the commit holds name's approval lock (the Spec 117 review-bound approval integration point). fn may only write fail-safe state; an error aborts the commit with nothing written.

func (*CommitTx) UpdateServer added in v0.71.0

func (tx *CommitTx) UpdateServer(name string, fn func(cur *config.ServerConfig) error) error

UpdateServer runs fn on a deep copy of the live entry and stores the result. fn must not change the name. Unknown names fail with *ServerNotFoundError.

type ConfigApplyResult

type ConfigApplyResult struct {
	Success            bool                     `json:"success"`
	AppliedImmediately bool                     `json:"applied_immediately"`
	RequiresRestart    bool                     `json:"requires_restart"`
	RestartReason      string                   `json:"restart_reason,omitempty"`
	ChangedFields      []string                 `json:"changed_fields,omitempty"`
	ValidationErrors   []config.ValidationError `json:"validation_errors,omitempty"`
}

ConfigApplyResult represents the result of applying a configuration

func DetectConfigChanges

func DetectConfigChanges(oldCfg, newCfg *config.Config) *ConfigApplyResult

func (*ConfigApplyResult) FormatChangedFields

func (r *ConfigApplyResult) FormatChangedFields() string

FormatChangedFields returns a human-readable string of changed fields

type ConfigDiff added in v0.70.0

type ConfigDiff struct {
	Changes []ProfileChange
}

ConfigDiff is the profile-level difference one MutateConfig applied. It is empty when the write touched nothing profile-related.

type ConnectInProgressError added in v0.70.0

type ConnectInProgressError struct{ ClientID string }

ConnectInProgressError is the 409 connect_in_progress refusal: a connect of the client holds the in-flight claim (FR-021a), so another connect, rotate, finalize or binding change must wait for it.

func (*ConnectInProgressError) Code added in v0.70.0

func (e *ConnectInProgressError) Code() string

Code is the wire `code` of the refusal.

func (*ConnectInProgressError) Error added in v0.70.0

func (e *ConnectInProgressError) Error() string

type ConservativeBindingGuard added in v0.70.0

type ConservativeBindingGuard struct{}

ConservativeBindingGuard is the guard for callers that cannot evaluate the tool-dependent reachability comparison (the runtime before the server wires the real evaluator, and the offline CLI without a running core). It treats every active named binding as bypassable while require_mcp_auth is off, so it is only ever stricter than the real evaluator.

func (ConservativeBindingGuard) BindingGuardActiveBindings added in v0.70.0

func (ConservativeBindingGuard) BindingGuardActiveBindings() []BindingRef

BindingGuardActiveBindings implements BindingGuard.

func (ConservativeBindingGuard) BindingGuardDelta added in v0.70.0

func (ConservativeBindingGuard) BindingGuardDelta(current, candidate GuardState) []BindingRef

BindingGuardDelta implements BindingGuard. Binding identity is the token name, unique across both kinds (a client's is client-<id>; a guard-bound token has no client id and must not collide with another token).

func (ConservativeBindingGuard) BindingGuardFixes added in v0.70.0

func (ConservativeBindingGuard) BindingGuardFixes(GuardState, []BindingRef) []GuardFix

BindingGuardFixes implements BindingGuard: with no evaluator, only turning auth on is a fix that is known to work.

type Counter added in v0.70.0

type Counter struct {
	Calls   int
	Blocked int
}

Counter is a calls/blocked pair over the last 24 hours.

type CredentialError added in v0.71.0

type CredentialError struct {
	ErrCode string
	Field   string
	Msg     string
	State   string
	Status  int
}

CredentialError is a typed refusal of the credentials service. Code is a profile.CredentialErrorCode*; Field names the argument at fault; State is set for identity_exists. Status is the HTTP status a REST surface answers (REST keeps its existing codes and texts; the MCP tool uses Code).

func (*CredentialError) Code added in v0.71.0

func (e *CredentialError) Code() string

Code is the wire `code`.

func (*CredentialError) Error added in v0.71.0

func (e *CredentialError) Error() string

type CredentialFilter added in v0.71.0

type CredentialFilter struct {
	Kind, Profile, State string
	// IncludeClients is false in the server edition (no client credentials).
	ExcludeClients bool
}

CredentialFilter narrows List.

type CredentialRef added in v0.71.0

type CredentialRef struct {
	Client, Token string
	// EnforceWriteGates (MCP) re-checks read_only_mode and disable_management
	// under bindingWriteMu, so a mutation queued behind a config write that
	// turns a gate on is refused (the handler's check alone is a TOCTOU).
	EnforceWriteGates bool
}

CredentialRef names exactly one credential: a custom client id or an agent token name (the OWNERLESS namespace only, data-model §9).

type CredentialScreen added in v0.71.0

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

CredentialScreen is one evaluation context of the screen: the forced detector and the live API key.

func NewCredentialScreen added in v0.71.0

func NewCredentialScreen(cfg *config.Config) *CredentialScreen

NewCredentialScreen builds the screen for the live config.

func (*CredentialScreen) ScreenArguments added in v0.71.0

func (c *CredentialScreen) ScreenArguments(args map[string]any, known map[string]bool) *SecretInputError

ScreenArguments screens a whole decoded MCP argument object (data-model §8): every key and every value at every depth, whatever its JSON type, plus the canonical JSON of each top-level argument. known names the argument names that may be echoed; any other offending argument is only counted.

func (*CredentialScreen) ScreenFields added in v0.71.0

func (c *CredentialScreen) ScreenFields(fields []ScreenField) *SecretInputError

ScreenFields screens named string values (the service-side screen of the persisted issuance fields, data-model §8.2). Every hit is collected; a field listed several times (an array) is reported once.

func (*CredentialScreen) SecretShaped added in v0.71.0

func (c *CredentialScreen) SecretShaped(s string) bool

SecretShaped reports whether s carries an issued-credential prefix, the configured API key, or anything the forced detector flags. A truncated scan is treated as a hit (fail closed).

type CredentialSupersededError added in v0.70.0

type CredentialSupersededError struct{ ClientID string }

CredentialSupersededError is the 409 credential_superseded refusal: the credential a connect wrote was replaced or revoked before it could be finalized, so the written secret must not be treated as live (FR-021a).

func (*CredentialSupersededError) Code added in v0.70.0

Code is the wire `code` of the refusal.

func (*CredentialSupersededError) Error added in v0.70.0

func (e *CredentialSupersededError) Error() string

type CredentialTokenStore added in v0.71.0

type CredentialTokenStore interface {
	CreateAgentToken(token auth.AgentToken, rawToken string, hmacKey []byte) error
	ListAgentTokens() ([]auth.AgentToken, error)
	GetAgentTokenByName(name string) (*auth.AgentToken, error)
	RevokeAgentToken(name string) error
}

CredentialTokenStore is the token-store surface the service needs. Every method addresses the OWNERLESS namespace (data-model §9): GetAgentTokenByName and RevokeAgentToken resolve ownerless tokens only, and List filters UserID == "". *storage.Manager implements it.

type CredentialView added in v0.71.0

type CredentialView struct {
	Kind         string                 `json:"kind"`
	ID           string                 `json:"id"`
	TokenName    string                 `json:"token_name"`
	DisplayName  string                 `json:"display_name,omitempty"`
	Profile      string                 `json:"profile"`
	Binding      string                 `json:"binding"`
	ProfileState string                 `json:"profile_state"`
	State        string                 `json:"state"`
	CreatedAt    time.Time              `json:"created_at"`
	ExpiresAt    *time.Time             `json:"expires_at,omitempty"`
	RevokedAt    *time.Time             `json:"revoked_at,omitempty"`
	LastUsedAt   *time.Time             `json:"last_used_at,omitempty"`
	Lease        bool                   `json:"lease"`
	Issuer       *auth.CredentialIssuer `json:"issuer,omitempty"`
	Purpose      string                 `json:"purpose,omitempty"`
	TokenPrefix  string                 `json:"token_prefix"`
	LegacyScope  *bool                  `json:"legacy_scope,omitempty"`
	// RateLimit is the token's own call budget (issue #1699), set at issue
	// time. Absent when the token has none and follows agent_token_rate_limit.
	RateLimit *auth.TokenRateLimit `json:"rate_limit,omitempty"`
}

CredentialView is the SAFE projection of a credential record (data-model §2): it never carries the secret, its HMAC hash, the pending-rotation hash or prefix, the prior binding or the owner.

func ViewOf added in v0.71.0

func ViewOf(t *auth.AgentToken, cfg *config.Config, now time.Time) CredentialView

ViewOf projects a record to its safe view.

type CredentialsService added in v0.71.0

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

CredentialsService is the one issuance and revocation path for both worker credential kinds (Spec 115, research D2): custom client credentials (delegated to ClientsService, which already owns them) and agent tokens (the logic that used to live inline in the REST token handler). The MCP `credentials` tool, REST POST/DELETE /api/v1/tokens, REST POST /api/v1/clients and the CLI (through REST) all call it, so validation, the secret-shaped input screen, the binding guard, the audit record and the live event cannot drift between surfaces.

Every create and revoke holds the runtime's bindingWriteMu (the same mutex as ClientsService and the guarded config apply), so a profile delete or rename can never interleave with an issue (FR-008).

func NewCredentialsService added in v0.71.0

func NewCredentialsService(d CredentialsServiceDeps) *CredentialsService

NewCredentialsService builds the service from its dependencies.

func (*CredentialsService) Get added in v0.71.0

Get returns one credential's safe view, or identity_not_found.

func (*CredentialsService) IssueClient added in v0.71.0

IssueClient mints a custom client credential through ClientsService. From REST (RefuseExistingRecord false) it keeps POST /clients' rules, including re-issuing over a revoked or expired record (A5); from MCP it refuses any existing record and requires a named profile and an explicit expiry.

func (*CredentialsService) IssueToken added in v0.71.0

IssueToken mints an agent token. The first step is the secret-shaped input screen over every caller-supplied value (FR-020b); nothing is generated, stored, audited or published before every check passed. After the commit nothing can fail the call (FR-007): the view is projected from the committed record and audit/event are best-effort.

func (*CredentialsService) List added in v0.71.0

List returns the safe views of every client credential and every OWNERLESS agent token, filtered, sorted by kind then id (FR-005, FR-005a).

func (*CredentialsService) Revoke added in v0.71.0

func (s *CredentialsService) Revoke(ctx context.Context, a Actor, ref CredentialRef, allowClientRecordByToken bool) (*RevokeResult, error)

Revoke marks one credential revoked (FR-006). An already-revoked credential answers Changed=false and writes nothing; an expired one is revoked (Changed=true). A client revoke goes through ClientsService.forgetLockedOpt (record kind `revoke`) and never waits for or is refused by an in-flight connect (A19). allowClientRecordByToken lets REST DELETE /tokens/{name} keep revoking a client record by its token name, as it always has.

type CredentialsServiceDeps added in v0.71.0

type CredentialsServiceDeps struct {
	Tokens   CredentialTokenStore
	Clients  *ClientsService
	HMACKey  func() ([]byte, error)
	Config   func() *config.Config
	Guard    func() BindingGuard
	Activity func(*storage.ActivityRecord) error
	Publish  func(Event)
	Now      func() time.Time
	Mu       *sync.Mutex
	Logger   *zap.Logger
	// Generate mints a raw agent-token secret (tests inject a spy).
	Generate func() (string, error)
}

CredentialsServiceDeps wires a CredentialsService. Zero values are safe in tests: Now defaults to time.Now, Mu to the clients service's mutex (or a private one), Guard to the conservative evaluator, Generate to auth.GenerateToken, Logger to a no-op.

type DeleteResult added in v0.70.0

type DeleteResult struct {
	Deleted                 string    `json:"deleted"`
	Moved                   MovedRefs `json:"moved"`
	AnonymousProfileMovedTo string    `json:"anonymous_profile_moved_to,omitempty"`
	// contains filtered or unexported fields
}

DeleteResult is the outcome of ProfilesService.Delete.

type EffectiveCounts added in v0.70.0

type EffectiveCounts struct {
	Visible  int            `json:"visible"`
	Hidden   int            `json:"hidden"`
	Callable *int           `json:"callable,omitempty"`
	ByReason map[string]int `json:"by_reason,omitempty"`
}

EffectiveCounts are the response-level counts. Visible and Hidden are for every caller; the rest are administrator-only.

type EffectiveTool added in v0.70.0

type EffectiveTool struct {
	Server              string         `json:"server"`
	Tool                string         `json:"tool"`
	IntrinsicTier       string         `json:"intrinsic_tier"`
	ProfileTier         string         `json:"profile_tier"`
	Access              ToolAccessView `json:"access"`
	ClassificationStale bool           `json:"classification_stale"`
}

EffectiveTool is one row of a profile's effective tools (data-model §7).

type EffectiveToolsOptions added in v0.70.0

type EffectiveToolsOptions struct {
	// Client evaluates that client's credential UNDER the profile ("what
	// would Cursor get on this profile"). Administrators only.
	Client string
	// Server keeps only that server's rows.
	Server string
	// Reason keeps only rows with that access reason. Administrators only.
	Reason string
	// Viewer bounds what the caller may see; the zero value is an
	// administrator.
	Viewer ViewerScope
}

EffectiveToolsOptions selects the rows of ProfileEvaluator.EffectiveTools.

type EffectiveToolsResult added in v0.70.0

type EffectiveToolsResult struct {
	Profile string          `json:"profile"`
	Tools   []EffectiveTool `json:"tools"`
	Counts  EffectiveCounts `json:"counts"`
	// StaleClassifications lists classify entries for tools that are now
	// annotated or no longer exist (FR-005). Administrators only.
	StaleClassifications []string `json:"stale_classifications,omitempty"`
	// StaleClassificationReasons maps each stale classify entry to why it no
	// longer applies: profile.StaleClassificationAnnotated or
	// profile.StaleClassificationMissing. It is computed over the UNFILTERED
	// tool set, so a server or reason filter never changes it. Administrators
	// only.
	StaleClassificationReasons map[string]string `json:"stale_classification_reasons,omitempty"`
}

EffectiveToolsResult is GET /profiles/{name}/effective-tools.

type Event

type Event struct {
	Type      EventType      `json:"type"`
	Timestamp time.Time      `json:"timestamp"`
	Payload   map[string]any `json:"payload,omitempty"`
}

Event is a typed notification published by the runtime event bus.

type EventType

type EventType string

EventType represents a runtime event category broadcast to subscribers.

const (
	// EventTypeServersChanged is emitted whenever the set of servers or their state changes.
	EventTypeServersChanged EventType = "servers.changed"
	// EventTypeConfigReloaded is emitted after configuration reload completes.
	EventTypeConfigReloaded EventType = "config.reloaded"
	// EventTypeConfigSaved is emitted after configuration is successfully saved to disk.
	EventTypeConfigSaved EventType = "config.saved"
	// EventTypeSecretsChanged is emitted when secrets are added, updated, or deleted.
	EventTypeSecretsChanged EventType = "secrets.changed"
	// EventTypeActiveProfileChanged is emitted when the server-level default
	// active profile changes (Profiles v2). UI surfaces (Web UI, tray) refetch
	// GET /api/v1/profiles/active to reflect a switch made by another client.
	EventTypeActiveProfileChanged EventType = "active_profile.changed"
	// EventTypeOAuthTokenRefreshed is emitted when proactive token refresh succeeds.
	EventTypeOAuthTokenRefreshed EventType = "oauth.token_refreshed"
	// EventTypeOAuthRefreshFailed is emitted when proactive token refresh fails after retries.
	EventTypeOAuthRefreshFailed EventType = "oauth.refresh_failed"
	// EventTypeAttentionChanged is emitted (debounced) whenever the set of
	// needs-attention item ids changes (Spec 109 FR-001/FR-002). The payload
	// carries the structured item list (`items: [{id, subject_type,
	// subject_id}]`); internal/httpapi renders it per subscriber as
	// `{count, ids}` (FR-006).
	EventTypeAttentionChanged EventType = "attention.changed"
	// EventTypeReviewChanged signals that the review queue or a server's
	// composed review payload changed. Its server field is scope-bearing.
	EventTypeReviewChanged EventType = "review.changed"
	// EventTypeClientPresenceChanged invalidates the derived client presence
	// and attention inputs after an MCP initialise observation.
	EventTypeClientPresenceChanged EventType = "clients.presence.changed"
	// EventTypeClientBindingChanged is emitted when a client credential's
	// profile binding is assigned, locked, unlocked or first minted (Spec 108
	// FR-026). Payload: {client_id, token_name, profile, previous_profile,
	// mode}. It discloses bindings, so it is administrator-only on SSE.
	EventTypeClientBindingChanged EventType = "client.binding_changed"
	// EventTypeProfilesChanged is emitted (Spec 108-f F9) once per changed
	// profile after a config snapshot that changed it is published: payload
	// {name, change: create|update|delete|anonymous, previous_name?}. It is an
	// INVALIDATION, not a log: a consumer refetches GET /profiles. It names
	// profiles a scoped caller may not reach, so it is administrator-only on
	// SSE. One emitter (the server's snapshot observer) covers service writes
	// and hand edits alike.
	EventTypeProfilesChanged EventType = "profiles.changed"
	// EventTypeCredentialsChanged is emitted (Spec 115 FR-024) after a client
	// credential or agent token is issued or revoked through the credentials
	// service, and after a client is forgotten. Payload: {kind, id,
	// token_name, change, profile}. It is an INVALIDATION carrying no secret,
	// prefix, purpose or expiry: subscribers refetch. It names identities and
	// profiles, so it is administrator-only on SSE.
	EventTypeCredentialsChanged EventType = "credentials.changed"

	// Activity logging events (RFC-003)
	// EventTypeActivityToolCallStarted is emitted when a tool execution begins.
	EventTypeActivityToolCallStarted EventType = "activity.tool_call.started"
	// EventTypeActivityToolCallCompleted is emitted when a tool execution finishes.
	EventTypeActivityToolCallCompleted EventType = "activity.tool_call.completed"
	// EventTypeActivityToolCallRejected is emitted when a concurrency limiter
	// sheds a tool call before it reaches the upstream (spec 093 FR-012). It is
	// published from the limiter's origin-independent seam, so it also covers
	// the dispatch paths that never pass through the MCP layer (sandboxed code
	// execution, activity replay).
	EventTypeActivityToolCallRejected EventType = "activity.tool_call.rejected"
	// EventTypeActivityPolicyDecision is emitted when a policy blocks a tool call.
	EventTypeActivityPolicyDecision EventType = "activity.policy_decision"
	// EventTypeActivityQuarantineChange is emitted when a server's quarantine state changes.
	EventTypeActivityQuarantineChange EventType = "activity.quarantine_change"

	// Spec 024: Expanded Activity Log events
	// EventTypeActivitySystemStart is emitted when MCPProxy server starts.
	EventTypeActivitySystemStart EventType = "activity.system.start"
	// EventTypeActivitySystemStop is emitted when MCPProxy server stops.
	EventTypeActivitySystemStop EventType = "activity.system.stop"
	// EventTypeActivityInternalToolCall is emitted when an internal tool (retrieve_tools, call_tool_*, etc.) completes.
	EventTypeActivityInternalToolCall EventType = "activity.internal_tool_call.completed"
	// EventTypeActivityConfigChange is emitted when configuration changes (server add/remove/update).
	EventTypeActivityConfigChange EventType = "activity.config_change"
	// EventTypeActivityPromptGet is emitted when an upstream prompts/get completes (Finding F10).
	EventTypeActivityPromptGet EventType = "activity.prompt_get.completed"
	// EventTypeUpstreamPromptsChanged is emitted (debounced) when a connected
	// upstream sends notifications/prompts/list_changed, so the aggregated prompt
	// set is rebuilt without waiting for an unrelated servers.changed (F13).
	// Carries no payload — RefreshPrompts re-aggregates from live state.
	EventTypeUpstreamPromptsChanged EventType = "upstream.prompts_changed"

	// Spec 026: Sensitive data detection event
	// EventTypeSensitiveDataDetected is emitted when sensitive data is detected in a tool call.
	EventTypeSensitiveDataDetected EventType = "sensitive_data.detected"

	// Spec 032: Tool-level quarantine events
	// EventTypeActivityToolQuarantineChange is emitted when a tool's quarantine status changes.
	EventTypeActivityToolQuarantineChange EventType = "activity.tool_quarantine_change"

	// Spec 039: Security scanner events
	// EventTypeSecurityScanStarted is emitted when a security scan begins.
	EventTypeSecurityScanStarted EventType = "security.scan_started"
	// EventTypeSecurityScanProgress is emitted for scanner progress updates.
	EventTypeSecurityScanProgress EventType = "security.scan_progress"
	// EventTypeSecurityScanCompleted is emitted when a security scan completes.
	EventTypeSecurityScanCompleted EventType = "security.scan_completed"
	// EventTypeSecurityScanFailed is emitted when a scanner fails.
	EventTypeSecurityScanFailed EventType = "security.scan_failed"
	// EventTypeSecurityScanSettled is the single, debounced terminal event that
	// Spec 077 US4 (MCP-2207) emits per server per scan. It collapses the
	// per-scanner scan_started/progress/completed/failed storm — including
	// repeats from reconnect storms — into one settled result.
	EventTypeSecurityScanSettled EventType = "security.scan_settled"
	// EventTypeSecurityIntegrityAlert is emitted for integrity violations.
	EventTypeSecurityIntegrityAlert EventType = "security.integrity_alert"
	// EventTypeSecurityScannerChanged is emitted when a scanner plugin's state
	// changes (e.g., background image pull started, completed, or failed).
	EventTypeSecurityScannerChanged EventType = "security.scanner_changed"
)

type ExpiryDefault added in v0.71.0

type ExpiryDefault int

ExpiryDefault says what an EMPTY raw ExpiresIn means (data-model §6). It never applies to a non-empty value, which is always parsed after the screen.

const (
	// ExpiryRequired (MCP): empty is missing_argument.
	ExpiryRequired ExpiryDefault = iota
	// ExpiryTokenDefault (REST/CLI tokens): empty is 30 days.
	ExpiryTokenDefault
	// ExpiryClientCap (REST/CLI clients): empty is 365 days.
	ExpiryClientCap
)

type ExplainProfileView added in v0.70.0

type ExplainProfileView struct {
	Name   string `json:"name"`
	Source string `json:"source"`
}

ExplainProfileView is the profile the subject resolved to and where that resolution came from (pin, binding, anonymous, ...).

type ExplainStepView added in v0.70.0

type ExplainStepView struct {
	Step   profile.ExplainStep      `json:"step"`
	Status profile.AccessStepStatus `json:"status"`
	Detail string                   `json:"detail"`
}

ExplainStepView is one evaluated step of the chain.

type ExplainSubjectView added in v0.70.0

type ExplainSubjectView struct {
	Kind profile.AccessSubjectKind `json:"kind"`
	Name string                    `json:"name,omitempty"`
}

ExplainSubjectView names whose access was explained.

type Fix added in v0.70.0

type Fix struct {
	Step   profile.ExplainStep `json:"step"`
	Action profile.FixAction   `json:"action"`
	Target string              `json:"target"`
	Label  string              `json:"label"`
	// Profile is set for move_client only: the destination profile slug the fix
	// moves the client to. Target stays the client id (UIs navigate by it) and
	// Label carries the title, so neither can name the slug.
	Profile string `json:"profile,omitempty"`
}

Fix is one remediation of the first failing step, in preference order.

type GuardFix added in v0.70.0

type GuardFix struct {
	Kind   string `json:"kind"`
	Target string `json:"target,omitempty"`
}

GuardFix is one remediation offered by a guard refusal (`fixes[]`). Kind is profile.GuardFixRequireMCPAuth or profile.GuardFixSetAnonymousProfile; Target is the profile name for the latter and is present only when that profile itself would not leave any binding bypassable.

type GuardState added in v0.70.0

type GuardState struct {
	Config *config.Config
	Tokens []auth.AgentToken
}

GuardState is one whole state the guard compares: a config plus the client credential records that would exist with it.

type IssueClientRequest added in v0.71.0

type IssueClientRequest struct {
	ID, DisplayName, Profile, Purpose string
	// ProfilePresent reports whether the caller sent `profile` at all (MCP:
	// absent is missing_argument, "" is profile_required).
	ProfilePresent bool
	Mode           *string
	ExpiresIn      string
	Expiry         ExpiryDefault
	// Now is the caller's clock reading (zero = the service clock).
	Now time.Time
	// RequireProfile and RefuseExistingRecord are both true from MCP.
	RequireProfile, RefuseExistingRecord bool
	// EnforceWriteGates (MCP): see CredentialRef.EnforceWriteGates.
	EnforceWriteGates bool
	// contains filtered or unexported fields
}

IssueClientRequest is a custom client issuance. ExpiresIn, Profile and Mode are the caller's RAW text; the service screens them before any parse.

type IssueTokenRequest added in v0.71.0

type IssueTokenRequest struct {
	Name           string
	Profile        string
	ProfilePresent bool
	ProfilePin     string
	Purpose        string
	// AllowedServers and Permissions are the REST legacy scope; MCP passes nil.
	AllowedServers, Permissions []string
	ExpiresIn                   string
	Expiry                      ExpiryDefault
	// RequireProfile is true from MCP; EnforceGuard (MCP) also stamps GuardBound.
	RequireProfile, EnforceGuard bool
	// EnforceWriteGates (MCP): see CredentialRef.EnforceWriteGates.
	EnforceWriteGates bool
	// ValidateServers checks REST allowed_servers against the known servers
	// (the REST handler supplies it so its error texts are unchanged).
	ValidateServers func([]string) error
	// RateLimit is the token's own call budget (issue #1699; REST/CLI only,
	// MCP passes nil). Nil = the token follows agent_token_rate_limit.
	RateLimit *auth.TokenRateLimit
}

IssueTokenRequest is an agent token issuance. Profile and ProfilePin are the two RAW aliases (MCP passes ProfilePin ""), ExpiresIn the raw text.

type IssuedCredentialResult added in v0.71.0

type IssuedCredentialResult struct {
	View   CredentialView
	Secret string
	// contains filtered or unexported fields
}

IssuedCredentialResult is a successful issuance: the safe view projected from the committed record and the raw secret, shown once.

func (*IssuedCredentialResult) Scope added in v0.71.0

func (r *IssuedCredentialResult) Scope() (allowedServers, permissions []string)

Scope returns the committed token's allowed servers and permissions (the REST create response echoes them without a post-commit store read).

type MovedRefs added in v0.70.0

type MovedRefs struct {
	Clients []string `json:"clients"`
	Tokens  []string `json:"tokens"`
}

MovedRefs names what a rename or a delete-with-reassign moved.

type NameMismatchError added in v0.70.0

type NameMismatchError struct{ Path, Body string }

NameMismatchError is `409 name_mismatch`: a PUT whose body names another profile than its path (a rename has its own route).

func (*NameMismatchError) Code added in v0.70.0

func (e *NameMismatchError) Code() string

Code is the wire `code`.

func (*NameMismatchError) Error added in v0.70.0

func (e *NameMismatchError) Error() string

type NoClientCredentialError added in v0.70.0

type NoClientCredentialError struct {
	ClientID string
	State    profile.CredentialState
}

NoClientCredentialError is the 409 no_client_credential refusal: the client has no active client credential, so a binding operation would have to mint one implicitly (FR-025 forbids it).

func (*NoClientCredentialError) Code added in v0.70.0

func (e *NoClientCredentialError) Code() string

Code is the wire `code` of the refusal.

func (*NoClientCredentialError) Error added in v0.70.0

func (e *NoClientCredentialError) Error() string

type Phase

type Phase string

Phase represents the lifecycle state of the core runtime.

const (
	PhaseInitializing Phase = "Initializing"
	PhaseLoading      Phase = "Loading"
	PhaseReady        Phase = "Ready"
	PhaseStarting     Phase = "Starting"
	PhaseRunning      Phase = "Running"
	PhaseStopping     Phase = "Stopping"
	PhaseStopped      Phase = "Stopped"
	PhaseError        Phase = "Error"
)

Core runtime phases.

type PreconditionFailedError added in v0.70.0

type PreconditionFailedError struct{}

PreconditionFailedError is the 409 precondition_failed of an apply whose token no longer matches what a fresh preview shows.

func (*PreconditionFailedError) Code added in v0.70.0

func (e *PreconditionFailedError) Code() string

Code is the wire `code`.

func (*PreconditionFailedError) Error added in v0.70.0

func (e *PreconditionFailedError) Error() string

type PreflightActivity added in v0.58.0

type PreflightActivity struct {
	// RequestID correlates the record with the response's X-Request-Id and with
	// every tool call the same workflow makes afterwards.
	RequestID string
	SessionID string
	Source    storage.ActivitySource
	// Verdict is the set-level verdict (preflight.Verdict*).
	Verdict string
	// Status overrides the derived activity status. Leave empty to derive it
	// from Verdict via PreflightActivityStatus.
	Status string
	// Surface names the surface that ran the preflight, for surfaces the
	// Source alone does not identify (spec 099 FR-013:
	// storage.PreflightSurfaceMCPCheck). Empty for the REST endpoint, whose
	// metadata then stays exactly as spec 098 shipped it.
	Surface string
	// Arguments is the request as the caller sent it (spec 099 FR-013). Set by
	// the in-band check surface; nil for the REST endpoint, whose metadata then
	// stays exactly as spec 098 shipped it.
	Arguments *PreflightArguments
	// Timestamp defaults to time.Now() when zero.
	Timestamp time.Time
	Tools     []PreflightToolOutcome

	// Multi-user identity (server edition); empty in the personal edition.
	UserID    string
	UserEmail string
}

PreflightActivity is one executed preflight, as the served surface hands it to the activity log. Everything here is either an enum value, a count or a tool ID — never a description, argument or hash (FR-014: local activity log only, nothing that could leak to a telemetry surface).

type PreflightArguments added in v0.58.0

type PreflightArguments struct {
	// ToolIDs is the RAW array: request order, untrimmed, duplicates intact.
	// len(ToolIDs) is the raw requested count.
	ToolIDs []string
	// Filters names the annotation filters in effect, in declared order. Empty
	// when the call carried none.
	Filters []string
}

PreflightArguments is one in-band caller's request AS SENT, before trimming and dedup (spec 099 FR-013).

It exists because ids_count is the count of UNIQUE ids — the definition the REST record already uses, and the one that makes the two records mean the same thing — which on its own would make "the agent asked for 12 ids, three of them duplicates" unrecoverable from the log. Nothing here is new data: the ids already appear per-tool, and the filter names are the closed enum describe_tool declares.

type PreflightToolOutcome added in v0.58.0

type PreflightToolOutcome struct {
	ID     string
	Status string
	Reason string
}

PreflightToolOutcome is one per-tool line of a preflight activity record. Reason is empty for a ready tool.

type ProfileChange added in v0.70.0

type ProfileChange struct {
	Kind            profile.ChangeKind
	Profile         string
	PreviousProfile string
	Diff            map[string]interface{}
}

ProfileChange is one attributed profile mutation derived from a config write (Spec 108 FR-030): what `profile_change` activity records are built from. Diff carries the changed field names only, never a secret-bearing value: a profile holds none, and anonymous_profile is a name.

type ProfileEvaluator added in v0.70.0

type ProfileEvaluator interface {
	EffectiveTools(ctx context.Context, name string, opt EffectiveToolsOptions) (*EffectiveToolsResult, error)
	TryProfile(ctx context.Context, draft config.ProfileConfig, query string, limit int) (*TryResult, error)
	Explain(ctx context.Context, subject profile.AccessSubject, tool string) (*AccessExplanation, error)
	ToolCounts(ctx context.Context, name string, viewer ViewerScope) ToolCounts
}

ProfileEvaluator is everything the profiles service needs from the server package's unexported predicates (the profile index, the shared per-tool gate, the search index). *server.MCPProxyServer implements it and Runtime.SetProfileEvaluator installs it (the SetBindingGuard pattern); an unwired evaluator answers ErrEvaluatorUnavailable (503), never an empty "allowed".

type ProfileExistsError added in v0.70.0

type ProfileExistsError struct{ Name string }

ProfileExistsError is `409 profile_exists`.

func (*ProfileExistsError) Code added in v0.70.0

func (e *ProfileExistsError) Code() string

Code is the wire `code`.

func (*ProfileExistsError) Error added in v0.70.0

func (e *ProfileExistsError) Error() string

type ProfileInUseError added in v0.70.0

type ProfileInUseError struct{ UsedBy UsedBy }

ProfileInUseError is `409 profile_in_use`: clients or tokens still point at the profile and neither reassign_to nor force was given.

func (*ProfileInUseError) Code added in v0.70.0

func (e *ProfileInUseError) Code() string

Code is the wire `code`.

func (*ProfileInUseError) Error added in v0.70.0

func (e *ProfileInUseError) Error() string

type ProfileIsAnonymousError added in v0.70.0

type ProfileIsAnonymousError struct{ UsedBy UsedBy }

ProfileIsAnonymousError is `409 profile_is_anonymous_profile`: the profile is the anonymous_profile and reassign_to was not given (force never overrides).

func (*ProfileIsAnonymousError) Code added in v0.70.0

func (e *ProfileIsAnonymousError) Code() string

Code is the wire `code`.

func (*ProfileIsAnonymousError) Error added in v0.70.0

func (e *ProfileIsAnonymousError) Error() string

type ProfileList added in v0.70.0

type ProfileList struct {
	Profiles         []ProfileView `json:"profiles"`
	AnonymousProfile string        `json:"anonymous_profile,omitempty"`
}

ProfileList is GET /profiles: the views and, for administrators, the anonymous_profile.

type ProfileNotFoundError added in v0.70.0

type ProfileNotFoundError struct{ Name string }

ProfileNotFoundError is `404 profile not found`.

func (*ProfileNotFoundError) Error added in v0.70.0

func (e *ProfileNotFoundError) Error() string

type ProfilePatch added in v0.72.0

type ProfilePatch struct {
	Profile  string               `json:"profile"`
	Changes  []string             `json:"changes"`
	Proposed config.ProfileConfig `json:"proposed"`
}

ProfilePatch is the proposed stored profile after applying every apply-ready suggestion for it. Proposed is a whole config.ProfileConfig, the document `PUT /api/v1/profiles/{name}` takes and the `profiles[]` entry of the config file. Changes lists what differs from the stored profile.

type ProfilePinStore added in v0.70.0

type ProfilePinStore interface {
	RepinProfile(from, to string) (before []auth.AgentToken, err error)
	RestorePins(before []auth.AgentToken) error
}

ProfilePinStore is the token-store surface a pin rewrite needs; *storage.Manager implements it.

type ProfileSessionHook added in v0.70.0

type ProfileSessionHook interface {
	ProfileRenamed(from, to string)
	ProfileDeleted(name string)
	// ProfileTokensMoved is called after a delete-with-reassign moved these
	// tokens' pins: their sessions' base changed, so each is re-listed and its
	// stored selection cleared (FR-026 semantics).
	ProfileTokensMoved(tokenNames []string)
	// HoldProfileNotifications defers the tools/list_changed delivery of the
	// config publication a write is about to make until release runs. A rename
	// holds it across publish AND ProfileRenamed, so the client's re-list sees
	// the rewritten selection (F5.2).
	HoldProfileNotifications() (release func())
}

ProfileSessionHook is implemented by the server: a rename rewrites the stored set_profile selection of live sessions, a delete clears it (F3).

type ProfileView added in v0.70.0

type ProfileView struct {
	Name        string                   `json:"name"`
	Title       string                   `json:"title,omitempty"`
	Description string                   `json:"description,omitempty"`
	Servers     []string                 `json:"servers"`
	MaxTier     string                   `json:"max_tier,omitempty"`
	Unannotated string                   `json:"unannotated,omitempty"`
	Tools       *config.ProfileToolRules `json:"tools,omitempty"`

	CodeExecution   *bool     `json:"code_execution,omitempty"`
	ManagementTools *bool     `json:"management_tools,omitempty"`
	SwitchableTo    *[]string `json:"switchable_to,omitempty"`

	EffectiveServers       []string `json:"effective_servers"`
	EffectiveUnannotated   string   `json:"effective_unannotated"`
	EffectiveCodeExecution bool     `json:"effective_code_execution"`
	IsLegacy               bool     `json:"is_legacy"`

	ToolCounts ToolCounts `json:"tool_counts"`
	// ToolCount is the v2 field: indexed tools on the effective servers.
	// Deprecated: use tool_counts.
	ToolCount  int     `json:"tool_count"`
	Calls24h   int     `json:"calls_24h"`
	Blocked24h int     `json:"blocked_24h"`
	UsedBy     *UsedBy `json:"used_by,omitempty"`
}

ProfileView is one profile as REST returns it: the config fields as stored, the derived effective values, tool counts, 24 h stats and (administrators only) used_by.

func ProfileViewFromConfig added in v0.70.0

func ProfileViewFromConfig(cfg *config.Config, p *config.ProfileConfig) ProfileView

ProfileViewFromConfig projects a stored profile and its derived effective values (no tool counts, stats or used_by: those need the runtime). It copies every slice and map, so the view never aliases the live config.

type ProfilesService added in v0.70.0

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

ProfilesService is THE service behind every profile operation (Spec 108 FR-034): list, get, create, update, rename, delete, classify, set the anonymous_profile, plus the evaluator-backed effective-tools, try and explain. REST, the CLI, the MCP `profiles` tool, the Web UI and the macOS app all call it, so records, guards and refusals cannot drift between surfaces.

Every mutation goes through Runtime.MutateConfig, which holds the runtime's binding lock across "read, mutate, FR-008a guard, token re-pin, apply, write the profile_change record" (F2), so a profile write and a client-binding write can never combine into a bypassable state.

func (*ProfilesService) Classify added in v0.70.0

func (s *ProfilesService) Classify(ctx context.Context, a Actor, name, tool, tier string) (*WriteResult, error)

Classify sets (or, with tier "", removes) the classification of one exact server:tool under the named profile, atomically under the write lock, and records a `classify` change (F29). Like a create or an update it returns the stored profile and the validator's warnings about it.

func (*ProfilesService) Create added in v0.70.0

Create adds a profile. A name that exists is *ProfileExistsError; a fatal validation rule is a *ValidationError with the offending field; the FR-008a guard may refuse with *BindingGuardError. Warnings are the validator's non-fatal findings about the new profile.

func (*ProfilesService) Delete added in v0.70.0

func (s *ProfilesService) Delete(ctx context.Context, a Actor, name, reassignTo string, force bool) (*DeleteResult, error)

Delete removes a profile (F4). It is *ProfileInUseError while clients or tokens point at it and neither reassignTo nor force is given; *ProfileIsAnonymousError whenever it is the anonymous_profile and reassignTo is empty, even with force. reassignTo must name another existing profile; force leaves pins dangling (deny-all). Both paths remove the name from every switchable_to.

func (*ProfilesService) EffectiveTools added in v0.70.0

EffectiveTools delegates to the evaluator (ErrEvaluatorUnavailable when none).

func (*ProfilesService) Explain added in v0.70.0

Explain delegates to the evaluator (ErrEvaluatorUnavailable when none).

func (*ProfilesService) Get added in v0.70.0

func (s *ProfilesService) Get(ctx context.Context, name string, viewer ViewerScope) (*ProfileView, error)

Get returns one profile's view, or *ProfileNotFoundError.

func (*ProfilesService) List added in v0.70.0

func (s *ProfilesService) List(ctx context.Context, viewer ViewerScope) (*ProfileList, error)

List returns every profile as a view, and the anonymous_profile. viewer bounds tool counts and stats; the caller-specific redaction of names (servers, rules, switchable_to) and the used_by omission are the REST layer's (it holds the auth context).

func (*ProfilesService) Rename added in v0.70.0

func (s *ProfilesService) Rename(ctx context.Context, a Actor, name, newName string) (*RenameResult, error)

Rename renames a profile and moves every reference to it - token pins, client bindings, other profiles' switchable_to and the anonymous_profile - in one write (D19). The order never widens: tokens move first (F3).

func (*ProfilesService) SetAnonymous added in v0.70.0

func (s *ProfilesService) SetAnonymous(ctx context.Context, a Actor, name string) error

SetAnonymous sets (or, with "", clears) the anonymous_profile. An unknown name is a *ValidationError on the field anonymous_profile.

func (*ProfilesService) SetSessionHook added in v0.70.0

func (s *ProfilesService) SetSessionHook(h ProfileSessionHook)

SetSessionHook installs the live-session rewriter used by rename and delete.

func (*ProfilesService) Stats24h added in v0.70.0

func (s *ProfilesService) Stats24h(ctx context.Context, viewer ViewerScope) ActivityStats24h

Stats24h returns the last-24 h rollup of calls and blocked calls by profile and by client for the viewer's scope, cached for 30 s per scope (F27). It is one streaming pass over a 24 h window: no new aggregate exists to keep.

func (*ProfilesService) Suggest added in v0.72.0

Suggest reads the blocked profile refusals in the window and returns the grouped, re-checked suggestions. Server-scope suggestions name servers the profile cannot see, so REST and MCP expose this to administrators only.

func (*ProfilesService) Try added in v0.70.0

func (s *ProfilesService) Try(ctx context.Context, draft config.ProfileConfig, query string, limit int) (*TryResult, error)

Try evaluates a draft profile against a query: nothing is persisted, no record is written, no event is published and the FR-008a guard does not run.

func (*ProfilesService) Update added in v0.70.0

Update replaces the named profile with p. The body's name must equal name (*NameMismatchError; a rename has its own operation). A write whose only change is tools.classify is recorded as `classify`.

func (*ProfilesService) UsedBy added in v0.70.0

func (s *ProfilesService) UsedBy(name string) (UsedBy, error)

UsedBy lists what points at the named profile.

type RejectionMetricSink added in v0.54.0

type RejectionMetricSink func(server, reason, scope string)

RejectionMetricSink counts one shed call. It runs on the caller's goroutine at the moment of rejection, so implementations must be non-blocking (a Prometheus counter increment is).

type RenameResult added in v0.70.0

type RenameResult struct {
	Profile ProfileView `json:"profile"`
	Moved   MovedRefs   `json:"moved"`
}

RenameResult is the outcome of ProfilesService.Rename.

type ReviewQueue added in v0.70.0

type ReviewQueue struct {
	Count   int              `json:"count"`
	Servers []ReviewQueueRow `json:"servers"`
}

ReviewQueue is the composed, server-level review list shared by REST, CLI, MCP and native clients.

type ReviewQueueRow added in v0.70.0

type ReviewQueueRow struct {
	Server      string `json:"server"`
	Kind        string `json:"kind"`
	Quarantined bool   `json:"quarantined"`
	// Enabled is the server's configured enabled state. A disabled server
	// stays in the queue (its review is still owed) but is not blocking any
	// live agent, which is how the Web UI and CLI tell it from an active
	// blocker. Always serialised, so an older core (field absent) reads as
	// "unknown" and clients treat that as enabled.
	Enabled       bool                   `json:"enabled"`
	ToolsCaptured int                    `json:"tools_captured,omitempty"`
	TierCounts    map[contracts.Tier]int `json:"tier_counts,omitempty"`
	Pending       int                    `json:"pending,omitempty"`
	Changed       int                    `json:"changed,omitempty"`
	Scan          *ReviewScan            `json:"scan,omitempty"`
	Since         *time.Time             `json:"since,omitempty"`
}

type ReviewScan added in v0.70.0

type ReviewScan struct {
	Verdict   string     `json:"verdict"`
	RiskScore int        `json:"risk_score"`
	ReportID  string     `json:"report_id,omitempty"`
	ScannedAt *time.Time `json:"scanned_at,omitempty"`
	// Coverage is always present; see the ReviewScanCoverage constants.
	Coverage string `json:"coverage"`
	// ToolsScanned is the number of tool definitions the covering job exported.
	ToolsScanned int `json:"tools_scanned,omitempty"`
	// UnscannedTools lists, sorted, the captured tools whose current
	// definition the scan did not cover. Set only when Coverage is "stale".
	UnscannedTools []string `json:"unscanned_tools,omitempty"`
}

type ReviewServer added in v0.70.0

type ReviewServer struct {
	Name        string            `json:"name"`
	Transport   string            `json:"transport"`
	Command     string            `json:"command,omitempty"`
	Args        []string          `json:"args,omitempty"`
	WorkingDir  string            `json:"working_dir,omitempty"`
	URL         string            `json:"url,omitempty"`
	Env         map[string]string `json:"env,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
	Quarantined bool              `json:"quarantined"`
	Enabled     bool              `json:"enabled"`
	Connected   bool              `json:"connected"`
	// Readiness is a conservative connection hint, not a callable verdict.
	// "connected" may still precede tool discovery; effective-tools supplies
	// the canonical per-tool callable projection.
	Readiness                string      `json:"readiness"`
	TrustMode                string      `json:"trust_mode"`
	SourceRegistryID         string      `json:"source_registry_id,omitempty"`
	SourceRegistryProvenance string      `json:"source_registry_provenance,omitempty"`
	Scan                     *ReviewScan `json:"scan,omitempty"`
	DefinitionsCaptured      bool        `json:"definitions_captured"`
	// LiveToolCount and LastCaptureAt are the fresh-capture proof: how many of
	// the stored records the upstream listed in its most recent capture, and
	// when that capture ran. They are separate from the stored-record
	// inventory (Tools), which retains operator decisions for absent tools.
	LiveToolCount int        `json:"live_tool_count,omitempty"`
	LastCaptureAt *time.Time `json:"last_capture_at,omitempty"`
	// Generation and Incarnation identify the committed server this review
	// shows (Spec 116 FR-017). A client echoes Incarnation back as
	// expected_incarnation on approve, block and unquarantine, so a decision
	// made on this review can never land on a server re-added under the same
	// name (409 server_replaced).
	Generation  int64 `json:"generation,omitempty"`
	Incarnation int64 `json:"incarnation,omitempty"`
}

type ReviewTool added in v0.70.0

type ReviewTool struct {
	Name           string                  `json:"name"`
	Description    string                  `json:"description"`
	InputSchema    json.RawMessage         `json:"input_schema"`
	OutputSchema   json.RawMessage         `json:"output_schema"`
	Annotations    *config.ToolAnnotations `json:"annotations"`
	Tier           contracts.Tier          `json:"tier"`
	ApprovalStatus string                  `json:"approval_status"`
	Disabled       bool                    `json:"disabled"`
	ScanVerdict    string                  `json:"scan_verdict"`
	HeldReason     string                  `json:"held_reason"`
	HeldSignals    []string                `json:"held_signals"`
	// DefaultAllowed is the review screens' fail-closed default selection
	// (D43). Always serialised, so an older core (field absent) reads as false.
	DefaultAllowed bool                `json:"default_allowed"`
	Previous       *ReviewToolPrevious `json:"previous"`
	Diff           *ReviewToolDiff     `json:"diff,omitempty"`
	// CurrentHash is the review fingerprint of this tool (Spec 117 PR-2,
	// #1566), not the storage CurrentHash: send it back in expected_hashes
	// to bind an approval to this review. Opaque; compare only with a later
	// review. The /tools/{tool}/diff payload's current_hash is a different
	// value (the storage hash).
	CurrentHash string `json:"current_hash,omitempty"`
}

type ReviewToolDiff added in v0.70.0

type ReviewToolDiff struct {
	Description  string `json:"description"`
	InputSchema  string `json:"input_schema"`
	OutputSchema string `json:"output_schema"`
	Annotations  string `json:"annotations"`
}

type ReviewToolPrevious added in v0.70.0

type ReviewToolPrevious struct {
	Description  string                  `json:"description"`
	InputSchema  json.RawMessage         `json:"input_schema"`
	OutputSchema json.RawMessage         `json:"output_schema"`
	Annotations  *config.ToolAnnotations `json:"annotations"`
}

type RevokeResult added in v0.71.0

type RevokeResult struct {
	View                  CredentialView
	Changed               bool
	ClientConfigUntouched bool
}

RevokeResult is a revoke outcome.

type Runtime

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

Runtime owns the non-HTTP lifecycle for the proxy process.

func New

func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, error)

New creates a runtime helper for the given config and prepares core managers.

func (*Runtime) ActivityService added in v0.17.0

func (r *Runtime) ActivityService() *ActivityService

ActivityService exposes the activity service for testing.

func (*Runtime) AddServerPurgeObserver added in v0.71.0

func (r *Runtime) AddServerPurgeObserver(fn func(names []string))

AddServerPurgeObserver registers fn to run after a commit purged servers (removed or replaced), outside every runtime lock. The security scanner uses it to drop its cached verdict of a removed server (FR-014a).

func (*Runtime) AddToolDefinitionsChangedObserver added in v0.72.0

func (r *Runtime) AddToolDefinitionsChangedObserver(fn func(serverName string))

AddToolDefinitionsChangedObserver registers fn to run after a discovery pass saw a server's tool inventory move after its baseline: a tool's definition changed (or a held one changed again), or a tool was added. Spec 118 uses it to arm the debounced informational rescan that brings the review screen's scan coverage back to "current".

fn runs on the discovery goroutine while the server's tool-approval lock is held, so it must return quickly and must not call back into the runtime's approval paths (record the name and schedule the work).

func (*Runtime) AggregateToolUsage added in v0.33.0

func (r *Runtime) AggregateToolUsage(since time.Time) (map[string]storage.ToolUsageStat, error)

AggregateToolUsage rolls up tool_call activity per (server,tool) since the given time (spec 050). Returns an empty map when storage is unavailable.

func (*Runtime) AppContext

func (r *Runtime) AppContext() context.Context

AppContext returns the long-lived runtime context.

func (*Runtime) ApplyConfig

func (r *Runtime) ApplyConfig(newCfg *config.Config, cfgPath string) (*ConfigApplyResult, error)

ApplyConfig applies a new configuration with hot-reload support.

Spec 116: the whole apply is one config commit. The reconcile of storage and the upstream manager against the new server set runs inside it, so when this returns the live config, storage and the file agree, and no asynchronous reconcile holding a copy of this config can overwrite a later writer (#1558).

func (*Runtime) ApprovalLockWaitersForTest added in v0.71.0

func (r *Runtime) ApprovalLockWaitersForTest(serverName string) int

ApprovalLockWaitersForTest exposes approvalLockWaiters to tests in other packages.

func (*Runtime) ApproveAllTools added in v0.21.0

func (r *Runtime) ApproveAllTools(serverName string, approvedBy string) (int, error)

ApproveAllTools approves all pending/changed tools for a server. Listing and approval run under one hold of the server's tool-approval lock; the count is the number of records actually approved.

func (*Runtime) ApproveAllToolsAt added in v0.71.0

func (r *Runtime) ApproveAllToolsAt(serverName string, approvedBy string, expectedIncarnation int64) (int, error)

ApproveAllToolsAt is ApproveAllTools bound to expectedIncarnation (0 binds to the incarnation current when the call starts; Spec 116 FR-014).

func (*Runtime) ApproveAllToolsReviewed added in v0.71.0

func (r *Runtime) ApproveAllToolsReviewed(serverName string, expected map[string]string, approvedBy string) (int, error)

ApproveAllToolsReviewed approves every pending and changed tool when each of them still matches its reviewed fingerprint (FR-006). expected == nil is exactly ApproveAllTools.

func (*Runtime) ApproveAllToolsReviewedAt added in v0.71.0

func (r *Runtime) ApproveAllToolsReviewedAt(serverName string, expected map[string]string, approvedBy string, expectedIncarnation int64) (int, error)

ApproveAllToolsReviewedAt is ApproveAllToolsReviewed bound to expectedIncarnation (see ApproveToolsReviewedAt).

func (*Runtime) ApproveTools added in v0.21.0

func (r *Runtime) ApproveTools(serverName string, toolNames []string, approvedBy string) error

ApproveTools approves specific tools for a server, updating their status to approved. It is bound to the server's incarnation when it starts (Spec 116 FR-014): if the server is removed or replaced before the write, it writes nothing and returns ErrServerReplaced.

func (*Runtime) ApproveToolsAt added in v0.71.0

func (r *Runtime) ApproveToolsAt(serverName string, toolNames []string, approvedBy string, expectedIncarnation int64) error

ApproveToolsAt is ApproveTools bound to expectedIncarnation, the incarnation the caller reviewed (the REST expected_incarnation). 0 binds to the incarnation current when the call starts.

func (*Runtime) ApproveToolsReviewed added in v0.71.0

func (r *Runtime) ApproveToolsReviewed(serverName string, toolNames []string, expected map[string]string, approvedBy string) (int, error)

ApproveToolsReviewed approves the named tools when every requested tool that has a record still matches its reviewed fingerprint (FR-006). A requested name without a record is skipped (the caller reports it as not approved). A bound request validates, writes and counts each name once; expected == nil is exactly ApproveTools (duplicates included).

func (*Runtime) ApproveToolsReviewedAt added in v0.71.0

func (r *Runtime) ApproveToolsReviewedAt(serverName string, toolNames []string, expected map[string]string, approvedBy string, expectedIncarnation int64) (int, error)

ApproveToolsReviewedAt is ApproveToolsReviewed bound to expectedIncarnation, the server identity the client reviewed (Spec 116 FR-014; 0 binds to the incarnation current when the call starts). The two bindings are independent and both enforced under the approval lock: a replaced server answers ErrServerReplaced (server_replaced), changed definitions answer *toolreview.StaleToolReviewError (review_out_of_date); the incarnation is checked first because a replaced server's records are not the reviewed ones.

func (*Runtime) Attention added in v0.70.0

func (r *Runtime) Attention() []contracts.AttentionItem

Attention returns the current needs-attention list (Spec 109 FR-001): one function, served verbatim by GET /api/v1/attention (filtered per caller by internal/httpapi), the CLI `attention`/`status`/`doctor` commands, and the same snapshot the SSE attention.changed event is derived from. Safe to call concurrently with the background recompute (atomic snapshot read).

func (*Runtime) AttentionClientWarnings added in v0.70.0

func (r *Runtime) AttentionClientWarnings() []AttentionClientWarning

AttentionClientWarnings derives the Spec 108 warnings for the attention list. It calls the same ClientsService.Warnings GET /clients uses, with the admin-key states from the PERSISTED last observations (108-f F11), and never reads a client config file (Spec 075: no macOS App-Data prompt). The server edition has no clients service, so the result is empty.

func (*Runtime) AttentionClients added in v0.70.0

func (r *Runtime) AttentionClients() []AttentionClient

AttentionClients returns the minimal client evidence needed by the attention subscriber. It intentionally does not inspect client config files or session rows, keeping attention snapshot construction bounded and privacy-safe.

func (*Runtime) BindingGuard added in v0.70.0

func (r *Runtime) BindingGuard() BindingGuard

BindingGuard returns the installed evaluator, or the conservative one.

func (*Runtime) BlockAllTools added in v0.39.0

func (r *Runtime) BlockAllTools(serverName string, blockedBy string) (int, error)

BlockAllTools blocks (approve+disable) every pending/changed tool for a server. Mirrors ApproveAllTools' selection set so the two bulk operations dismiss the same quarantine queue — approve keeps tools visible, block hides them. Returns the number of tools blocked.

func (*Runtime) BlockAllToolsAt added in v0.71.0

func (r *Runtime) BlockAllToolsAt(serverName string, blockedBy string, expectedIncarnation int64) (int, error)

BlockAllToolsAt is BlockAllTools bound to expectedIncarnation (0 binds to the incarnation current when the call starts; Spec 116 FR-014).

func (*Runtime) BlockTools added in v0.39.0

func (r *Runtime) BlockTools(serverName string, toolNames []string, blockedBy string) (int, error)

BlockTools atomically "blocks" the named tools for a server. A block is an approve+disable performed as a single, all-or-nothing record write per tool: the tool's quarantine status is promoted to approved (clearing any pending / changed flag, exactly like ApproveTools) AND its Disabled flag is set so it is hidden from MCP clients. Because both mutations land in one SaveToolApproval, a tool is never observably left in the approved+enabled state — that is the invariant this endpoint exists to guarantee.

Why a single combined write instead of ApproveTools followed by SetToolEnabled(disabled): two sequential saves leave a window where a crash or I/O error after the approve but before the disable yields an approved+enabled tool — the exact state callers want to avoid. Folding both into one write removes that window.

Config-denied tools (enabled_tools / disabled_tools) need no special handling: block only ever disables, so it can never enable a tool the operator forbids.

Returns the number of tools actually blocked. Missing approval records are skipped with a warning (mirrors ApproveTools), not treated as a hard error.

func (*Runtime) BlockToolsAt added in v0.71.0

func (r *Runtime) BlockToolsAt(serverName string, toolNames []string, blockedBy string, expectedIncarnation int64) (int, error)

BlockToolsAt is BlockTools bound to expectedIncarnation (0 binds to the incarnation current when the call starts; Spec 116 FR-014).

func (*Runtime) BulkEnableServers

func (r *Runtime) BulkEnableServers(serverNames []string, enabled bool) (map[string]error, error)

BulkEnableServers toggles the enabled state for multiple servers in one config commit (one storage transaction, one file write). Returns a map of per-server errors for operations that could not be applied.

func (*Runtime) CacheManager

func (r *Runtime) CacheManager() *cache.Manager

CacheManager exposes the cache manager.

func (*Runtime) CalculateTokenSavings

func (r *Runtime) CalculateTokenSavings() (*contracts.ServerTokenMetrics, error)

CalculateTokenSavings calculates token savings from using MCPProxy

func (*Runtime) CaptureApprovalIncarnation added in v0.71.0

func (r *Runtime) CaptureApprovalIncarnation(name string, expected int64) (int64, error)

CaptureApprovalIncarnation is step 1 of an approval writer: it returns expected when the caller supplied one (> 0), otherwise the server's current incarnation. A server that is not configured fails with ErrServerNotFound once the database is authoritative. It runs the approvalAfterCapture seam.

func (*Runtime) ClassifyDisabledTool added in v0.32.0

func (r *Runtime) ClassifyDisabledTool(serverName, toolName string) contracts.DisabledToolStatus

ClassifyDisabledTool returns the single machine-branchable reason a tool is not callable, by fixed first-match precedence (Spec 049). Pure, request-time, read-only — nothing is written to BBolt. Only meaningful for tools that are already known non-callable; it never lies (indeterminate → unknown).

func (*Runtime) ClearToolReviewDirtyForTest added in v0.71.0

func (r *Runtime) ClearToolReviewDirtyForTest(serverName string, seq uint64)

ClearToolReviewDirtyForTest clears serverName's dirty mark as a complete capture newer than seq would. Test-only.

func (*Runtime) ClientsService added in v0.70.0

func (r *Runtime) ClientsService() *ClientsService

ClientsService returns the runtime's single client-credential service (Spec 108, FR-026).

func (*Runtime) Close

func (r *Runtime) Close() error

Close releases runtime resources.

func (*Runtime) Commit added in v0.71.0

func (r *Runtime) Commit(reason string, fn func(tx *CommitTx) error) (*CommitResult, error)

Commit runs fn against a working copy of the live configuration while holding configCommitMu, then persists and publishes the result (see the pipeline above). An error from fn, or from any step before publication, aborts the commit with nothing published and storage untouched.

func (*Runtime) CommitConfig added in v0.71.0

func (r *Runtime) CommitConfig(cfg *config.Config) error

CommitConfig makes cfg the live configuration through one config commit and returns its error. cfg must be a configuration the caller owns and submits now (D14); see UpdateConfig.

func (*Runtime) CommitServerApproval added in v0.71.0

func (r *Runtime) CommitServerApproval(serverName string, blocks []string, expected map[string]string, by string, commit func() error) (int, error)

CommitServerApproval is a security (server) approval's critical section (Spec 117 FR-011/FR-012/FR-023). It runs as one config commit that clears the server's quarantine (Spec 116: one storage transaction, the config file and the live config together), and the commit's approval-lock hook does, under the same hold of the server's tool-approval lock that then covers the storage flip:

  1. validate the binding (bound requests only): nothing is written on a mismatch, the server stays quarantined;
  2. record the server's tool baseline decision (source server_approval, by);
  3. commit(): the scanner's integrity baseline (+ blocks) save;
  4. promote the pending records present now, never one filed after this section (no promote-all after the unquarantine);

and the commit then writes quarantined=false to storage before it releases the lock. Events, the activity record and the reindex follow after the lock (notifyToolsApproved here, FinishServerApproval for the rest).

It returns the number of tools promoted. A failure after the hook (config file or storage write) leaves the hook's writes in place while the server stays quarantined: those are fail-safe (a quarantined server exposes no tool, and a retry validates the same fingerprints, which ignore status).

func (*Runtime) CommitServerApprovalAt added in v0.71.0

func (r *Runtime) CommitServerApprovalAt(serverName string, inc int64, blocks []string, expected map[string]string, by string, commit func() error) (int, error)

CommitServerApprovalAt is CommitServerApproval bound to a server incarnation (Spec 116 FR-014): under the approval lock, before the fingerprints are validated or the marker is written, the stored row must still carry inc, else ErrServerReplaced and nothing is recorded or committed (the server stays quarantined). The removal commit purges the marker under the same lock.

func (*Runtime) CommitWaitersForTest added in v0.71.0

func (r *Runtime) CommitWaitersForTest() int

CommitWaitersForTest exposes commitWaiters to tests in other packages.

func (*Runtime) ConcurrencyStats added in v0.54.0

func (r *Runtime) ConcurrencyStats() (global limiter.Stats, servers map[string]limiter.Stats)

ConcurrencyStats reports the live occupancy of the global aggregate limiter and of every per-server limiter (spec 093 FR-013). Sampled by the metrics bridge to publish the queue-depth gauges.

func (*Runtime) Config

func (r *Runtime) Config() *config.Config

Config returns the underlying configuration pointer. Deprecated: Use ConfigSnapshot() for lock-free reads. This method exists for backward compatibility.

func (*Runtime) ConfigPath

func (r *Runtime) ConfigPath() string

ConfigPath returns the tracked config path.

func (*Runtime) ConfigService

func (r *Runtime) ConfigService() *configsvc.Service

ConfigService returns the configuration service for advanced access patterns.

func (*Runtime) ConfigSnapshot

func (r *Runtime) ConfigSnapshot() *configsvc.Snapshot

ConfigSnapshot returns an immutable configuration snapshot. This is the preferred way to read configuration - it's lock-free and non-blocking.

func (*Runtime) CredentialsService added in v0.71.0

func (r *Runtime) CredentialsService() *CredentialsService

CredentialsService returns the runtime's credential lifecycle service (Spec 115).

func (*Runtime) CurrentCredentialBinding added in v0.71.0

func (r *Runtime) CurrentCredentialBinding(serverName string) (commitview.CredentialBinding, bool)

CurrentCredentialBinding reports the credential binding of the instance that serves serverName now (Spec 116 PR2b). It implements oauth.RefreshBindingResolver: the RefreshManager ignores the outcome of a refresh flight that ran under another binding.

func (*Runtime) CurrentPhase

func (r *Runtime) CurrentPhase() Phase

CurrentPhase returns the current lifecycle phase.

func (*Runtime) CurrentStatus

func (r *Runtime) CurrentStatus() Status

CurrentStatus returns a copy of the underlying status struct.

func (*Runtime) DiscoverAndIndexTools

func (r *Runtime) DiscoverAndIndexTools(ctx context.Context) error

DiscoverAndIndexTools discovers tools from ALL connected upstream servers and indexes them. Used by event-driven callers (boot, server reload, manual refresh) that want a full sweep regardless of per-server cadence.

func (*Runtime) DiscoverAndIndexToolsForServer

func (r *Runtime) DiscoverAndIndexToolsForServer(ctx context.Context, serverName string) error

DiscoverAndIndexToolsForServer discovers and indexes tools for a single server. This is the LENIENT entry point used by reactive tool discovery (server connect, notifications/tools/list_changed): a successful ListTools that returns zero tools is treated as a transient blip and leaves the existing index untouched (see the authoritative variant for the explicit-refresh path). Implements retry logic with exponential backoff for robustness.

func (*Runtime) EmitActiveProfileChanged added in v0.46.0

func (r *Runtime) EmitActiveProfileChanged(profile string)

EmitActiveProfileChanged emits an event when the server-level default active profile changes (Profiles v2). UI surfaces subscribe and refetch GET /api/v1/profiles/active so a switch made by one client (Web UI, tray, CLI) is reflected everywhere. An empty profile means "all servers".

func (*Runtime) EmitActivityConfigChange

func (r *Runtime) EmitActivityConfigChange(action, affectedEntity, source string, changedFields []string, previousValues, newValues map[string]interface{})

EmitActivityConfigChange emits an event when configuration changes (Spec 024). action is one of: server_added, server_removed, server_updated, settings_changed source indicates how the change was triggered: "mcp", "cli", or "api"

func (*Runtime) EmitActivityInternalToolCall

func (r *Runtime) EmitActivityInternalToolCall(internalToolName, targetServer, targetTool, toolVariant, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{}, intent map[string]interface{}, contentTrust string)

EmitActivityInternalToolCall emits an event when an internal tool is called (Spec 024). internalToolName is the name of the internal tool (retrieve_tools, call_tool_read, etc.) targetServer and targetTool are used for call_tool_* handlers arguments contains the input parameters, response contains the output intent is the intent declaration metadata

func (*Runtime) EmitActivityInternalToolCallAttributed added in v0.70.0

func (r *Runtime) EmitActivityInternalToolCallAttributed(internalToolName, targetServer, targetTool, toolVariant, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{}, intent map[string]interface{}, contentTrust string, responseTruncated bool, attr ActivityAttribution)

EmitActivityInternalToolCallAttributed is EmitActivityInternalToolCallTruncated plus the Spec 108 FR-029 scope attribution.

func (*Runtime) EmitActivityInternalToolCallTruncated added in v0.64.0

func (r *Runtime) EmitActivityInternalToolCallTruncated(internalToolName, targetServer, targetTool, toolVariant, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{}, intent map[string]interface{}, contentTrust string, responseTruncated bool)

EmitActivityInternalToolCallTruncated is EmitActivityInternalToolCall for a built-in whose RECORDED response is larger than the one the agent received.

The non-internal path has carried this since Spec 024 (see the "response_truncated" key in EmitActivityToolCallCompleted); the internal path did not, and that asymmetry is a correctness problem rather than a cosmetic one. retrieve_tools deliberately writes its FULL pre-truncation response to the activity log while the agent consumed only the cut text, so a record that does not say it was truncated is indistinguishable from a complete one. Anything recomputing cost from the log then tokenizes text the agent never paid for and OVERSTATES what mcpproxy cost — the one direction of error the Spec 103 token benchmark exists to prevent, and one that cannot be detected after the fact.

func (*Runtime) EmitActivityPolicyDecision

func (r *Runtime) EmitActivityPolicyDecision(serverName, toolName, sessionID, requestID, decision, reason string)

EmitActivityPolicyDecision emits an event when a policy blocks a tool call.

requestID is the dispatch's correlation id, and it is what lets a consumer recognise the live event and the record persisted from it as one thing rather than two. Every other activity event already carries it; policy decisions gained it in spec 090, so records written before then have none and must not be correlated at all (FR-015) rather than correlated by an empty key.

func (*Runtime) EmitActivityPolicyDecisionAttributed added in v0.70.0

func (r *Runtime) EmitActivityPolicyDecisionAttributed(serverName, toolName, sessionID, requestID, decision, reason, blockReason string, attr ActivityAttribution)

EmitActivityPolicyDecisionAttributed is the policy-decision emitter with the Spec 108 FR-029 scope attribution. blockReason may be empty.

func (*Runtime) EmitActivityPolicyDecisionWithBlockReason added in v0.70.0

func (r *Runtime) EmitActivityPolicyDecisionWithBlockReason(serverName, toolName, sessionID, requestID, decision, reason, blockReason string)

EmitActivityPolicyDecisionWithBlockReason records the typed profile reason alongside the operator-facing policy decision metadata.

func (*Runtime) EmitActivityPromptGet added in v0.59.0

func (r *Runtime) EmitActivityPromptGet(serverName, promptName, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{})

EmitActivityPromptGet emits an event when an upstream prompts/get completes (Finding F10). serverName/promptName identify the prompt, arguments are the prompt inputs, response is the *mcp.GetPromptResult (marshaled by the handler).

func (*Runtime) EmitActivityPromptGetAttributed added in v0.70.0

func (r *Runtime) EmitActivityPromptGetAttributed(serverName, promptName, sessionID, requestID, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response interface{}, attr ActivityAttribution)

EmitActivityPromptGetAttributed is EmitActivityPromptGet plus the Spec 108 FR-029 scope attribution.

func (*Runtime) EmitActivityQuarantineChange

func (r *Runtime) EmitActivityQuarantineChange(serverName string, quarantined bool, reason string)

EmitActivityQuarantineChange emits an event when a server's quarantine state changes.

func (*Runtime) EmitActivityServerRemoved added in v0.71.0

func (r *Runtime) EmitActivityServerRemoved(name, source string, purged map[string]int)

EmitActivityServerRemoved records a server removal as a config change. purged is the removal's purge summary ({bucket: count}, Spec 116 PR2); the activity record carries it in metadata["purged"] (additive).

func (*Runtime) EmitActivitySystemStart

func (r *Runtime) EmitActivitySystemStart(version, listenAddress string, startupDurationMs int64, configPath string)

EmitActivitySystemStart emits an event when MCPProxy server starts (Spec 024).

func (*Runtime) EmitActivitySystemStop

func (r *Runtime) EmitActivitySystemStop(reason, signal string, uptimeSeconds int64, errorMsg string)

EmitActivitySystemStop emits an event when MCPProxy server stops (Spec 024).

func (*Runtime) EmitActivityToolCallCompleted

func (r *Runtime) EmitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response string, responseTruncated bool, toolVariant string, intent map[string]interface{}, contentTrust, profile string, requestBytes, responseBytes int, detectionText string, toonOutput map[string]interface{}, parentID string)

EmitActivityToolCallCompleted emits an event when a tool execution finishes. This is used to track activity for observability and debugging. source indicates how the call was triggered: "mcp", "cli", or "api" arguments is the input parameters passed to the tool call toolVariant is the MCP tool variant used (call_tool_read/write/destructive) - optional intent is the intent declaration metadata - optional detectionText is the spec-084 pre-encoding sensitive-data scan input (FR-007b); empty means "scan response as before" (feature off / non-call_tool_* paths) toonOutput is the spec-084 per-block encoding decision metadata (FR-010) - optional parentID is the correlation id of the parent code_execution call for a sandbox sub-call; empty for every top-level dispatch

func (*Runtime) EmitActivityToolCallCompletedAttributed added in v0.70.0

func (r *Runtime) EmitActivityToolCallCompletedAttributed(serverName, toolName, sessionID, requestID, source, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response string, responseTruncated bool, toolVariant string, intent map[string]interface{}, contentTrust, profile string, requestBytes, responseBytes int, detectionText string, toonOutput map[string]interface{}, parentID string, blockReason string, attr ActivityAttribution, outcome ActivityCallOutcome)

EmitActivityToolCallCompletedAttributed is EmitActivityToolCallCompleted plus the Spec 108 FR-029 scope attribution (profile, client, token in effect for this call). attr is the LAST parameter, so the position of `status` that TestActivityCompletionNeverHardcodesSuccess pins does not move; the zero value leaves the payload exactly as it was before Spec 108. blockReason is the profile.BlockReason of a profile-refused sub-call, "" for everything else. outcome (Spec 113-c) is the call-error taxonomy; it is the LAST parameter for the same reason as attr, and its zero value adds nothing to the payload.

func (*Runtime) EmitActivityToolCallRejected added in v0.54.0

func (r *Runtime) EmitActivityToolCallRejected(serverName, toolName, source, requestID, reason, scope, message string, limit int, retryAfterMs, waitedMs int64)

EmitActivityToolCallRejected emits an event when a concurrency limiter shed a tool call (spec 093 FR-012). This is the ORIGIN-INDEPENDENT rejection seam: it is invoked from the limiter observer inside the managed client, so a shed is recorded identically whether the call came from an MCP tool-call variant, the REST endpoint, a sandboxed code-execution script or an activity replay.

reason is queue_full | queue_timeout | rate_limited; scope is server | global | token. Unlike every other activity emission, the RECORD is written synchronously here rather than by the activity service's bus subscriber: publishEvent drops events for any subscriber whose channel is full, and a burst of sheds is precisely the load that fills it. The bus copy is still published, but only so live subscribers (SSE, tray) see the rejection — the durable row no longer depends on it.

func (*Runtime) EmitActivityToolCallRejectedAttributed added in v0.72.0

func (r *Runtime) EmitActivityToolCallRejectedAttributed(serverName, toolName, source, requestID, reason, scope, message string, limit int, retryAfterMs, waitedMs int64, attr ActivityAttribution)

EmitActivityToolCallRejectedAttributed is EmitActivityToolCallRejected for a rejection that names the caller. A rate_limited rejection is about ONE agent token, so its record carries the token (and client) in the attribution fields; the concurrency sheds stay unattributed, as before. reason is also rate_limited, and scope token, for that case.

func (*Runtime) EmitActivityToolCallStarted

func (r *Runtime) EmitActivityToolCallStarted(serverName, toolName, sessionID, requestID, source string, args map[string]any)

EmitActivityToolCallStarted emits an event when a tool execution begins. This is used to track activity for observability and debugging. source indicates how the call was triggered: "mcp", "cli", or "api"

func (*Runtime) EmitOAuthRefreshFailed

func (r *Runtime) EmitOAuthRefreshFailed(serverName string, errorMsg string)

EmitOAuthRefreshFailed emits an event when proactive token refresh fails after retries. This is used by the RefreshManager to notify subscribers that re-authentication is needed.

func (*Runtime) EmitOAuthTokenRefreshed

func (r *Runtime) EmitOAuthTokenRefreshed(serverName string, expiresAt time.Time)

EmitOAuthTokenRefreshed emits an event when proactive token refresh succeeds. This is used by the RefreshManager to notify subscribers of successful token refresh.

func (*Runtime) EmitProfilesChanged added in v0.70.0

func (r *Runtime) EmitProfilesChanged(name, change, previousName string)

EmitProfilesChanged publishes profiles.changed for one changed profile (or, with change "anonymous", the anonymous_profile). previousName is optional.

func (*Runtime) EmitSecurityIntegrityAlert added in v0.24.0

func (r *Runtime) EmitSecurityIntegrityAlert(serverName, alertType, action string)

EmitSecurityIntegrityAlert emits an event for integrity violations (Spec 039).

func (*Runtime) EmitSecurityScanCompleted added in v0.24.0

func (r *Runtime) EmitSecurityScanCompleted(serverName string, findingsSummary map[string]int)

EmitSecurityScanCompleted records a terminal scan result for the debouncer, which publishes exactly one settled event per server per scan (Spec 077 US4).

func (*Runtime) EmitSecurityScanFailed added in v0.24.0

func (r *Runtime) EmitSecurityScanFailed(serverName, _, errMsg string)

EmitSecurityScanFailed records a terminal failure for the debouncer. Under Spec 077 the baseline verdict is derived elsewhere; here we only ensure the storm still collapses to a single settled event (Spec 077 US4).

func (*Runtime) EmitSecurityScanProgress added in v0.24.0

func (r *Runtime) EmitSecurityScanProgress(_, _, _ string, _ int)

EmitSecurityScanProgress is dropped: intermediate per-scanner progress is the noise the settled-event model eliminates (Spec 077 US4).

func (*Runtime) EmitSecurityScanStarted added in v0.24.0

func (r *Runtime) EmitSecurityScanStarted(serverName string, _ []string, _ string)

EmitSecurityScanStarted feeds the scan-notification debouncer (Spec 077 US4, MCP-2207). The started signal is intentionally dropped: it is part of the per-scanner storm the debouncer collapses. The service still invalidates its summary cache independently so the UI shows "scanning" while the scan runs.

func (*Runtime) EmitSecurityScanTelemetry added in v0.53.0

func (r *Runtime) EmitSecurityScanTelemetry(completed bool, findingsBySeverity map[string]int)

EmitSecurityScanTelemetry is the sole producer of the schema-v8 TPA scanner counters. The scanner package calls it exactly once per terminal, real (non-dry-run) Pass-1 scan JOB — never per scanner and never for the Pass-2 deep supply-chain audit — so scans_completed/scans_failed count scans, not scanner invocations or passes. See scanCallbackAdapter.countsForTelemetry.

Only counts cross this boundary: the server name, the scanner id, and the error text are not parameters at all, and the registry drops any severity key outside the fixed enum. Nil-safe: telemetry may be disabled or not yet initialized.

func (*Runtime) EmitSecurityScannerChanged added in v0.24.0

func (r *Runtime) EmitSecurityScannerChanged(scannerID, status, errMsg string)

EmitSecurityScannerChanged emits an event when a scanner plugin's state changes — notably while a Docker image is being pulled in the background (Spec 039). The UI listens for this and refreshes its scanner list.

func (*Runtime) EmitSensitiveDataDetected added in v0.17.0

func (r *Runtime) EmitSensitiveDataDetected(activityID string, detectionCount int, maxSeverity string, detectionTypes []string, serverName string)

EmitSensitiveDataDetected emits an event when sensitive data is detected in a tool call (Spec 026). activityID is the ID of the activity record where sensitive data was detected. detectionCount is the number of sensitive data detections found. maxSeverity is the highest severity level among detections (e.g., "high", "medium", "low"). detectionTypes is a list of detection type names (e.g., "credit_card", "api_key").

func (*Runtime) EmitServersChanged

func (r *Runtime) EmitServersChanged(reason string, extra map[string]any)

EmitServersChanged implements the EventEmitter interface for the management service. This delegates to the runtime's internal event emission mechanism.

func (*Runtime) EnableServer

func (r *Runtime) EnableServer(serverName string, enabled bool) error

EnableServer enables or disables a server and persists the change.

Spec 116: one commit. The flag reaches the live config, storage and the file together, the commit purges a disabled server's tools from the index, and the connect/disconnect runs after the commit lock is released.

func (*Runtime) FinishServerApproval added in v0.71.0

func (r *Runtime) FinishServerApproval(serverName string) error

FinishServerApproval runs the part of a security (server) approval that follows CommitServerApproval's critical section, without the approval lock: the activity record and the upstream/index refresh. Unlike QuarantineServer(false) it promotes nothing, so a tool filed after the commit stays pending (FR-012).

func (*Runtime) ForceReconnectAllServers

func (r *Runtime) ForceReconnectAllServers(reason string) error

ForceReconnectAllServers triggers reconnection attempts for all managed servers.

func (*Runtime) GetActivationFirstMCPClient added in v0.29.0

func (r *Runtime) GetActivationFirstMCPClient() (bool, []string)

GetActivationFirstMCPClient returns Spec 044's FirstMCPClientEver flag and the capped list of recognized client names from the activation bucket. Used by the v2 onboarding wizard (Spec 046 v2) Verify tab. Nil-safe: when telemetry/activation isn't wired (CI/test or telemetry disabled) returns (false, nil).

func (*Runtime) GetActivity

func (r *Runtime) GetActivity(id string) (*storage.ActivityRecord, error)

GetActivity returns a single activity record by ID.

func (*Runtime) GetAllServers

func (r *Runtime) GetAllServers() ([]map[string]interface{}, error)

GetAllServers implements RuntimeOperations interface for management service. Returns all servers with their current status using the Supervisor's StateView.

func (*Runtime) GetConfig

func (r *Runtime) GetConfig() (*config.Config, error)

GetConfig returns a copy of the current configuration

func (*Runtime) GetConnectedServerCount added in v0.22.0

func (r *Runtime) GetConnectedServerCount() int

GetConnectedServerCount returns the number of connected upstream servers (implements telemetry.RuntimeStats).

func (*Runtime) GetCurrentConfig

func (r *Runtime) GetCurrentConfig() *config.Config

GetCurrentConfig returns the current configuration. It may be nil only before the config is installed; New rejects a nil config outright.

func (*Runtime) GetDesiredConfig added in v0.63.0

func (r *Runtime) GetDesiredConfig() (*config.Config, error)

GetDesiredConfig returns the configuration as persisted on disk — what the next start will use. Identical to GetConfig() unless a restart-gated field is pending; callers that read-modify-write the configuration MUST merge onto this one, or they silently revert whatever is waiting for a restart.

Shares the same aliasing caveat as GetConfig: the caller must not mutate the returned value in place.

func (*Runtime) GetDirectToolResponseMode added in v0.63.0

func (r *Runtime) GetDirectToolResponseMode() string

GetDirectToolResponseMode returns the direct-surface serialization mode as a closed enum (implements telemetry.RuntimeStats, schema v10). Live-snapshot read, for the same reason as above.

func (*Runtime) GetDockerCLISource added in v0.40.0

func (r *Runtime) GetDockerCLISource() string

GetDockerCLISource returns the coarse, fixed-enum branch that resolved the docker CLI — "path" | "bundled" | "login_shell" | "absent" (implements telemetry.RuntimeStats, schema v5 / MCP-2745). This is the direct #696 fleet signal (docker installed but not on the spawn PATH). It delegates to shellwrap.ResolveDockerSource, which shares the process-wide docker-path cache, so this is cheap on the heartbeat path. NEVER returns the path itself.

func (*Runtime) GetDockerIsolatedServerCount added in v0.24.4

func (r *Runtime) GetDockerIsolatedServerCount() int

GetDockerIsolatedServerCount returns how many currently-configured servers the runtime actually wraps in a Docker container (implements telemetry.RuntimeStats, schema v3).

Implementation note: we reuse core.IsolationManager.ShouldIsolate — the same function the stdio connection path consults — so the count matches the runtime's real behavior rather than a config-only approximation. When DockerIsolation is nil or disabled globally, ShouldIsolate returns false for every server, giving a count of 0.

func (*Runtime) GetDockerRecoveryStatus

func (r *Runtime) GetDockerRecoveryStatus() *storage.DockerRecoveryState

GetDockerRecoveryStatus returns the current Docker recovery status from the upstream manager

func (*Runtime) GetManagementService

func (r *Runtime) GetManagementService() management.Service

GetManagementService returns the management service instance, or nil while none is installed. Safe to call from any goroutine: the field is swapped atomically, so a background reader (the servers.changed coalescer, the attention subscriber) never tears against SetManagementService.

func (*Runtime) GetOnboardingState added in v0.29.0

func (r *Runtime) GetOnboardingState() (*storage.OnboardingState, error)

GetOnboardingState returns the current wizard engagement state (Spec 046).

func (*Runtime) GetRecentSessions

func (r *Runtime) GetRecentSessions(f storage.SessionFilter) ([]*contracts.MCPSession, int, error)

GetRecentSessions returns recent MCP sessions.

f.Status filters on the session status ("active" / "closed"); f.Profile, f.ClientID and f.TokenName are the Spec 108 scope filters ("-" = unattributed). The filters and the last-activity ordering are pushed down into storage, so they are applied before truncation to f.Limit.

func (*Runtime) GetReviewQueue added in v0.70.0

func (r *Runtime) GetReviewQueue(ctx context.Context) (*ReviewQueue, error)

GetReviewQueue composes one row for each quarantined server and each trusted server with pending or changed tool definitions.

func (*Runtime) GetRoutingMode added in v0.22.0

func (r *Runtime) GetRoutingMode() string

GetRoutingMode returns the current routing mode (implements telemetry.RuntimeStats).

func (*Runtime) GetSecretResolver

func (r *Runtime) GetSecretResolver() *secret.Resolver

GetSecretResolver returns the secret resolver instance

func (*Runtime) GetServerCount added in v0.22.0

func (r *Runtime) GetServerCount() int

GetServerCount returns the total number of configured servers (implements telemetry.RuntimeStats).

func (*Runtime) GetServerReview added in v0.70.0

func (r *Runtime) GetServerReview(ctx context.Context, serverName string) (*ServerReview, error)

GetServerReview returns a caller-independent review view. Server command, URL, environment, header, and argument values are redacted unconditionally.

func (*Runtime) GetServerToolCalls

func (r *Runtime) GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)

GetServerToolCalls retrieves tool call history for a specific server

func (*Runtime) GetServerTools

func (r *Runtime) GetServerTools(serverName string) ([]map[string]interface{}, error)

GetServerTools implements RuntimeOperations interface for management service. Returns all tools for a specific upstream server from StateView cache (lock-free read).

func (*Runtime) GetSessionByID

func (r *Runtime) GetSessionByID(sessionID string) (*contracts.MCPSession, error)

GetSessionByID returns a session by its ID

func (*Runtime) GetToolApproval added in v0.21.0

func (r *Runtime) GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)

GetToolApproval returns a single tool approval record (Spec 032).

func (*Runtime) GetToolCallByID

func (r *Runtime) GetToolCallByID(id string) (*contracts.ToolCallRecord, error)

GetToolCallByID retrieves a single tool call by ID

func (*Runtime) GetToolCalls

func (r *Runtime) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)

GetToolCalls retrieves tool call history with pagination.

scope restricts the result to a set of server names (nil = unrestricted, #1166 follow-up). It is applied BEFORE pagination so `total`, the page and the offset all describe the same record set — a post-filter in the handler would shrink the page while the total kept counting the hidden records, which is both a broken pager and an exact oracle for what was hidden.

func (*Runtime) GetToolCallsBySession

func (r *Runtime) GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)

GetToolCallsBySession returns tool calls filtered by session ID.

scope restricts the result to a set of server names (nil = unrestricted). It is pushed down into storage so it lands in the same pass that computes `total` (#1166 follow-up).

func (*Runtime) GetToolCount added in v0.22.0

func (r *Runtime) GetToolCount() int

GetToolCount returns the total number of indexed tools (implements telemetry.RuntimeStats).

This reads the Bleve index document count — one document per tool, durable across restarts — rather than the upstream manager's per-client tool-count cache. Reading that cache made the telemetry heartbeat report tool_count=0 for installs that held a fully populated index: every indexing pass calls InvalidateAllToolCountCaches() as its LAST step (see lifecycle.go), and the only paths that refill the cache without re-zeroing it are UI/API-triggered ListTools calls. The field metric was therefore biased toward installs whose owner had opened the dashboard, which is not what "indexed tools" means.

Per-profile indexes are not double-counted: RebuildProfileFromShared derives each of them from this shared index, so the shared count is the superset.

When the index CANNOT answer — it is closed, mid-reopen, or returned an error — the last successful POSITIVE count is reported instead of falling through to the upstream cache. That matters most at shutdown: Close() performs a final graceful heartbeat flush (telemetryService.Stop), and the upstream clients are disconnected by then, so the cache path would answer 0 for an install with a fully populated durable index — reintroducing the exact structural zero this function was changed to remove. Close() also now closes the index AFTER that flush, so this is defence in depth rather than the only guard.

A memoised ZERO is deliberately not preferred over the cache. Zero is only ever memoised when the index genuinely held no tools at the last successful read, and in that state the cache cannot produce the structural zero this guard exists for — it can only report MORE (tools held by live clients that the index has not caught up with yet), which is the closer answer. So the guard protects the one value that is expensive to lose and lets the cache arbitrate the empty case.

The upstream cache is otherwise the fallback only for the case it is actually right for: no index manager wired at all (unit tests, early startup).

func (*Runtime) GetToolResponseMode added in v0.63.0

func (r *Runtime) GetToolResponseMode() string

GetToolResponseMode returns the retrieve_tools serialization mode as a closed enum (implements telemetry.RuntimeStats, schema v10).

Reads the LIVE snapshot via Config() rather than the legacy r.cfg field the older getters use: these are hot-reloadable settings, and a heartbeat that reported the value an operator had at startup would be measuring the wrong thing precisely for the installs that experimented with the mode.

func (*Runtime) GetVersionInfo

func (r *Runtime) GetVersionInfo() *updatecheck.VersionInfo

GetVersionInfo returns the current version information from the update checker. Returns nil if the update checker has not been initialized.

func (*Runtime) GuardedApplyConfig added in v0.70.0

func (r *Runtime) GuardedApplyConfig(newCfg *config.Config, cfgPath string) (*ConfigApplyResult, error)

GuardedApplyConfig applies newCfg after the FR-008a guard. It is MutateConfig with `replace the desired config with newCfg` as the mutation and no attributed actor; callers that know who is writing use MutateConfig.

func (*Runtime) HandleUpstreamServerChange

func (r *Runtime) HandleUpstreamServerChange(ctx context.Context)

HandleUpstreamServerChange should be called when upstream servers change.

func (*Runtime) HealthRefreshState added in v0.66.0

func (r *Runtime) HealthRefreshState(name string, cfg *config.ServerConfig) *oauth.RefreshStateInfo

HealthRefreshState returns the RefreshManager state to feed into the health calculator for the named server, or nil when there is none or when the token it rides on is not in play for this server (StoredOAuthTokenInPlay). Every CalculateHealth call site must read refresh state through this, or the REST, MCP and tray surfaces disagree about a header-authenticated server.

func (*Runtime) IndexManager

func (r *Runtime) IndexManager() *index.Manager

IndexManager exposes the index manager.

func (*Runtime) IsDockerAvailable added in v0.24.4

func (r *Runtime) IsDockerAvailable() bool

IsDockerAvailable reports whether the host has a reachable Docker daemon (implements telemetry.RuntimeStats, schema v3). Uses a time-based cache — see dockerProbeTTLPositive / dockerProbeTTLNegative for reasoning.

func (*Runtime) IsQuarantineEnabled added in v0.22.0

func (r *Runtime) IsQuarantineEnabled() bool

IsQuarantineEnabled returns whether tool-level quarantine is enabled (implements telemetry.RuntimeStats).

func (*Runtime) IsRunning

func (r *Runtime) IsRunning() bool

IsRunning reports the last known running state.

func (*Runtime) IsToolConfigDenied added in v0.32.0

func (r *Runtime) IsToolConfigDenied(serverName, toolName string) bool

IsToolConfigDenied reports whether toolName is denied by the server's static enabled_tools / disabled_tools config. Evaluated at call time — nothing is written to BBolt. Returns false (allow) when the server is unknown or has no filter configured.

func (*Runtime) ListActivities

func (r *Runtime) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)

ListActivities returns activity records matching the filter.

func (*Runtime) ListRegistries

func (r *Runtime) ListRegistries() ([]interface{}, error)

ListRegistries returns the list of available MCP server registries (Phase 7).

It routes through the SAME merged source (built-in defaults + user-configured registries, keyed by ID) that search/add use via SetRegistriesFromConfig, so `mcpproxy registry list` / the Web UI never omit a built-in that is still searchable/addable and never show the legacy hard-coded Smithery entry instead of the shipped defaults (FR-006 / MCP-800 finding 2).

func (*Runtime) ListToolApprovals added in v0.21.0

func (r *Runtime) ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error)

ListToolApprovals returns all tool approval records for a server (Spec 032).

func (*Runtime) LockBindingWrites added in v0.70.0

func (r *Runtime) LockBindingWrites() (unlock func())

LockBindingWrites serializes every guarded write: the guard check and the write it protects run under this one mutex (plan D3), so two individually safe concurrent writes (a config write and a binding write) can never combine into a bypassable state. Callers must not hold it across another LockBindingWrites call.

func (*Runtime) Logger

func (r *Runtime) Logger() *zap.Logger

Logger returns the runtime logger.

func (*Runtime) MarkFirstConnectedServerForActivation added in v0.25.0

func (r *Runtime) MarkFirstConnectedServerForActivation()

MarkFirstConnectedServerForActivation sets the first_connected_server_ever flag. Called from the supervisor's connect-success callback. Spec 044 US2.

func (*Runtime) MarkToolReviewDirtyForTest added in v0.71.0

func (r *Runtime) MarkToolReviewDirtyForTest(serverName string, seq uint64)

MarkToolReviewDirtyForTest marks serverName review-dirty at seq, as a capture whose writes failed would (Spec 117 FR-018). Test-only: packages outside runtime (internal/server) assert the dispatch refusal with it.

func (*Runtime) MutateConfig added in v0.70.0

func (r *Runtime) MutateConfig(
	ctx context.Context,
	actor Actor,
	mutate func(desired *config.Config) (ChangeHint, error),
	tokens TokenRewrite,
) (*ConfigApplyResult, *ConfigDiff, error)

MutateConfig is THE funnel for every write of the desired configuration that can move a profile, a binding or an anonymous_profile (Spec 108-f F2): the PATCH /config, POST /config/apply and PATCH /config/docker-isolation routes, and every profiles-service mutation. Under bindingWriteMu it

  1. reads the desired configuration (a private copy),
  2. lets mutate edit that copy (the read-merge of a PATCH lives INSIDE the lock, so a concurrent profile write is never lost),
  3. runs the FR-008a guard over the whole candidate: the mutated config plus the client credentials as they would be after the token rewrite,
  4. rewrites token pins in one storage transaction (only when asked),
  5. applies the config, restoring the pins if that fails, and
  6. writes the `profile_change` records the write amounts to (FR-030).

The ordering never widens (F3): tokens move first, so a crash between (4) and (5) leaves a pin naming a profile the running config lacks (deny-all) or already has (the requested target), never the old wider scope.

A refused guard, a failed mutate or a failed apply writes no record.

func (*Runtime) NotifyClientPresenceChanged added in v0.70.0

func (r *Runtime) NotifyClientPresenceChanged()

NotifyClientPresenceChanged prompts derived presenters to refresh after a successful connect or disconnect write performed outside Runtime.

func (*Runtime) NotifySecretsChanged

func (r *Runtime) NotifySecretsChanged(ctx context.Context, operation, secretName string) error

NotifySecretsChanged notifies the runtime that secrets have changed and restarts affected servers. This method should be called by the HTTP API when secrets are added, updated, or deleted.

func (*Runtime) ProfilesService added in v0.70.0

func (r *Runtime) ProfilesService() *ProfilesService

ProfilesService returns the runtime's single profiles service.

func (*Runtime) QuarantineServer

func (r *Runtime) QuarantineServer(serverName string, quarantined bool) error

QuarantineServer updates the quarantine state and persists the change. Security: When quarantining a server, all its tools are removed from the index to prevent Tool Poisoning Attacks (TPA) from exposing potentially malicious tool descriptions.

Spec 116: one commit. The flag is stamped as an explicit decision (#937), written to storage under the server's approval lock in the same step that purges the index (FR-008), and published before this returns.

func (*Runtime) QuarantineServerAt added in v0.71.0

func (r *Runtime) QuarantineServerAt(serverName string, quarantined bool, expectedIncarnation int64) error

QuarantineServerAt is QuarantineServer bound to expectedIncarnation (Spec 116 FR-015, FR-017): when it is > 0 the commit fails with ErrServerReplaced (and changes nothing) unless the server still has that incarnation — the scanner approval and an unquarantine the operator reviewed in the Web UI use it, so a remove and re-add in between can never release the replacement.

func (*Runtime) ReapWorkSessions added in v0.49.0

func (r *Runtime) ReapWorkSessions(maxIdle time.Duration) int

ReapWorkSessions drops work sessions idle past maxIdle, so a long-lived daemon does not accumulate one map entry per identity forever.

func (*Runtime) ReconcileServers added in v0.71.0

func (r *Runtime) ReconcileServers() error

ReconcileServers reconciles storage and the upstream manager with the live configuration (projection repair, Spec 116 ReconcileLive). It never replaces the configuration and never writes the config file.

func (*Runtime) RecordAvailabilityBlock added in v0.58.0

func (r *Runtime) RecordAvailabilityBlock(reason string)

RecordAvailabilityBlock counts one policy block by its structured reason key (closed enum; see telemetry.BlockReason*).

func (*Runtime) RecordClientSeen added in v0.70.0

func (r *Runtime) RecordClientSeen(clientName string)

RecordClientSeen persists an initialize observation independently of the telemetry activation funnel. Presence must remain accurate when telemetry is disabled, and UpdateOnboardingState keeps this write from racing connect or onboarding mutations.

func (*Runtime) RecordDiscoveryOmission added in v0.58.0

func (r *Runtime) RecordDiscoveryOmission()

RecordDiscoveryOmission counts one retrieve_tools response that withheld locked/quarantined matches the caller could not see.

func (*Runtime) RecordFilterDiagnosticsEmitted added in v0.58.0

func (r *Runtime) RecordFilterDiagnosticsEmitted(missingAnnotation, explicit int)

RecordFilterDiagnosticsEmitted counts one retrieve_tools response that attached a spec-094 filter_diagnostics block, plus that block's summed per-reason-class counts.

func (*Runtime) RecordFilterDiagnosticsFollowed added in v0.58.0

func (r *Runtime) RecordFilterDiagnosticsFollowed()

RecordFilterDiagnosticsFollowed counts one diagnostics block the agent acted on within the same MCP session.

func (*Runtime) RecordMCPClientForActivation added in v0.25.0

func (r *Runtime) RecordMCPClientForActivation(rawClientName string)

RecordMCPClientForActivation records a sanitized MCP client name and marks the first-ever-client flag (Spec 044 US2). No-op if activation store not wired or if the raw name cannot be plumbed through (nil-safe all the way down). Intentionally takes the raw name; sanitization happens inside the store.

func (*Runtime) RecordPreflight added in v0.58.0

func (r *Runtime) RecordPreflight(rec PreflightActivity) error

RecordPreflight is the Runtime-level passthrough onto the activity service's synchronous preflight write, so a served surface holding only the runtime can satisfy FR-014 without reaching for the service directly.

func (*Runtime) RecordRealToolCallForActivation added in v0.49.0

func (r *Runtime) RecordRealToolCallForActivation()

RecordRealToolCallForActivation marks the first-ever real (upstream) tool call. "Real" means a call proxied to an upstream server, as opposed to a built-in tool such as retrieve_tools.

This is the lifetime counterpart of RecordRetrieveToolsCallForActivation. Until it existed, the retrieve step had a lifetime flag while the call step had only a windowed counter, so the retrieve→call funnel compared a lifetime value against a 24h one and understated conversion badly.

No-op if the activation store is not wired.

func (*Runtime) RecordRetrieveToolsCallForActivation added in v0.25.0

func (r *Runtime) RecordRetrieveToolsCallForActivation()

RecordRetrieveToolsCallForActivation bumps the 24h retrieve_tools counter and marks the first-ever-call flag (Spec 044 US2). No-op if the activation store is not wired.

func (*Runtime) RecordTokensSavedForActivation added in v0.25.0

func (r *Runtime) RecordTokensSavedForActivation(n int)

RecordTokensSavedForActivation adds n to the 24h tokens-saved estimator. n <= 0 is a no-op. Spec 044 US2.

func (*Runtime) RecordToolBlocksForSecurityApproval added in v0.70.0

func (r *Runtime) RecordToolBlocksForSecurityApproval(serverName string, toolNames []string, blockedBy string)

RecordToolBlocksForSecurityApproval publishes the per-tool audit events for records that the scanner service has already committed atomically with the integrity baseline. It deliberately does not write approval state again.

func (*Runtime) RefreshHeldScanEvidence added in v0.72.0

func (r *Runtime) RefreshHeldScanEvidence(server string) error

RefreshHeldScanEvidence re-runs the in-process TPA scan over the stored current definition of every pending or changed tool record of one server and refreshes only the held-scan evidence (HeldVerdict, HeldSignals), so a newly activated bundle's verdict is visible on tools that are already held for review (Spec 101 FR-019 leg (i), tasks B17). It takes the tool-approval lock and works for quarantined servers too.

It is evidence only: Status, ApprovedHash, ApprovedBy and the server's quarantine flag are never written, and nothing is approved or unquarantined (RT-02). A signature removed by a newer bundle leaves the tool held, with verdict clean and reason awaiting_review. Approved records are not this leg's business: the cached informational scan covers them.

Unlike the discovery pass, which rescans a pending record only when its definition moved or it has no verdict yet, this rescans every held record: a stored verdict was computed under the previous corpus.

func (*Runtime) RefreshManager added in v0.16.0

func (r *Runtime) RefreshManager() *oauth.RefreshManager

RefreshManager returns the OAuth refresh manager for health status integration. Returns nil if refresh manager hasn't been initialized.

func (*Runtime) RefreshOAuthToken

func (r *Runtime) RefreshOAuthToken(serverName string) error

RefreshOAuthToken implements RuntimeOperations interface for management service. Triggers token refresh for a specific server.

func (*Runtime) RefreshRegistryCache added in v0.35.0

func (r *Runtime) RefreshRegistryCache(registryID string) (int, error)

RefreshRegistryCache invalidates all cached server lists for a registry, forcing the next search to re-fetch from the source (FR-007). Returns the number of cache entries dropped.

func (*Runtime) RefreshServerTools added in v0.52.0

func (r *Runtime) RefreshServerTools(ctx context.Context, serverName string) error

RefreshServerTools re-discovers and re-indexes a single server AUTHORITATIVELY (issue #873): a successful ListTools that returns zero tools is taken as the truth — the server's stale index entries are removed and its last-good snapshot is cleared, so a later approval-driven reindex cannot resurface tools that no longer exist upstream. This is the explicit operator refresh/discover path; the reactive callbacks keep the lenient behavior above.

func (*Runtime) RefreshVersionInfo

func (r *Runtime) RefreshVersionInfo() *updatecheck.VersionInfo

RefreshVersionInfo performs an immediate update check and returns the result. Returns nil if the update checker has not been initialized.

func (*Runtime) ReloadConfiguration

func (r *Runtime) ReloadConfiguration() error

ReloadConfiguration reloads the configuration from disk and resyncs state.

Spec 116: one commit. The file is read inside the commit lock and published once, pinned (the raw file is never published unpinned); storage and the manager are reconciled against it before the snapshot is published.

func (*Runtime) ReplayToolCall

func (r *Runtime) ReplayToolCall(ctx context.Context, id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)

ReplayToolCall replays a tool call with modified arguments.

ctx is the CALLER's context (the HTTP request's). It governs the whole replay, including the wait for a concurrency slot: a client that disconnects mid-queue releases the slot immediately instead of leaving a call queued for a caller that is gone (FR-005).

func (*Runtime) ResolveWorkSession added in v0.49.0

func (r *Runtime) ResolveWorkSession(id WorkSessionIdentity) string

ResolveWorkSession derives the work session for an identity, opening a new one when it has been idle past the window. Called once per connection.

func (*Runtime) RestartServer

func (r *Runtime) RestartServer(serverName string) error

RestartServer restarts an upstream server by disconnecting and reconnecting it. Validation and disconnect are synchronous; reconnection and reindexing happen asynchronously so the caller (HTTP handler) returns immediately.

func (*Runtime) SaveConfiguration

func (r *Runtime) SaveConfiguration() error

SaveConfiguration persists the live configuration to disk.

Spec 116 (FR-004): it no longer rebuilds the server list from storage — storage is a projection of the live configuration written by every commit, so there is nothing to splice back and nothing a pending removal could be resurrected from (#1559). It is a commit with ForceDisk: the file is written even when nothing changed, pending-aware as before (a restart-gated value saved but not yet adopted stays on disk).

func (*Runtime) SaveOnboardingState added in v0.29.0

func (r *Runtime) SaveOnboardingState(state *storage.OnboardingState) error

SaveOnboardingState persists the wizard engagement state (Spec 046).

func (*Runtime) SearchRegistryServers

func (r *Runtime) SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, *contracts.RegistryCacheInfo, error)

SearchRegistryServers searches for servers in a specific registry (Phase 7). Results are cached per (registry, tag, query, limit) via the cache manager; a cached list is served while flagging its freshness (FR-007), and the returned *contracts.RegistryCacheInfo carries the age/stale indicator. A registry that requires an unconfigured API key surfaces as a wrapped registries.ErrRegistryKeyMissing so the caller can mark it unavailable without failing the overall search (FR-008).

func (*Runtime) ServedRoutingMode added in v0.63.0

func (r *Runtime) ServedRoutingMode() string

ServedRoutingMode returns the mode /mcp is actually serving, or "" before the server has bound one.

func (*Runtime) ServerAwaitsOAuthLogin added in v0.72.0

func (r *Runtime) ServerAwaitsOAuthLogin(serverName string) bool

ServerAwaitsOAuthLogin reports whether the named server cannot connect until a person completes its OAuth login: a manual login flow is in flight for it, or its live instance is parked in Pending Auth (GH #1722). Background restarts (the security scan's reconnect) stand down for such a server, because replacing its instance retires the pending flow.

func (*Runtime) ServerIncarnation added in v0.71.0

func (r *Runtime) ServerIncarnation(name string) (int64, bool)

ServerIncarnation returns name's committed incarnation from the live snapshot. ok is false when the server is not configured. A snapshot no commit has published (no generations at all: a fixture or a pre-boot state) reports a configured server as (0, true): known, but unbound.

func (*Runtime) SetAllToolsEnabled added in v0.31.0

func (r *Runtime) SetAllToolsEnabled(serverName string, enabled bool, updatedBy string) (int, error)

SetAllToolsEnabled bulk-toggles every tool currently known for a server to the given enabled state. Returns the count of tools whose state was changed (i.e. excluding tools already in the desired state).

Tool inventory comes from the StateView when available (so it covers tools the user has seen even if not yet indexed) and falls back to the search index. Tools without an approval record get one synthesized — see setToolEnabledNoEmit for the rationale.

SSE emission: the loop calls setToolEnabledNoEmit (no per-tool servers.changed). A single trailing emitServersChanged fires after the loop when at least one tool actually flipped, mirroring the ApproveAllTools pattern. With the lazy-build coalescer (Spec 047 §B2 + PR #463) the bulk operation pays exactly one payload build no matter how many tools changed.

func (*Runtime) SetAllToolsEnabledAt added in v0.71.0

func (r *Runtime) SetAllToolsEnabledAt(serverName string, enabled bool, updatedBy string, expectedIncarnation int64) (int, error)

SetAllToolsEnabledAt is SetAllToolsEnabled bound to expectedIncarnation (0 binds to the incarnation current when the call starts; Spec 116 FR-014). Every per-tool write re-checks it, so a remove and re-add midway stops the loop's writes on the replacement.

func (*Runtime) SetApprovalAfterCaptureHookForTest added in v0.71.0

func (r *Runtime) SetApprovalAfterCaptureHookForTest(fn func(serverName string, incarnation int64))

SetApprovalAfterCaptureHookForTest installs the approvalAfterCapture seam. Test-only: the prompt approval writers in internal/server capture through the runtime.

func (*Runtime) SetBindingGuard added in v0.70.0

func (r *Runtime) SetBindingGuard(g BindingGuard)

SetBindingGuard installs the FR-008a evaluator (the server's *MCPProxyServer). Until it is installed, every guarded path uses the ConservativeBindingGuard, which is only ever stricter.

func (*Runtime) SetBundleRefresher added in v0.72.0

func (r *Runtime) SetBundleRefresher(refresher *scanner.BundleRefresher)

SetBundleRefresher registers the TPA bundle refresher so the runtime owns its lifecycle: StartBackgroundInitialization starts it with the app context and Close stops and joins it (Spec 087 / Spec 101 US3 B19). Call it once during server construction, before StartBackgroundInitialization; nil clears it.

func (*Runtime) SetDiscoveryBeforeIndexHookForTest added in v0.71.0

func (r *Runtime) SetDiscoveryBeforeIndexHookForTest(fn func(serverName string))

SetDiscoveryBeforeIndexHookForTest installs the discoveryBeforeIndex seam. Test-only.

func (*Runtime) SetManagementService

func (r *Runtime) SetManagementService(svc management.Service)

SetManagementService stores the management service instance. It is called after runtime initialization because the service is CONSTRUCTED on top of the Runtime (it takes one as its RuntimeOperations), not because of an import cycle — internal/management does not import internal/runtime.

func (*Runtime) SetProfileEvaluator added in v0.70.0

func (r *Runtime) SetProfileEvaluator(e ProfileEvaluator)

SetProfileEvaluator installs the server-side evaluator (the SetBindingGuard pattern). Until it is installed, effective-tools, try and explain answer ErrEvaluatorUnavailable.

func (*Runtime) SetReconcileEntryHookForTest added in v0.71.0

func (r *Runtime) SetReconcileEntryHookForTest(fn func())

SetReconcileEntryHookForTest installs the reconcileEntry seam. Test-only: packages outside runtime (internal/server) drive the same interleavings.

func (*Runtime) SetReconcileExitHookForTest added in v0.71.0

func (r *Runtime) SetReconcileExitHookForTest(fn func())

SetReconcileExitHookForTest installs the reconcileExit seam. Test-only.

func (*Runtime) SetRefreshMetricsRecorder added in v0.16.0

func (r *Runtime) SetRefreshMetricsRecorder(recorder oauth.RefreshMetricsRecorder)

SetRefreshMetricsRecorder sets the metrics recorder for OAuth token refresh operations. This enables FR-011: OAuth refresh metrics emission.

func (*Runtime) SetRejectionMetricSink added in v0.54.0

func (r *Runtime) SetRejectionMetricSink(sink RejectionMetricSink)

SetRejectionMetricSink installs the synchronous rejection counter (spec 093 FR-013). Passing nil detaches it.

func (*Runtime) SetRunning

func (r *Runtime) SetRunning(running bool)

SetRunning records whether the server HTTP layer is active.

func (*Runtime) SetServedRoutingMode added in v0.63.0

func (r *Runtime) SetServedRoutingMode(mode string)

SetServedRoutingMode records the routing mode /mcp bound at startup. Called once, from the server as it registers the handler.

func (*Runtime) SetServerShared added in v0.66.1

func (r *Runtime) SetServerShared(name string, shared bool) (*config.ServerConfig, error)

SetServerShared commits sharing against the current configuration and publishes it before returning. A successful unshare must not leave a file watcher delay in which existing credentials can still reach the server. It is one config commit (Spec 116); the default disk write keeps any change still pending a restart.

func (*Runtime) SetSessionClientResolver added in v0.49.0

func (r *Runtime) SetSessionClientResolver(resolver SessionClientResolver)

SetSessionClientResolver wires the session -> MCP client lookup that stamps client_name / client_version onto every activity record at write time. No-op if the activity service is not wired.

func (*Runtime) SetTelemetry added in v0.22.0

func (r *Runtime) SetTelemetry(version, edition string)

SetTelemetry initializes the telemetry service with the given version and edition. This should be called once during server startup.

func (*Runtime) SetToolEnabled added in v0.29.3

func (r *Runtime) SetToolEnabled(serverName, toolName string, enabled bool, updatedBy string) error

SetToolEnabled sets whether a tool is enabled for exposure to MCP clients. Thin wrapper over setToolEnabledNoEmit that adds the per-toggle SSE servers.changed emit so single-tool consumers (CLI, REST) see the state transition without polling. The emit is skipped when the call was a no-op (already in the desired state) to avoid wasted SSE traffic.

func (*Runtime) SetToolEnabledAt added in v0.71.0

func (r *Runtime) SetToolEnabledAt(serverName, toolName string, enabled bool, updatedBy string, expectedIncarnation int64) error

SetToolEnabledAt is SetToolEnabled bound to expectedIncarnation (0 binds to the incarnation current when the call starts; Spec 116 FR-014).

func (*Runtime) SetVersion

func (r *Runtime) SetVersion(version string)

SetVersion initializes the update checker with the given version. This should be called once during server startup with the build version.

func (*Runtime) SetWorkSessionResolver added in v0.49.0

func (r *Runtime) SetWorkSessionResolver(resolver SessionWorkSessionResolver)

SetWorkSessionResolver wires the session -> work-session lookup used to stamp every activity record (Spec 082).

The resolver reads the id CACHED on the connection rather than re-deriving it. Re-deriving per record would let one connection's records disagree: the first resolves before the client's project has arrived, the second after.

func (*Runtime) SetWorkerActHooksForTest added in v0.71.0

func (r *Runtime) SetWorkerActHooksForTest(before, after func(serverName string, gen int64))

SetWorkerActHooksForTest installs the PR3 worker seams. Test-only; packages outside runtime (internal/server) hold back a commit's worker with it.

func (*Runtime) ShouldCaptureReviewDefinitionsAfterScan added in v0.70.0

func (r *Runtime) ShouldCaptureReviewDefinitionsAfterScan(serverName string) bool

ShouldCaptureReviewDefinitionsAfterScan reports whether a just-settled scan should be followed by an automatic capture of the server's tool definitions for review (Spec 109 fix-review-screen, D-4). It is true only when the server is still quarantined, has no approval records yet, and its newest baseline job completed after exporting at least one tool definition.

The tool-export gate is the safety property: it means MCPProxy already started the quarantined upstream and listed its tools for that scan, so the follow-up capture (the inspection-only RefreshServerTools path: no indexing, no tool routing) adds no new trust exposure. With automatic baseline scans off and no manual scan, no job exists and nothing is started.

func (*Runtime) SignatureCache added in v0.51.0

func (r *Runtime) SignatureCache() *toolsig.Cache

SignatureCache exposes the process-wide compact-signature cache (Spec 085 FR-008). Exactly one instance exists: the indexing path warms it and the MCP request path (via NewMCPProxyServer) reads it. Never construct a second cache — warming a cache the request path does not hold is a silent no-op.

func (*Runtime) StartBackgroundInitialization

func (r *Runtime) StartBackgroundInitialization()

StartBackgroundInitialization kicks off configuration sync and background loops.

func (*Runtime) StatusChannel

func (r *Runtime) StatusChannel() <-chan Status

StatusChannel exposes the status updates stream.

func (*Runtime) StatusSnapshot

func (r *Runtime) StatusSnapshot(serverRunning bool) map[string]interface{}

StatusSnapshot returns the latest status as a map for API responses. The serverRunning parameter should come from the authoritative server running state.

func (*Runtime) StorageManager

func (r *Runtime) StorageManager() *storage.Manager

StorageManager exposes the storage manager.

func (*Runtime) StoredOAuthTokenInPlay added in v0.66.0

func (r *Runtime) StoredOAuthTokenInPlay(name string, cfg *config.ServerConfig) bool

StoredOAuthTokenInPlay reports whether a record in the oauth_tokens bucket (and the RefreshManager schedule built from it) is evidence about the named server's authentication state (GH #1172).

It is not when the server has no `oauth` block and carries a static Authorization header: the headers-auth strategy runs first and OAuth is never attempted while it works, and OAuth would populate that very header, so a token left behind by an earlier OAuth login (autodiscovery servers have no `oauth` block whose removal could have cleared it) is stale. Consulting it used to report a connected, tool-serving upstream as unhealthy / "Token expired" / login for as long as the record existed, and its failed refresh schedule as "Refresh token expired". The record is left alone (logout still removes it); it is simply not consulted.

The live connection has the final say: if the configured header was rejected and the OAuth strategy rescued the connection with that very token, the token IS in play and is reported as for any other OAuth server. A nil config (server known only to the state view) keeps the historical behaviour of consulting the record.

func (*Runtime) StreamActivities

func (r *Runtime) StreamActivities(ctx context.Context, filter storage.ActivityFilter) <-chan *storage.ActivityRecord

StreamActivities returns a channel that yields activity records matching the filter. A consumer that stops reading early must cancel ctx so the producer releases its read transaction (see storage.Manager.StreamActivities).

func (*Runtime) SubscribeEvents

func (r *Runtime) SubscribeEvents() chan Event

SubscribeEvents registers a new subscriber and returns a channel that will receive runtime events. Callers must not close the returned channel; use UnsubscribeEvents when finished.

func (*Runtime) Supervisor

func (r *Runtime) Supervisor() *supervisor.Supervisor

Supervisor returns the supervisor instance for lock-free state reads via StateView. Phase 6: Provides access to fast server status without storage queries.

func (*Runtime) TelemetryRegistry added in v0.24.0

func (r *Runtime) TelemetryRegistry() *telemetry.CounterRegistry

TelemetryRegistry returns the Tier 2 counter registry, or nil if telemetry has not been initialized yet. Callers can record events without nil-checking — use telemetry.RecordSurfaceOn(reg, ...) which is nil-safe.

func (*Runtime) TelemetryService added in v0.22.0

func (r *Runtime) TelemetryService() *telemetry.Service

TelemetryService returns the telemetry service instance.

func (*Runtime) Tokenizer

func (r *Runtime) Tokenizer() tokens.Tokenizer

Tokenizer returns the tokenizer instance.

func (*Runtime) ToolDefinitionsObserverCount added in v0.72.0

func (r *Runtime) ToolDefinitionsObserverCount() int

ToolDefinitionsObserverCount reports how many observers are registered. It exists so the server package can pin that its rescan subscribes at construction (the observer set is otherwise unexported).

func (*Runtime) ToolReviewDirty added in v0.71.0

func (r *Runtime) ToolReviewDirty(serverName string) bool

ToolReviewDirty reports whether serverName's latest capture could not be fully recorded (FR-018). It takes no lock, so dispatch never waits behind a capture; the mirror is written under the approval lock before the failing capture releases it.

func (*Runtime) TriggerOAuthLogin

func (r *Runtime) TriggerOAuthLogin(serverName string) error

TriggerOAuthLogin implements RuntimeOperations interface for management service. Initiates OAuth 2.x authentication flow for a specific server.

func (*Runtime) TriggerOAuthLoginQuick

func (r *Runtime) TriggerOAuthLoginQuick(serverName string) (*core.OAuthStartResult, error)

TriggerOAuthLoginQuick implements RuntimeOperations interface for management service. Returns OAuthStartResult with actual browser status, auth URL, and any errors. This is the synchronous version that provides immediate feedback about browser opening.

func (*Runtime) TriggerOAuthLogout

func (r *Runtime) TriggerOAuthLogout(serverName string) error

TriggerOAuthLogout implements RuntimeOperations interface for management service. Clears OAuth token and disconnects a specific server.

func (*Runtime) Truncator

func (r *Runtime) Truncator() *truncate.Truncator

Truncator exposes the current tool-response truncator. It is safe to call concurrently with a config hot-reload that swaps the truncator (#861): the field is an atomic.Pointer, so the read never tears against the swap. Callers on the serving path MUST call this at use time rather than caching the returned pointer, so a hot-reloaded tool_response_limit takes effect.

func (*Runtime) UnsubscribeEvents

func (r *Runtime) UnsubscribeEvents(ch chan Event)

UnsubscribeEvents removes the subscriber and closes the channel.

func (*Runtime) UpdateConfig

func (r *Runtime) UpdateConfig(cfg *config.Config, cfgPath string)

UpdateConfig replaces the runtime configuration with cfg, through a config commit (Spec 116): storage, the config file (when a path is known) and the published snapshot all move together. cfg must be a configuration the caller owns and submits in this call (D14); a copy of an earlier Config() read is a stale replacement — use Commit with a CommitTx operation instead.

UpdateConfig schedules no manager work, as before Spec 116: the supervisor reconciles the manager to the new desired configuration. No production writer uses it any more (each one commits its own operation, which schedules its connect workers); a second actor here would race the supervisor's reconnect of the same server and leave the replacement instance disconnected or replaced by a config without a transport.

func (*Runtime) UpdateListenAddress

func (r *Runtime) UpdateListenAddress(addr string) error

UpdateListenAddress mutates the in-memory listen address used by the runtime.

func (*Runtime) UpdateOnboardingState added in v0.70.0

func (r *Runtime) UpdateOnboardingState(fn func(*storage.OnboardingState) error) error

UpdateOnboardingState runs fn against the current onboarding state and persists it atomically (Spec 109-b, T035): every writer (the mark handler, the connect success path, the `initialize` hook) goes through this so concurrent writes never drop each other's fields.

func (*Runtime) UpdatePhase

func (r *Runtime) UpdatePhase(phase Phase, message string)

UpdatePhase gathers runtime metrics and broadcasts a status update.

func (*Runtime) UpdatePhaseMessage

func (r *Runtime) UpdatePhaseMessage(message string)

UpdatePhaseMessage refreshes the status message without moving to a new phase.

func (*Runtime) UpdatePolicy added in v0.54.0

func (r *Runtime) UpdatePolicy() updatecheck.Policy

UpdatePolicy returns the effective update policy (Spec 092 FR-015): the kill-switch state, the release channel, and whether UI nudges are suppressed. Without an update checker automatic checking cannot happen at all, which is reported as an explicit disabled policy rather than as missing data.

func (*Runtime) UpdateStatus

func (r *Runtime) UpdateStatus(phase Phase, message string, stats map[string]interface{}, toolsIndexed int)

UpdateStatus mutates the status object and notifies subscribers.

func (*Runtime) UpdateTelemetry added in v0.71.0

func (r *Runtime) UpdateTelemetry(reason string, fn func(tc *config.TelemetryConfig) bool) error

UpdateTelemetry applies fn to the telemetry block through one config commit (#1592). fn edits a private copy (a fresh block when none is configured) and reports whether it changed anything; false makes the call a no-op. Routing the startup outcome and first-run notice flag through the commit keeps the live config and the file consistent, so a concurrent disk-writing commit cannot drop them.

func (*Runtime) UpstreamManager

func (r *Runtime) UpstreamManager() *upstream.Manager

UpstreamManager exposes the upstream manager.

func (*Runtime) UsageSnapshot added in v0.36.0

func (r *Runtime) UsageSnapshot() *UsageAggregate

UsageSnapshot returns the actor-owned in-memory usage aggregate snapshot (spec 069 A2/A3). Reads are lock-free; the returned value is immutable and must be treated as read-only. Returns nil when the activity service is unavailable.

func (*Runtime) ValidateConfig

func (r *Runtime) ValidateConfig(cfg *config.Config) ([]config.ValidationError, error)

ValidateConfig validates a configuration without applying it

func (*Runtime) WithServerApprovalLockAt added in v0.71.0

func (r *Runtime) WithServerApprovalLockAt(name string, inc int64, fn func() error) error

WithServerApprovalLockAt runs fn while holding name's approval lock, after checking (under that lock) that the stored row still carries incarnation inc. On a mismatch fn does not run and the error is ErrServerReplaced. Writers outside the runtime that touch name-keyed approval state — the scanner's baseline and blocks, the prompt approvals — use it. fn must not call back into a runtime method that takes the same lock, nor Commit.

func (*Runtime) WithToolApprovalLock added in v0.71.0

func (r *Runtime) WithToolApprovalLock(serverName string, fn func() error) error

WithToolApprovalLock runs fn while holding serverName's tool-approval lock. It lets writers outside the runtime that touch approval records directly — the security scanner's atomic baseline+blocks commit — serialize with discovery passes and operator approvals. fn must not call back into any runtime method that takes the same lock.

type ScreenField added in v0.71.0

type ScreenField struct {
	Name   string
	Values []string
}

ScreenField is one named, caller-supplied field and its raw value(s).

type SecretInputError added in v0.71.0

type SecretInputError struct {
	Fields       []string
	UnknownCount int
}

SecretInputError is the `secret_in_argument` refusal. Fields are the KNOWN offending argument names (sorted, deduplicated); UnknownCount counts the offending arguments whose names are not known (never named).

func (*SecretInputError) Code added in v0.71.0

func (e *SecretInputError) Code() string

Code is the wire `code`.

func (*SecretInputError) Error added in v0.71.0

func (e *SecretInputError) Error() string

Error names the field, never the value.

func (*SecretInputError) Field added in v0.71.0

func (e *SecretInputError) Field() string

Field is the first offending known argument, or the fixed placeholder.

type SensitiveDataEventEmitter added in v0.17.0

type SensitiveDataEventEmitter interface {
	// EmitSensitiveDataDetected emits an event when sensitive data is detected.
	EmitSensitiveDataDetected(activityID string, detectionCount int, maxSeverity string, detectionTypes []string, serverName string)
}

SensitiveDataEventEmitter provides the ability to emit sensitive data detection events. This interface is implemented by Runtime to enable event emission from ActivityService.

type ServerChange added in v0.71.0

type ServerChange = configsvc.ServerChange

ServerChange is one server's change in a commit.

type ServerExistsError added in v0.71.0

type ServerExistsError struct{ Name string }

ServerExistsError is returned when a create names a server that is already configured (or still stored). Its text is part of the #1570 contract: the REST 409 mapping, cliclient and the registry add all match "already exists".

func (*ServerExistsError) Error added in v0.71.0

func (e *ServerExistsError) Error() string

type ServerNotFoundError added in v0.71.0

type ServerNotFoundError struct{ Name string }

ServerNotFoundError reports a server that is not in the live configuration.

func (*ServerNotFoundError) Error added in v0.71.0

func (e *ServerNotFoundError) Error() string

func (*ServerNotFoundError) Is added in v0.71.0

func (e *ServerNotFoundError) Is(target error) bool

Is makes errors.Is(err, ErrServerNotFound) match.

type ServerReview added in v0.70.0

type ServerReview struct {
	Server ReviewServer `json:"server"`
	Tools  []ReviewTool `json:"tools"`
}

type SessionClientResolver added in v0.49.0

type SessionClientResolver func(sessionID string) (name, version string)

SessionClientResolver maps an MCP session id to the client that opened it (clientInfo.name / clientInfo.version from the initialize handshake). Returns empty strings when the session is unknown.

type SessionWorkSessionResolver added in v0.49.0

type SessionWorkSessionResolver func(sessionID string) string

SessionWorkSessionResolver maps an MCP session id to the WORK session it belongs to (Spec 082): one client, one project, across reconnects.

It returns the id cached on the connection — deliberately not a fresh derivation, so every record from one connection agrees on its work session.

type Signal added in v0.72.0

type Signal struct {
	Rule   string
	Reason string
	Path   string
}

Signal is one structural-gate hold signal: a rule id (one of contracts.HoldSignal*), a reason and a path. Rendered as `rule[:reason[:path]]`, e.g. `GATE-SCHEMA-SHAPE:new-required:bcc`.

func (Signal) String added in v0.72.0

func (s Signal) String() string

String renders the signal as it is recorded on the approval record.

type Skipped added in v0.70.0

type Skipped struct {
	ClientID string `json:"client_id"`
	Code     string `json:"code"`
	Error    string `json:"error"`
}

Skipped is a bulk-move client that was not moved.

type Status

type Status struct {
	Phase         Phase                  `json:"phase"`
	Message       string                 `json:"message"`
	UpstreamStats map[string]interface{} `json:"upstream_stats"`
	ToolsIndexed  int                    `json:"tools_indexed"`
	LastUpdated   time.Time              `json:"last_updated"`
}

Status captures high-level state for API consumers.

type StrictOfflineBindingGuard added in v0.70.0

type StrictOfflineBindingGuard struct{}

StrictOfflineBindingGuard is the guard of the offline CLI connect (no daemon, no published tool snapshot). It cannot evaluate reach, so it exempts only an UNCHANGED binding: the identity of a binding is (client_id, profile_pin, profile_mode), and any candidate bypassable binding without an identical one among the current bypassable bindings is refused. A reconnect that keeps the recorded binding passes; a re-point or mode change of an already-bound client does not, which ConservativeBindingGuard (whose re-point allowance other callers rely on) would let through.

func (StrictOfflineBindingGuard) BindingGuardActiveBindings added in v0.70.0

func (StrictOfflineBindingGuard) BindingGuardActiveBindings() []BindingRef

BindingGuardActiveBindings implements BindingGuard.

func (StrictOfflineBindingGuard) BindingGuardDelta added in v0.70.0

func (StrictOfflineBindingGuard) BindingGuardDelta(current, candidate GuardState) []BindingRef

BindingGuardDelta implements BindingGuard.

func (StrictOfflineBindingGuard) BindingGuardFixes added in v0.70.0

func (StrictOfflineBindingGuard) BindingGuardFixes(st GuardState, delta []BindingRef) []GuardFix

BindingGuardFixes implements BindingGuard.

type SuggestRequest added in v0.72.0

type SuggestRequest struct {
	// Since is the look-back window; 0 means DefaultSuggestWindow.
	Since time.Duration
	// Profile and Token restrict the run to one profile or one token ("" = all).
	Profile string
	Token   string
	// IncludePatch also returns, per profile, the proposed profile document.
	IncludePatch bool
}

SuggestRequest narrows one suggest run.

type SuggestionKind added in v0.72.0

type SuggestionKind string

SuggestionKind is the one change a suggestion proposes.

const (
	// SuggestAllow adds the tool to the profile's tools.allow.
	SuggestAllow SuggestionKind = "allow"
	// SuggestAddServer adds the server to the profile's servers.
	SuggestAddServer SuggestionKind = "add_server"
	// SuggestClassify gives an unannotated tool a tier. The tier is never
	// pre-filled: a person decides read, write or destructive.
	SuggestClassify SuggestionKind = "classify"
	// SuggestNone means no profile change is proposed; Note says why.
	SuggestNone SuggestionKind = "none"
)

type TimeBucket added in v0.35.0

type TimeBucket struct {
	Start        time.Time `json:"start"`
	Calls        int64     `json:"calls"`
	Errors       int64     `json:"errors"`
	RespBytesSum int64     `json:"resp_bytes_sum"`
}

TimeBucket is a pre-bucketed slice of call volume over time for the timeline.

type TokenRewrite added in v0.70.0

type TokenRewrite struct {
	From string
	To   string
}

TokenRewrite asks MutateConfig to move every stored token pinned to From onto To as part of the same write (a profile rename or delete-with-reassign, D19). The zero value rewrites nothing.

type ToolAccessView added in v0.70.0

type ToolAccessView struct {
	Visible  bool   `json:"visible"`
	Callable bool   `json:"callable"`
	Reason   string `json:"reason"`
}

ToolAccessView is a row's verdict: visible = listed by discovery, callable = a real call would run.

type ToolApprovalResult added in v0.21.0

type ToolApprovalResult struct {
	// BlockedTools is the set of tool names that should not be indexed (pending, changed, or disabled).
	BlockedTools map[string]bool
	// PendingCount is the number of newly discovered tools awaiting approval.
	PendingCount int
	// ChangedCount is the number of tools whose description/schema changed since approval.
	ChangedCount int
}

ToolApprovalResult contains the result of checking tool approvals for a server.

type ToolCounts added in v0.70.0

type ToolCounts struct {
	Read              int `json:"read"`
	Write             int `json:"write"`
	Destructive       int `json:"destructive"`
	UnannotatedHidden int `json:"unannotated_hidden"`
}

ToolCounts is the number of a profile's VISIBLE tools by the tier the profile gives them, plus the unannotated tools it hides (FR-034).

type ToolUsage added in v0.35.0

type ToolUsage struct {
	Server         string    `json:"server"`
	Tool           string    `json:"tool"`
	Calls          int64     `json:"calls"`
	Errors         int64     `json:"errors"`
	Blocked        int64     `json:"blocked"`
	Rejected       int64     `json:"rejected"` // spec 093: shed by a concurrency limit, never executed
	ReqBytesSum    int64     `json:"req_bytes_sum"`
	RespBytesSum   int64     `json:"resp_bytes_sum"`
	SizedReqCalls  int64     `json:"sized_req_calls"`  // calls with RequestBytes>0
	SizedRespCalls int64     `json:"sized_resp_calls"` // calls with ResponseBytes>0
	LatencyBuckets []int64   `json:"latency_buckets"`  // len == numLatencyBuckets()
	LastUsed       time.Time `json:"last_used"`
}

ToolUsage is a per-(server,tool) incremental rollup.

func (*ToolUsage) AvgReqBytes added in v0.35.0

func (t *ToolUsage) AvgReqBytes() (avg int64, ok bool)

AvgReqBytes returns the average request size over sized calls only (records with RequestBytes>0). ok is false when there are no sized calls.

func (*ToolUsage) AvgRespBytes added in v0.35.0

func (t *ToolUsage) AvgRespBytes() (avg int64, ok bool)

AvgRespBytes returns the average response size over sized calls only (records with ResponseBytes>0). ok is false when there are no sized calls.

func (*ToolUsage) ErrorRate added in v0.35.0

func (t *ToolUsage) ErrorRate() float64

ErrorRate returns Errors/Calls (0 when there are no calls).

func (*ToolUsage) Percentile added in v0.35.0

func (t *ToolUsage) Percentile(p float64) (ms int64, exceeds bool)

Percentile returns an approximate latency percentile (in ms) derived from the fixed latency histogram. p is in [0,1].

ms is the upper BOUND of the bucket the percentile falls in, never a measured duration — the true value is somewhere at or below it. exceeds reports the one case where that reading inverts: the overflow bucket has no upper bound, so its ms is the last bound and the true value is ABOVE it. Callers must render the two differently ("≤ 5 ms" vs "> 10 s"); printing the number bare is how a bucketed estimate came to be read as a measurement (F22, #1046).

An empty histogram returns (0, false): no calls, nothing to bound.

type TransitionReason added in v0.23.1

type TransitionReason string

TransitionReason explains why a tool approval state transition is occurring.

const (
	ReasonHashMatch         TransitionReason = "hash_match"
	ReasonDescriptionRevert TransitionReason = "description_revert"
	ReasonFormulaMigration  TransitionReason = "formula_migration"
	ReasonContentMatch      TransitionReason = "content_match"
	ReasonDescriptionMatch  TransitionReason = "description_match"
	ReasonUserApprove       TransitionReason = "user_approve"
	ReasonAutoApprove       TransitionReason = "auto_approve"
	// ReasonBaselineTrust marks promotion of a never-reviewed (pending) tool to
	// approved because the server is trusted (non-quarantined) and has no prior
	// approved baseline yet — the current toolset IS the baseline (MCP-2931).
	ReasonBaselineTrust TransitionReason = "baseline_trust"
	// ReasonAutoApproveChanges marks promotion driven by the explicit per-server
	// auto_approve_tool_changes flag (MCP-2931/MCP-2930). It is the ONLY reason,
	// besides explicit user action, that may clear a changed (rug-pull) record —
	// because the operator opted into auto-approving changes for that server.
	ReasonAutoApproveChanges TransitionReason = "auto_approve_changes"
	// ReasonScanApproved marks a tool auto-approved because the server runs in
	// trust_mode: scan AND a synchronous, offline TPA scan of its current
	// definition returned a green (clean) verdict: a NEW tool (spec 086 stage
	// 2) and, since spec 119, a CHANGED contract too. Under manual the 2026-10-11
	// RT-02 rule still applies (a changed contract is held whatever the
	// verdict); the gate uses this reason only under scan.
	ReasonScanApproved TransitionReason = "scan_approved"
)

type TryHidden added in v0.70.0

type TryHidden struct {
	Server string `json:"server"`
	Tool   string `json:"tool"`
	Reason string `json:"reason"`
}

TryHidden is one search hit the draft profile would hide.

type TryResult added in v0.70.0

type TryResult struct {
	Results         []map[string]interface{} `json:"results"`
	HiddenByProfile int                      `json:"hidden_by_profile"`
	Hidden          []TryHidden              `json:"hidden"`
	HiddenTruncated bool                     `json:"hidden_truncated"`
}

TryResult is POST /profiles/try: what retrieve_tools would return under a draft profile, with what the draft hides. Nothing is persisted.

type UpgradeFailure added in v0.70.0

type UpgradeFailure struct {
	ClientID string `json:"client_id"`
	Error    string `json:"error"`
}

UpgradeFailure is a client whose write did not go through.

type UpgradeGuard added in v0.70.0

type UpgradeGuard struct {
	Code     string       `json:"code"`
	Bindings []BindingRef `json:"bindings"`
	Fixes    []GuardFix   `json:"fixes"`
}

UpgradeGuard reports that the request as a whole would be refused by the FR-008a guard.

type UpgradePreview added in v0.70.0

type UpgradePreview struct {
	Preview           []UpgradeRow  `json:"preview"`
	PreconditionToken string        `json:"precondition_token"`
	Guard             *UpgradeGuard `json:"guard,omitempty"`
	// NextStep is rotate_admin_api_key once nothing holds the admin key and no
	// client is unresolved (an unresolved client may still hold it).
	NextStep string `json:"next_step,omitempty"`
}

UpgradePreview is the answer of POST /clients/upgrade-admin-key-holders without `apply`.

type UpgradeRequest added in v0.70.0

type UpgradeRequest struct {
	Profile *string
	Mode    *string
	// PreconditionToken, on apply, is the combined token a preview returned.
	PreconditionToken string
}

UpgradeRequest names the binding every upgraded client is given. A nil Profile means none: the clients get the default (All servers, switchable), so the FR-008a guard never has a named binding to refuse.

type UpgradeResult added in v0.70.0

type UpgradeResult struct {
	Upgraded []string         `json:"upgraded"`
	Failed   []UpgradeFailure `json:"failed"`
	NextStep string           `json:"next_step,omitempty"`
}

UpgradeResult is the answer of an apply.

type UpgradeRow added in v0.70.0

type UpgradeRow struct {
	ClientID    string                 `json:"client_id"`
	DisplayName string                 `json:"display_name"`
	DisplayPath string                 `json:"display_path,omitempty"`
	Diff        map[string]interface{} `json:"diff"`
	// Credential is the masked value the write would embed (mcp_cli_••••).
	Credential        string `json:"credential"`
	Profile           string `json:"profile"`
	Mode              string `json:"mode"`
	PreconditionToken string `json:"precondition_token"`
	Error             string `json:"error,omitempty"`
}

UpgradeRow is one client the upgrade would move, as a preview shows it.

type UsageAggregate added in v0.35.0

type UsageAggregate struct {
	Tools     map[string]*ToolUsage `json:"tools"`
	Buckets   map[int64]*TimeBucket `json:"buckets"` // key = bucket start unix seconds
	UpdatedAt time.Time             `json:"updated_at"`
	// RetrieveToolsRespBytesSum/RetrieveToolsSizedCalls (Spec 109-k, the
	// ServerTokenMetrics.Estimated flip): retrieve_tools calls are internal
	// built-ins and deliberately excluded from the per-tool rollup above
	// (applyToolRollup's default case — admitting them would invent a tool row
	// no upstream owns), so CalculateTokenSavings has nowhere to read a REAL
	// observed retrieve_tools response size from. This dedicated, non-per-tool
	// counter is that source: a zero value (no sized call yet) is exactly the
	// "no real data" state the estimate flag needs. A persisted snapshot from
	// before this field existed loads it as zero, which is correct (no
	// AdmissionVersion bump needed — it does not change what Tools/Buckets
	// admit, only adds a value alongside them).
	RetrieveToolsRespBytesSum int64 `json:"retrieve_tools_resp_bytes_sum,omitempty"`
	RetrieveToolsSizedCalls   int64 `json:"retrieve_tools_sized_calls,omitempty"`
	// RetrieveToolsObservedCalls counts every successful retrieve_tools call,
	// truncated or not — unlike RetrieveToolsSizedCalls, which only counts the
	// non-truncated ones whose ResponseBytes can be trusted as a real
	// (undistorted) delivered size. A deployment whose retrieve_tools
	// responses routinely exceed tool_response_limit would otherwise leave
	// RetrieveToolsSizedCalls at zero forever, contradicting
	// contracts.ServerTokenMetrics.Estimated's documented promise ("false
	// once at least one real retrieve_tools call has ... completed") even
	// though real calls plainly have. This counter is what lets the Estimated
	// flip answer that question correctly while AvgRetrieveToolsRespBytes
	// keeps answering a different one (the real average SIZE, which truncated
	// calls cannot honestly contribute to — see truncatedBuiltinOverstatesDelivery).
	RetrieveToolsObservedCalls int64 `json:"retrieve_tools_observed_calls,omitempty"`
	// ClientCalls is a bounded hourly rolling counter keyed by the persisted
	// activity client_name. It avoids an activity-log scan on /clients while
	// retaining enough resolution to answer the 24-hour presence row.
	ClientCalls map[string]map[int64]int64 `json:"client_calls,omitempty"`
	// AdmissionVersion stamps which population rule built this aggregate. A
	// persisted snapshot whose stamp differs from usageAdmissionVersion was
	// counted under a different rule and cannot be patched incrementally —
	// the loader discards it and rebuilds from a full activity scan instead.
	AdmissionVersion int `json:"admission_version,omitempty"`
}

UsageAggregate is the actor-owned rollup. Exported fields are JSON-serialized for persistence; unexported config fields are restored on construction.

func NewUsageAggregate added in v0.70.0

func NewUsageAggregate() *UsageAggregate

NewUsageAggregate returns an empty aggregate at the current admission version, for callers that fold a filtered stream of records through Apply (GET /activity/usage under a profile/client/token filter, Spec 108 FR-031) instead of reading the persisted lifetime rollup.

func (*UsageAggregate) Apply added in v0.35.0

func (a *UsageAggregate) Apply(rec *storage.ActivityRecord)

Apply folds a single activity record into the aggregate. Apply is not safe for concurrent use; it is called only by the owning goroutine (see UsageStore).

Two populations live in here and they are NOT the same:

  • the per-tool rollup (ToolUsage) describes UPSTREAM TOOLS: calls, latency percentiles, byte averages, blocked and shed attempts. Only records that name an upstream tool belong in it.
  • the timeline (TimeBucket) describes WHAT THE USER SAW. It must match the glance row-for-row, or the bars under the list disagree with the list above them — the single most confusing thing a dashboard can do.

Which records reach the timeline is NOT decided here: it is storage.CountsAsCall, the one definition of "a call the user made", shared with the Activity Log's own counters so the two surfaces cannot drift apart (audit finding F1, #1046). Apply only decides what each admitted record does to the PER-TOOL rollup, which is a narrower population — upstream tools only.

func (*UsageAggregate) AvgRetrieveToolsRespBytes added in v0.70.0

func (a *UsageAggregate) AvgRetrieveToolsRespBytes() (avg int64, ok bool)

AvgRetrieveToolsRespBytes returns the average real retrieve_tools response size over sized, non-truncated calls. ok is false before any such call.

func (*UsageAggregate) ClientCallsSince added in v0.70.0

func (a *UsageAggregate) ClientCallsSince(aliases []string, since time.Time) int

ClientCallsSince returns calls observed under any known client alias in the requested interval. Activity records persist the client name at write time.

func (*UsageAggregate) HasObservedRetrieveToolsCall added in v0.70.0

func (a *UsageAggregate) HasObservedRetrieveToolsCall() bool

HasObservedRetrieveToolsCall reports whether at least one successful retrieve_tools call has completed, truncated or not. See RetrieveToolsObservedCalls for why this is a different question from AvgRetrieveToolsRespBytes's ok.

func (*UsageAggregate) Timeline added in v0.35.0

func (a *UsageAggregate) Timeline() []TimeBucket

Timeline returns the time buckets in chronological order.

type UsageStore added in v0.35.0

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

UsageStore owns the working aggregate and publishes immutable snapshots via an atomic pointer (copy-on-write).

Spec 069 / MCP-835: the activity write path must stay O(1) and must not block. Apply therefore folds the record into the working aggregate under a short writer lock and only marks the published snapshot stale — it does NOT clone. The O(tools×buckets) clone is deferred to Snapshot (publish-on-read): the first reader after a burst of writes materializes one fresh snapshot; the owning activity goroutine never pays the clone cost on the hot path. Reads with no pending writes are lock-free (atomic load); the A3 endpoint and the 30s persist flush are the only readers, so clones are rare relative to writes.

func (*UsageStore) Apply added in v0.35.0

func (s *UsageStore) Apply(rec *storage.ActivityRecord)

Apply folds a record into the working aggregate. O(1): it mutates under the writer lock and marks the snapshot stale, but never clones on the hot path.

func (*UsageStore) Replace added in v0.35.0

func (s *UsageStore) Replace(agg *UsageAggregate)

Replace swaps in a freshly built aggregate (cold-start load or rebuild). The new snapshot is materialized lazily on the next read, like Apply.

func (*UsageStore) Snapshot added in v0.35.0

func (s *UsageStore) Snapshot() *UsageAggregate

Snapshot returns the latest immutable aggregate snapshot reflecting all writes applied so far. When writes have occurred since the last publish it materializes one fresh snapshot here (the clone runs off the activity hot path); otherwise it is a lock-free atomic load. The returned value must be treated as read-only.

type UsedBy added in v0.70.0

type UsedBy struct {
	Clients          []UsedByClient `json:"clients"`
	Tokens           []string       `json:"tokens"`
	AnonymousProfile bool           `json:"anonymous_profile"`
}

UsedBy lists what points at a profile: non-revoked client credentials, non- revoked regular tokens pinned to it, and whether it is the anonymous_profile. It discloses other credentials' bindings, so REST shows it to administrators only (FR-032).

func (UsedBy) Empty added in v0.70.0

func (u UsedBy) Empty() bool

Empty reports whether nothing points at the profile through a client or a token (the anonymous_profile flag is its own refusal).

type UsedByClient added in v0.70.0

type UsedByClient struct {
	ID   string `json:"id"`
	Mode string `json:"mode"`
}

UsedByClient names one client credential bound to a profile.

type ValidationError added in v0.70.0

type ValidationError struct {
	Field   string
	Message string
}

ValidationError is a 400 {error, field} refusal.

func (*ValidationError) Error added in v0.70.0

func (e *ValidationError) Error() string

type ViewerScope added in v0.70.0

type ViewerScope struct {
	// Restricted marks a non-administrator viewer.
	Restricted bool
	// Visible reports whether the viewer may learn a server exists. nil for an
	// administrator.
	Visible func(server string) bool
	// AllowedServers is the viewer's server grant (nil = unrestricted); it
	// bounds the 24 h stats.
	AllowedServers []string
}

ViewerScope says how much of the world a profile read may reveal. The zero value is an administrator.

type Warning added in v0.70.0

type Warning struct {
	Code     profile.WarningCode     `json:"code"`
	Severity profile.WarningSeverity `json:"severity"`
	ClientID string                  `json:"client_id,omitempty"`
	Message  string                  `json:"message"`
	Action   *WarningAction          `json:"action,omitempty"`
	Bindings []BindingRef            `json:"bindings,omitempty"`
	Fixes    []GuardFix              `json:"fixes,omitempty"`
}

Warning is one Clients-surface warning (data-model §7 ClientView.warnings): the ONE shape every surface renders. Severity is info for a rotation that is merely in progress and warn for everything else.

type WarningAction added in v0.70.0

type WarningAction struct {
	Kind   string `json:"kind"`
	Target string `json:"target,omitempty"`
}

WarningAction is what a warning's "fix it" control does (data-model §7): kind is a profile.FixAction spelling (change_setting, reconnect_client, move_client, edit_token) or profile.WarningActionUpgradeAdminKeyHolders; target names what to act on (a setting, a client id or a token name).

type WorkSessionIdentity added in v0.49.0

type WorkSessionIdentity struct {
	// Principal is the authenticated identity (agent token subject / API key).
	// Empty when the proxy is used unauthenticated.
	Principal string

	// ClientName / ClientVersion come from the MCP clientInfo.
	ClientName    string
	ClientVersion string

	// WorkspaceRoot is the project the client is working in, as it disclosed
	// via MCP roots. Empty for clients that do not disclose it — measured:
	// Claude Code, Gemini and opencode do; Codex does not.
	WorkspaceRoot string

	// CorrelationID is a client-supplied conversation id. No MCP client offers
	// one today (Claude Code has a conversation UUID but does not send it), so
	// this is always empty for now. When a client finally does, it OVERRIDES the
	// derivation below and the grouping stops being a heuristic.
	CorrelationID string
}

WorkSessionIdentity is everything we know about who is doing the work. Every field is optional — the derivation degrades rather than failing.

type WorkSessionTracker added in v0.49.0

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

WorkSessionTracker maps an identity to a stable work-session id, opening a new one when the idle window lapses. Safe for concurrent use.

func NewWorkSessionTracker added in v0.49.0

func NewWorkSessionTracker(idleWindow time.Duration) *WorkSessionTracker

NewWorkSessionTracker returns a tracker with the given idle window. A zero or negative window falls back to the default.

func (*WorkSessionTracker) Reap added in v0.49.0

func (t *WorkSessionTracker) Reap(maxIdle time.Duration) int

Reap drops work sessions idle for more than maxIdle, so the tracker cannot grow without bound on a long-lived proxy.

func (*WorkSessionTracker) Resolve added in v0.49.0

Resolve returns the work-session id for this activity, opening a new one when the identity is unseen or its previous activity is older than the idle window.

Returns "" when we know nothing about the caller: an unattributable record is better left unattributed than grouped into a bucket that means nothing.

func (*WorkSessionTracker) SetIdleWindow added in v0.49.0

func (t *WorkSessionTracker) SetIdleWindow(d time.Duration)

SetIdleWindow updates the idle window (hot-reloadable config).

func (*WorkSessionTracker) StartedAt added in v0.49.0

func (t *WorkSessionTracker) StartedAt(workSessionID string) (time.Time, bool)

StartedAt returns when the given work session began, and whether it is known.

type WriteResult added in v0.70.0

type WriteResult struct {
	Profile  ProfileView `json:"profile"`
	Warnings []string    `json:"warnings"`
}

WriteResult is the outcome of a create or update: the stored profile and the validator's warnings about it.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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