tools

package
v1.54.0 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DescriptionParam is the parameter name for the description
	DescriptionParam = "description"
)

Variables

This section is empty.

Functions

func As

func As[T any](ts ToolSet) (T, bool)

As performs a type assertion on a ToolSet, walking the wrapper chain if needed. It checks the outermost toolset first, then recursively unwraps through any Unwrapper implementations (including StartableToolSet and decorator wrappers) until it finds a match or reaches the end of the chain.

Example:

if pp, ok := tools.As[tools.PromptProvider](toolset); ok {
    prompts, _ := pp.ListPrompts(ctx)
}

func ConfigureHandlers

func ConfigureHandlers(ts ToolSet, elicitHandler ElicitationHandler, oauthHandler func(), managedOAuth bool)

ConfigureHandlers sets all applicable handlers on a toolset. It checks for Elicitable and OAuthCapable interfaces and configures them. This is a convenience function that handles the capability checking internally.

func ConvertSchema

func ConvertSchema(params, v any) error

func DescribeToolSet

func DescribeToolSet(ts ToolSet) string

DescribeToolSet returns a short description for ts suitable for user-visible messages. It walks the wrapper chain (e.g. through WithName / StartableToolSet) so any inner Describer is reachable; falls back to the Go type name when no inner toolset implements Describer.

func ExtractDescription

func ExtractDescription(arguments string) string

ExtractDescription extracts the description from tool call arguments.

func GetInstructions

func GetInstructions(ts ToolSet) string

GetInstructions returns instructions if the toolset implements Instructable. Returns empty string if the toolset doesn't provide instructions.

func GetName added in v1.54.0

func GetName(ts ToolSet) string

GetName returns the toolset's Name when an inner toolset advertises one via Named, walking through any Unwrapper-reachable wrapper chain. The empty string is returned when no wrapper provides a name.

func MustSchemaFor

func MustSchemaFor[T any]() any

func SchemaFor

func SchemaFor[T any]() (any, error)

func SchemaToMap

func SchemaToMap(params any) (map[string]any, error)

func ToolsetIdentifier

func ToolsetIdentifier(ts ToolSet) string

ToolsetIdentifier returns a human-readable identifier for a toolset. It falls back to the toolset type when no metadata is available.

Types

type AudioContent

type AudioContent = MediaContent

AudioContent is an alias kept for readability at call sites.

type ChangeNotifier

type ChangeNotifier interface {
	SetToolsChangedHandler(handler func())
}

ChangeNotifier is implemented by toolsets that can notify when their tool list changes (e.g. after an MCP ToolListChanged notification).

type Describer

type Describer interface {
	Describe() string
}

Describer can be implemented by a ToolSet to provide a short, user-visible description that uniquely identifies the toolset instance (e.g. for use in error messages and warnings). The string must never contain secrets.

type Elicitable

type Elicitable interface {
	SetElicitationHandler(handler ElicitationHandler)
}

Elicitable is implemented by toolsets that support MCP elicitation.

type ElicitationAction

type ElicitationAction string
const (
	ElicitationActionAccept  ElicitationAction = "accept"
	ElicitationActionDecline ElicitationAction = "decline"
	ElicitationActionCancel  ElicitationAction = "cancel"
)

type ElicitationHandler

type ElicitationHandler func(ctx context.Context, req *mcp.ElicitParams) (ElicitationResult, error)

ElicitationHandler is a function type that handles elicitation requests from the MCP server This allows the runtime to handle elicitation requests and propagate them to its own client

type ElicitationResult

type ElicitationResult struct {
	Action  ElicitationAction `json:"action"`
	Content map[string]any    `json:"content,omitempty"`
}

type FunctionCall

