op

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 15 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
	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 apply and confirm rules are enforced here, once, for every surface: reads never apply, and a destructive apply without confirmation is refused 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, 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.

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, including the standard apply and confirm controls. 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. 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"`
	// 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.

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.

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"
	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
	// 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
	// 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).

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

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