op

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package op is the operation registry. A tool declares each operation once, with typed input and output structs, an effect and a handler. The CLI, HTTP API, OpenAPI document, MCP tools and metadata are all derived from that one declaration, and every surface calls the same Entry.Call.

Index

Constants

View Source
const (
	FieldApply   = "apply"
	FieldConfirm = "confirm"
)

Reserved wire fields the registry adds to inputs.

View Source
const MetadataSchemaID = "toolkit.metadata.v1"

MetadataSchemaID is the schema identifier of the metadata document.

Variables

This section is empty.

Functions

func Add

func Add[In, Out any](r *Registry, o Op[In, Out])

Add registers an operation. It panics on an invalid declaration, since that is a programming error found the first time the tool starts.

func MetadataSchema

func MetadataSchema() []byte

MetadataSchema returns the JSON Schema that every metadata document validates against.

Types

type Authorizer

type Authorizer interface {
	Authorize(ctx context.Context, e *Entry, req Request) error
}

Authorizer decides whether a remote caller may run an operation. The HTTP and HTTP-MCP surfaces consult it after input validation and confirmation.

var AllowAll Authorizer = AuthorizerFunc(func(context.Context, *Entry, Request) error { return nil })

AllowAll allows every call. Local surfaces (the CLI and stdio MCP) use it: their caller already runs the binary with the user's credentials.

var DenyWrites Authorizer = AuthorizerFunc(func(_ context.Context, e *Entry, req Request) error {
	if req.Apply && e.Effect.Mutates() {
		return &Error{Kind: KindAuth, Code: "write_not_authorized",
			Message:     e.Name + " would change state and this caller is not authorized to apply writes",
			Suggestions: []string{"preview without apply, or run the CLI on the host"}}
	}
	return nil
})

DenyWrites allows reads and previews, and refuses any call that would apply a write or destructive change. It is the default for served surfaces.

type AuthorizerFunc

type AuthorizerFunc func(ctx context.Context, e *Entry, req Request) error

AuthorizerFunc adapts a function to Authorizer.

func (AuthorizerFunc) Authorize

func (f AuthorizerFunc) Authorize(ctx context.Context, e *Entry, req Request) error

type Effect

type Effect string

Effect classifies what an operation does to the outside world.

const (
	// Read operations never change state.
	Read Effect = "read"
	// Write operations change state. They preview unless the caller sets apply.
	Write Effect = "write"
	// Destructive operations change state in a way that is hard to undo. They
	// preview unless the caller sets apply, and apply also requires confirm.
	Destructive Effect = "destructive"
)

func (Effect) Mutates

func (e Effect) Mutates() bool

Mutates reports whether the effect can change state.

type Entry

type Entry struct {
	Name    string
	CLIPath []string
	Summary string
	Effect  Effect
	MCP     bool
	// DefaultCommand is Op.DefaultCommand.
	DefaultCommand bool
	// Aliases is Op.Aliases.
	Aliases []string
	// CLIImmediate is Op.CLIImmediate.
	CLIImmediate bool
	// CLIConfirmed is Op.CLIConfirmed.
	CLIConfirmed bool
	// Paged is Op.Paged.
	Paged bool
	// CLIOnlyInputs are the json names of the input fields tagged
	// toolkit:"cli-only", sorted.
	CLIOnlyInputs []string
	In, Out       reflect.Type
	// contains filtered or unexported fields
}

Entry is the type-erased view of an operation that surfaces use.

func (*Entry) CLI

func (e *Entry) CLI() string

CLI is the command path as declared, e.g. "note <id> delete".

func (*Entry) Call

func (e *Entry) Call(ctx context.Context, req Request, in any) (any, error)

Call runs the handler. The surface, apply and confirm rules are enforced here, once, for every surface: a cli-only input set off the CLI is refused, reads never apply, and a destructive apply without confirmation is refused, all before the handler runs.

func (*Entry) CallJSON

func (e *Entry) CallJSON(ctx context.Context, req Request, raw json.RawMessage, auth Authorizer) (any, error)

