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
- func Add[In, Out any](r *Registry, o Op[In, Out])
- func MetadataSchema() []byte
- type Authorizer
- type AuthorizerFunc
- type Effect
- type Entry
- func (e *Entry) CLI() string
- func (e *Entry) Call(ctx context.Context, req Request, in any) (any, error)
- func (e *Entry) CallJSON(ctx context.Context, req Request, raw json.RawMessage, auth Authorizer) (any, error)
- func (e *Entry) CanRender() bool
- func (e *Entry) CommandKey() string
- func (e *Entry) Decode(raw json.RawMessage) (in any, apply, confirm bool, err error)
- func (e *Entry) InputSchema() *jsonschema.Schema
- func (e *Entry) MCPName() string
- func (e *Entry) NewInput() any
- func (e *Entry) OutputSchema() *jsonschema.Schema
- func (e *Entry) Render(w io.Writer, out any) error
- func (e *Entry) RenderWithInput(w io.Writer, in, out any) error
- func (e *Entry) Warnings(out any) []string
- type Error
- type Kind
- type Metadata
- type Op
- type OperationInfo
- type Registry
- type Request
- type Surface
Constants ¶
const ( FieldApply = "apply" FieldConfirm = "confirm" )
Reserved wire fields the registry adds to inputs.
const MetadataSchemaID = "toolkit.metadata.v1"
MetadataSchemaID is the schema identifier of the metadata document.
Variables ¶
This section is empty.
Functions ¶
func Add ¶
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 ¶
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 ¶
AuthorizerFunc adapts a function to Authorizer.
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" )
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) Call ¶
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 ¶
CanRender reports whether the operation has a human render hook, Render or RenderWithInput.
func (*Entry) CommandKey ¶
CommandKey is the CLI path without placeholders, e.g. "note delete".
func (*Entry) Decode ¶
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 ¶
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 ¶
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 ¶
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
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.
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 ¶
AsError returns err as an *Error. Errors that are not already an *Error get the fallback kind, and context deadlines map to KindTimeout.
func (*Error) 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.
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" KindPartial Kind = "partial" )
func (Kind) HTTPStatus ¶
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 ¶
Registry is one tool's operations.
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.