spec

package
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 13 Imported by: ? modules, 2 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 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

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CLIOutputFunc added in v0.4.1

type CLIOutputFunc func(w io.Writer, v any) error

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

func Define[T, R any](name string, h Handler[T, R]) *Command[T, R]

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]) CLI

func (c *Command[T, R]) CLI(h CliHints) *Command[T, R]

CLI attaches command-level CLI options.

func (*Command[T, R]) Description

func (c *Command[T, R]) Description(s string) *Command[T, R]

Description sets a longer explanation shown in full help and tool docs.

func (*Command[T, R]) Entry

func (c *Command[T, R]) Entry() (*Entry, error)

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]) HTTP

func (c *Command[T, R]) HTTP(h HTTPHints) *Command[T, R]

HTTP attaches command-level HTTP options.

func (*Command[T, R]) MCP

func (c *Command[T, R]) MCP(h MCPHints) *Command[T, R]

MCP attaches command-level MCP options.

func (*Command[T, R]) Name

func (c *Command[T, R]) Name() string

Name returns the command's registered name.

func (*Command[T, R]) Register

func (c *Command[T, R]) Register(r Registrar) (*Entry, error)

Register builds the Entry and registers it, returning the registered Entry.

func (*Command[T, R]) RegisterDefault

func (c *Command[T, R]) RegisterDefault() (*Entry, error)

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.

func (*Command[T, R]) Summary

func (c *Command[T, R]) Summary(s string) *Command[T, R]

Summary sets the one-line description used by help texts and the MCP tool list.

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

func (e *Entry) CLIDefaults() map[string]any

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

func (e *Entry) HTTPDefaults() map[string]any

HTTPDefaults is CLIDefaults for the HTTP frontend.

func (*Entry) MCPDefaults

func (e *Entry) MCPDefaults() map[string]any

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  string        // GET, POST, ...
	Path    string        // route pattern, e.g. "/users"
	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

type HTTPOutputFunc func(w http.ResponseWriter, r *http.Request, e *Entry, v any) error

HTTPOutputFunc 自定义一条命令的 HTTP 响应:状态码/响应头/响应体全权 交予调用方。

type Handler

type Handler[T, R any] func(ctx context.Context, in *T) (R, error)

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
}

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
}

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
	// 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

type MCPOutputFunc func(w io.Writer, v any) error

MCPOutputFunc 自定义一条命令的 MCP 文本内容(textContent 部分): 写入 w 的内容成为唯一的 TextContent;structuredContent 由框架保留。

type Registrar

type Registrar interface {
	Add(*Entry) error
}

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.

Jump to

Keyboard shortcuts

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