CallJSON is the remote path used by HTTP and MCP: decode and validate the wire input, refuse cli-only inputs, enforce confirmation, authorize, then Call. A nil authorizer means DenyWrites.

func (*Entry) CanRender

func (e *Entry) CanRender() bool

CanRender reports whether the operation has a human render hook, Render or RenderWithInput.

func (*Entry) CommandKey

func (e *Entry) CommandKey() string

CommandKey is the CLI path without placeholders, e.g. "note delete".

func (*Entry) Decode

func (e *Entry) Decode(raw json.RawMessage) (in any, apply, confirm bool, err error)

Decode builds a typed input from wire JSON after validating it against the input schema. It returns the input pointer and the apply and confirm controls, which are removed from the object before decoding.

func (*Entry) InputSchema

func (e *Entry) InputSchema() *jsonschema.Schema

InputSchema is the JSON Schema of the wire input that HTTP and MCP accept, including the standard apply and confirm controls and omitting cli-only inputs. The caller gets a copy.

func (*Entry) MCPName

func (e *Entry) MCPName() string

MCPName is the MCP tool name and OpenAPI operationId. Dots are not valid in every model provider's function-name grammar, so they become underscores.

func (*Entry) NewInput

func (e *Entry) NewInput() any

NewInput returns a pointer to a fresh input with kong default tags applied.

func (*Entry) OutputSchema

func (e *Entry) OutputSchema() *jsonschema.Schema

OutputSchema is the JSON Schema of the result. The caller gets a copy.

func (*Entry) Render

func (e *Entry) Render(w io.Writer, out any) error

Render prints the human form of out. A RenderWithInput hook receives the zero input. It errors when there is no hook.

func (*Entry) RenderWithInput added in v0.1.4

func (e *Entry) RenderWithInput(w io.Writer, in, out any) error

RenderWithInput prints the human form of out for the call with input in, the *In that Decode returns, an In, or nil for the zero input. A Render hook ignores in. It errors when there is no hook.

func (*Entry) Warnings added in v0.1.3

func (e *Entry) Warnings(out any) []string

Warnings returns the warnings the operation's Warnings hook finds in out, or nil without a hook.

type Error

type Error struct {
	Kind        Kind     `json:"-"`
	Code        string   `json:"code"`
	Message     string   `json:"message"`
	Suggestions []string `json:"suggestions,omitempty"`
	// Retryable overrides whether a caller may retry. Unset, the CLI
	// envelope derives it from the kind (rate and timeout are retryable) and
	// HTTP and MCP omit it. Set, every surface prints it, false included.
	Retryable *bool `json:"retryable,omitempty"`
	// HTTPStatus is the status of the failed provider response, such as 503.
	// It is not the status of the toolkit's own HTTP response, which follows
	// the kind.
	HTTPStatus int `json:"http_status,omitempty"`
	// RetryAfterSeconds is how long the provider asked the caller to wait.
	// The HTTP surface also sends it as a Retry-After header.
	RetryAfterSeconds int `json:"retry_after_seconds,omitempty"`
	// RequestID is the provider's identifier of the failed request.
	RequestID string `json:"request_id,omitempty"`
	// Result is output the operation produced before it failed, such as the
	// per-item report of a batch that stopped part way. It must have the
	// operation's output type. Every surface returns it with the error: the
	// CLI prints it to stdout (rendered or as JSON) and the error to stderr,
	// and HTTP and MCP add it to the error body as "result".
	Result any `json:"-"`
}

Error is the one error type operations return. Its wire form, {code, message, suggestions}, is the same on every surface.

A failure that came from a provider response may also carry the details a caller needs to classify it and schedule a retry: Retryable, HTTPStatus, RetryAfterSeconds and RequestID. Each is added to the CLI JSON envelope, the HTTP error body and the MCP error result only when set, under the same key on every surface, so an error without them is unchanged. Carry only sanitized values: they reach every caller.

func AsError

func AsError(err error, fallback Kind) *Error

AsError returns err as an *Error. Errors that are not already an *Error get the fallback kind, and context deadlines map to KindTimeout.

func Errorf

func Errorf(kind Kind, code, format string, args ...any) *Error

