native

package
v0.6.45 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 34 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

Added for moxy POC dynamic-perms

Index

Constants

View Source
const DefaultDynamicPermsTimeout = 2 * time.Second

DefaultDynamicPermsTimeout is used when the spec sets timeout-ms = 0.

Variables

This section is empty.

Functions

func BuildExtraArgs

func BuildExtraArgs(arguments json.RawMessage, inputSchema json.RawMessage, argOrder []string) ([]string, error)

BuildExtraArgs is the exported alias of buildExtraArgs, used by the dynamic-perms executor in dynperms.go so it shares argv-shaping with the main tool dispatcher. Added for moxy POC dynamic-perms

func BuildPermsArgs

func BuildPermsArgs(arguments json.RawMessage, inputSchema json.RawMessage, argOrder []string) ([]string, error)

BuildPermsArgs is BuildExtraArgs's strict cousin. When argOrder is non-empty, only the listed keys are emitted as positional argv; unlisted JSON keys are silently dropped. When argOrder is empty, the behavior is identical to BuildExtraArgs (schema-required + sorted remainder).

This is the right shape for the dynamic-perms gate: the perms script declares which inputs it actually wants to see via its own [dynamic-perms].arg-order. Trailing keys like a file's content have no business in a path check and may even contain path-shaped tokens that trigger spurious permission prompts.

func DefaultMoxinPath

func DefaultMoxinPath(home, cwd, systemDir string) string

DefaultMoxinPath computes a MOXIN_PATH from the legacy hierarchy convention:

<cwd>/.moxy/moxins:<intermediate>/.moxy/moxins:~/.config/moxy/moxins:<systemDir>

Only directories that exist on disk are included. Used by the `moxy moxin-path` subcommand.

func ParseMoxinPath

func ParseMoxinPath(path string) []string

ParseMoxinPath splits a colon-separated MOXIN_PATH into directory entries. Empty entries are skipped.

func SystemMoxinDir

func SystemMoxinDir() string

SystemMoxinDir returns the path to the moxin configs shipped with the moxy binary. It checks (in order):

  1. Compile-time injected path (nix builds)
  2. Executable-relative <prefix>/share/moxy/moxins/ (dev builds)

Returns "" if neither exists (graceful degradation).

Types

type BlobWriter

type BlobWriter interface {
	Start() error
	Wait() error
	Cleanup()
}

BlobWriter pumps bytes for a single blob into its pipe write end. Real implementation runs `madder cat <digest>` as a subprocess; tests can swap in an in-memory implementation. Lifecycle: Start once, Wait once, Cleanup is idempotent and best-effort.

type CacheResults

type CacheResults string

CacheResults controls when a tool's output is written to the madder blob store and surfaced as a resource URI (#319). Decoupled from content-type: the mime is a label stamped onto whatever resource block caching produces, never itself a reason to cache.

const (
	// CacheAlways writes every non-empty output to the blob store; small
	// outputs come back as resource blocks (URI + text + mime if declared).
	// For tools whose small outputs are composable artifacts (re-piped
	// into jq, folio.read, etc.).
	CacheAlways CacheResults = "always"
	// CacheThreshold (the default) writes only outputs above the token
	// threshold; small outputs are plain text blocks with no blob write
	// and no mime.
	CacheThreshold CacheResults = "threshold"
	// CacheNever never writes the blob store — even oversized outputs are
	// returned as plain full text. The tool author owns the context cost.
	CacheNever CacheResults = "never"
	// CacheDynamic defers the decision to a per-result `_meta."moxy/cache"`
	// intent the tool emits (RFC 0001). Only valid with result-type =
	// "mcp-result" (the tool must own its envelope to carry _meta); a result
	// with no valid intent falls back to CacheThreshold.
	CacheDynamic CacheResults = "dynamic"
)

type DiscoverResult

type DiscoverResult struct {
	Configs []*NativeConfig
	Errors  []MoxinError
	// Dirs lists the MOXIN_PATH directories that were scanned, in priority
	// order (highest first). Useful for status display.
	Dirs []string
}

DiscoverResult holds both successfully loaded moxins and load failures.

func DiscoverAll

func DiscoverAll(moxinPath string, systemDir string) (DiscoverResult, error)

DiscoverAll loads moxin configs and collects load failures instead of logging them to stderr. Uses the same resolution and merge logic as DiscoverConfigs (the server runtime path).

type DynamicPermsDecision

type DynamicPermsDecision string

DynamicPermsDecision is one of "allow", "ask", "deny", or "" (fall-through). The empty string lets the hook caller delegate to the client (matching the existing delegate-to-client convention when no decision is asserted).