type FunctionCall struct {
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`
}

type ImageContent

type ImageContent = MediaContent

ImageContent is an alias kept for readability at call sites.

type Instructable

type Instructable interface {
	Instructions() string
}

Instructable is implemented by toolsets that provide custom instructions.

type Kinder added in v1.54.0

type Kinder interface {
	Kind() string
}

Kinder is implemented by ToolSets that can produce a short, user-friendly classification of themselves (e.g. "MCP", "Remote MCP", "LSP"). The string is meant for human display in surfaces like the /tools dialog. Toolsets that do not implement Kinder are surfaced without a Kind, which the renderer treats as "Built-in".

type MediaContent

type MediaContent struct {
	// Data is the base64-encoded payload.
	Data string `json:"data"`
	// MimeType identifies the content type (e.g. "image/png", "audio/wav").
	MimeType string `json:"mimeType"`
}

MediaContent represents base64-encoded binary data (image, audio, etc.) returned by a tool.

type Named added in v1.54.0

type Named interface {
	Name() string
}

Named is implemented by toolsets that carry a user-visible name.

The convention is:

  • For toolsets that take a `name:` in their YAML entry (currently MCP, A2A, OpenAPI), Name() returns that user-set value.
  • For built-in toolsets that don't expose a `name:` field (`shell`, `filesystem`, `memory`, …), the registry wraps the toolset with WithName(toolset.Type) so Name() returns the YAML `type:` instead. The point is that no surface ever has to display a Go type ("*builtin.ShellTool") to the user.

type OAuthCapable

type OAuthCapable interface {
	SetOAuthSuccessHandler(handler func())
	SetManagedOAuth(managed bool)
}

OAuthCapable is implemented by toolsets that support OAuth flows.

type Restartable added in v1.54.0

type Restartable interface {
	Restart(ctx context.Context) error
}

Restartable is implemented by toolsets that can be restarted in place (typically the supervisor-backed MCP and LSP toolsets). Restart closes the active session and waits for the supervisor to bring up a fresh one, or returns an error on timeout.

The expected use case is post-OAuth recovery ("I just authenticated, reconnect this MCP") and operator-driven debugging through the /toolset-restart slash command.

type Startable

type Startable interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

Startable is implemented by toolsets that require initialization before use. Toolsets that don't implement this interface are assumed to be ready immediately.

type StartableToolSet

type StartableToolSet struct {
	ToolSet
	// contains filtered or unexported fields
}

StartableToolSet wraps a ToolSet with lazy, single-flight start semantics. This is the canonical way to manage toolset lifecycle.

It also de-duplicates start-failure warnings: when Start() fails repeatedly (e.g. an MCP server is down), only the *first* failure of each streak is reported via ShouldReportFailure(). A successful Start() automatically clears the streak, so a future failure is again reported as fresh — no caller-visible "recovery" event is needed.

func NewStartable

func NewStartable(ts ToolSet) *StartableToolSet

NewStartable wraps a ToolSet for lazy initialization.

func (*StartableToolSet) IsStarted

func (s *StartableToolSet) IsStarted() bool

IsStarted returns whether the toolset has been successfully started. For toolsets that don't implement Startable, this always returns true.

func (*StartableToolSet) ShouldReportFailure added in v1.48.0

func (s *StartableToolSet) ShouldReportFailure() bool

ShouldReportFailure returns true exactly once per failure streak — after the first failed Start() and before the streak ends (a successful Start() or Stop()). Subsequent calls return false until a new streak begins. Calling it when no failure is pending always returns false.

func (*StartableToolSet) Start

func (s *StartableToolSet) Start(ctx context.Context) error

Start starts the toolset with single-flight semantics. Concurrent callers block until the start attempt completes. If start fails, a future call will retry. If the underlying toolset doesn't implement Startable, this is a no-op.

func (*StartableToolSet) Stop

func (s *StartableToolSet) Stop(ctx context.Context) error

Stop stops the toolset if it implements Startable and resets the started flag so that a subsequent Start will re-initialize.

func (*StartableToolSet) Unwrap

func (s *StartableToolSet) Unwrap() ToolSet

Unwrap returns the underlying ToolSet.

type Statable added in v1.54.0

type Statable interface {
	State() lifecycle.StateInfo
}

Statable is implemented by toolsets that expose a lifecycle state snapshot (Stopped/Starting/Ready/Degraded/Restarting/Failed) plus the most recent error and restart count. The TUI uses this to render the /tools dialog without polling each transport individually.

Toolsets that do not implement Statable are reported as "unknown" by status surfaces.

type Tool

type Tool struct {
	Name                    string          `json:"name"`
	Category                string          `json:"category"`
	Description             string          `json:"description,omitempty"`
	Parameters              any             `json:"parameters"`
	Annotations             ToolAnnotations `json:"annotations"`
	OutputSchema            any             `json:"outputSchema"`
	Handler                 ToolHandler     `json:"-"`
	AddDescriptionParameter bool            `json:"-"`
	// ModelOverride is the per-toolset model for the LLM turn that processes
	// this tool's results. Set automatically from the toolset "model" field.
	ModelOverride string `json:"-"`
}

func AddDescriptionParameter

func AddDescriptionParameter(toolList []Tool) []Tool

AddDescriptionParameter adds a "description" parameter to tools that have AddDescriptionParameter set to true. This allows the LLM to provide context about what it's doing with each tool call.

func (*Tool) DisplayName

func (t *Tool) DisplayName() string

type ToolAnnotations

type ToolAnnotations mcp.ToolAnnotations

type ToolCall

type ToolCall struct {
	ID       string       `json:"id,omitempty"`
	Type     ToolType     `json:"type"`
	Function FunctionCall `json:"function"`
}

type ToolCallResult

type ToolCallResult struct {
	Output  string `json:"output"`
	IsError bool   `json:"isError,omitempty"`
	Meta    any    `json:"meta,omitempty"`
	// Images contains optional image attachments returned by the tool.
	Images []MediaContent `json:"images,omitempty"`
	// Audios contains optional audio attachments returned by the tool.
	Audios []MediaContent `json:"audios,omitempty"`
	// StructuredContent holds optional structured output returned by an MCP
	// tool whose definition includes an OutputSchema. When non-nil it is the
	// JSON-decoded structured result from the server.
	StructuredContent any `json:"structuredContent,omitempty"`
}

func ResultError

func ResultError(output string) *ToolCallResult

func ResultJSON added in v1.30.1

func ResultJSON(v any) *ToolCallResult

ResultJSON marshals v as JSON and returns it as a successful tool result. If marshaling fails, it returns an error result.

func ResultSuccess

func ResultSuccess(output string) *ToolCallResult

type ToolHandler

type ToolHandler func(ctx context.Context, toolCall ToolCall) (*ToolCallResult, error)

func NewHandler

func NewHandler[T any](fn func(context.Context, T) (*ToolCallResult, error)) ToolHandler

NewHandler creates a type-safe tool handler from a function that accepts typed parameters. It handles JSON unmarshaling of the tool call arguments into the specified type T.

type ToolSet

type ToolSet interface {
	Tools(ctx context.Context) ([]Tool, error)
}

ToolSet defines the interface for a set of tools.

func WithName added in v1.54.0

func WithName(ts ToolSet, name string) ToolSet

WithName returns ts wrapped so it advertises Name() == name. If ts (or any inner toolset reachable via Unwrap) already advertises a non-empty Name(), ts is returned unchanged so the original implementation wins.

The returned wrapper participates in As[T]: every capability of ts remains reachable through the wrapper.

type ToolType

type ToolType string

type ToolsetMetadata

type ToolsetMetadata interface {
	ToolsetID() string
}

ToolsetMetadata exposes optional details for toolset identification. Implemented by toolsets that can provide additional context for warnings.

type ToolsetStatus added in v1.54.0

type ToolsetStatus struct {
	// Name is the toolset name as configured in the agent YAML (or a
	// derived label when the YAML has no name).
	Name string
	// Kind is a short, user-friendly label such as "MCP", "Remote MCP"
	// or "LSP". Empty when the toolset does not implement Kinder; the
	// TUI renders that case as "Built-in".
	Kind string
	// Description is the user-visible Describer.Describe() output, never
	// containing secrets. Empty when the toolset does not implement
	// Describer. Kept for non-TUI surfaces (logs, JSON status); the TUI
	// uses Name + Kind instead because Description tends to leak Go
	// implementation detail ("mcp(stdio cmd=docker)").
	Description string
	// State is the lifecycle state. For toolsets that don't implement
	// Statable, the runtime sets it to StateReady when the toolset has a
	// usable tool list and StateStopped otherwise — matching what the
	// user actually observes.
	State lifecycle.State
	// LastError is the most recent failure recorded by the supervisor, or
	// nil. Toolsets that don't implement Statable always report nil.
	LastError error
	// RestartCount is the number of supervisor restarts since the last
	// successful Ready transition. Zero for toolsets without a supervisor.
	RestartCount int
}

ToolsetStatus is a snapshot of a single toolset's lifecycle, suitable for status surfaces (TUI /tools dialog, JSON status endpoints, logs).

The fields are intentionally flat and self-describing so they can be rendered without the renderer needing to import lifecycle.

type Unwrapper

type Unwrapper interface {
	Unwrap() ToolSet
}

Unwrapper is implemented by toolset wrappers that decorate another ToolSet. This allows As to walk the wrapper chain and find inner capabilities.

Directories

Path Synopsis
Package a2a provides a toolset implementation for connecting to remote A2A agents.
Package a2a provides a toolset implementation for connecting to remote A2A agents.
Package lifecycle defines the shared vocabulary used by long-running toolsets (MCP servers, remote MCP, LSP servers): typed error sentinels, a State enum, a Tracker, and a Supervisor that drives a Connector through connect / watch / restart / stop.
Package lifecycle defines the shared vocabulary used by long-running toolsets (MCP servers, remote MCP, LSP servers): typed error sentinels, a State enum, a Tracker, and a Supervisor that drives a Connector through connect / watch / restart / stop.

Jump to

Keyboard shortcuts

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