Errorf builds an Error with a formatted message.

func (*Error) CLIError

func (e *Error) CLIError() *output.CLIError

CLIError converts the error to the shared output package's CLI error, so a tool's JSON error envelope and exit code stay as they are today. Its Retryable is the Retryable override, or else true for the rate and timeout kinds. The other provider details have no place in output.CLIError: the cli package adds them to the envelope it prints.

func (*Error) Error

func (e *Error) Error() string

type Kind

type Kind string

Kind is the surface-neutral error class. The CLI maps it to the family exit code, HTTP to a status, and MCP to an isError result.

const (
	KindError         Kind = "error"
	KindUsage         Kind = "usage"
	KindNotFound      Kind = "not_found"
	KindConflict      Kind = "conflict"
	KindDuplicateSend Kind = "duplicate_send"
	KindAuth          Kind = "auth"
	KindRate          Kind = "rate"
	KindTimeout       Kind = "timeout"
	KindStaleIndex    Kind = "stale_index"
	KindModelUnavail  Kind = "model_unavailable"
	KindPartial       Kind = "partial"
)

func (Kind) ExitCode

func (k Kind) ExitCode() int

ExitCode is the CLI exit code for the kind. Unknown kinds map to 1.

func (Kind) HTTPStatus

func (k Kind) HTTPStatus() int

HTTPStatus is the HTTP status for the kind. Unknown kinds map to 500.

type Metadata

type Metadata struct {
	Schema     string          `json:"schema"`
	Tool       string          `json:"tool"`
	Version    string          `json:"version"`
	Operations []OperationInfo `json:"operations"`
}

Metadata is the registry dump that `<tool> metadata --json` prints and `GET /ops` serves.

type Op

type Op[In, Out any] struct {
	// Name is the canonical dotted name, e.g. "note.delete".
	Name string
	// CLI is the command path, e.g. "note <id> delete". A word in angle
	// brackets is a positional argument owned by the parent command and fills
	// the string input field with that json name. Empty means Name with dots
	// replaced by spaces.
	CLI     string
	Summary string
	Effect  Effect
	// MCP exposes the operation as an MCP tool.
	MCP bool
	// DefaultCommand makes the last CLI word the default subcommand of its
	// parent, so "workflow <id> show" also runs as "workflow <id>", and
	// "items list" as "items". The word still works and is hidden from help.
	// At most one operation may be the default under a parent.
	DefaultCommand bool
	// Aliases are extra names of the last CLI word, as kong aliases: with
	// Aliases ["s"], "search <query>" also runs as "s <query>". They are
	// CLI-only and change no HTTP route, MCP name or operation name.
	Aliases []string
	// CLIImmediate makes the CLI apply a write or destructive operation
	// without --apply, for clearly scoped mutations such as "player pause".
	// The CLI gains --dry-run to preview instead and still accepts --apply as
	// a no-op. A destructive operation still needs --yes or a confirmed
	// prompt, unless it sets CLIConfirmed. HTTP and MCP are unchanged: they apply only with "apply": true,
	// and the served default authorizer still refuses applied writes.
	CLIImmediate bool
	// CLIConfirmed makes the command line itself the confirmation for a
	// destructive operation: with CLIImmediate it applies on the CLI with no
	// --yes or prompt. HTTP and MCP still need "apply": true and "confirm": true.
	// Needs Effect Destructive and CLIImmediate.
	CLIConfirmed bool
	// Paged declares that the output is a page: an object whose items array
	// holds the results, next to envelope keys such as next_cursor and
	// has_more. The CLI's --fields then keeps the named keys of each item and
	// every envelope key, rather than the named top-level keys. The output
	// must have an items array.
	Paged bool
	// Handler implements the operation. For write and destructive operations
	// it must not change state unless req.Apply is true.
	Handler func(ctx context.Context, req Request, in In) (Out, error)
	// Render optionally prints a human summary of the result. Without it the
	// CLI prints JSON.
	Render func(w io.Writer, out Out) error
	// RenderWithInput is Render for a summary that depends on the call, such
	// as a footer that repeats the caller's --limit. It receives the decoded
	// input. Set at most one of Render and RenderWithInput.
	RenderWithInput func(w io.Writer, in In, out Out) error
	// Warnings optionally lists warnings carried in the result. In human
	// output the CLI prints each to stderr as "warning: <text>" before the
	// result. With --json or --agent, and on HTTP and MCP, nothing extra is
	// printed: callers read the warnings in the result itself.
	Warnings func(out Out) []string
}

