cmdcore

package
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 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 cmdcore defines a command once and serves it through both doors: the command line and an MCP tool. A command is a params struct P, a result struct R and a Run function. Tags on P give the flag, positional, JSON name, description and enum; R's JSON tags are the --json object and the MCP structured content; R's Text method is the human output and the MCP text.

Param tags: json:"name" (MCP), flag:"--name" and optional short:"-n" (CLI option), arg:"name" or arg:"name,optional" (CLI positional, in field order), desc:"...", mcpdesc:"..." (replaces desc in the MCP schema), enum:"a,b", required:"true" (required in the MCP schema), repeat:"true" (a []string given by repeating the flag), value:"number" (the placeholder for a flag's value in --help), min:"1" (the smallest whole number an integer field takes). Field types are string, bool, int, *int and []string.

Index

Constants

View Source
const DetailParamDescription = "Return the fuller object. Default false: the usual, minimal one."

DetailParamDescription is the description of the MCP param that asks for the fuller object.

View Source
const SessionNoEndpointHint = "start the session with MASH_ENDPOINT=<address>"

SessionNoEndpointHint is the hint of NoneForSession.

Variables

This section is empty.

Functions

func GlobalOptions

func GlobalOptions(fr Frame) string

GlobalOptions is the "Global options:" section of fr: the heading and the table (no trailing newline), "" when fr has none.

func ListLine

func ListLine(synopsis, desc string, col int) string

ListLine is one entry of a tool's command list: two spaces, the synopsis, and the description from column col, wrapped to 80 columns with its continuation lines indented to col. When the synopsis reaches col the description starts on a line of its own.

func NoCredentials

func NoCredentials(addr, path string) *cliframe.Error

NoCredentials is the failure for an endpoint whose creds file is not there (exit 1). path is shown as the person knows it, with ~ for the home folder.

func NoEndpoint

func NoEndpoint(kind NoEndpointKind, command string, addresses []string) *cliframe.Error

NoEndpoint is the one place the three wordings of having no endpoint are made. command is the command being run (the hint of SeveralInstalled names it: "mash send --endpoint acme.demo.alice"); addresses are the installed endpoints, for SeveralInstalled only.

func NoSuchEndpoint

func NoSuchEndpoint(addr string) *cliframe.Error

NoSuchEndpoint is the failure for an address nothing answers to (exit 1).

func NotSignedIn

func NotSignedIn(addr string) *cliframe.Error

NotSignedIn is the failure for an endpoint whose credentials the server refused (exit 1).

func ParentHelp

func ParentHelp(fr Frame, description string, usages []string) string

ParentHelp is the --help of a command that only holds others (mash key): its description, Usage with one line per command under it, and the Global options, in the same layout and width as a command's own.

func ParseAddress

func ParseAddress(s, hint string) (string, error)

ParseAddress is the one check every command that takes an address makes. An address is owner.group.name: three dotted parts, each lower-case letters, digits and single dashes. It returns the address as it is shown (the same string). Anything else, the flat owner_group_name and the slashed owner/group/name included, is a usage error (exit 2): "<s> is not an address; write it as <the dotted form>", with the hint when it is not empty (the command's own help). When no dotted form can be made from s, the error says owner.group.name.

func ParsePrefix

func ParsePrefix(s, hint string) (string, error)

ParsePrefix is the check `mash who` makes of its prefix: an owner (acme), an owner and group (acme.demo) or a full address (acme.demo.bob), each part lower-case letters, digits and single dashes. acme.* and acme.demo.* are accepted and mean acme and acme.demo; there is no other pattern. It returns the prefix without the ".*". Anything else, the flat acme_demo and the slashed acme/demo included, is a usage error (exit 2): "<s> is not an owner, an owner.group or an address", as the specification words it.

func RecipientSuspended

func RecipientSuspended(addr string) *cliframe.Error

RecipientSuspended is the failure for a send to an endpoint that is suspended or was deleted: its inbox takes no mail (exit 1).

func RefusedMessage

func RefusedMessage(n int) *cliframe.Error

RefusedMessage is the failure for the number of a message serve refused because it was not verified (exit 1).

func Schema

func Schema[P any]() map[string]any

Schema builds the JSON Schema of an MCP input from the params type P.

func ServerNotAnswering

func ServerNotAnswering(url string) *cliframe.Error

ServerNotAnswering is the failure for a server that could not be reached or did not answer (exit 1).

func StaticHelp

func StaticHelp(fr Frame, c StaticCommand) string

StaticHelp is the --help of c in the layout of helpText: description, Usage, Examples, Arguments, Options and Global options, each after a blank line, no line wider than 80 columns.

func ToolError

func ToolError(err error) error

ToolError renders err as an MCP tool's error does: "error: MSG" plus "\nhint: HINT" for a framed failure, for the tools that are not commands of the table.

Types

type CLIFunc

type CLIFunc func(args []string, stdin io.Reader, stdout, stderr io.Writer, g cliframe.Global) int

CLIFunc runs one command from its arguments (the global options already removed by cliframe.Extract) and returns the process exit code.

func CLI

func CLI[P any, R Result](c Command[P, R], env EnvFunc) CLIFunc

CLI adapts c to the command line.

Arguments are parsed from the params tags: positionals in field order, --flag value, --flag=value, short flags, bool flags, repeated flags for []string, and "--" to end the options. A bare "-" is a positional (standard input for --file, and for send's message). An unknown option, a missing value, a bad enum value, number or boolean, an empty required positional, a single-value option given twice and surplus positionals are usage errors (exit 2). On success the result's Text, or with --json its compact JSON, goes to stdout; a result that is an ExitCoder sets the exit code and one that is a Hinter adds a hint line on stderr.

func CLIWith

func CLIWith[P any, R Result](c Command[P, R], env EnvFunc, frame Frame) CLIFunc

CLIWith is CLI with the frame that --help prints around the command. --help or -h anywhere before a "--" prints the help on stdout and exits 0, and nothing else is read or run.

type Command

type Command[P any, R Result] struct {
	Name string
	// Group is the heading the tool's own help lists the command under (the specification's x-group): Everyday, Setup,
	// Integration or Raw SAP.
	Group string
	// NoMCP says the command has no MCP tool (the specification's x-mcp tool is null): a setup command an agent does
	// not hold. The command table's Tools and MCPTools leave it out.
	NoMCP          bool
	Summary        string
	MCPDescription string
	Description    string
	Examples       []string
	Run            func(ctx context.Context, env *Env, p P) (R, error)
}

Command is one command: its CLI name (the verb, also the MCP tool name), a one-line summary, the one-line description and the examples that --help prints, and its Run. MCPDescription is the MCP tool's description, written for the model; when empty the tool's description is the Summary. Group is the heading the tool's own help lists the command under.

type Detailer

type Detailer interface {
	DetailText(o Opts) string
	DetailValue() any
}

Detailer is implemented by a result that has more to say under the global detail option (cliframe.DetailFlag). In text the command line and the MCP tool print Text and then DetailText, the 'label: value' lines; with --json they print DetailValue, a fuller object that contains the usual one, in place of the result. A command whose result has no Detailer has nothing more to say, and the option changes nothing (a Text may still read Opts.Detail on its own). An MCP tool whose result is a Detailer takes the boolean param cliframe.DetailParam.

type Entry

type Entry interface {
	CLIName() string
	Summary() string
	// Group is the heading the tool's own help lists the command under.
	Group() string
	// HasMCP is whether the command is also an MCP tool.
	HasMCP() bool
	Tool(env EnvFunc) Tool
	RunCLI(env EnvFunc, fr Frame, args []string, stdin io.Reader, stdout, stderr io.Writer, g cliframe.Global) int
	// HelpFor is the --help text when args ask for it, and whether they do: it reads nothing and runs nothing.
	HelpFor(fr Frame, args []string) (string, bool)
	// Usage is the synopsis, "mash send <address> [<message>] [options]", and the one-line description.
	Usage(tool string) (synopsis, description string)
}

Entry is one registered command, usable through both doors without its type parameters.

func Register

func Register[P any, R Result](c Command[P, R]) Entry

Register wraps c as an Entry. It panics when the tags of the params type P are inconsistent (see paramFields).

type Env

type Env struct {
	Svc  any
	Now  func() time.Time
	Opts Opts
	// Stdin is the standard input of a CLI run, nil for an MCP call. StdinPiped says it is a pipe or file rather than a
	// terminal.
	Stdin      io.Reader
	StdinPiped bool
	// StdinTimeout bounds a read of Stdin: a pipe that never writes would otherwise block the command for ever. Zero
	// means no bound.
	StdinTimeout time.Duration
	// ReadFile reads a file for --file style options; nil means os.ReadFile.
	ReadFile func(path string) ([]byte, error)
}

Env is what a command runs against. Svc is the command package's own service, asserted to the interface it needs, so tests can fake it.

type EnvFunc

type EnvFunc func(ctx context.Context) (*Env, error)

EnvFunc makes the Env for one run.

type ExitCoder

type ExitCoder interface {
	ExitCode() int
}

ExitCoder is implemented by a result that carries the exit code of a report: status and doctor report on stdout and exit 1 when they found a problem: a problem is a result (exit 1 on the command line), not a failure to run. A result without it exits 0.

type Frame

type Frame struct {
	Tool    string
	Globals []HelpOption
}

Frame is what --help prints around a command: the tool's name and its global options.

type HelpOption

type HelpOption struct {
	Flag  string // "--endpoint"
	Short string // "-v", or ""
	Value string // placeholder for the value, "address", or "" for a switch
	Desc  string
}

HelpOption is one global option as --help lists it.

type Hinter

type Hinter interface {
	Hint() string
}

Hinter is implemented by a result that carries a hint for a person: the command line prints it as "hint: HINT" on standard error (never with --json, whose object is the whole answer), and an MCP tool, which has no standard error, ends its text with the same line. An empty hint is no hint.

type NoEndpointKind

type NoEndpointKind int

NoEndpointKind says where having no endpoint was found out, which decides its words (rules.json: "Having no endpoint reads the same in every mash command").

const (
	// NoneInstalled is a shell with no endpoint chosen and none installed (exit 2).
	NoneInstalled NoEndpointKind = iota
	// SeveralInstalled is a shell with no endpoint chosen and several installed (exit 2).
	SeveralInstalled
	// NoneForSession is an MCP tool in a session that names no endpoint (exit 1).
	NoneForSession
)

type Opts

type Opts = render.Opts

Opts are the output options Text receives.

type Registry

type Registry struct {
	Entries []Entry
	Env     EnvFunc
	Frame   Frame // what --help prints around each command
}

Registry is one table of commands that both doors range over.

func NewRegistry

func NewRegistry(env EnvFunc, entries ...Entry) *Registry

NewRegistry returns a Registry of entries that make their Env with env.

func (*Registry) Group

func (r *Registry) Group(name string) string

Group returns the heading of the command named name ("" when there is no such command).

func (*Registry) Groups

func (r *Registry) Groups(group string) []string

Groups returns the names of the table's commands under heading group, in table order.

func (*Registry) HelpFor

func (r *Registry) HelpFor(name string, args []string) (string, bool)

HelpFor is the --help text of the command named name when args ask for it.

func (*Registry) ListLine

func (r *Registry) ListLine(name string, col int) string

ListLine is the line the tool's own help gives the command named name: two spaces, its synopsis, and its one-line description starting at column col (on a line of its own, indented to col, when the synopsis is too long), wrapped to 80 columns. It is "" when there is no such command.

func (*Registry) Lookup

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

Lookup returns the entry for a CLI verb.

func (*Registry) MCPTools

func (r *Registry) MCPTools() []mcp.Tool

MCPTools returns Tools converted for the MCP server.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns the CLI verbs in sorted order.

func (*Registry) RunCLI

func (r *Registry) RunCLI(name string, args []string, stdin io.Reader, stdout, stderr io.Writer, g cliframe.Global) int

RunCLI runs the command named name. The caller has checked Lookup.

func (*Registry) Tools

func (r *Registry) Tools() []Tool

Tools returns every command that has one as an MCP tool, in registration order.

func (*Registry) WithFrame

func (r *Registry) WithFrame(fr Frame) *Registry

WithFrame sets what --help prints around each command, and returns r.

type Result

type Result interface {
	Text(o Opts) string
}

Result is what a command returns: a struct whose JSON form is the structured result, and the text for people.

type StaticCommand

type StaticCommand struct {
	Name        string
	Description string
	Usage       string // the synopsis, "mash serve [options]"
	Examples    []string
	Arguments   [][2]string
	Options     [][2]string
}

StaticCommand is a command that is not on the table (its parameters are not a struct) but whose --help is the same layout: the texts are the specification's. Arguments and Options are (label, description) rows, the label as printed ("address", "--wake-count <n>").

type Tool

type Tool struct {
	Name           string
	Description    string
	Schema         map[string]any
	CallStructured func(ctx context.Context, args json.RawMessage) (text string, structured any, err error)
}

Tool is one command as an MCP tool. CallStructured returns the text for the content block and the structured value (nil when the result is not a JSON object). An error's text is "error: MSG" plus "\nhint: HINT" when there is a hint.

internal/mcp.Tool has no structured result yet; MCP converts a Tool to one that returns the text only.

func MCPTool

func MCPTool[P any, R Result](c Command[P, R], env EnvFunc) Tool

MCPTool adapts c to an MCP tool. The input schema comes from the params tags; the arguments are decoded into P by their JSON names after the required fields and enums are checked.

func (Tool) MCP

func (t Tool) MCP() mcp.Tool

MCP converts t to an mcp.Tool whose CallStructured returns the text and the result object (the server sends the object as structuredContent only when 2025-06-18 was negotiated).

Directories

Path Synopsis
Package cmds holds the commands defined on cmdcore: each is a params struct, a result struct and a Run, served through both the command line and the MCP tool.
Package cmds holds the commands defined on cmdcore: each is a params struct, a result struct and a Run, served through both the command line and the MCP tool.
Package render holds the small text helpers shared by the commands' human output: relative times, aligned tables, the terminal width, colour and plural counts.
Package render holds the small text helpers shared by the commands' human output: relative times, aligned tables, the terminal width, colour and plural counts.

Jump to

Keyboard shortcuts

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