Machine Contract
Prose --help is for humans. Agents, shell drivers, and test harnesses need a
stable data shape, so every cmdguard CLI exposes describe: a versioned JSON
document describing the whole command tree, including flag metadata that pflag
cannot model.
The command
Section titled “The command”describe is registered automatically at Execute time, not at NewCLI, so
the contract always reflects the finished tree. It is hidden, and it never
enforces required flags, so it works before the caller knows any business flags.
Real bytes from the flagship example (excerpt — examples/taskctl, command
taskctl describe; the full document lists every command and inherited flag):
$ taskctl describe{ "schema_version": "1", "name": "taskctl", "short": "A production-grade task manager CLI", "version": "dev", "flags": [ { "name": "admin-email", "type": "string", "default": "admin@example.com", "usage": "Admin contact email" }, /* … api-url … */ { "name": "data-dir", "shorthand": "d", "type": "string", "default": "./data", "usage": "Directory for task storage", "env": "TASKCTL_TASK_DATA_DIR" }, /* … debug, help, log-level, no-color, output, port, timeout … */ { "name": "verbose", "shorthand": "v", "type": "count", "default": "0", "usage": "Verbosity (-v, -vv, -vvv)", "count": true }, { "name": "version", "type": "bool", "default": "false", "usage": "version for taskctl" } ], "commands": [ { "name": "add", "path": "taskctl add", "short": "Add a new task", /* … long, example: the original help text as written — terminal styling (glamour/fang) never leaks into the contract … */ "group": "tasks", "flags": [ { "name": "admin-email", "type": "string", "default": "admin@example.com", "usage": "Admin contact email", "inherited": true }, /* … api-url … port: the other inherited root flags … */ { "name": "priority", "shorthand": "P", "type": "string", "default": "medium", "usage": "Priority", "values": [ "low", "medium", "high" ] }, /* … timeout (inherited) … */ { "name": "title", "shorthand": "t", "type": "string", "usage": "Task title", "required": true, "prompt": "Task title?", "validate": "min=3" }, /* … verbose (inherited) … */ ], "commands": [] }, /* … complete, completion, config, db, describe, doctor, done, inspect, list, man, secret, stats, version … */ ]}(The /* … */ elisions above are the only non-verbatim part; long/example
fields carry each command’s help text verbatim and are omitted here for
brevity.)
What each flag carries
Section titled “What each flag carries”Every entry is enough to construct a valid invocation without reading source:
| Field | Meaning |
|---|---|
name, shorthand |
The spellings the parser accepts |
type |
The pflag type (string, int, bool, duration, …) |
default, usage |
What --help shows, verbatim |
env |
The environment variable, with WithEnvPrefix already applied |
values |
The enum constraint from the values tag |
required |
Whether a flag or env var must supply the value |
count |
Counting flag (-vvv) |
prompt, validate |
The tag text, so a driver can reproduce the rule |
hidden, deprecated, inherited, secret |
Visibility and provenance |
secret:"true" is reported as a boolean; the value itself is never part of the
contract.
Programmatic access
Section titled “Programmatic access”The same document is available without spawning the binary:
description := cli.Describe()if description.SchemaVersion != "1" { return fmt.Errorf("unsupported contract version %q", description.SchemaVersion)}
// Or write it anywhere.if err := cli.WriteDescription(os.Stdout); err != nil { return err}GenerateDocs(w) renders the same facts as Markdown for a docs site, which is
why the flag table in generated docs and the JSON contract cannot disagree.
Stability rules
Section titled “Stability rules”schema_versiononly changes when the contract breaks compatibility.- Within a major version, fields may be added; existing names and meanings never change.
- Unknown fields must be ignored by consumers.
- The exact bytes for a comprehensive fixture CLI are pinned by a golden test, so accidental drift fails CI instead of reaching agents.
Opting out and overriding
Section titled “Opting out and overriding”- A consumer command named
describewins; the built-in is skipped. WithoutDescribeCommand()disables the built-in entirely.Describe()andWriteDescription()keep working because they do not depend on the command.
Driving a CLI from an agent
Section titled “Driving a CLI from an agent”The whole loop, walked end-to-end — every output below is what a cmdguard CLI actually prints:
1. Discover the tree (never scrape --help):
taskctl describe > contract.json2. Build the invocation from the contract and run it. The flagship
example wires WithOutputFormat(output.FormatTable) — Table stays the human
default and the option REGISTERS the --output flag — so pass --output json
and every failure comes back structured:
$ taskctl add --output json3. Read the JSON error envelope (printed to stderr — type is the error
class, message the stable text, hint the actionable fix, error_code the
stable machine identifier, code the process exit code). Real bytes from the
flagship, walked 2026-11-21:
{ "error": { "type": "flag", "message": "command \"add\": required flag not set: \"title\" is missing", "hint": "pass the flag on the command line, or set its env var or config-file value", "error_code": "required_flag", "code": 1 }}4. Decide the recovery from error_code, never from message text — codes
are stable across releases even when messages change:
error_code |
The agent’s recovery |
|---|---|
required_flag |
Supply the flag (or its env var) named in the message |
flag_not_found |
Fix the spelling — the contract lists the accepted names |
value_out_of_range |
Re-read the flag’s type/bounds in the contract and retry |
config_unknown_key |
Drop or rename the config key (the message suggests the fix) |
command_timeout |
Retry with a longer deadline or check the underlying operation |
The full table of all 62 codes with hints lives in the generated
Error Reference;
ErrorCode(err) / ErrorHint(err) expose the same vocabulary to programmatic
callers.
Human-readable output stays useful too: the same failure prints one Hint:
line, and typos get suggestions (taskctl lst → Did you mean this? list).
MCP recipe: one tool per command, generated from the contract
Section titled “MCP recipe: one tool per command, generated from the contract”cmdguard does not ship an MCP server; the contract makes one almost mechanical to write. An MCP wrapper for a cmdguard CLI needs exactly three moving parts:
- At server startup, run
describeonce and hold the parsed contract. For each entry incommands(skip hidden ones — they carry"hidden": true), declare an MCP tool whosenameis the command’spathjoined with dashes (taskctl-add) and whoseinputSchemais derived fromflags:string→{"type": "string"}(+"enum"fromvalues),int→{"type": "integer"},bool→{"type": "boolean"},count→{"type": "integer", "minimum": 0}, plus"required": [flags with "required": true]. Flags withsecret: truestay out of tool descriptions; they are supplied per-call, never logged. - Per tool call, assemble argv from the arguments —
--flag valueper key, repeated keys for count flags — and append--output jsonwhen the CLI registered the output flag, so every failure comes back as the envelope above. - On non-zero exit, parse the JSON error envelope from stderr and return
{ error_code, hint }to the model as the tool’sisErrorcontent. The recovery table above turns a failed call into the model’s next attempt without any message-text parsing.
Because schema_version only moves on a compatibility break, the wrapper can
cache the contract across restarts and re-derive tools only when it changes.
For tooling: schemas, not scraping
Section titled “For tooling: schemas, not scraping”- Schema Generation —
schema.FromCLIandschema.FromConfigturn the same tags into a JSON Schema 2020-12 document, so config-file validation for your CLI’s users is generated, not hand-written. cli.Describe()/cli.WriteDescription(w)give tests and harnesses the contract in-process, no subprocess needed.
Where to go next
Section titled “Where to go next”- Error Handling:
error_code,hint, and exit code mapping. - Type-Safe Flags: the tags that populate each flag entry.
- Production Batteries: how
describegets registered. - Schema Generation: the JSON Schema for config files, derived from the same tags.