Op declares one operation. In is a struct. Out is usually a struct but may be any type that encodes to JSON: any and json.RawMessage declare an output that may be any JSON value, and map[string]any any JSON object. Input field tags carry both the wire shape (json) and the CLI shape (kong: arg, name, short, help, default).

An input field tagged toolkit:"cli-only", such as a flag that names a local file to read or write, is accepted only on the command line. HTTP and MCP input schemas and the metadata input omit it, the metadata lists it in cli_only_inputs, and a call on any other surface that sets it is refused with the usage error cli_only before the handler runs. The field must be optional (json omitempty) and have no default.

type OperationInfo

type OperationInfo struct {
	Name    string   `json:"name"`
	CLI     string   `json:"cli"`
	Aliases []string `json:"aliases,omitempty"`
	Summary string   `json:"summary"`
	Effect  Effect   `json:"effect"`
	MCP     bool     `json:"mcp"`
	MCPName string   `json:"mcp_name"`
	// CLIImmediate is Op.CLIImmediate: the CLI applies without --apply and
	// previews with --dry-run. HTTP and MCP still need apply.
	CLIImmediate bool `json:"cli_immediate,omitempty"`
	// CLIConfirmed is Op.CLIConfirmed: the CLI applies a destructive
	// operation without --yes. HTTP and MCP still need apply and confirm.
	CLIConfirmed bool `json:"cli_confirmed,omitempty"`
	// CLIOnlyInputs is Entry.CLIOnlyInputs: input fields accepted only on
	// the CLI. Input omits them, as the HTTP and MCP schemas do.
	CLIOnlyInputs []string           `json:"cli_only_inputs,omitempty"`
	Input         *jsonschema.Schema `json:"input"`
	Output        *jsonschema.Schema `json:"output"`
}

OperationInfo describes one operation in the metadata document.

type Registry

type Registry struct {
	Tool    string
	Version string
	// contains filtered or unexported fields
}

Registry is one tool's operations.

func New

func New(tool, version string) *Registry

New returns an empty registry.

func (*Registry) Entries

func (r *Registry) Entries() []*Entry

Entries returns operations sorted by name.

func (*Registry) Lookup

func (r *Registry) Lookup(name string) *Entry

Lookup finds an operation by canonical name.

func (*Registry) Metadata

func (r *Registry) Metadata() Metadata

Metadata describes every operation, sorted by name.

type Request

type Request struct {
	Surface Surface
	// Apply asks a write or destructive operation to perform the change.
	// Without it the handler must only preview. Always false for reads.
	Apply bool
	// Confirm is the caller's explicit confirmation of a destructive apply.
	Confirm bool
	// HTTP is the inbound request on the HTTP and HTTP-MCP surfaces, for
	// authorizers that read transport identity. Nil on the CLI and stdio MCP.
	HTTP *http.Request
	// Meta is a copy of the MCP tool call's request _meta on the MCP surface
	// (stdio and HTTP), or nil when the call has none. Clients may add
	// protocol keys under io.modelcontextprotocol/, so read only the keys you
	// define. It is always nil on the CLI and the HTTP API, and is never read
	// from the arguments, so a model that fills in arguments cannot set it.
	// It is caller-supplied
	// transport context, trusted only as much as the transport: on stdio,
	// the parent process that spawned the server; on HTTP, whoever can reach
	// the socket.
	Meta map[string]any
}

Request carries the call-level controls every surface supplies alongside the typed input.

type Surface

type Surface string

Surface names the adapter a call arrived through.

const (
	SurfaceCLI  Surface = "cli"
	SurfaceHTTP Surface = "http"
	SurfaceMCP  Surface = "mcp"
)

Jump to

Keyboard shortcuts

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