runtime

package
v0.70.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 58 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 (
	// 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 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 NextStepRotateAdminKey = "rotate_admin_api_key"

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

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 ErrConfigUnavailable = errors.New("configuration unavailable")

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

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

Functions

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

func SortBindingRefs(refs []BindingRef)

SortBindingRefs orders refs by client id (the refusal's stable order).

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

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 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 client credential record to its BindingRef.

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

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

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

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

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

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

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.

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.

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

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

BulkEnableServers toggles the enabled state for multiple servers in a single storage/config save to avoid repeated file writes. Returns a map of per-server errors for operations that could not be applied.

func (*Runtime) CacheManager

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

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.

func (*Runtime) EmitActivityToolCallRejected added in v0.54.0

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

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

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

func (*Runtime) EmitActivityToolCallStarted

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

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

func (*Runtime) EmitOAuthRefreshFailed

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.

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. Returns nil if service hasn't been set yet.

func (*Runtime) GetOnboardingState added in v0.29.0

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

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

func (*Runtime) GetRecentSessions

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

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

LoadConfiguredServers synchronizes storage and upstream manager from the given or current config. If cfg is nil, it will use the current runtime configuration.

func (*Runtime) 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) 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.

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

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 runtime configuration to disk.

func (*Runtime) SaveOnboardingState added in v0.29.0

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

SaveOnboardingState persists the wizard engagement state (Spec 046).

func (*Runtime) SearchRegistryServers

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

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

func (*Runtime) ServedRoutingMode added in v0.63.0

func (r *Runtime) ServedRoutingMode() string

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

func (*Runtime) SetAllToolsEnabled added in v0.31.0

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

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

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

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

func (*Runtime) 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) 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) 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.

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) 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) 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(filter storage.ActivityFilter) <-chan *storage.ActivityRecord

StreamActivities returns a channel that yields activity records matching the filter.

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) 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 in-place. This now updates both the legacy field and the ConfigService.

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

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 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 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 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 change/addition auto-approved because the server
	// runs in trust_mode: scan AND a synchronous, offline TPA scan of the changed
	// tool returned a green (clean) verdict (spec 086 stage 2). Like
	// ReasonAutoApproveChanges it may clear a changed (rug-pull) record, but only
	// with the scanner's positive attestation — a non-green or degraded/absent
	// verdict never reaches this reason (the gate fails closed before it).
	ReasonScanApproved TransitionReason = "scan_approved"
)

type 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