murliv1.0.2
{ } github
§ Language Reference

Go ● stable v1.0.2

Three adapters cover the major Go CLI frameworks: spf13/cobra, urfave/cli v2, and urfave/cli v3. Each adapter exposes the same conceptual operations with framework-idiomatic signatures.

cobra adapter

Import path: github.com/murli-cli/murli-go/cobra

FunctionSignaturePurpose
Execute Execute(root *cobra.Command) error Drop-in replacement for root.Execute(). Injects flags, mounts subcommands, wraps all RunE handlers.
Enable Enable(root *cobra.Command) Injects without replacing Execute. Use when you need to call root.Execute() yourself.
NewWriter NewWriter(cmd *cobra.Command) *murli.Writer Creates a Writer configured from the command’s injected flags (--agent, --force, --dry-run).
Annotate Annotate(cmd *cobra.Command, meta murli.Metadata) Serialises Metadata into cmd.Annotations["agentcobra"] for schema output.
EmitSchema EmitSchema(cmd *cobra.Command) error Writes the command schema as JSON to stdout.
BuildDescribeTree BuildDescribeTree(cmd *cobra.Command) murli.DescribeCommandSchema Builds the recursive schema tree for a command and its subcommands.

urfave/cli v2 adapter

Import path: github.com/murli-cli/murli-go/cli/v2

FunctionSignaturePurpose
Run Run(app *cli.App, args []string) error Drop-in replacement for app.Run(args).
NewWriter NewWriter(ctx *cli.Context) *murli.Writer Creates a Writer from the action context.
Annotate Annotate(cmd *cli.Command, meta murli.Metadata) Attaches metadata to a command. Uses a pointer-keyed map internally (urfave/cli v2 has no native metadata field).
AnnotateApp AnnotateApp(app *cli.App, meta murli.Metadata) Attaches metadata to the root app.
EmitSchema EmitSchema(cmd *cli.Command, w io.Writer) error Writes the command schema as JSON to the provided writer.
BuildV2DescribeTree BuildV2DescribeTree(cmd *cli.Command) murli.DescribeCommandSchema Builds the schema tree for a command.

urfave/cli v3 adapter

Import path: github.com/murli-cli/murli-go/cli/v3

FunctionSignaturePurpose
Run Run(app *cli.Command, args []string) error Drop-in replacement for app.Run(ctx, args).
Wrap Wrap(app *cli.Command) In-place setup: injects flags, wraps Actions, mounts subcommands. Use when you need to call app.Run yourself.
NewWriter NewWriter(cmd *cli.Command) *murli.Writer Creates a Writer from the command context.
Annotate Annotate(cmd *cli.Command, meta murli.Metadata) Stores metadata in cmd.Metadata["murli"].
EmitSchema EmitSchema(cmd *cli.Command, w io.Writer) error Writes the command schema as JSON.
BuildV3DescribeTree BuildV3DescribeTree(cmd *cli.Command) murli.DescribeCommandSchema Builds the schema tree for a command.

Writer

Package: github.com/murli-cli/murli-go

The Writer is the primary output surface. Obtain one via the adapter’s NewWriter in every handler. Do not construct one directly in normal use.

Constructor

go
func NewWriter(stdout, stderr io.Writer, agentMode bool, opts ...WriterOption) *Writer

Use the adapter’s NewWriter in handlers. The bare constructor is for testing or building custom adapters.

WriterOption functions

FunctionEffect
WithOutputFormat(f OutputFormat)Override the output format (OutputFormatJSON, OutputFormatNDJSON, OutputFormatText)
WithProtocolVersion(v string)Set the protocol version string in envelope output. Default: "0.2".
WithForce(force bool)Set the forced state directly (used by adapters reading the --force flag)
WithDryRun(dryRun bool)Set the dry-run state directly

Output methods

MethodWrites toWhen
WriteSuccess(humanText string, jsonPayload any)stdoutCommand completed successfully
WritePlan(humanText string, plan any)stdoutDry-run: show what would happen
WriteError(err *AgentError)stderrCommand failed; calls os.Exit with the error code
WriteEvent(v any)stdoutOne NDJSON line per call for streaming output
WriteProgress(evt ProgressEvent)stdout (agent) / stderr (TTY)Typed progress update
Log(msg string)stderrDiagnostic line with deduplication
Progress(msg string)stderrUnstructured progress line
Flush()Flush buffered log/progress output

State methods

MethodReturns
IsTTY() boolTrue if stdout is a terminal
IsForced() boolTrue if --force or --yes was passed
IsDryRun() boolTrue if --dry-run was passed
Format() OutputFormatCurrent output format
ProtocolVersion() stringProtocol version string included in envelopes

OutputFormat constants

ConstantValueMeaning
OutputFormatDefault""Auto-detect: JSON if not TTY, text if TTY
OutputFormatJSON"json"Single JSON object
OutputFormatNDJSON"ndjson"Newline-delimited JSON
OutputFormatText"text"Plain text, no JSON envelopes

ProgressEvent struct

go
type ProgressEvent struct {
    Stage   string  `json:"stage,omitempty"`
    Current int     `json:"current,omitempty"`
    Total   int     `json:"total,omitempty"`
    Percent float64 `json:"percent,omitempty"`
    EtaMs   int64   `json:"eta_ms,omitempty"`
    Message string  `json:"message,omitempty"`
}

Logger

Package: github.com/murli-cli/murli-go

The Logger writes diagnostic output to stderr with consecutive line deduplication. w.Log() and w.Progress() use an internal logger. Use NewLogger directly only when building outside a standard handler context.