const (
	DynPermsAllow       DynamicPermsDecision = "allow"
	DynPermsAsk         DynamicPermsDecision = "ask"
	DynPermsDeny        DynamicPermsDecision = "deny"
	DynPermsFallThrough DynamicPermsDecision = ""
)

func EvalDynamicPerms

func EvalDynamicPerms(
	ctx context.Context,
	spec *DynamicPermsSpec,
	mainInputSchema json.RawMessage,
	arguments json.RawMessage,
) (DynamicPermsDecision, string)

EvalDynamicPerms runs the dynamic-perms predicate for one tool call and returns a decision plus a human-readable reason for the hook to surface.

Exit code mapping:

0 → allow
1 → ask
2 → deny
other → fall-through (empty decision; client decides)

On timeout, spawn error, or unmapped non-zero exit, the call collapses to "ask" and the reason describes what went wrong so the user understands why they're being prompted.

func EvalDynamicPermsInDir

func EvalDynamicPermsInDir(
	ctx context.Context,
	spec *DynamicPermsSpec,
	mainInputSchema json.RawMessage,
	arguments json.RawMessage,
	cwd string,
) (DynamicPermsDecision, string)

EvalDynamicPermsInDir is EvalDynamicPerms with an explicit working directory for the spawned predicate. When cwd is non-empty it becomes cmd.Dir, so the script's $PWD matches the agent's CWD at tool-call time — this is what lets perms scripts realpath relative paths correctly. Pass "" to inherit the moxy process's CWD.

type DynamicPermsSpec

type DynamicPermsSpec struct {
	Command    string   `toml:"command"           json:"command"`
	Args       []string `toml:"args"              json:"args,omitempty"`
	ArgOrder   []string `toml:"arg-order"         json:"arg-order,omitempty"`
	StdinParam string   `toml:"stdin-param"       json:"stdin-param,omitempty"`
	TimeoutMS  int      `toml:"timeout-ms"        json:"timeout-ms,omitempty"`
}

DynamicPermsSpec describes how to invoke the per-call permission predicate. Mirrors the main tool's argv/stdin shaping so the existing input pipeline can be reused at execution time. Added for moxy POC dynamic-perms

type InputSchema

type InputSchema struct {
	Type        string                    `toml:"type"        json:"type"`
	Description string                    `toml:"description" json:"description,omitempty"`
	Required    []string                  `toml:"required"    json:"required,omitempty"`
	Properties  map[string]PropertySchema `toml:"properties"  json:"properties,omitempty"`
}

InputSchema is the typed representation of a moxin tool's [input] section. Only the JSON Schema keywords actually used by moxin TOML files are modeled.

type MadderBackend

type MadderBackend interface {
	// Write streams content into the default blob store and returns
	// the resulting digest (markl-id).
	Write(ctx context.Context, content io.Reader) (string, error)
	// OpenBlob opens a pipe and prepares a writer that fills it with
	// the named blob's bytes. Used by substitution to stream into a
	// child process's fd without buffering the full payload.
	OpenBlob(ctx context.Context, digest string) (*os.File, BlobWriter, error)
	// CatBytes returns the raw bytes of a single blob synchronously.
	// Used by the resource provider for client reads.
	CatBytes(ctx context.Context, digest string) ([]byte, error)
}

MadderBackend is the subset of *MadderClient that the proxy and native Server depend on. Defined as an interface so tests can stub the blob store without touching a real `madder` binary or initializing a store on disk.

*MadderClient is the canonical implementation; a stub is in substitute_test.go for unit tests.

type MadderClient

type MadderClient struct {
	// contains filtered or unexported fields
}

MadderClient is a process-level handle to the madder blob-store library. It holds a long-lived parent context; each operation builds a fresh per-call errors.Context + BlobStoreEnv and runs the work inside errors.Context.Run, which recovers madder's panic/cancel error model into a returned Go error. The env is NOT shared across calls: BlobStoreEnv is itself an errors.Context and its stores capture that context at discovery, so a cancel on one call's error path would poison a shared env (madder#277 tracks a composable-context API that would let us cache discovery safely).

func NewMadderClient

func NewMadderClient() (*MadderClient, error)

NewMadderClient returns a library-backed client. No binary resolution — the madder Go library is linked in-process.

func (*MadderClient) CatBytes

func (c *MadderClient) CatBytes(ctx context.Context, digest string) ([]byte, error)

CatBytes reads a blob by digest into memory. Buffered — not for very large blobs; streaming consumers use OpenBlob.

func (*MadderClient) OpenBlob

func (c *MadderClient) OpenBlob(ctx context.Context, digest string) (*os.File, BlobWriter, error)

OpenBlob implements blobSource. It fails fast if the blob is missing in every store (moxy#11 — the old CLI path deferred this to a `madder cat` that could hang), then opens a pipe and returns its read end for the moxin child's ExtraFiles plus a BlobWriter that streams the blob's bytes into the pipe in-process (an io.Copy goroutine, replacing the old `madder cat` subprocess).

func (*MadderClient) VerifyDefaultStore

func (c *MadderClient) VerifyDefaultStore(ctx context.Context) error

VerifyDefaultStore confirms the .default store is discoverable. A successful env build with a non-empty default id is the verification.

func (*MadderClient) Version added in v0.6.45

func (c *MadderClient) Version() string

Version reports the madder Go module's version from the binary's build info (replaces the old binary-path reporting). Returns "" if unavailable (e.g. a `go run` build with no module info).

func (*MadderClient) Write

func (c *MadderClient) Write(ctx context.Context, content io.Reader) (string, error)

Write streams content into the .default store and returns the resulting markl-id (blob digest).

func (*MadderClient) WriteToStore

func (c *MadderClient) WriteToStore(ctx context.Context, storeID string, content io.Reader) (string, error)

WriteToStore streams content into the named store and returns the resulting markl-id. storeID is a blob-store-id (e.g. ".default" or a user-scoped id).

type MoxinError

type MoxinError struct {
	Dir string
	Err error
}

DiscoverConfigs loads moxin configs from MOXIN_PATH directories. Each moxin is a subdirectory containing _moxin.toml. Dirs are processed from last to first; earlier path entries override later ones by server name. systemDir is appended as the lowest-priority entry (pass "" to omit).

When moxinPath is empty, the default hierarchy is computed from the current working directory (same directories as `moxy moxin-path`), so discovery works without an explicit MOXIN_PATH env var. MoxinError records a moxin directory that failed to load.

type MoxinMeta

type MoxinMeta struct {
	Schema      int    `toml:"schema"`
	Name        string `toml:"name"`
	Description string `toml:"description"`
}

MoxinMeta is the parsed content of _moxin.toml.

type NativeConfig

type NativeConfig struct {
	Name        string
	Description string
	SourceDir   string
	Tools       []ToolSpec
}

NativeConfig is the assembled output consumed by Server, proxy, and hooks.

func DiscoverConfigs

func DiscoverConfigs(moxinPath string, systemDir string) ([]*NativeConfig, error)

func ParseMoxinDir

func ParseMoxinDir(dirPath string) (*NativeConfig, error)

ParseMoxinDir parses a moxin directory containing _moxin.toml + per-tool files.

type ParseResult

type ParseResult struct {
	Config    *NativeConfig
	Undecoded []string
	Warnings  []string
}

ParseResult holds the parsed config and any undecoded keys found in the TOML files.

func ParseMoxinDirFull

func ParseMoxinDirFull(dirPath string) (*ParseResult, error)

ParseMoxinDirFull parses a moxin directory and reports undecoded keys.

type PermsRequest

type PermsRequest string

PermsRequest controls how the hook system handles permission for a tool.

const (
	// PermsDelegateToClient lets the MCP client decide (default if omitted).
	PermsDelegateToClient PermsRequest = "delegate-to-client"
	// PermsAlwaysAllow skips the permission prompt.
	PermsAlwaysAllow PermsRequest = "always-allow"
	// PermsEachUse forces a user confirmation prompt every time.
	PermsEachUse PermsRequest = "each-use"
	// PermsDynamic runs the [dynamic-perms] script per call to derive a decision.
	// Added for moxy POC dynamic-perms
	PermsDynamic PermsRequest = "dynamic"
)

type PropertySchema

type PropertySchema struct {
	Type                 string     `toml:"type"                  json:"type"`
	Description          string     `toml:"description"           json:"description,omitempty"`
	Enum                 []string   `toml:"enum"                  json:"enum,omitempty"`
	Items                *SchemaRef `toml:"items"                 json:"items,omitempty"`
	AdditionalProperties *SchemaRef `toml:"additionalProperties"  json:"additionalProperties,omitempty"`
}

PropertySchema describes a single property within an input schema.

type ResultType

type ResultType string

ResultType controls how a tool's stdout is interpreted.

const (
	// ResultTypeText wraps stdout as a text content block (default for schema 1).
	ResultTypeText ResultType = "text"
	// ResultTypeMCPResult parses stdout as a ToolCallResultV1 JSON object.
	ResultTypeMCPResult ResultType = "mcp-result"
)

type SchemaRef

type SchemaRef struct {
	Type        string `toml:"type"        json:"type"`
	Description string `toml:"description" json:"description,omitempty"`
}

SchemaRef is a leaf schema reference (for array items or map values).

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server implements proxy.ServerBackend for native (config-declared) tools. It dispatches MCP method calls locally without spawning a child MCP server.

func NewServer

func NewServer(cfg *NativeConfig) *Server

NewServer constructs a Server from a parsed NativeConfig. The madder backend may be nil for tests that don't exercise large-output caching; tools that produce >tokenThreshold output will then return inline content without a cache URI.

func (*Server) Call

func (s *Server) Call(ctx context.Context, method string, params any) (json.RawMessage, error)

Call dispatches an MCP JSON-RPC method and returns the result as raw JSON.

func (*Server) Close

func (s *Server) Close() error

Close is a no-op; native servers hold no external resources.

func (*Server) InitializeResult

func (s *Server) InitializeResult() *protocol.InitializeResultV1

InitializeResult synthesizes an MCP initialize result from the config.

func (*Server) Name

func (s *Server) Name() string

Name returns the server's configured name.

func (*Server) Notify

func (s *Server) Notify(string, any) error

Notify is a no-op; native servers do not process notifications.

func (*Server) SetMadder

func (s *Server) SetMadder(m MadderBackend)

SetMadder wires the madder blob store into this Server. Tools that produce large outputs use it to stash content and return a madder://blobs/<digest> URI to the caller. Substitution (madder://blobs/... → /dev/fd/N) also goes through this backend.

func (*Server) SetOnNotification

func (s *Server) SetOnNotification(func(*jsonrpc.Message))

SetOnNotification is a no-op; native servers do not emit notifications.

func (*Server) SetSession

func (s *Server) SetSession(id string)

SetSession overrides the session identifier used for diagnostics.

type ToolAdapter

type ToolAdapter struct {
	Srv *Server
}

ToolAdapter wraps a native Server to implement server.ToolProviderV1, allowing it to be served directly over stdio without the proxy layer.

func (*ToolAdapter) CallTool

func (a *ToolAdapter) CallTool(ctx context.Context, name string, args json.RawMessage) (*protocol.ToolCallResult, error)

func (*ToolAdapter) CallToolV1

func (a *ToolAdapter) CallToolV1(ctx context.Context, name string, args json.RawMessage) (*protocol.ToolCallResultV1, error)

func (*ToolAdapter) ListTools

func (a *ToolAdapter) ListTools(ctx context.Context) ([]protocol.Tool, error)

func (*ToolAdapter) ListToolsV1

func (a *ToolAdapter) ListToolsV1(ctx context.Context, _ string) (*protocol.ToolsListResultV1, error)

type ToolAnnotations

type ToolAnnotations struct {
	Title           string `toml:"title"`
	ReadOnlyHint    *bool  `toml:"read-only-hint"`
	DestructiveHint *bool  `toml:"destructive-hint"`
	IdempotentHint  *bool  `toml:"idempotent-hint"`
	OpenWorldHint   *bool  `toml:"open-world-hint"`
}

ToolAnnotations holds optional behavior hints for a tool.

type ToolSpec

type ToolSpec struct {
	Name                 string
	Description          string
	Command              string
	Args                 []string
	ArgOrder             []string
	StdinParam           string
	PermsRequest         PermsRequest
	DynamicPerms         *DynamicPermsSpec // Added for moxy POC dynamic-perms
	PermitAsync          *bool             // nil = eligible (see PermitsAsync); #317
	ContentType          string
	ResultType           ResultType
	CacheResults         CacheResults // resolved; never empty (#319)
	NoTruncate           bool
	SubstituteResultURIs *bool
	Annotations          *ToolAnnotations
	Input                json.RawMessage
	InputParsed          *InputSchema
}

ToolSpec describes a single tool within a moxin.

func (*ToolSpec) PermitsAsync

func (s *ToolSpec) PermitsAsync() bool

PermitsAsync reports whether this tool may be dispatched asynchronously (FDR 0004, #317). Omitted defaults to eligible; only an explicit `permit-async = false` forbids backgrounding — the permission tier is a separate, additional gate enforced by the async preflight. *bool keeps omitted distinguishable from explicit-false for the future tools/list execution.taskSupport surfacing.

func (*ToolSpec) ShouldSubstituteURIs

func (s *ToolSpec) ShouldSubstituteURIs() bool

ShouldSubstituteURIs reports whether madder://blobs/<digest> URIs in this tool's arguments should be rewritten to /dev/fd/N pipes.

Source Files

  • adapter.go
  • cache.go
  • config.go
  • discovery.go
  • dynperms.go
  • exec_unix.go
  • madder.go
  • server.go
  • substitute.go

Jump to

Keyboard shortcuts

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