Documentation
¶
Overview ¶
Package httpapi provides an HTTP/JSON API handler that wraps a memstore.Store. It is used by the memstored daemon and can be mounted on any HTTP server.
Architectural boundary: httpapi must not import pgstore or any other concrete store implementation. All storage is accessed through memstore interfaces (Store, SessionStore, Embedder, Generator). Composition happens in cmd/memstored.
Index ¶
- Constants
- Variables
- func Mount(prefix string, api http.Handler, opts ...MountOpt) *http.ServeMux
- func ValidScopes() []string
- func WithIdentity(ctx context.Context, id Identity) context.Context
- type BackfillResult
- type DetectBackfill
- type DetectScorer
- type EmbedQueue
- type ExtractQueue
- func (q *ExtractQueue) BackfillFeedback(ctx context.Context, progress func(done, total int)) (*BackfillResult, error)
- func (q *ExtractQueue) BackfillFeedbackFor(ctx context.Context, store memstore.Store, sess memstore.SessionStore, ...) (*BackfillResult, error)
- func (q *ExtractQueue) BackfillFeedbackService(ctx context.Context, store memstore.Store, sess memstore.SessionStore, ...) (*BackfillResult, error)
- func (q *ExtractQueue) Enqueue(job extractJob)
- func (q *ExtractQueue) ProcessOnce() bool
- func (q *ExtractQueue) SetSimilarityPolicy(pol memstore.SimilarityPolicy)
- func (q *ExtractQueue) Start()
- func (q *ExtractQueue) Stop()
- type Handler
- type HandlerOpt
- func WithExtractQueue(eq *ExtractQueue) HandlerOpt
- func WithGenerator(g memstore.Generator) HandlerOpt
- func WithMaxBodyBytes(n int64) HandlerOpt
- func WithProtectedResource(p ProtectedResource) HandlerOpt
- func WithReranker(rr embedding.Reranker, pol memstore.RerankPolicy) HandlerOpt
- func WithSessionContext(sc *SessionContext) HandlerOpt
- func WithSessionStore(ss memstore.SessionStore) HandlerOpt
- func WithTokenVerifier(v TokenVerifier) HandlerOpt
- type Identity
- type MountOpt
- type OAuthVerifier
- type ProtectedResource
- func (p ProtectedResource) Configured() bool
- func (p ProtectedResource) Metadata() *oauthex.ProtectedResourceMetadata
- func (p ProtectedResource) MetadataHandler() http.Handler
- func (p ProtectedResource) MetadataPath() string
- func (p ProtectedResource) MetadataURL() string
- func (p ProtectedResource) ResourceURL() string
- func (p ProtectedResource) Validate() error
- type ProvisioningResolver
- type SessionContext
- func (sc *SessionContext) FilterSeen(sessionID string, ids []int64) []int64
- func (sc *SessionContext) MarkSeen(sessionID string, ids []int64)
- func (sc *SessionContext) RecentFiles(sessionID string) []string
- func (sc *SessionContext) Stop()
- func (sc *SessionContext) TouchFiles(sessionID string, files []string)
- type TokenVerifier
- type UserResolver
- type WhoAmIResponse
Constants ¶
const ( ScopeRead = memstore.ScopeRead ScopeWrite = memstore.ScopeWrite ScopeAdmin = memstore.ScopeAdmin ScopeIngest = memstore.ScopeIngest )
Scopes carried by API tokens, re-exported from the root package so handlers and route registration read naturally. The canonical definitions live in memstore.Scope* because pgstore validates against the same set at issuance and must not import this package.
Every route declares the scope it requires at registration; see registerRoutes. What each implies is documented on Allows.
const DefaultPrefix = "/memstore"
DefaultPrefix is where the daemon's own surface is mounted. It exists so a second service on this host has an obvious place of its own rather than finding memstore already occupying the root.
Variables ¶
ErrAuthUnavailable means a caller could not be authenticated because something on our side failed -- the authorization server's keys could not be fetched, or the user could not be resolved. It is deliberately distinct from an invalid token: this is a 503, and a bad token is a 401. Telling a client its token is bad when the truth is that the issuer is unreachable sends it into a reauthentication loop against a server that is already struggling.
Functions ¶
func Mount ¶
Mount composes the daemon's top-level handler.
The API is mounted under prefix, and knows nothing about it: every route it registers is relative to /, and http.StripPrefix makes the mount point the host's business. That is the whole composition contract -- a second service (another MCP surface, a web UI) mounts the same way, and no module has to agree with any other about who owns which path.
Two consequences worth stating, because both are easy to get wrong later.
A module must never build an absolute URL from the request it is serving. StripPrefix rewrites the path a handler sees, so a handler that reconstructs its own URL reconstructs the wrong one -- it cannot see the prefix it is mounted under. Anything that emits an absolute URL (OAuth metadata, a redirect, a link in a web UI) has to be told its public base by the host.
/.well-known/ is reserved here and never delegated by accident. Well-known URIs are root-scoped by specification and cannot be prefixed: RFC 9728 puts the resource path after the well-known segment, so a protected-resource document for /memstore/mcp lives at /.well-known/oauth-protected-resource/ memstore/mcp -- rooted, not nested. Reserving it keeps the space the host's, so the second module to want a well-known document cannot collide with the first.
func ValidScopes ¶
func ValidScopes() []string
ValidScopes re-exports the canonical scope list so whoami and its tests read against the same source as issuance.
Types ¶
type BackfillResult ¶
type BackfillResult struct {
Sessions int `json:"sessions"` // sessions processed
Rated int `json:"rated"` // total fact ratings written
Errors int `json:"errors"` // sessions that failed
}
BackfillResult summarizes a backfill-feedback run.
type DetectBackfill ¶
type DetectBackfill struct {
// contains filtered or unexported fields
}
DetectBackfill scores the facts that predate the detect_score column, so the read filter has something to act on.
It exists because the score cannot be computed in SQL, so the migration that added the column could not populate it. Until this runs, every existing fact reads as "not yet computed" -- which is deliberately permissive, since treating unknown as hostile would withhold the whole corpus the moment the column landed.
It runs regardless of screen_mode. The read filter is the regex screen, which is independent of the model pass, so a deployment with the model screen off still needs its corpus scored.
func NewDetectBackfill ¶
func NewDetectBackfill(store DetectScorer, interval time.Duration, batch int) *DetectBackfill
NewDetectBackfill creates the backfill runner. A zero interval or batch takes a sensible default.
func (*DetectBackfill) Start ¶
func (b *DetectBackfill) Start()
Start begins draining the backlog in the background.
func (*DetectBackfill) Stop ¶
func (b *DetectBackfill) Stop()
Stop signals the loop to finish and waits for it. Safe to call more than once, and safe to call after the loop has already exited on its own.
type DetectScorer ¶
type DetectScorer interface {
// BackfillDetectScores scores up to limit facts that have none, returning how
// many it scored. Zero means there is nothing left to do.
BackfillDetectScores(ctx context.Context, limit int) (int, error)
// DetectWithheldCount reports how many facts the read filter is currently
// hiding, so the completion log can say what the scoring actually cost.
DetectWithheldCount(ctx context.Context) (int, error)
}
DetectScorer is the store capability DetectBackfill needs. Both backends implement it; it is an interface here so the runner can be tested without a database.
type EmbedQueue ¶
type EmbedQueue struct {
// contains filtered or unexported fields
}
EmbedQueue processes facts that need embeddings in the background.
func NewEmbedQueue ¶
func NewEmbedQueue(store memstore.Store, embedder embedding.Embedder, interval time.Duration, batchSize int) *EmbedQueue
NewEmbedQueue creates a background embedding processor. It polls for unembedded facts every interval and processes them in batches.
func (*EmbedQueue) ProcessOnce ¶
func (eq *EmbedQueue) ProcessOnce()
ProcessOnce drains one tick's worth of unembedded facts. Called from the background loop and exposed for tests.
func (*EmbedQueue) SetCeiling ¶
func (eq *EmbedQueue) SetCeiling(n int)
SetCeiling sets the hard byte bound on any single embed request, normally the configured embedder's effective budget (embedding.Config.Limits().MaxBytes).
It has to be passed in because the Embedder interface does not expose it, and it must be the *configured* budget rather than the model's registered one: a deployment lowers it when the backend serving the model is stricter than the model itself, and sizing against the registered figure while the request is clipped to a lower configured one truncates every chunk's tail silently.
Zero leaves chunk sizing to the retrieval target alone.
func (*EmbedQueue) Start ¶
func (eq *EmbedQueue) Start()
Start begins the background embedding loop.
func (*EmbedQueue) Stop ¶
func (eq *EmbedQueue) Stop()
Stop signals the loop to stop and waits for it to finish.
type ExtractQueue ¶
type ExtractQueue struct {
// contains filtered or unexported fields
}
ExtractQueue processes session transcripts through the FactExtractor pipeline after they have been saved, producing durable facts, session summaries, and A-MEM Zettelkasten-style links. If hintStore is non-nil, a second stage runs to generate context hints for the next session via the Ollama pipeline. If hintStore also implements hintRater, a third stage auto-rates hints from the previous session that were injected into this one.
func NewExtractQueue ¶
func (*ExtractQueue) BackfillFeedback ¶
func (q *ExtractQueue) BackfillFeedback(ctx context.Context, progress func(done, total int)) (*BackfillResult, error)
BackfillFeedback iterates all sessions with unrated fact injections and auto-rates each one. This is the batch version of autoRateFacts, used to bootstrap feedback scores from historical sessions.
progress is called after each session with (completed, total). May be nil.
func (*ExtractQueue) BackfillFeedbackFor ¶
func (q *ExtractQueue) BackfillFeedbackFor(ctx context.Context, store memstore.Store, sess memstore.SessionStore, progress func(done, total int)) (*BackfillResult, error)
BackfillFeedbackFor runs backfill against an explicit store and session store, scoping the entire operation to whatever user those stores resolve to. The HTTP handler passes the request-scoped store and session store so a caller backfills only its own sessions and facts -- never another user's. sess must implement the backfillRater interface (the pg SessionStore does); if it does not, an error is returned.
func (*ExtractQueue) BackfillFeedbackService ¶
func (q *ExtractQueue) BackfillFeedbackService(ctx context.Context, store memstore.Store, sess memstore.SessionStore, progress func(done, total int)) (*BackfillResult, error)
BackfillFeedbackService is like BackfillFeedback but uses service-scoped store and session store so it can reach facts and sessions across all users. Called from main where pgStore.ServiceScope() and sessionStore.ServiceScope() are available. The service scope is privileged -- never place it on a request context or derive it from user input. Mechanically identical to BackfillFeedbackFor; the distinct name documents the privileged caller.
func (*ExtractQueue) Enqueue ¶
func (q *ExtractQueue) Enqueue(job extractJob)
Enqueue submits a job for background processing. Non-blocking: if the buffer is full the job is logged and dropped rather than blocking the HTTP handler.
func (*ExtractQueue) ProcessOnce ¶
func (q *ExtractQueue) ProcessOnce() bool
ProcessOnce pulls one queued job and runs it synchronously, returning true if a job was processed and false if the queue was empty. It is the synchronous drain seam mirroring EmbedQueue.ProcessOnce: the background worker (Start) uses processJob directly, while tests and any caller that needs deterministic draining can pull one job at a time without racing the worker. Do not call it concurrently with a running Start loop -- they would compete for the same channel.
func (*ExtractQueue) SetSimilarityPolicy ¶ added in v0.5.1
func (q *ExtractQueue) SetSimilarityPolicy(pol memstore.SimilarityPolicy)
NewExtractQueue creates an ExtractQueue with a buffered job channel. Pass a non-nil hintStore to enable context hint generation (Stage 2). If hintStore also implements hintRater, auto-rating of injected hints is enabled. SetSimilarityPolicy sets the cosine gates for auto-linking and auto-supersession. Call before Start; extractors built per job inherit it.
func (*ExtractQueue) Start ¶
func (q *ExtractQueue) Start()
Start launches the background worker goroutine.
func (*ExtractQueue) Stop ¶
func (q *ExtractQueue) Stop()
Stop signals the worker to finish and waits for it.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler serves the memstore HTTP API.
func New ¶
func New(store memstore.Store, embedder embedding.Embedder, apiKey string, opts ...HandlerOpt) *Handler
New creates an API handler backed by the given store. If apiKey is non-empty, requests must include Authorization: Bearer <key>.
type HandlerOpt ¶
type HandlerOpt func(*Handler)
HandlerOpt configures optional Handler fields.
func WithExtractQueue ¶
func WithExtractQueue(eq *ExtractQueue) HandlerOpt
WithExtractQueue enables post-session fact extraction.
func WithGenerator ¶
func WithGenerator(g memstore.Generator) HandlerOpt
WithGenerator sets the LLM generator for the /v1/generate endpoints.
func WithMaxBodyBytes ¶
func WithMaxBodyBytes(n int64) HandlerOpt
WithMaxBodyBytes caps the request body size accepted by any endpoint.
func WithProtectedResource ¶
func WithProtectedResource(p ProtectedResource) HandlerOpt
WithProtectedResource tells the API how to describe itself as an OAuth protected resource, so a 401 on the MCP endpoint can point a client at the metadata document. The document itself is served by Mount, not here -- see protectedresource.go. Without this, no challenge is emitted and behaviour is exactly as before.
func WithReranker ¶
func WithReranker(rr embedding.Reranker, pol memstore.RerankPolicy) HandlerOpt
WithReranker enables second-stage reranking, using the given reranker under the supplied policy. Mode/Threshold drive the /v1/recall pipeline; Candidates caps the per-request search default pool and RecallCandidates caps the recall pool (separate because recall runs per-prompt under a tight budget). A disabled mode (RerankOff) leaves recall first-stage only even if a reranker is passed. The reranker should be the same instance set on the store.
func WithSessionContext ¶
func WithSessionContext(sc *SessionContext) HandlerOpt
WithSessionContext sets the session context tracker for the /v1/recall endpoint.
func WithSessionStore ¶
func WithSessionStore(ss memstore.SessionStore) HandlerOpt
WithSessionStore enables persistence of Claude Code session events.
func WithTokenVerifier ¶
func WithTokenVerifier(v TokenVerifier) HandlerOpt
WithTokenVerifier enables bearer-token auth backed by the given verifier (typically a pgstore.TokenStore). When set, requests must carry a valid token; the legacy single-key check is bypassed.
type Identity ¶
type Identity struct {
// Name is the human-readable identity, e.g. "matthew-laptop" for a bearer
// token row or the CN of an mTLS client cert.
Name string
// Scopes are coarse-grained permission strings attached to the identity,
// e.g. "read", "write", "admin". Consumed by Allows, which every route
// consults through requireScope; GET /v1/whoami reports the effective set
// so callers need not reimplement the implication rules.
Scopes []string
// Source records how the identity was established: "bearer", "mtls", or
// "legacy" for the single-key MEMSTORE_API_KEY fallback. Useful for audit
// and for handlers that only trust one source.
Source string
// UserID is the database ID of the owning user row. Set from the token
// store's VerifyResult.UserID on the bearer-token path; 0 on the legacy
// single-key path (maps to the default user via the store fallback).
UserID int64
}
Identity is the resolved caller for an authenticated request. It is set by the auth middleware (bearer-token verification, mTLS handshake, or any future source) and read by handlers that need to know who is calling.
func IdentityFromContext ¶
IdentityFromContext returns the Identity stored on ctx, or zero+false if the request was unauthenticated (or the middleware didn't run).
func PeerIdentity ¶
PeerIdentity returns the Identity established by the TLS layer (mTLS client cert), or zero+false if the request did not present a verified client cert. Independent of bearer-token auth: a request can carry both, and handlers may consult either.
func (Identity) Allows ¶
Allows reports whether the identity may exercise the given scope.
Two implications exist, and one deliberate non-implication:
ScopeAdmin implies ScopeRead and ScopeWrite. An administrator can already do both by other means; requiring the grant to be spelled out adds friction without adding a boundary.
An identity with NO scopes gets ScopeRead and ScopeWrite. Tokens issued before scope enforcement existed carry an empty scope set, as does the legacy single-key auth path, and revoking their access on upgrade would break running deployments for no security gain -- they already had it.
ScopeIngest is implied by NOTHING. Not by admin, not by the legacy grant. It must be granted explicitly on the token.
That last rule is the one worth defending. The document corpus derives its trustworthiness from provenance the model cannot author, and the structural guarantee behind that is simply that no credential the model holds can reach the ingest path. In practice the MCP server's token is often an admin token, so if admin implied ingest the guarantee would be void exactly where it matters. Admin is authority over the store; ingest is the authority to assert where bytes came from. They are different powers and this keeps them apart.
type MountOpt ¶
type MountOpt func(*mountConfig)
MountOpt configures Mount.
func WithProtectedResourceMetadata ¶
func WithProtectedResourceMetadata(p ProtectedResource) MountOpt
WithProtectedResourceMetadata serves p's RFC 9728 document from the host's reserved well-known space. Without it that space stays reserved and empty.
type OAuthVerifier ¶
type OAuthVerifier struct {
// contains filtered or unexported fields
}
OAuthVerifier authenticates bearer tokens issued by the configured authorization server. It implements TokenVerifier, so it plugs into the same seam as the static-token store and every handler and scope check downstream is unchanged.
func NewOAuthVerifier ¶
func NewOAuthVerifier(rs *oidclient.ResourceServer, users UserResolver, scopePrefix string) (*OAuthVerifier, error)
NewOAuthVerifier returns a verifier backed by rs, resolving users through users. rs and users are required.
scopePrefix is the namespace this resource's scopes carry at the authorization server -- "memstore:" for a server that also serves other resources, empty for one that does not. It is configuration rather than a constant because it is a convention between two deployments, not a property of either program.
func (*OAuthVerifier) VerifyToken ¶
VerifyToken implements TokenVerifier.
type ProtectedResource ¶
type ProtectedResource struct {
// PublicBaseURL is the scheme and authority this daemon is reached at from
// outside, with no path -- "https://memstore.example.net". It cannot be
// derived from a request: the daemon may sit behind a proxy, and a module
// behind StripPrefix cannot see its own prefix. The host must supply it.
PublicBaseURL string
// Prefix is the mount prefix, matching what is passed to Mount. Empty means
// the daemon is mounted at the root.
Prefix string
// AuthorizationServers are the issuer identifiers a client may authenticate
// against. At least one is required; there is no useful metadata document
// without one.
AuthorizationServers []string
// ScopesSupported is advertised so a client knows what to ask for, in bare
// form; ScopePrefix is applied on the way out. Ingest is never included:
// memstore refuses it on an OAuth credential regardless, and advertising it
// would invite a request that cannot be honoured.
ScopesSupported []string
// ScopePrefix namespaces this resource's scopes at the authorization
// server -- "memstore:" where one server serves several resources, empty
// where it does not. It must match what the verifier is configured with,
// or memstore would advertise scopes it then refuses to recognise.
ScopePrefix string
}
ProtectedResource describes this deployment's MCP endpoint as an OAuth 2.1 protected resource. The zero value means OAuth is not configured, which is the current default -- see docs/mcp-oauth-scope.md for why the verifier is not enabled in production until webauth can express a scope grant.
func (ProtectedResource) Configured ¶
func (p ProtectedResource) Configured() bool
Configured reports whether OAuth discovery is set up.
func (ProtectedResource) Metadata ¶
func (p ProtectedResource) Metadata() *oauthex.ProtectedResourceMetadata
Metadata builds the RFC 9728 document.
func (ProtectedResource) MetadataHandler ¶
func (p ProtectedResource) MetadataHandler() http.Handler
MetadataHandler serves the document, unauthenticated and CORS-open. Both are required by RFC 9728 §3.1: this is public configuration data, fetched by clients that by definition do not have a credential yet.
func (ProtectedResource) MetadataPath ¶
func (p ProtectedResource) MetadataPath() string
MetadataPath is where the metadata document is served, rooted at the host.
func (ProtectedResource) MetadataURL ¶
func (p ProtectedResource) MetadataURL() string
MetadataURL is the absolute form of MetadataPath, as advertised in the WWW-Authenticate challenge.
func (ProtectedResource) ResourceURL ¶
func (p ProtectedResource) ResourceURL() string
ResourceURL is the canonical identifier of this protected resource: the absolute URL of the MCP endpoint. It is what a token's aud claim must name, and what a client sends as the RFC 8707 resource indicator.
func (ProtectedResource) Validate ¶
func (p ProtectedResource) Validate() error
Validate reports whether p can produce a usable metadata document.
type ProvisioningResolver ¶
type ProvisioningResolver struct {
// contains filtered or unexported fields
}
ProvisioningResolver resolves an OAuth caller to a local memstore user, creating one on first sight of a subject.
It is a thin adapter: the policy -- key on (issuer, subject), never match by email, sync mutable claims onto the existing row -- lives in github.com/infodancer/oidclient/rpuser, shared with the websites, and the SQL lives in pgstore. What is here is the conversion from rpuser's string key to the int64 the store layer scopes by.
This is memstore's implementation of decision 5 in docs/mcp-oauth-scope.md: admission is the authorization server's decision to express, so a validated token for an unknown subject provisions rather than being refused. That delegation is only real once webauth can express the grant (sections B1-B3), which is why the OAuth path is not enabled in production before then.
func NewProvisioningResolver ¶
func NewProvisioningResolver(store rpuser.UserStore, issuer string, logf func(string, ...any)) (*ProvisioningResolver, error)
NewProvisioningResolver returns a resolver over store, provisioning users for tokens issued by issuer. The issuer is the configured one the resource server validates against, not a value read out of a token.
func (*ProvisioningResolver) ResolveUser ¶
func (r *ProvisioningResolver) ResolveUser(ctx context.Context, tok *oidclient.AccessToken) (int64, error)
ResolveUser implements UserResolver.
type SessionContext ¶
type SessionContext struct {
// contains filtered or unexported fields
}
SessionContext tracks per-session file access for recall context boosting. It maintains an in-memory ring buffer of recently touched files per session.
func NewSessionContext ¶
func NewSessionContext() *SessionContext
NewSessionContext creates a context tracker with background cleanup of idle sessions.
func (*SessionContext) FilterSeen ¶
func (sc *SessionContext) FilterSeen(sessionID string, ids []int64) []int64
FilterSeen removes fact IDs that have already been returned in this session. Returns the subset of IDs that are new.
func (*SessionContext) MarkSeen ¶
func (sc *SessionContext) MarkSeen(sessionID string, ids []int64)
MarkSeen records fact IDs as having been returned in this session.
func (*SessionContext) RecentFiles ¶
func (sc *SessionContext) RecentFiles(sessionID string) []string
RecentFiles returns the recently accessed files for a session.
func (*SessionContext) Stop ¶
func (sc *SessionContext) Stop()
Stop terminates the background cleanup goroutine.
func (*SessionContext) TouchFiles ¶
func (sc *SessionContext) TouchFiles(sessionID string, files []string)
TouchFiles records file paths as recently accessed for a session.
type TokenVerifier ¶
TokenVerifier resolves a presented bearer token to an Identity. It is the integration seam between httpapi and any concrete token store (currently pgstore.TokenStore). Returning a non-nil error means "401, do not auth"; callers must not leak the underlying reason in the response body.
type UserResolver ¶
type UserResolver interface {
ResolveUser(ctx context.Context, tok *oidclient.AccessToken) (int64, error)
}
UserResolver maps a verified token subject to a local memstore user id.
Implementations own the provisioning policy. memstore's decision (decision 5 of the scope doc) is to autoprovision: admission is the authorization server's decision to express, not a roster memstore maintains in parallel and has to keep in sync. The subject is the key -- never the email, which can change and at some providers can be released and re-registered by a different person, which would make account takeover a matter of waiting for an address to be recycled. Email is passed for storage as a display attribute only.
The whole token is passed rather than a subject and an email, because a provisioning policy also records email_verified and the display name -- narrowing the argument list here would silently discard them and pin email_verified to false on every row.
type WhoAmIResponse ¶
type WhoAmIResponse = memstore.WhoAmIResponse
WhoAmIResponse is the wire shape of GET /v1/whoami. It is an alias for the root-package type so httpclient can decode it without importing this package (and with it the whole server) into every client binary.