Documentation
¶
Overview ¶
Package apikit is the API framework the anfra hosts share: an operation is declared once, as a Def, and served by every host and transport the same way — its input validated against the schema of its type, its errors rendered from their codes, its OpenAPI derived from both.
A host adds what is its own through hooks, never by forking the framework: who may call an op and how a request becomes the caller a handler receives (Admission), which codes it serves and with which HTTP status (httpkit.Codes), and what its transport reads and writes beyond the op (HTTP's hooks). `anfra serve` admits everyone; a hosted server resolves sessions, orgs and permissions. The handler and its input and output types do not change.
The design is anfra-cloud's api_framework.md.
Index ¶
- Constants
- func CheckRef[Call, In any](set OpSet[Call], ref OpRef[In]) error
- func ExactlyOne(args []string) []*huma.Schema
- func GroupOf(op string) string
- func Mount[Call, Caller, BoundCall, In any](into *Registry[Call, Caller], from OpSet[BoundCall], ref OpRef[In], ...)
- func OutputType(out reflect.Type) reflect.Type
- func Register[Call, Caller, In, Out any](reg *Registry[Call, Caller], adm Admission[Call, Caller], ...)
- type Admission
- type Base
- type Def
- type Discovery
- func (d Discovery[Call]) Group(ctx context.Context, reg OpSet[Call], r Call, include func(Meta) bool, ...) (GroupListing, error)
- func (d Discovery[Call]) Index(ctx context.Context, reg OpSet[Call], r Call, include func(Meta) bool) (Index, error)
- func (d Discovery[Call]) Usage(ctx context.Context, rt *Runtime, reg OpSet[Call], r Call, ...) (Usage, error)
- type ErrorEntry
- type Events
- type Execution
- type Executor
- type GroupEntry
- type GroupListing
- type HTTP
- type Index
- type MCP
- type Meta
- type MountOption
- type Mounting
- type Op
- type OpEntry
- type OpRef
- type OpSet
- type Registry
- type RegistryConfig
- type Run
- type Runtime
- type ScopeRequirements
- type StreamEnd
- type StreamPing
- type StreamStart
- type StreamStatus
- type Submission
- type Usage
- type Work
Constants ¶
const DefaultTimeout = 30 * time.Second
DefaultTimeout bounds an op that states no Timeout.
const NDJSON = "application/x-ndjson"
NDJSON is the media type of a streamed response: one JSON event per line.
Variables ¶
This section is empty.
Functions ¶
func CheckRef ¶ added in v0.11.1
CheckRef reports whether ref names an op of set that takes ref's input: for a registry to test the refs it exports.
func ExactlyOne ¶
ExactlyOne is the schema of a group of fields of which exactly one must be set, for an input type's schema to carry in OneOf (huma.SchemaTransformer): a oneOf over each field being required. A caller missing the group, or setting more than one, is told which fields to fix.
func Mount ¶
func Mount[Call, Caller, BoundCall, In any](into *Registry[Call, Caller], from OpSet[BoundCall], ref OpRef[In], m Mounting[Call, Caller, BoundCall, In], opts ...MountOption)
Mount serves from's op that ref names in into, with m and opts. It panics, as Register does, on an op from does not hold, one that does not take ref's input, a name into already holds, or a malformed m.
func OutputType ¶ added in v0.11.1
OutputType is what an op whose handler returns out answers: a Run's page, or out itself.
func Register ¶
func Register[Call, Caller, In, Out any](reg *Registry[Call, Caller], adm Admission[Call, Caller], d *Def[Caller, In, Out])
Register checks d and adds it to reg, admitted by adm, as huma.Register and mcp.AddTool do for theirs. A malformed declaration, or a name reg already holds, panics: a wiring mistake, and failing at startup is the only safe answer.
The op is a copy of d, taken now, so a later change to d does not change the running op. Ext is copied as a value; a host keeps it free of anything it would mutate.
Types ¶
type Admission ¶
type Admission[Call, Caller any] struct { // Admit resolves the request into Caller, or refuses it. It runs before the input // is read, so a caller who may not call the op cannot probe its validation. Admit func(ctx context.Context, r Call) (Caller, error) // Authorize checks what the admitted caller may do with this input: a // permission derived from it, say. in is the op's In, as Def.Prepare answers // it. Nil: admission is all. Authorize func(ctx context.Context, r Call, c Caller, in any) error }
Admission is how a host turns a request into the call context a handler receives. Call is what the host's transports pass for each request — its credential; Caller is what its handlers take.
type Base ¶
type Base struct {
Path string
Variables map[string]*huma.ServerVariable
}
Base is a path below /api that ops are served under, with variables: "/o/{org}". A variable is a path wildcard to the router (r.PathValue("org")) and a server variable to the OpenAPI document, which requires a default.
type Def ¶
type Def[Caller, In, Out any] struct { // Name is the op's name: dotted, group then verb ("invitations.create"). It // routes the op (POST /api/<Name>), names its MCP tool, and groups it for // discovery. Name string Summary string // one line Doc string // full usage, written for an agent: when to use it, the common mistake // Errors are the public codes the op itself returns, beyond those the host's // admission and transports produce. Published in OpenAPI; checked in strict // mode. Errors []apperr.AnyCode // ReadOnly: the op changes nothing, so a client may retry it freely. // Idempotent: repeating it with the same input has no further effect. // NonDestructive: the op changes things, but only adds to them; it deletes // and overwrites nothing. Meaningless for a ReadOnly op. Unset, an op that // changes things may destroy something, as MCP assumes too. // POST-only routing carries no method semantics, so the op states them; they // feed MCP's tool hints and client retry policy. ReadOnly bool Idempotent bool NonDestructive bool // Timeout bounds the op's own work — its handler, and a Run's work from // when it starts (Run) — zero means DefaultTimeout. Timeout time.Duration HTTP bool // served at POST /api/<Name> MCP bool // served as an MCP tool named Name // Events are the types a Run's events may be, one value of each, when its // Event type is an interface: each its own schema, told apart by its type. // Empty when Event is one struct. Events []any // Ext is the host's own declaration of the op, carried to Meta for the host's // transports: who may call it, its rate limit. apikit never reads it. Ext any // Prepare readies the decoded input for authorization and the handler: what // the schema publishes but validation does not apply (defaults), and the // rules between fields that it does not state. Authorization and the handler // see the input it answers. It reads nothing but the input — no store, no // repo — since it runs before authorization: a caller refused there must // learn nothing from it. Nil: the input as decoded. Prepare func(in In) (In, error) // Handle is glue: it maps In to a service call and the result to Out, with no // branching on domain state. Handle func(ctx context.Context, c Caller, in In) (Out, error) }
Def declares one operation: what it takes, what it answers, and how it runs. Caller is the call context its handler receives — the caller, as the host's Admission resolves it.
type Discovery ¶
type Discovery[Call any] struct { // Visible reports which of ops the caller of r may call: the host's // admission and fixed permissions, short of the input. Nil: every op. Visible func(ctx context.Context, r Call, ops []Meta) ([]bool, error) // Errors are the codes the host adds to an op (HTTP.Errors), and Codes how // it serves them: an op's usage lists both with its own. Errors func(m Meta) []apperr.Code Codes httpkit.Codes }
Discovery renders a registry's ops in three levels, for an agent to drill through instead of reading a whole contract: the index (each group, in one line), a group (its ops, each in one line), and an op's usage (its doc, schemas and codes). Every level shows only what the caller may call, as the host's Visible says. HTTP and MCP serve the same levels.
func (Discovery[Call]) Group ¶
func (d Discovery[Call]) Group(ctx context.Context, reg OpSet[Call], r Call, include func(Meta) bool, group string) (GroupListing, error)
Group is group's ops the caller may call; not_found for a group with none.
func (Discovery[Call]) Index ¶
func (d Discovery[Call]) Index(ctx context.Context, reg OpSet[Call], r Call, include func(Meta) bool) (Index, error)
Index is the groups whose ops, among those include admits, the caller may call, in the order their first op was registered.
func (Discovery[Call]) Usage ¶
func (d Discovery[Call]) Usage(ctx context.Context, rt *Runtime, reg OpSet[Call], r Call, include func(Meta) bool, name string) (Usage, error)
Usage is the op named name, for a caller who may call it; not_found otherwise, alike, so discovery does not reveal an op the caller cannot see.
type ErrorEntry ¶
type ErrorEntry struct {
Code string `json:"code"`
Scope string `json:"scope"`
Message string `json:"message"`
}
ErrorEntry is a code an op can fail with.
type Events ¶ added in v0.11.1
type Events[Event any] struct { // contains filtered or unexported fields }
Events is how a Run's Stream emits: its own events, and its phase.
func NewEvents ¶ added in v0.11.1
NewEvents is Events sending to emit: for reading a Run's stream outside a transport, as a test does.
type Execution ¶ added in v0.11.1
Execution is a run as its executor executes it: its id, and the same Page and Stream as the run's work — the run's own, or the executor's around them. ID is sent on the stream's start; "" for an executor that keeps no record. Every Execution Submit answers is executed exactly once, by its Page or its Stream — with a cancelled context when its client left before it began — so an executor always sees the end of what it took.
type Executor ¶ added in v0.11.1
type Executor[Caller any] interface { // Submit takes a run an op has accepted, for caller, before anything of it // is sent. It may refuse it: the call is answered that error, as any // before the run. Otherwise it answers the run's Execution; nothing of the // run is done until the Execution's Page or Stream is called. Submit(ctx context.Context, caller Caller, s Submission) (Execution, error) }
Executor executes a registry's runs: when and where each runs, and what is kept of it. The registry's (RegistryConfig.Executor) executes the runs of its ops, mounted ones included; with none, each run is executed now, in its call.
type GroupEntry ¶
GroupEntry is a group in the index.
type GroupListing ¶
type GroupListing struct {
Name string `json:"name"`
Summary string `json:"summary"`
Ops []OpEntry `json:"ops"`
}
GroupListing is a group's ops the caller may call.
type HTTP ¶
type HTTP[Call any] struct { // Codes are what the server serves, with their statuses: an op's error // responses, and every error's rendering. Codes httpkit.Codes // Title and Version are the OpenAPI document's info; Extensions its own // extensions (a compatibility number, say). Title, Version string Extensions map[string]any // Request reads what the op is admitted from: the request's credential, and // the base's path values (r.PathValue). It may write to w — clearing a cookie // that no longer resolves, say. Required. Request func(w http.ResponseWriter, r *http.Request) (Call, error) // Base is where an op is served below /api, or nil for /api itself. Base func(m Meta) *Base // Guard returns the check an op's requests pass before the body is read — a // compatibility header, a rate limit — or nil for none. It is called once per // op, when the handler is built. Guard func(m Meta) func(w http.ResponseWriter, r *http.Request) error // After sees a successful output before it is written: setting a cookie the // op asked for, say. A stream has no output, and is not seen. After func(w http.ResponseWriter, out any) // BeforeError sees the original error before an HTTP error response begins. // It may set headers only; httpkit still owns status, body and logging. // Errors carried inside an already-started stream do not call it. Nil: none. BeforeError func(w http.ResponseWriter, r *http.Request, err error) // Headers are the request headers the host reads for an op, published with // it. Headers func(m Meta) []*huma.Param // Errors are the codes the host's admission and Guard can answer an op with, // published with the codes it declares, in this order. Errors func(m Meta) []apperr.Code // Visible reports which ops the caller may call, for discovery (Discovery). // Nil: every op. Visible func(ctx context.Context, r Call, ops []Meta) ([]bool, error) }
HTTP serves a registry's HTTP ops: every op at POST /api/<name> — or below a base the host gives it, /api/o/{org}/<name> — its whole input as the JSON body, its output as the body of a 200, an error as its code's body. An op that returns a Run answers its page, or streams its events as NDJSON to a request that accepts them (Accept: application/x-ndjson). It translates and nothing more: the op layer validates, admits and runs; the host's hooks add what is its own.
In the OpenAPI document an op's path is its name alone, /<name>, below the server it is served from: /api, or its base. So an op has the same path on every host, whatever base one serves it under, and a client takes the base once, when it is built.
func (HTTP[Call]) Handler ¶
Handler is the router with every HTTP op registered. Anything else under /api is a JSON not_found, not whatever is mounted beside it: an API typo that answers 200 with HTML is much harder to diagnose than one that says so. It has no middleware: wrap it in httpkit.Wrap, which renders errors with h.Codes.
type Index ¶
type Index struct {
Groups []GroupEntry `json:"groups"`
}
Index is the top level: every group with at least one op the caller may call.
type MCP ¶
type MCP[Call any] struct { // Name and Version name the server to clients. Name, Version string // Stateless resolves the caller and tools for every HTTP request. No MCP // session ID conveys authority. The default preserves stateful local serving. Stateless bool // Codes are what the server serves: a failed tool's body is its code's. Codes httpkit.Codes // Request reads the caller's credential from each request in stateless mode, // or the session-opening request otherwise. Required. Request func(r *http.Request) (Call, error) // Visible reports which ops the caller may call (HTTP.Visible). Nil: every op. Visible func(ctx context.Context, r Call, ops []Meta) ([]bool, error) // Errors are the codes the host adds to an op (HTTP.Errors), for // describe_operation. Errors func(m Meta) []apperr.Code }
MCP serves a registry's MCP ops as tools over MCP's streamable HTTP: one named tool per op that declares MCP — its input schema the one HTTP validates, its result the op's output, its failure the same error body HTTP renders — and two tools of discovery, list_operations and describe_operation, the same levels HTTP serves at /ops.
Each session gets the tools its caller may call, through Request and Visible. Stateless hosts rebuild these from every HTTP request, so credentials and visibility are never captured across requests. Named tools keep a client's per-tool approval and the read-only hints.
type Meta ¶
type Meta struct {
Name, Summary, Doc string
Errors []apperr.Code
ReadOnly bool
Idempotent bool // implied by ReadOnly
Destructive bool // it changes things, and may delete or overwrite: not ReadOnly, nor NonDestructive
Timeout time.Duration
HTTP bool
MCP bool
Ext any
}
Meta is an op's declaration without its types.
type MountOption ¶ added in v0.11.1
type MountOption func(*Meta)
MountOption amends a mounted op's declaration for the host serving it: never its name, schemas or codes, which are the op's.
func AppendDoc ¶ added in v0.11.1
func AppendDoc(doc string) MountOption
AppendDoc adds what is particular to calling the op on this host after the op's own doc.
func WithExt ¶ added in v0.11.1
func WithExt(ext any) MountOption
WithExt is the host's own declaration of the op (Def.Ext), for its transports and executor.
func WithTimeout ¶ added in v0.11.1
func WithTimeout(d time.Duration) MountOption
WithTimeout bounds the op on this host, as the op's own timeout does — its handler, and its run from when the run starts — when it is the tighter. Zero: the op's own.
type Mounting ¶
type Mounting[Call, Caller, BoundCall, In any] struct { // Admit resolves the call into the host's caller, or refuses it. It runs // before the input is read. Required. Admit func(ctx context.Context, call Call) (Caller, error) // Authorize checks what the caller may do with the input, as the op // prepared it, and answers the caller Bind gets: narrowed to what it was // authorized for, say. It must not change in. Nil: admission is all, and // Bind gets the caller Admit answered. Authorize func(ctx context.Context, call Call, caller Caller, in In) (Caller, error) // Bind builds what the mounted op is called with, for this caller. // Required. Bind func(ctx context.Context, caller Caller) (BoundCall, error) }
Mounting is how a host serves another registry's op as it is — its name, schemas, handler and codes unchanged — under its own admission. Call is what the host's transports pass; Caller is the host's caller; BoundCall is what the mounted op is called with: its own registry's Call (the engine's Invocation, say); In is the op's input, as its OpRef says.
A call runs Admit; then the op's decoding and preparation (Def.Prepare); then Authorize, on the prepared input; then Bind, with the caller Authorize answered; then the mounted op, on the same input, decoded once. A run it returns is the host's: submitted to the host's registry's executor, for the host's caller.
type Op ¶
type Op[Call any] interface { Meta() Meta // InSchema is the input's schema, as Invoke validates it: transports publish // it, so what is validated and what is published are the same. InSchema(rt *Runtime) *huma.Schema // OutType is what Invoke answers: the output, or a Run's page. OutType() reflect.Type // EventTypes are what InvokeStream emits, beside apikit's own events: a // Run's events, of one type or several (Def.Events). Nil for an op that does // not return a Run, which only Invoke serves. EventTypes() []reflect.Type // Invoke runs the op on raw JSON input, for the request r. An op that // returns a Run answers its page. Invoke(ctx context.Context, rt *Runtime, r Call, raw []byte) (any, error) // InvokeStream runs an op that returns a Run, emitting its events. An error // returned before the first event is the op refusing, as Invoke's would be; // after it, the run failing. InvokeStream(ctx context.Context, rt *Runtime, r Call, raw []byte, emit func(event any) error) error }
Op is a registered op, its types hidden: what a Registry holds and transports iterate. Only Register makes one.
type OpEntry ¶
type OpEntry struct {
Name string `json:"name"`
Summary string `json:"summary"`
ReadOnly bool `json:"read_only"`
Idempotent bool `json:"idempotent"`
Destructive bool `json:"destructive"`
RequiredScopes []string `json:"required_scopes,omitempty"`
PossibleRequiredScopes []string `json:"possible_required_scopes,omitempty"`
}
OpEntry is an op in its group's listing.
type OpRef ¶ added in v0.11.1
OpRef names an op with its input type: what a host mounts an op by, so that its authorization reads the op's input, typed, and a derivation for another type does not compile. A registry whose ops hosts mount exports one per op they authorize on; Mount checks, at startup, that the op named takes In.
type OpSet ¶ added in v0.11.1
type OpSet[Call any] interface { // Ops are the ops, in registration order. Ops() []Op[Call] // Lookup is the op named name. Lookup(name string) (Op[Call], bool) // GroupSummary is a declared group's one-line summary; "" for none. GroupSummary(group string) string }
OpSet is a registry's ops as its transports serve them, whatever its Caller: what HTTP, MCP and Discovery take, and Mount mounts from.
type Registry ¶
type Registry[Call, Caller any] struct { // contains filtered or unexported fields }
Registry is the set of ops one server serves: called with the same Call (what its transports pass for each call), and admitted into the same Caller (whom a call is for). The composition root makes one and passes it to each module, which registers its ops with Register.
func NewRegistry ¶
func NewRegistry[Call, Caller any](c RegistryConfig[Call, Caller]) *Registry[Call, Caller]
NewRegistry returns an empty registry.
func (*Registry[Call, Caller]) Group ¶
Group declares a group of ops — the first segment of their names — with its one-line summary: the index level of discovery. An op is registered only into a declared group, so the index never shows a blank. Declaring a group twice panics.
func (*Registry[Call, Caller]) GroupSummary ¶ added in v0.11.1
GroupSummary is the group's summary, as declared (Group); "" for none.
type RegistryConfig ¶
type RegistryConfig[Call, Caller any] struct { // Namespace is the host's: each op's private step is op.<name> in it. Namespace apperr.Namespace // StepParams are an op step's parameters for a call — who called, in which // org — for its log entry and span. Nil: none. StepParams func(call Call) []any // Executor executes the runs of the registry's ops, mounted ones included. // Nil: each run is executed now, in its call. Executor Executor[Caller] }
RegistryConfig is what a registry needs of its host.
type Run ¶ added in v0.11.1
type Run[Page, Event any] struct { Page func(ctx context.Context) (Page, error) Stream func(ctx context.Context, events Events[Event]) error }
Run is the output of an op that answers as it works: what its handler returns instead of a finished value, when the work is long or its result large. Its work is done when it is executed — by its registry's executor — in the form its transport takes:
- Page: the work, then one answer — what a JSON client, MCP and the CLI get. It is the op's output as discovery and OpenAPI describe it.
- Stream: the work, emitting its events as they happen — progress, then the result in batches — for a client that follows it (HTTP, Accept: application/x-ndjson).
The op's timeout bounds the handler, and the work from when it starts — when its executor calls Page or Stream — not what the executor does before (waiting for capacity, say). The op's step spans both: the work runs inside the op, only later than its handler.
Neither is called more than once, nor both. A handler builds a Run from closures over its input; the handler itself checks the input and returns without doing the work, so that what it refuses is an ordinary error, before the stream starts.
A stream's events ¶
Every event is a JSON object whose "type" names it. A stream is:
- start: first, as soon as the handler has returned the Run — the op has accepted the request. Its status is sent with it, so what fails after it is reported in the stream (end), not as an error response;
- status: the run's phase, whenever the op reports one (Events.Status);
- the op's own events (Events.Emit), of its Event type;
- end: always last, once — succeeded, or failed with the error as an error response's body would carry it. A stream without one was cut;
- ping: while nothing else is sent, so that proxies do not close it as idle.
apikit owns start, status, end and ping; an op's Event type names its own types, none of them those (Register checks).
type Runtime ¶
type Runtime struct {
// Schemas holds the JSON Schemas generated from op types. Transports share
// it: HTTP builds its OpenAPI from it, MCP its tool schemas, so the validated
// schema and the published one are the same.
Schemas huma.Registry
// Strict fails an op that returns a public code it did not declare, or an
// output that does not match its schema. On in tests, so the OpenAPI built
// from the declarations cannot quietly lie.
Strict bool
// Implied are the public codes the host's admission and transports produce,
// which no op declares. With apikit's own (internal_server_error,
// invalid_request), strict mode accepts them from any op.
Implied []apperr.Code
// Timeout makes the error of an op that ran out of its time the host's —
// its "unavailable", say. Nil leaves the error as it is. Its code is implied
// for every op, as Implied's are: an op cannot know it, least of all a
// mounted one, whose host's timeout may be the one that ran out.
Timeout func(err error) error
}
Runtime is what Invoke needs beyond the op: one per server.
func NewRuntime ¶
func NewRuntime() *Runtime
NewRuntime returns a runtime with a fresh schema registry.
type ScopeRequirements ¶ added in v0.12.0
type ScopeRequirements interface {
OAuthScopeRequirements() (required, possible []string)
}
ScopeRequirements is optional host metadata, not an authorization decision. Derived requirements describe candidate visibility; invocation checks exact input.
type StreamEnd ¶ added in v0.11.1
type StreamEnd struct {
Type string `json:"type" enum:"end"`
Status string `json:"status" enum:"succeeded,failed"`
Error *apperr.Response `json:"error,omitempty"`
}
StreamEnd is a stream's last event: how the run ended. Error is set when it failed, as an error response's body would carry it.
type StreamPing ¶ added in v0.11.1
type StreamPing struct {
Type string `json:"type" enum:"ping"`
}
StreamPing is sent while a stream has nothing else to send, so that proxies do not close it as idle. It carries nothing.
type StreamStart ¶ added in v0.11.1
type StreamStart struct {
Type string `json:"type" enum:"start"`
ID string `json:"id,omitempty" doc:"the run's id, on a host that keeps a record of runs"`
}
StreamStart is a stream's first event: the op has accepted the request, and its executor the run. ID is the run's, when the executor keeps a record of runs: to come back to it.
type StreamStatus ¶ added in v0.11.1
type StreamStatus struct {
Type string `json:"type" enum:"status"`
Phase string `json:"phase"`
// Position is, while queued, how many runs are ahead of this one: 0 is next.
// Absent for any other phase, and when the executor does not say.
Position *int `json:"position,omitempty" doc:"while queued: how many runs are ahead of this one, 0 being next; absent otherwise"`
}
StreamStatus is the run's phase, as the op reports it — or, before the run starts, as its executor does: "queued", while it waits for capacity, with its place in line when the executor knows it.
type Submission ¶ added in v0.11.1
type Submission struct {
// Op is the op, as the registry serving it declares it: for a mounted op,
// the mounting registry's declaration, its Ext the host's.
Op Meta
// Input is the op's input as its handler received it: decoded, validated
// and prepared (Def.Prepare) — the value the run runs on, of the op's In:
// for a mounted op, the mounted op's. For an executor that keeps it, to
// record what was asked, or to run it again.
Input any
Work Work
}
Submission is a run handed to the executor: of which op, on what input, and its work.
type Usage ¶
type Usage struct {
Name string `json:"name"`
Summary string `json:"summary"`
Doc string `json:"doc,omitempty"`
ReadOnly bool `json:"read_only"`
Idempotent bool `json:"idempotent"`
Destructive bool `json:"destructive"`
Input map[string]any `json:"input"`
Output map[string]any `json:"output"`
Errors []ErrorEntry `json:"errors"`
RequiredScopes []string `json:"required_scopes,omitempty"`
PossibleRequiredScopes []string `json:"possible_required_scopes,omitempty"`
// Events are what the op streams, over HTTP with Accept:
// application/x-ndjson, instead of answering its page: for an op that
// returns a Run.
Events []map[string]any `json:"events,omitempty"`
}
Usage is all an agent needs to call an op: what it is for, what it takes, what it answers, and how it can fail.