Documentation
¶
Overview ¶
Package tooltrust is the MCP tool-trust primitive (ADR-0034): a privileged human explicitly trusts ONE exact observed tool fingerprint for ONE declared purpose, and that trust disappears the instant the observed capability no longer matches what was reviewed. It is a SUPPLY-CHAIN TRUST decision, never an execution authorization — runtime policy remains authoritative for every call, and a tool becoming catalog.Usable bypasses nothing (policy, approvals, confirmation, allowances, inspection, rollout, kill switch, identity, credential controls all still apply).
The durable ToolApproval store is the SOURCE OF TRUTH; catalog.Usable is a materialized projection of it (ADR-0034 D2). This package is I/O-free on its decision path: every current fact it validates against is supplied by the caller (the coordinator loads live catalog/registry facts), so the trust decision is deterministic and unit-testable, and the clock is injected. Persistence and reconciliation live in store.go.
Nothing here executes a business operation, calls an upstream MCP server, materializes a credential, contacts a provider, or activates a rollout mode.
Index ¶
- Constants
- type Config
- type CurrentTarget
- type FingerprintDigest
- type Purpose
- type RequestInput
- type ReviewedOperationClass
- type Status
- type Store
- func (s *Store) ActiveApprovals(now time.Time) []*ToolApproval
- func (s *Store) ActiveLiveApprovals(now time.Time) []*ToolApproval
- func (s *Store) AllForTenant(tenant string) []*ToolApproval
- func (s *Store) Approve(id, approver string, target CurrentTarget) (*ToolApproval, error)
- func (s *Store) CreateRequest(in RequestInput) (*ToolApproval, error)
- func (s *Store) ExpireDue(now time.Time) ([]*ToolApproval, error)
- func (s *Store) Get(id, tenant string) (*ToolApproval, error)
- func (s *Store) List(tenant string, limit int) []*ToolApproval
- func (s *Store) Load() error
- func (s *Store) Reject(id, actor, reason string) error
- func (s *Store) Revoke(id, actor, tenant, reason string) (*ToolApproval, error)
- func (s *Store) ToolRefs() []ToolRef
- type ToolApproval
- type ToolRef
Constants ¶
const MaxLiveExecutionApprovalTTL = 24 * time.Hour
MaxLiveExecutionApprovalTTL is the hard ceiling on how long a live_execution approval may remain valid for the FIRST Canary (§6). A live-execution grant is the authority to cause a real, irreversible upstream side effect, so it is short-lived by construction: it must be deliberately re-issued rather than lingering to silently re-authorize execution weeks later. This is the SINGLE authority for the ceiling — canary.MaxInitialCanaryApprovalTTL is defined as this value, so the ISSUE path (this package) and the CONSUMPTION path (internal/mcp/canary) can never disagree about how long a live grant may live. A later phase may relax it under its own review. It never applies to a shadow_evaluation approval (evaluation causes no side effect).
const SchemaVersion uint16 = 1
SchemaVersion is the durable ToolApproval envelope version. A pre-change reader rejects a newer version (fail closed); a same-version reader is byte-stable.
It stays 1 across the live-execution-trust slice: a live_execution record uses the SAME envelope and the SAME fields as a shadow_evaluation record (only Purpose differs, plus the mandatory expiry + four-eyes evidence a live record must carry), so a pre-change reader that somehow saw a live record would reject it as a non-issuable purpose (validateStored), not as an unknown schema. No field was added, so no version bump is warranted.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Path is the durable approvals file, e.g. <dataDir>/mcp_tooltrust/approvals.json.
Path string
// Clock is the injected time source (default time.Now). Every expiry decision
// reads it, so tests drive expiry deterministically.
Clock func() time.Time
// MaxRecords bounds the TOTAL number of stored records (pending + active +
// terminal). At capacity a new request prunes the oldest terminal record; if
// none can be pruned the request fails closed.
MaxRecords int
// MaxPerTenant bounds the number of NON-terminal (pending + active) records per
// tenant, so one tenant cannot exhaust the global budget.
MaxPerTenant int
}
Config configures a Store. Path is the durable file; the bounds keep the file (and the in-memory index) from growing without limit under a hostile or careless caller. Zero bounds fall back to conservative defaults.
type CurrentTarget ¶
type CurrentTarget struct {
ServerExists bool
ServerUsable bool
Tenant string // the server's registry OwnerScope
ToolExists bool
Approvable bool // current eligibility is promotable (not ServerDisabled)
Fingerprint FingerprintDigest
FingerprintFormatVersion uint16
CatalogRevision uint64
ServerRevision uint64
}
CurrentTarget is the authoritative, coordinator-loaded set of CURRENT facts an Approve decision is verified against (ADR-0034 D6). The coordinator reads these from the LIVE catalog + registry immediately before the decision; the store never trusts caller-submitted facts and never retargets to a different tool.
type FingerprintDigest ¶
type FingerprintDigest [32]byte
FingerprintDigest is the 32-byte canonical tool fingerprint — catalog.Fingerprint.Sum(). An approval binds to this exact value; any change to any of the fingerprint's dimensions changes the digest and the approval no longer matches (the rug-pull invariant, ADR-0034 D4). It is a digest of PUBLIC capability facts, never a secret.
type Purpose ¶
type Purpose uint8
Purpose is a ToolApproval's trust ceiling (ADR-0034 D5). It is deliberately NOT a boolean: a shadow_evaluation approval MUST NEVER be usable as a live-execution authorization, and a future live phase must introduce a stronger purpose explicitly.
const ( // PurposeUnset is the invalid zero value (fails closed). PurposeUnset Purpose = iota // PurposeShadowEvaluation trusts the tool ONLY for Controlled Shadow evaluation. It is // the ONLY purpose issuable in this slice. PurposeShadowEvaluation // PurposeLiveExecution trusts the tool for a real upstream side effect. It is issuable ONLY // under the stronger live-execution governance the issue path enforces (§3): a mandatory // finite expiry no longer than MaxLiveExecutionApprovalTTL, FOUR-EYES (a distinct requester // and approver, compared on canonical authenticated principals), and exact-current-state // revalidation at approve. A shadow_evaluation approval can NEVER become a live grant, and a // live grant never materializes catalog.Usable (live trust is orthogonal to Shadow usability // — it is consumed only by the Canary preflight). Issuing one arms NOTHING: no executor, no // live tier, no Canary transition (§22). PurposeLiveExecution )
func ParsePurpose ¶
ParsePurpose resolves a wire label to a Purpose. It returns (PurposeUnset, false) for an unknown label — the caller fails closed rather than guessing.
func (Purpose) Issuable ¶
Issuable reports whether this purpose may be issued at all. Both shadow_evaluation and live_execution are now issuable — but at very different governance ceilings, and this coarse gate does NOT convey them: live_execution issuance additionally requires the stronger controls the issue path enforces (mandatory finite ≤MaxLiveExecutionApprovalTTL expiry, four-eyes on canonical principals, exact-current-state revalidation). PurposeUnset stays non-issuable (fails closed). A caller must never read this predicate as "may be issued with shadow semantics" — the request/approve/load paths layer the purpose-specific requirements on top.
func (Purpose) PermitsLiveExecution ¶
PermitsLiveExecution reports whether an approval of this purpose may satisfy a CANARY / live-execution trust requirement. ONLY live_execution qualifies — the firewall's OTHER positive half, and the mirror of PermitsShadowEvaluation: a shadow_evaluation approval can NEVER authorize a real upstream side effect, and a live_execution approval can never satisfy the Shadow "usable tool" prerequisite. The two purposes are disjoint by construction (a Purpose is exactly one value), so no approval satisfies both. This makes the "shadow != live" invariant a compile-checkable predicate, not a runtime convention. Issuance of live_execution stays refused fail-closed (Issuable) in this build; this predicate only defines what a live_execution approval WOULD permit once a future, separately-reviewed live phase makes it issuable under stronger governance.
func (Purpose) PermitsShadowEvaluation ¶
PermitsShadowEvaluation reports whether an approval of this purpose may satisfy the Controlled Shadow "usable scoped tool" prerequisite. ONLY shadow_evaluation qualifies — this is the live-execution firewall's positive half.
type RequestInput ¶
type RequestInput struct {
Tenant string
ServerID string
ToolName string
Fingerprint FingerprintDigest
FingerprintFormatVersion uint16
Purpose Purpose
// ReviewedOperationClass is what the review determined about this exact capability's
// effect on the world (see reviewed_operation.go). It is REQUIRED for a
// PurposeLiveExecution request and optional for a shadow one — a shadow approval never
// authorizes a side effect, so there is nothing for the class to widen there.
ReviewedOperationClass ReviewedOperationClass
CatalogRevision uint64
ServerRevision uint64
RequestedBy string
Reason string
TicketRef string
ExpiresAt *time.Time
}
RequestInput is the caller-supplied input to CreateRequest. It carries only safe references, the reviewed fingerprint digest, and the revisions the reviewer reasoned about — never a token, credential, raw schema/body, or client-submitted server fact. Tenancy flows through the server (its registry OwnerScope), resolved by the coordinator; it is never a value a client submits directly here.
type ReviewedOperationClass ¶ added in v1.0.228
type ReviewedOperationClass uint8
ReviewedOperationClass is what a human review determined about an exact approved tool's effect on the world, at the exact fingerprint the approval binds.
const ( // ReviewedOpUnset is the invalid zero value: no review stated the semantics. It is never // read-only, and a live_execution request that leaves it unset is refused at creation — // an approval that may authorize a real side effect must say what it reviewed. ReviewedOpUnset ReviewedOperationClass = iota // ReviewedOpReadOnly — the review determined this exact capability does not mutate state // at the upstream, for ANY admissible invocation of it. This is the ONLY value that can // make a tools/call read-first. ReviewedOpReadOnly // ReviewedOpMutating — the review determined this exact capability can change state (or // could not determine that it does not, which is the same answer). It is the honest // classification for a tool whose effect depends on its arguments. ReviewedOpMutating )
func ParseReviewedOperationClass ¶ added in v1.0.228
func ParseReviewedOperationClass(s string) (ReviewedOperationClass, bool)
ParseReviewedOperationClass resolves a wire label. An unknown label returns (ReviewedOpUnset, false) so the caller fails closed rather than guessing — in particular, a typo must never land on read_only.
func (ReviewedOperationClass) ReadOnly ¶ added in v1.0.228
func (c ReviewedOperationClass) ReadOnly() bool
ReadOnly reports whether the review determined this exact capability is non-mutating. It is the ONE positive predicate in this file, written once so no consumer re-derives it as `!= ReviewedOpMutating` — which would read an UNSET class as read-only and invert the fail-closed default.
func (ReviewedOperationClass) Stated ¶ added in v1.0.228
func (c ReviewedOperationClass) Stated() bool
Stated reports whether a review actually answered the question. It is the predicate the live-request path requires: an approval that may authorize a real upstream side effect must carry an explicit determination, in either direction.
func (ReviewedOperationClass) String ¶ added in v1.0.228
func (c ReviewedOperationClass) String() string
String returns a stable wire label.
type Status ¶
type Status uint8
Status is the ToolApproval lifecycle status. Rejected/Revoked/Expired are terminal and never re-activate — a revoked or expired approval never becomes valid again from a later identical tools/list; re-approval requires a NEW human decision (ADR-0034 D7).
const ( // StatusUnset is the invalid zero value (fails closed). StatusUnset Status = iota // StatusPending is a request awaiting an approve/reject decision. StatusPending // StatusActive is a live grant — the only status that can materialize catalog.Usable. StatusActive // StatusRejected is a terminal denial of a pending request. StatusRejected // StatusRevoked is a terminal operator revocation of an active grant. StatusRevoked // StatusExpired is a terminal expiry of an active grant. StatusExpired )
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the durable, bounded, tenant-scoped, secret-free ToolApproval store — the SOURCE OF TRUTH for MCP tool trust (ADR-0034 D2/D3). It persists to a single atomically-rewritten file and is recoverable independently of the MCP events spool. All state transitions happen under the store lock and are made durable BEFORE they are published to the in-memory index (persist-before-effect): a persistence failure leaves the in-memory state byte-unchanged and fails closed.
The catalog's Usable state is a MATERIALIZED PROJECTION of this store; the coordinator (package main) owns the derivation and reconciles the catalog. The store itself never touches the catalog, dials a server, or materializes a credential.
func NewStore ¶
NewStore constructs a Store bound to cfg. It does NOT read the durable file; call Load once at startup (kept separate so tests control recovery). The parent directory is created if absent so the first AtomicWrite succeeds.
func (*Store) ActiveApprovals ¶
func (s *Store) ActiveApprovals(now time.Time) []*ToolApproval
ActiveApprovals returns copies of every grant that is live as of now (active, shadow-purpose, unexpired) across ALL tenants. The coordinator (a trusted, in-process caller — never a tenant-scoped request handler) uses it to derive the catalog Usable projection at startup Recover and after each ingest. It NEVER consults a fingerprint — the coordinator matches each against the tool's CURRENT observed fingerprint, so a drifted tool is not promoted.
func (*Store) ActiveLiveApprovals ¶
func (s *Store) ActiveLiveApprovals(now time.Time) []*ToolApproval
ActiveLiveApprovals returns copies of every LIVE-execution grant that is live as of now (active, live-purpose, unexpired) across ALL tenants. The coordinator (a trusted, in-process caller — never a tenant-scoped request handler) uses it to feed the Canary activation preflight's per-tool live-approval bindings. Like ActiveApprovals it is the mirror for the live firewall half and NEVER consults a fingerprint — the caller matches each against the tool's CURRENT observed target, and canary.SatisfiesLiveExecution re-checks four-eyes, the TTL ceiling, and the exact target. It NEVER materializes catalog.Usable: live trust is orthogonal to Shadow usability (§15), so no live grant reaches the ActiveApprovals→Usable projection.
func (*Store) AllForTenant ¶
func (s *Store) AllForTenant(tenant string) []*ToolApproval
AllForTenant returns copies of EVERY approval for the tenant, unsorted and unbounded (the store's total-record cap already bounds it). It exists so a caller enriching a whole inventory response snapshots the tenant's approvals ONCE and builds a per-tool index, instead of calling List (which pre-allocates a large slice and scans/sorts) once per tool.
func (*Store) Approve ¶
func (s *Store) Approve(id, approver string, target CurrentTarget) (*ToolApproval, error)
Approve transitions a pending request to an active grant, after re-verifying the bound target against the CURRENT facts (ADR-0034 D5/D6): the purpose must be issuable (shadow only), the server must still exist, be usable, and belong to the approval's tenant, the tool must still exist in an approvable state, and its current fingerprint (and format version) must EXACTLY match the reviewed digest. Any mismatch fails closed and never retargets. The transition is persisted durably before it is published. A repeat approve of an already-active grant is idempotent. It does NOT touch the catalog — the coordinator promotes after.
func (*Store) CreateRequest ¶
func (s *Store) CreateRequest(in RequestInput) (*ToolApproval, error)
CreateRequest records a new pending trust request. It validates every bound, refuses a non-issuable purpose fail-closed, and persists the request durably before it becomes visible. The generated ApprovalID is unpredictable (crypto/rand). No catalog state changes here — a request is not a grant.
func (*Store) ExpireDue ¶
func (s *Store) ExpireDue(now time.Time) ([]*ToolApproval, error)
ExpireDue transitions every active grant past its expiry to Expired durably and returns copies of those transitioned, so the coordinator can demote their tools. It is idempotent and driven by the injected clock (a periodic coordinator sweep and startup Recover call it). Expiry is also derivable at read time, so trust is never live for an expired grant even before a sweep runs.
func (*Store) Get ¶
func (s *Store) Get(id, tenant string) (*ToolApproval, error)
Get returns a copy of the approval iff it exists within the caller's tenant scope. A tenant mismatch returns a uniform not-found so existence never leaks across tenants.
func (*Store) List ¶
func (s *Store) List(tenant string, limit int) []*ToolApproval
List returns a bounded, tenant-scoped view of approvals in NEWEST-FIRST order (RequestedAt descending, then ApprovalID for determinism). Results are copies. The order is deliberately newest-first: the endpoint exposes no cursor/offset, so an ascending sort followed by truncation would return only the OLDEST records and hide every request past the limit — including brand-new pending approvals an admin needs to decide.
func (*Store) Load ¶
Load reads the durable file into the in-memory index. A missing file is a fresh store (no error). A corrupt file, an unknown/newer schema version, or any record that fails structural validation is a fail-CLOSED error (never a permissive empty state that would silently revoke every prior trust decision).
func (*Store) Reject ¶
Reject decides a pending request as rejected (terminal). It persists durably before publishing. A repeat identical rejection is idempotent; rejecting a non-pending request fails closed with the precise terminal reason.
func (*Store) Revoke ¶
func (s *Store) Revoke(id, actor, tenant, reason string) (*ToolApproval, error)
Revoke terminates an active (or pending) grant. Revocation is durable, tenant-scoped, exact-ApprovalID, idempotent, and fail-closed; it causes an IMMEDIATE loss of usability once the coordinator demotes the returned tool. A revoked approval NEVER re-activates from a later identical tools/list — a fresh human decision is required (ADR-0034 D7). The revoked approval is returned so the coordinator can demote its tool.
func (*Store) ToolRefs ¶
ToolRefs returns the distinct (server, tool) pairs referenced by ANY stored approval, active or terminal. The coordinator re-derives each so a tool whose only grants have expired or been revoked is demoted even when persisting the terminal status failed — the catalog demotion must not depend on the durable write.
type ToolApproval ¶
type ToolApproval struct {
SchemaVersion uint16 `json:"schema_version"`
ApprovalID string `json:"approval_id"`
// Tenant is the server's registry OwnerScope. Tenancy flows through the server, never a
// field a client may submit.
Tenant string `json:"tenant"`
ServerID string `json:"server_id"`
ToolName string `json:"tool_name"`
// Fingerprint is the exact reviewed capability digest. FingerprintFormatVersion records
// which fingerprint scheme produced it so a format change can never silently re-interpret
// an old digest.
Fingerprint FingerprintDigest `json:"fingerprint"`
FingerprintFormatVersion uint16 `json:"fingerprint_format_version"`
// CatalogRevision / ServerRevision record the catalog (and, when carried, registry)
// revision the decision was reasoned about — the optimistic-concurrency / stale-target
// evidence (ADR-0034 D6). ServerRevision is 0 when the registry carries no per-server
// revision.
CatalogRevision uint64 `json:"catalog_revision"`
ServerRevision uint64 `json:"server_revision,omitempty"`
Purpose Purpose `json:"purpose"`
// ReviewedOperationClass records what the review determined about this exact
// capability's effect on the world, at THIS fingerprint (see reviewed_operation.go). It
// is the only authority that can make a tools/call read-first, and it is bound to the
// fingerprint beside it: a tool that moves to a new digest carries no determination at
// all until a new review states one.
//
// It is REQUIRED on a live_execution approval and refused at creation when absent. The
// zero value is "no review stated it", which every consumer reads as NOT read-only, so
// an older record that predates this field can never widen what may execute.
ReviewedOperationClass ReviewedOperationClass `json:"reviewed_operation_class"`
Status Status `json:"status"`
RequestedBy string `json:"requested_by"`
RequestedAt time.Time `json:"requested_at"`
ApprovedBy string `json:"approved_by,omitempty"`
ApprovedAt time.Time `json:"approved_at,omitempty"`
Reason string `json:"reason,omitempty"`
TicketRef string `json:"ticket_ref,omitempty"`
// ExpiresAt is an optional expiry; nil means no expiry. An expired active approval keeps
// no tool Usable (ADR-0034 D7).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
RevokedBy string `json:"revoked_by,omitempty"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
RevocationReason string `json:"revocation_reason,omitempty"`
// RejectedBy / RejectedAt record WHO denied a pending request and WHEN. They are the
// rejection's OWN decision-evidence fields — deliberately DISTINCT from ApprovedBy /
// ApprovedAt, which a rejection previously reused. A shared evidence shape let a single
// valid-JSON status byte flip (Rejected 3 → Active 2) pass Load's per-status lifecycle
// check and materialize an active grant from a denial (ADR-0034 recovery is fail-closed
// against single-field tamper). With distinct fields, a flipped-to-Active record still
// carries RejectedBy/RejectedAt, which the Active-lifecycle invariant forbids.
RejectedBy string `json:"rejected_by,omitempty"`
RejectedAt *time.Time `json:"rejected_at,omitempty"`
// RejectedReason records why a pending request was rejected (governance evidence).
RejectedReason string `json:"rejected_reason,omitempty"`
}
ToolApproval is one durable, typed, secret-free trust decision (ADR-0034 D2/D4). It binds a tenant + server + tool + EXACT fingerprint digest + purpose to an authenticated human decision. It carries only safe references and the fingerprint digest — never a token, credential, raw schema/argument/output body, or private identity material.
Only StatusActive approvals whose Fingerprint matches a tool's CURRENT observed fingerprint (and whose server is usable, purpose permits, and which are not expired) materialize catalog.Usable. Every other status keeps the tool at its observed disposition.
func (*ToolApproval) MatchesTool ¶
func (a *ToolApproval) MatchesTool(tenant, serverID, toolName string, fp FingerprintDigest, fpFormat uint16) bool
MatchesTool reports whether this approval binds to the given tool identity AND exact fingerprint. Tenant, server, name, and the full fingerprint digest must all match — an approval never authorizes two different fingerprints or a same-named tool on another server (ADR-0034 D4). The fingerprint-format version must also match so a scheme change invalidates.