apikit

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

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

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout bounds an op that states no Timeout.

Variables

This section is empty.

Functions

func ExactlyOne

func ExactlyOne(args []string) []*huma.Schema

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 GroupOf

func GroupOf(op string) string

GroupOf is the group an op name belongs to: its first segment.

func Mount

func Mount[R, C, From any](into *Registry[R], from *Registry[From], name string, m Mounting[R, C, From])

Mount serves from's op named name in into, with m. It panics, as Register does, on an op from does not hold, a name into already holds, or a malformed m.

func Register

func Register[R, C, In, Out any](reg *Registry[R], adm Admission[R, C], d *Def[C, 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[R, C any] struct {
	// Admit resolves the request into C, 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 R) (C, error)
	// Authorize checks what the admitted caller may do with this input: a
	// permission derived from it, say. in is the op's In. Nil: admission is all.
	Authorize func(ctx context.Context, r R, c C, in any) error
}

Admission is how a host turns a request into the call context a handler receives. R is what the host's transports pass for each request — its credential; C is what its handlers take.

type Args

type Args = map[string]any

Args is an op's input as the client sent it: a JSON object, by field name, before it is validated. What a mounting host authorizes from.

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[C, 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; zero means DefaultTimeout.
	Timeout time.Duration

	HTTP bool // served at POST /api/<Name>
	MCP  bool // served as an MCP tool named Name

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

	// 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 C, in In) (Out, error)
}

Def declares one operation: what it takes, what it answers, and how it runs. C is the call context its handler receives — the caller, as the host's Admission resolves it.

type Discovery

type Discovery[R 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 R, 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[R]) Group

func (d Discovery[R]) Group(ctx context.Context, reg *Registry[R], r R, 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[R]) Index

func (d Discovery[R]) Index(ctx context.Context, reg *Registry[R], r R, 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[R]) Usage

func (d Discovery[R]) Usage(ctx context.Context, rt *Runtime, reg *Registry[R], r R, 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 GroupEntry

type GroupEntry struct {
	Name    string `json:"name"`
	Summary string `json:"summary"`
}

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[R 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) (R, 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.
	After func(w http.ResponseWriter, out any)
	// 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 R, 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. 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[R]) Handler

func (h HTTP[R]) Handler(rt *Runtime, reg *Registry[R]) http.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.

func (HTTP[R]) Spec

func (h HTTP[R]) Spec(rt *Runtime, reg *Registry[R]) ([]byte, error)

Spec is the OpenAPI document for reg's HTTP ops, in YAML, built without a server: what the server publishes, for a committed snapshot and generated clients.

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[R any] struct {
	// Name and Version name the server to clients.
	Name, Version string
	// Codes are what the server serves: a failed tool's body is its code's.
	Codes httpkit.Codes
	// Request reads what the session's ops are admitted from, from the request
	// that opens it: its credential. Required.
	Request func(r *http.Request) (R, error)
	// Visible reports which ops the caller may call (HTTP.Visible). Nil: every op.
	Visible func(ctx context.Context, r R, 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: the server for a session is built from the request that opens it, through Request and Visible. Named tools keep a client's per-tool approval and the read-only hints; one generic "run" tool would make approval all-or-nothing.

func (MCP[R]) Handler

func (m MCP[R]) Handler(rt *Runtime, reg *Registry[R]) http.Handler

Handler is the MCP endpoint, to mount at /mcp behind the same middleware and guards as the HTTP API.

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 Mounting

type Mounting[R, C, From any] struct {
	// Admit resolves the request into the host's caller, or refuses it. Required.
	Admit func(ctx context.Context, r R) (C, error)
	// Authorize checks what the caller may do with this input. Nil: admission
	// is all.
	Authorize func(ctx context.Context, r R, c C, input Args) error
	// Bind builds what the mounted op is admitted from, for this caller.
	// Required.
	Bind func(ctx context.Context, c C) (From, error)
	// Overlay amends the op's declaration for this host — its doc, its timeout,
	// its Ext — never its name, schemas or codes. Nil: as it is.
	Overlay func(m Meta) Meta
}

Mounting is how a host serves another registry's op as it is — its name, schemas, handler and codes unchanged — under its own admission. R is what the host's transports pass; C is the host's caller; From is what the mounted op is admitted from (the engine's invocation, say).

A call runs Admit, then Authorize, then Bind, then the mounted op, which validates its input and runs. So authorization sees the input as the client sent it, not yet validated: a caller who may not call the op is refused before anything about the input is said.

type Op

type Op[R 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() reflect.Type
	// Invoke runs the op on raw JSON input, for the request r.
	Invoke(ctx context.Context, rt *Runtime, r R, raw []byte) (any, 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"`
}

OpEntry is an op in its group's listing.

type Registry

type Registry[R any] struct {
	// contains filtered or unexported fields
}

Registry is the set of ops one server serves, all admitted from the same per-request R. The composition root makes one and passes it to each module, which registers its ops with Register.

func NewRegistry

func NewRegistry[R any](c RegistryConfig[R]) *Registry[R]

NewRegistry returns an empty registry.

func (*Registry[R]) Group

func (r *Registry[R]) Group(name, summary string)

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[R]) Lookup

func (r *Registry[R]) Lookup(n string) (Op[R], bool)

Lookup returns the op named n.

func (*Registry[R]) Ops

func (r *Registry[R]) Ops() []Op[R]

Ops returns the registered ops, in registration order.

type RegistryConfig

type RegistryConfig[R 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 request — who called, in
	// which org — for its log entry and span. Nil: none.
	StepParams func(r R) []any
}

RegistryConfig is what a registry needs of its host.

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

func (*Runtime) Inline

func (rt *Runtime) Inline(s *huma.Schema) (map[string]any, error)

Inline is s as a self-contained JSON Schema: every reference into Schemas replaced by what it names. For a document that must stand alone — an MCP tool's input, an op's usage. A schema that refers to itself cannot be inlined, and is an error.

func (*Runtime) Schema

func (rt *Runtime) Schema(t reflect.Type) *huma.Schema

Schema is t's JSON Schema, as Invoke validates against it: a reference into Schemas for a named type, inline for the empty struct. Transports publish it, so what is validated and what is published are the same.

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

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.

Directories

Path Synopsis
internal
decode
Package decode is how apikit reads an op's input and checks its output, against the schemas huma generates from the Go types.
Package decode is how apikit reads an op's input and checks its output, against the schemas huma generates from the Go types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL