tools

package
v0.0.0-...-7986b5b Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrSkillRuntimeUnavailable = errors.New("skill runtime is unavailable")

ErrSkillRuntimeUnavailable is returned when activation or restore is attempted without discovered skills.

Functions

func Error

func Error(message, code string) string

Error marshals a tool error as JSON: {"error": message, "code": code}.

func FormatMCPServersForDisplay

func FormatMCPServersForDisplay(servers []string) []string

FormatMCPServersForDisplay formats a list of MCP server specs for display

func FormatToolError

func FormatToolError(err error) (string, bool)

FormatToolError checks whether err wraps a *ToolError and, if so, returns the JSON-serialized error string. Returns ("", false) otherwise.

func GetMCPDisplayName

func GetMCPDisplayName(serverSpec string) string

GetMCPDisplayName returns a display-friendly name for an MCP server spec Formats: "file.json → command args" or "file.json#server → command args"

func LoadMCPConfigFile

func LoadMCPConfigFile(jsonFile string) (map[string]MCPConfig, error)

LoadMCPConfigFile parses a config file and returns server configs Requires mcpServers format: {"mcpServers": {"name": {...}}}

func ParseServerSpec

func ParseServerSpec(spec string) (jsonFile string, serverName string)

ParseServerSpec splits a server spec into file path and server name Format: "path/to/config.json" or "path/to/config.json#servername"

func Result

func Result(v any) string

Result marshals v as a JSON string for tool results. Falls back to an error JSON on marshal failure.

Types

type Args

type Args map[string]any

Args wraps map[string]any with typed accessors for tool arguments. JSON unmarshals numbers as float64, so direct type assertions on int will panic. Use Args helpers instead.

Usage: args := tools.Args(rawArgs)

func (Args) Bool

func (a Args) Bool(key string) bool

Bool returns the boolean value for key, or false if missing or wrong type.

func (Args) Float

func (a Args) Float(key string, defaultValue float64) float64

Float returns the float64 value for key. Returns defaultValue if missing or wrong type.

func (Args) Int

func (a Args) Int(key string, defaultValue int) int

Int returns the integer value for key, handling float64 (from JSON), int, and int64 types. Returns defaultValue if missing or wrong type.

func (Args) String

func (a Args) String(key string) string

String returns the string value for key, or empty string if missing or wrong type.

func (Args) StringSlice

func (a Args) StringSlice(key string) []string

StringSlice returns a deduplicated string slice for key, handling both []any (from JSON) and []string. Skips empty strings.

type BashTool

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

BashTool executes shell commands via bash -c.

func NewBashTool

func NewBashTool(workDir string) *BashTool

NewBashTool creates a bash tool that runs commands in the given working directory. If workDir is empty, commands run in the current process directory.

func (*BashTool) Execute

func (t *BashTool) Execute(ctx context.Context, args map[string]any) (string, error)

func (*BashTool) GetName

func (t *BashTool) GetName() string

func (*BashTool) GetSchema

func (t *BashTool) GetSchema() *schema.ToolSchema

func (*BashTool) GetSource

func (t *BashTool) GetSource() string

func (*BashTool) GetType

func (t *BashTool) GetType() string

func (*BashTool) WithSandbox

func (t *BashTool) WithSandbox(sb sandbox.Sandbox) *BashTool

WithSandbox returns a copy with sandboxing enabled.

type Func

type Func struct {
	Name     string
	Desc     string
	Params   schema.Params
	Required []string
	Source   string // defaults to "builtin"
	Run      func(ctx context.Context, args Args) (string, error)
}

Func is a declarative tool definition. It implements Tool.

func (*Func) Execute

func (f *Func) Execute(ctx context.Context, args map[string]any) (string, error)

func (*Func) GetName

func (f *Func) GetName() string

func (*Func) GetSchema

func (f *Func) GetSchema() *schema.ToolSchema

func (*Func) GetSource

func (f *Func) GetSource() string

func (*Func) GetType

func (f *Func) GetType() string

type LoadResult

type LoadResult struct {
	Type    string         // "native", "shell", "mcp"
	Servers []ServerResult // For MCP, one per server loaded; for shell/native, single entry
}

LoadResult contains information about tools that were loaded

type MCPClient

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

MCPClient manages connection to an MCP server

func NewMCPClient

func NewMCPClient(serverSpec string) (*MCPClient, error)

NewMCPClient creates a new MCP client from a server spec Format: "path/to/config.json" or "path/to/config.json#servername"

func NewMCPClientFromConfig

func NewMCPClientFromConfig(config *MCPConfig, sb sandbox.Sandbox) (*MCPClient, error)

NewMCPClientFromConfig creates a new MCP client from a JSON configuration. If sb is non-nil and transport is stdio, the server process runs sandboxed.

func (*MCPClient) Close

func (c *MCPClient) Close() error

Close closes the MCP client connection

func (*MCPClient) ListTools

func (c *MCPClient) ListTools() ([]Tool, error)

ListTools returns all tools available from the MCP server

type MCPConfig

type MCPConfig struct {
	// Local/stdio transport fields
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`

	// Remote transport fields
	URL       string            `json:"url,omitempty"`       // Remote server URL
	Transport string            `json:"transport,omitempty"` // "stdio" | "sse" | "streamable"
	Headers   map[string]string `json:"headers,omitempty"`   // Auth headers, API keys
	Timeout   string            `json:"timeout,omitempty"`   // Connection timeout (e.g., "30s")

	// Sandboxing (stdio only). true for defaults, or {"allowNetwork":true,"writablePaths":[...]}.
	Sandbox json.RawMessage `json:"sandbox,omitempty"`
}

MCPConfig represents the JSON configuration for an MCP server

func (*MCPConfig) SandboxConfig

func (c *MCPConfig) SandboxConfig() (*sandbox.Config, error)

SandboxConfig returns the parsed sandbox config for merging overrides, or nil when the user didn't specify any sandbox overrides.

func (*MCPConfig) SandboxOptOut

func (c *MCPConfig) SandboxOptOut() bool

SandboxOptOut reports whether the user explicitly disabled sandboxing for this server by setting "sandbox": false in their config.

type MCPServersConfig

type MCPServersConfig struct {
	MCPServers map[string]MCPConfig `json:"mcpServers"`
}

MCPServersConfig represents the Claude Desktop format with multiple servers

type MCPTool

type MCPTool struct {
	Source string // Server spec that provided this tool
	// contains filtered or unexported fields
}

MCPTool wraps an MCP tool to implement the Tool interface

func NewMCPTool

func NewMCPTool(session *mcp.ClientSession, tool *mcp.Tool) *MCPTool

NewMCPTool creates a new MCP tool wrapper

func (*MCPTool) Execute

func (m *MCPTool) Execute(ctx context.Context, args map[string]any) (string, error)

Execute runs the MCP tool with the given arguments

func (*MCPTool) GetName

func (m *MCPTool) GetName() string

GetName returns the name of the tool

func (*MCPTool) GetSchema

func (m *MCPTool) GetSchema() *schema.ToolSchema

GetSchema returns the tool's schema (cached after first call)

func (*MCPTool) GetSource

func (m *MCPTool) GetSource() string

GetSource returns the server spec that provided this tool

func (*MCPTool) GetType

func (m *MCPTool) GetType() string

GetType returns "mcp" for MCP tools

type NamespacedTool

type NamespacedTool struct {
	Tool
	// contains filtered or unexported fields
}

NamespacedTool wraps a tool to provide a namespaced schema

func (*NamespacedTool) GetName

func (n *NamespacedTool) GetName() string

GetName returns the namespaced name

func (*NamespacedTool) GetSchema

func (n *NamespacedTool) GetSchema() *schema.ToolSchema

GetSchema returns a schema with the namespaced title

type NativeTool

type NativeTool struct{}

NativeTool provides default GetType and GetSource implementations for native Go tools. Embed it to avoid repeating boilerplate:

type myTool struct {
    tools.NativeTool
    // ...
}

func (NativeTool) GetSource

func (NativeTool) GetSource() string

func (NativeTool) GetType

func (NativeTool) GetType() string

type RegistryOption

type RegistryOption func(*registryOptions)

RegistryOption configures a ToolRegistry.

func WithSandboxFactory

func WithSandboxFactory(factory func(sandbox.Config) (sandbox.Sandbox, error), baseCfg sandbox.Config) RegistryOption

WithSandboxFactory sets the sandbox factory and base config for the registry.

type ServerResult

type ServerResult struct {
	Name      string   // Server/tool name (e.g., "git", "filesystem", "datetime")
	ToolNames []string // Fully namespaced tool names loaded
}

ServerResult contains information about tools loaded from a single source

type ShellTool

type ShellTool struct {
	Command string
	// contains filtered or unexported fields
}

ShellTool wraps external commands/scripts as tools

func NewShellTool

func NewShellTool(command string, schemaSandbox ...sandbox.Sandbox) (*ShellTool, error)

NewShellTool creates a new shell tool from a command. An optional sandbox.Sandbox can be provided to run the --schema invocation inside a sandbox, preventing untrusted scripts from executing side effects during schema loading.

func (*ShellTool) Execute

func (s *ShellTool) Execute(ctx context.Context, args map[string]any) (string, error)

Execute runs the tool with the given arguments

func (*ShellTool) GetName

func (s *ShellTool) GetName() string

GetName returns the name of the tool

func (*ShellTool) GetSchema

func (s *ShellTool) GetSchema() *schema.ToolSchema

GetSchema returns the tool's schema, annotated with [sandboxed] if applicable

func (*ShellTool) GetSource

func (s *ShellTool) GetSource() string

GetSource returns the command/script path

func (*ShellTool) GetType

func (s *ShellTool) GetType() string

GetType returns "shell" for shell tools

func (*ShellTool) SandboxConfig

func (s *ShellTool) SandboxConfig() *sandbox.Config

SandboxConfig returns sandbox override config parsed from the script's schema, or nil if the tool didn't declare any overrides.

func (*ShellTool) SandboxOptOut

func (s *ShellTool) SandboxOptOut() bool

SandboxOptOut reports whether the script explicitly disabled sandboxing by setting "sandbox": false in its schema.

func (*ShellTool) WantsSandbox

func (s *ShellTool) WantsSandbox() bool

WantsSandbox reports whether the script's schema declared sandbox overrides.

func (*ShellTool) WithSandbox

func (s *ShellTool) WithSandbox(sb sandbox.Sandbox) *ShellTool

WithSandbox returns a copy with sandboxing enabled.

type SkillActivateTool

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

SkillActivateTool loads a skill's instructions and registers any executable scripts.

func NewSkillActivateTool

func NewSkillActivateTool(catalog *skills.Catalog, registry *ToolRegistry) *SkillActivateTool

NewSkillActivateTool creates the skill activation tool.

func (*SkillActivateTool) ActivatedSkills

func (t *SkillActivateTool) ActivatedSkills() []string

ActivatedSkills returns the activated skill names in stable order.

func (*SkillActivateTool) Execute

func (t *SkillActivateTool) Execute(ctx context.Context, args map[string]any) (string, error)

func (*SkillActivateTool) GetName

func (t *SkillActivateTool) GetName() string

func (*SkillActivateTool) GetSchema

func (t *SkillActivateTool) GetSchema() *schema.ToolSchema

func (*SkillActivateTool) GetSource

func (t *SkillActivateTool) GetSource() string

func (*SkillActivateTool) GetType

func (t *SkillActivateTool) GetType() string

type SkillReadFileTool

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

SkillReadFileTool returns the contents of a file inside a discovered skill.

func NewSkillReadFileTool

func NewSkillReadFileTool(catalog *skills.Catalog) *SkillReadFileTool

NewSkillReadFileTool creates the skill file reader tool.

func (*SkillReadFileTool) Execute

func (t *SkillReadFileTool) Execute(ctx context.Context, args map[string]any) (string, error)

func (*SkillReadFileTool) GetName

func (t *SkillReadFileTool) GetName() string

func (*SkillReadFileTool) GetSchema

func (t *SkillReadFileTool) GetSchema() *schema.ToolSchema

func (*SkillReadFileTool) GetSource

func (t *SkillReadFileTool) GetSource() string

func (*SkillReadFileTool) GetType

func (t *SkillReadFileTool) GetType() string

type SkillRuntime

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

SkillRuntime exposes a public API for skill activation, restore, and state export.

func NewSkillRuntime

func NewSkillRuntime(catalog *skills.Catalog, registry *ToolRegistry) (*SkillRuntime, error)

NewSkillRuntime registers the built-in skill tools on the registry and returns a runtime facade.

func (*SkillRuntime) Activate

func (r *SkillRuntime) Activate(name string) (string, error)

Activate activates a skill immediately and commits the resulting tools and policy into the registry.

func (*SkillRuntime) ActivatedSkills

func (r *SkillRuntime) ActivatedSkills() []string

ActivatedSkills returns the currently activated skill names in stable order.

func (*SkillRuntime) Catalog

func (r *SkillRuntime) Catalog() *skills.Catalog

Catalog returns the discovered skill catalog backing the runtime.

func (*SkillRuntime) Enabled

func (r *SkillRuntime) Enabled() bool

Enabled reports whether discovered skills are available for activation.

func (*SkillRuntime) Restore

func (r *SkillRuntime) Restore(names []string) error

Restore reactivates previously active skills and commits their tools and policy into the registry.

type Tool

type Tool interface {
	// Execution methods
	GetSchema() *schema.ToolSchema
	Execute(ctx context.Context, args map[string]any) (string, error)

	// Metadata methods
	GetName() string   // Returns the namespaced name (e.g., "script__toolname")
	GetType() string   // Returns the tool type: "shell", "mcp", or "native"
	GetSource() string // Returns the source path/spec (e.g., "/path/to/script.sh")
}

Tool is the generic interface for all tools

func LoadShellTools

func LoadShellTools(paths []string) ([]Tool, error)

LoadShellTools loads shell tools from the given file paths

type ToolCall

type ToolCall struct {
	ID   string         // Provider-specific ID (if any)
	Name string         // Tool name
	Args map[string]any // Parsed arguments
}

ToolCall represents a request to execute a tool

type ToolError

type ToolError struct {
	Message string `json:"error"`
	Code    string `json:"code,omitempty"`
}

ToolError is a structured error returned by tools. When a tool returns a *ToolError from Execute, the agent serializes it as JSON with "error" and "code" fields instead of the generic "Error: ..." format.

func NewToolError

func NewToolError(message, code string) *ToolError

NewToolError creates a structured tool error with message and code.

func (*ToolError) Error

func (e *ToolError) Error() string

type ToolLoaderInfo

type ToolLoaderInfo struct {
	Name   string `json:"name"`   // Full namespaced tool name
	Type   string `json:"type"`   // "shell", "mcp", or "native"
	Source string `json:"source"` // Path for shell, server spec for MCP, "builtin" for native
}

ToolLoaderInfo stores information needed to reload a specific tool

type ToolRegistry

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

ToolRegistry manages available tools

func NewToolRegistry

func NewToolRegistry(tools []Tool, opts ...RegistryOption) *ToolRegistry

NewToolRegistry creates a new tool registry from a list of tools

func (*ToolRegistry) All

func (r *ToolRegistry) All() []Tool

All returns all tools in the registry

func (*ToolRegistry) Close

func (r *ToolRegistry) Close() error

Close cleans up all resources

func (*ToolRegistry) CommitPendingChanges

func (r *ToolRegistry) CommitPendingChanges()

CommitPendingChanges applies staged skill activations between agent turns.

func (*ToolRegistry) Get

func (r *ToolRegistry) Get(name string) (Tool, bool)

Get retrieves a tool by name

func (*ToolRegistry) GetActiveToolLoaders

func (r *ToolRegistry) GetActiveToolLoaders() []ToolLoaderInfo

GetActiveToolLoaders returns loader information for all tools This returns one entry per tool to allow selective loading

func (*ToolRegistry) GetIfAllowed

func (r *ToolRegistry) GetIfAllowed(name string) (tool Tool, exists bool, allowed bool)

GetIfAllowed retrieves a tool by name, returning existence and allowance in a single lock acquisition.

func (*ToolRegistry) GetLoadedMCPServers

func (r *ToolRegistry) GetLoadedMCPServers() []string

GetLoadedMCPServers returns list of loaded server specs

func (*ToolRegistry) GetSchemas

func (r *ToolRegistry) GetSchemas() []*schema.ToolSchema

GetSchemas returns all tool schemas

func (*ToolRegistry) HasSandbox

func (r *ToolRegistry) HasSandbox() bool

HasSandbox reports whether sandboxing is available.

func (*ToolRegistry) LoadMCPServer

func (r *ToolRegistry) LoadMCPServer(serverSpec string) (LoadResult, error)

LoadMCPServer connects to an MCP server and registers its tools with namespace For multi-server configs (mcpServers format), loads ALL servers

func (*ToolRegistry) LoadMCPServerWithFilter

func (r *ToolRegistry) LoadMCPServerWithFilter(serverSpec string, allowedTools []string) error

LoadMCPServerWithFilter connects to an MCP server and only registers specified tools serverSpec format: "path/to/config.json#servername"

func (*ToolRegistry) LoadMCPServerWithNamespacePrefix

func (r *ToolRegistry) LoadMCPServerWithNamespacePrefix(serverSpec, namespacePrefix string) (LoadResult, error)

LoadMCPServerWithNamespacePrefix loads all servers from a config file with an explicit namespace prefix.

func (*ToolRegistry) LoadShellTool

func (r *ToolRegistry) LoadShellTool(path string) (LoadResult, error)

LoadShellTool loads a single shell tool from a file path with the default namespace.

func (*ToolRegistry) LoadShellToolWithNamespace

func (r *ToolRegistry) LoadShellToolWithNamespace(path, namespace string) (LoadResult, error)

LoadShellToolWithNamespace loads a single shell tool from a file path with an explicit namespace.

func (*ToolRegistry) LoadToolAuto

func (r *ToolRegistry) LoadToolAuto(pathOrServer string) (LoadResult, error)

LoadToolAuto attempts to load a tool, auto-detecting if it's native, shell tool, or MCP server

func (*ToolRegistry) MarkAlwaysAllowed

func (r *ToolRegistry) MarkAlwaysAllowed(name string)

MarkAlwaysAllowed exempts a tool from active skill allowlist filtering.

func (*ToolRegistry) NewSandbox

func (r *ToolRegistry) NewSandbox(overlay *sandbox.Config) (sandbox.Sandbox, error)

NewSandbox creates a sandbox with the base config merged with optional per-tool overrides.

func (*ToolRegistry) NewSandboxDirect

func (r *ToolRegistry) NewSandboxDirect(cfg sandbox.Config) (sandbox.Sandbox, error)

NewSandboxDirect creates a sandbox from an explicit config, ignoring the base config.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(tool Tool)

Register adds a tool to the registry

func (*ToolRegistry) RegisterNative

func (r *ToolRegistry) RegisterNative(name string, factory func() Tool)

RegisterNative registers a native tool factory

func (*ToolRegistry) Remove

func (r *ToolRegistry) Remove(namespacedName string)

Remove removes a tool by namespaced name from the registry

func (*ToolRegistry) UnloadMCPServer

func (r *ToolRegistry) UnloadMCPServer(serverSpec string) error

UnloadMCPServer removes all tools from a server and closes it

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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