Function / MethodSignaturePurpose
NewLoggerNewLogger(writer io.Writer, isTTY bool) *LoggerCreates a logger writing to writer
Log(l *Logger) Log(line string)Writes a log line to stderr. Suppresses if identical to the previous line.
LogProgress(l *Logger) LogProgress(line string)Writes a progress line. In TTY mode, overwrites the previous progress line.
Flush(l *Logger) Flush()Flushes any buffered output

AgentError

Package: github.com/murli-cli/murli-go

Constructors

FunctionExit codeUse when
NewUserError(message, suggestion string) *AgentError1Invalid input, bad flags, user mistake
NewToolError(message string) *AgentError2Internal failure, dependency error

For other exit codes, construct an AgentError directly:

go
w.WriteError(&murli.AgentError{
    Code:        murli.ExitNotFound,
    ErrorType:   "not_found",
    Message:     "index file does not exist",
    Suggestion:  "Run `mytool index build` to create it.",
    Recoverable: true,
})

AgentError fields

FieldTypeJSON keyPurpose
CodeintcodeExit code. Use the Exit* constants.
ErrorTypestringerrorMachine-readable error category (e.g. "user_error", "not_found")
MessagestringmessageHuman-readable description of what failed
SuggestionstringsuggestionWhat the caller should do next
RecoverableboolrecoverableTrue if retrying the same call might succeed
ValidValues[]stringvalid_valuesAcceptable values when an enum constraint was violated
RetryAfterMsintretry_after_msMilliseconds to wait before retrying (rate-limit errors)
DocURLstringdoc_urlLink to relevant documentation
FieldstringfieldFlag or argument name that caused the error
SchemaVersionstringschema_versionSet automatically by WriteError
ToolVersionstringtool_versionSet automatically by WriteError

Metadata

Package: github.com/murli-cli/murli-go

Pass to the adapter’s Annotate function. All fields are optional.

go
type Metadata struct {
    AgentDescription string
    WhenToUse        string
    Idempotent       bool
    Mutating         bool
    Arguments        []ArgumentMetadata
    Returns          *ReturnSchema
    Examples         []Example
    FlagAnnotations  map[string]FlagAnnotation
    DryRunnable      bool
    Destructive      bool
}

ArgumentMetadata

go
type ArgumentMetadata struct {
    Name        string `json:"name"`
    Type        string `json:"type"`
    Required    bool   `json:"required"`
    Description string `json:"description"`
}

ReturnSchema

go
type ReturnSchema struct {
    Type         string          `json:"type"`
    Description  string          `json:"description"`
    Shape        map[string]any  `json:"shape,omitempty"`
    OutputSchema json.RawMessage `json:"output_schema,omitempty"`
}

Example

go
type Example struct {
    Command          string `json:"command"`
    Description      string `json:"description,omitempty"`
    ExpectedExitCode int    `json:"expected_exit_code,omitempty"`
}

Profiles

Package: github.com/murli-cli/murli-go

The profile subcommand handles profile management automatically. Use the ProfileStore API directly only when you need programmatic access to profiles outside a command handler.

Function / MethodSignaturePurpose
ProfilePathProfilePath(toolName string) stringReturns the path to ~/.config/<toolName>/profiles.json
LoadProfileStoreLoadProfileStore(toolName string) (*ProfileStore, error)Loads profiles from disk. Creates an empty store if the file does not exist.
Save(*ProfileStore) Save(toolName string) errorWrites the store to disk
Get(*ProfileStore) Get(name string) (Profile, bool)Returns the named profile and whether it exists
Set(*ProfileStore) Set(name string, p Profile)Creates or replaces a named profile
Delete(*ProfileStore) Delete(name string)Removes a profile
SetDefault(*ProfileStore) SetDefault(name string) errorSets the default profile (used when no --profile flag is given)
Names(*ProfileStore) Names() []stringReturns all profile names in sorted order

Profile struct

go
type Profile struct {
    Flags map[string]string `json:"flags"`
}

type ProfileStore struct {
    Default  string             `json:"default,omitempty"`
    Profiles map[string]Profile `json:"profiles"`
}

Utilities

Package: github.com/murli-cli/murli-go

CheckConventions

Requires -tags murlidev. The function is a no-op stub in release builds.

go
func CheckConventions(commandNames, flagNames []string, w io.Writer) int

Checks command and flag names against the conventional vocabulary. Writes advisory warnings to w for non-standard names. Returns the count of issues found. Does not modify any state. Use in tests or CI to enforce naming standards.

Non-standard verbs flagged (with suggested replacement): fetchget, infoget, retrieveget, show-alllist, removedelete, rmdelete, addcreate, editupdate, modifyupdate.

Non-standard flags flagged: skip-confirmationsforce, silentquiet, previewdry-run, formatoutput.

FormatAgentsMD

go
func FormatAgentsMD(out DescribeOutput) string

Generates an AGENTS.md stub from a DescribeOutput. Produces a Markdown document that lists each command, its description, flags, and examples. Intended as a starting point for agent-facing documentation.

Version constants

IdentifierTypeValue / Purpose
SchemaVersionconst string"1.0" — included in all envelope output as schema_version
ToolVersionvar stringSet at build time via -ldflags "-X github.com/murli-cli/murli-go.ToolVersion=1.0.2". Included in envelopes as tool_version.
ExitFuncvar func(int)Defaults to os.Exit. Override in tests to prevent process exit: murli.ExitFunc = func(code int) { ... }