Documentation
¶
Overview ¶
Package spec is the single source of truth for a command: one Go struct with tags is analyzed once and produces the metadata every frontend needs (CLI flags, HTTP bindings, MCP JSON Schema) plus an Invoke closure that decodes transport-shaped input (map[string]any) into the typed argument struct, applies defaults and validation, and runs the handler.
Frontends never import the typed command: they consume *Entry and its metadata, so a new transport can be added without touching the core. The contract every frontend implements is "reduce its transport's input to a map[string]any, call Entry.Invoke, and render the returned any or coded error" — the shared pipeline lives here, the rendering strategies live in each frontend.
Index ¶
- type CLIOutputFunc
- type CliField
- type CliFieldHint
- type CliHints
- type Command
- func (c *Command[T, R]) CLI(h CliHints) *Command[T, R]
- func (c *Command[T, R]) Description(s string) *Command[T, R]
- func (c *Command[T, R]) Entry() (*Entry, error)
- func (c *Command[T, R]) HTTP(h HTTPHints) *Command[T, R]
- func (c *Command[T, R]) MCP(h MCPHints) *Command[T, R]
- func (c *Command[T, R]) Name() string
- func (c *Command[T, R]) Register(r Registrar) (*Entry, error)
- func (c *Command[T, R]) RegisterDefault() (*Entry, error)
- func (c *Command[T, R]) Summary(s string) *Command[T, R]
- type Entry
- type FieldMeta
- type HTTPField
- type HTTPFieldHint
- type HTTPHints
- type HTTPOutputFunc
- type Handler
- type MCPField
- type MCPFieldHint
- type MCPHints
- type MCPOutputFunc
- type Registrar
- type Schema
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CLIOutputFunc ¶ added in v0.4.1
CLIOutputFunc 自定义一条命令的 CLI 结果渲染。
type CliField ¶
type CliField struct {
Shorthand string // single character, e.g. "n"
Positional bool // consumes the next positional argument
Hidden bool // excluded from --help listings
Skip bool // cli:"-": invisible to the CLI frontend
EnvVar string // fall back to this environment variable when unset
Default any // CLI-only default; overrides the global default tag for the CLI frontend
}
CliField holds the field-level bindings the CLI frontend reads.
type CliFieldHint ¶
type CliFieldHint struct {
Shorthand string // single character, e.g. "a"
Positional bool // consume the next positional argument
Hidden bool // exclude from --help listings
Skip bool // invisible to the CLI frontend (tag equivalent: cli:"-")
EnvVar string // fall back to this environment variable when unset
Default any // CLI-only default; overrides the global default tag for the CLI frontend
}
CliFieldHint is Define-time per-field configuration for the CLI frontend.
type CliHints ¶
type CliHints struct {
Usage string // one-line invocation, e.g. "add <name>"
Aliases []string // alternative subcommand spellings
Hidden bool // omit from help listings
// Default makes this command the default child of its parent node: when
// the first argument is not a registered command segment (and is not a
// flag), the whole argument list is forwarded to it (udf image.tar with
// default extract == udf extract image.tar).
Default bool
// Skip 从 CLI 通道整体移除该命令:不建子命令、别名不生效、不出现在
// completion。与 Hidden 的区别:Hidden 只是帮助列表藏起、仍可执行。
Skip bool
// Daemon 声明「长驻命令」:handler 阻塞到 ctx 取消再返回。语义:
// 隐含 HTTP/MCP 双 Skip(通道层面不消费);执行时不渲染返回值
// (handler 的 error 照常分类映射);ctx 取消即优雅关停、退出 0。
Daemon bool
// Before/After 是 -h 帮助的自定义文本块:分别插在帮助最前(description
// 之前)与最后(Global Flags 之后)。原样输出(多行、缩进自控;结尾换行
// 归一)。空 = 不插入。
Before string
After string
Fields map[string]CliFieldHint // per-field CLI configuration
// Format 覆盖本命令的默认 CLI 输出格式(auto|text|json|jsonl|markdown)。
// 空 = 沿用全局 Config.Format。优先级低于命令行 --format/--xyz.format、
// 高于全局代码配置(xyz-spec §10.7)。设具体值即钉死该命令的输出形态;
// 设 auto(或留空且全局为 auto)则按 stdout 是否 TTY 解析。
Format string
// Output 自定义该命令的 CLI 结果渲染(富文本/彩色等),替代默认
// Render;--json 机器模式仍优先(见 spec/output.go 的契约说明)。
Output CLIOutputFunc
}
CliHints is command-level configuration for the CLI frontend. Field-level bindings can live in two places: on the argument struct's cli tags, or here in Fields (keyed by the field's JSON or Go name). A Fields entry is merged over the tag binding — zero-valued hint fields keep the tag value, so you can set the shorthand in the tag and only override the default in the builder.
type Command ¶
type Command[T, R any] struct { // contains filtered or unexported fields }
Command is the builder for one command definition. Obtain one with Define and chain transport hints before calling Entry or Register.
func Define ¶
Define starts a command definition. name must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ (MCP tool-name compatible); the check runs in Entry, so Define itself never fails.
func (*Command[T, R]) Description ¶
Description sets a longer explanation shown in full help and tool docs.
func (*Command[T, R]) Entry ¶
Entry analyzes the argument type once and returns the frontend-facing Entry without registering it. All definition errors (bad names, bad tags, unsupported field kinds) surface here rather than at first invocation.
func (*Command[T, R]) Register ¶
Register builds the Entry and registers it, returning the registered Entry.
func (*Command[T, R]) RegisterDefault ¶
RegisterDefault builds the Entry and registers it into DefaultRegistrar. It is the singleton flavor: pair it with xyz.Main() and user code never constructs or imports a registry.
type Entry ¶
type Entry struct {
Name string
Summary string
Description string
// InputSchema is the JSON Schema of the argument struct; the MCP frontend
// and the future OpenAPI document consume it directly.
InputSchema *Schema
// OutputSchema is the JSON Schema of the handler's return type
// (MCP tool.outputSchema / OpenAPI response schema). Nil when the result
// type cannot be schema-ed (interfaces, maps, recursive types).
OutputSchema *Schema
// Root describes the argument struct tree (tags, defaults, CLI/HTTP
// bindings) for frontends that generate flags, routes or binders.
Root *FieldMeta
CLI CliHints
HTTP HTTPHints
MCP MCPHints
// Invoke decodes args — any frontend's reduced map shape — applies
// defaults, validates and runs the handler. Decode and validation
// failures are always returned as coded KindInvalidInput errors.
Invoke func(ctx context.Context, args map[string]any) (any, error)
}
Entry is the type-erased view of one command. This is the ONLY surface frontends see: metadata, InputSchema and Invoke. The concrete argument and result types stay hidden inside the Invoke closure.
func (*Entry) CLIDefaults ¶
CLIDefaults returns the CLI-specific default for every bindable field, keyed by JSON name. The CLI frontend injects these into the argument map before Invoke; the global tag defaults are applied by Invoke itself, so precedence is CLI override > global tag > zero value.
func (*Entry) HTTPDefaults ¶
HTTPDefaults is CLIDefaults for the HTTP frontend.
func (*Entry) MCPDefaults ¶
MCPDefaults is CLIDefaults for the MCP frontend. MCP overrides also replace the global default in InputSchema.
type FieldMeta ¶
type FieldMeta struct {
Name string // Go field name
JSONName string // wire name from the json tag
Type reflect.Type
Kind reflect.Kind
Index []int // index path from the owning struct, for FieldByIndex
Description string
Required bool
Secret bool // redact this value in help text, logs and error echoes
Validate string
Enum []any
Default any // parsed, typed default; nil means no default
Skip bool // json:"-": excluded from binding and schema
CLI CliField
HTTP HTTPField
MCP MCPField
Elem *FieldMeta // element or pointee type when Kind is Ptr or Slice
Fields []*FieldMeta // children when Kind is Struct
// contains filtered or unexported fields
}
FieldMeta describes one field of the argument struct tree. Struct fields populate Fields; pointer and slice element types populate Elem. Only declared fields carry Description/Default/Enum/Validate.
type HTTPField ¶
type HTTPField struct {
Location string // "", query, path, header, form, body
Name string // httpName override, e.g. "X-Custom-Header"
Default any // HTTP-only default; overrides the global default tag for the HTTP frontend
}
HTTPField holds the field-level bindings the HTTP frontend reads.
type HTTPFieldHint ¶
type HTTPFieldHint struct {
Location string // "", query, path, header, form, body
Name string // wire name override, e.g. "X-Custom-Header"
Default any // HTTP-only default; overrides the global default tag for the HTTP frontend
}
HTTPFieldHint is Define-time per-field configuration for the HTTP frontend.
type HTTPHints ¶
type HTTPHints struct {
// Method 是路由的 HTTP 方法:空 = 默认同时注册 GET 与 POST(GET 绑定
// query、POST 绑定 body+query,走同一处理器);单个方法("POST")或逗号
// 分隔列表("GET,POST,PUT")钉住具体方法。
Method string // 空 = GET+POST;或 "GET" / "GET,POST,PUT"
Path string // route pattern, e.g. "/users"(有 Path 即参与路由)
Timeout time.Duration // per-request override; 0 keeps the frontend default
// Skip 从 HTTP 通道整体移除该命令:不注册路由、不进 /openapi.json。
// 比「不给 Method/Path」更声明式(适合只适合 CLI 的命令)。
Skip bool
Fields map[string]HTTPFieldHint // per-field HTTP configuration
// Output 全权接管该命令的 HTTP 响应(状态码/头/体)。设置后前端不再
// 自动写 JSON 响应(错误路径不经过 Output)。
Output HTTPOutputFunc
}
HTTPHints is command-level configuration for the HTTP frontend. Field-level binding locations can live on the http tags or here in Fields, with the same merge semantics as CliHints.
type HTTPOutputFunc ¶ added in v0.4.1
HTTPOutputFunc 自定义一条命令的 HTTP 响应:状态码/响应头/响应体全权 交予调用方。
type Handler ¶
Handler implements one command: it receives the fully decoded, defaulted and validated argument struct and returns an arbitrary result value. The result type R may itself be a pointer (return nil on "no result") or any other value.
type MCPField ¶
type MCPField struct {
Default any // MCP-only default; also replaces the global default in the input schema
// Description overrides the field's description in the generated MCP
// inputSchema (empty keeps the shared `desc` tag).
Description string
}
MCPField holds the field-level bindings the MCP frontend reads.
type MCPFieldHint ¶
type MCPFieldHint struct {
Default any // MCP-only default; also replaces the global default in the generated input schema
// Description overrides this field's description in the generated MCP
// inputSchema (and thus the tool's parameter docs). Empty keeps the
// shared `desc` tag.
Description string
}
MCPFieldHint is Define-time per-field configuration for the MCP frontend.
type MCPHints ¶
type MCPHints struct {
// Name overrides the tool name offered to MCP clients. Empty keeps the
// entry name (the dotted path shared with the CLI frontend); a non-empty
// value decouples the tool name from the CLI/HTTP naming, so prefixes
// and namespaces can differ per channel.
Name string
// Title is a human-friendly display name for the tool (carried as the
// MCP annotations.title). Empty falls back to a `title:…` annotation
// string, then to none.
Title string
// Description overrides the tool description. Empty keeps the §3.3 merge
// of the command's Summary + Description.
Description string
// Meta is arbitrary per-tool metadata merged into the tool's reserved
// `_meta` object (nil = none).
Meta map[string]any
// Annotations e.g. "read", "write", "destructive".
Annotations []string
Fields map[string]MCPFieldHint // per-field MCP configuration
// Skip 从 MCP 通道整体移除该命令:不成为工具(负担重的守护/本地命令
// 用;配合 CLI.Skip/HTTP.Skip 自由组合每个命令的通道面)。
Skip bool
// Output 自定义该命令 MCP 结果的文本内容(textContent):写入 w 的文本
// 成为唯一的 TextContent;structuredContent 仍由框架生成(双份契约)。
Output MCPOutputFunc
}
MCPHints is command-level configuration for the MCP frontend. Field-level overrides can live here in Fields, with the same merge semantics as CliHints.
type MCPOutputFunc ¶ added in v0.4.1
MCPOutputFunc 自定义一条命令的 MCP 文本内容(textContent 部分): 写入 w 的内容成为唯一的 TextContent;structuredContent 由框架保留。
type Registrar ¶
Registrar is implemented by registry.Registry. Keeping it an interface here avoids a spec -> registry import cycle.
var DefaultRegistrar Registrar
DefaultRegistrar is the target of RegisterDefault. The registry package wires its process-wide default registry into this slot at init time, so programs that import xyz (or registry) never set it themselves. Programs that use only explicit registries can ignore it. Set to nil (e.g. in tests) to observe RegisterDefault's error path.
type Schema ¶
type Schema struct {
Type string `json:"type,omitempty"`
Description string `json:"description,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Items *Schema `json:"items,omitempty"`
Required []string `json:"required,omitempty"`
Enum []any `json:"enum,omitempty"`
Default any `json:"default,omitempty"`
Format string `json:"format,omitempty"`
}
Schema is a minimal JSON Schema (draft-07 flavored) document. It is kept deliberately small: the MCP inputSchema and the future OpenAPI generation only need this subset, and nested structs are inlined rather than put into $defs, which MCP servers expect.