tool

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: Apache-2.0 Imports: 16 Imported by: 1

Documentation

Index

Constants

View Source
const (
	ModeAsk      = "ask"       // ask user for every tool call
	ModeAuto     = "auto"      // execute automatically
	ModeDeny     = "deny"      // refuse tool execution
	ModeBestPath = "best_path" // auto-approve safe tools, block risky/destructive tools
)

Mode constants for tool execution behaviour.

Variables

This section is empty.

Functions

func AddInternalService

func AddInternalService(reg Registry, s svc.Service)

AddInternalService attempts to register a service as an internal MCP client on the default registry.

func BestPathAllowed

func BestPathAllowed(name string) bool

BestPathAllowed returns true when the tool appears safe for automatic execution under ModeBestPath. Internal tools remain always allowed.

func InjectVirtualAgentTools

func InjectVirtualAgentTools(reg Registry, agents []*agent.Agent, domain string)

InjectVirtualAgentTools exposes agents as virtual tools when supported by the registry implementation.

func IsPolicyError

func IsPolicyError(err error) bool

IsPolicyError reports whether err is a policy denial/rejection.

func MarkApprovalQueueTool

func MarkApprovalQueueTool(ctx context.Context, name string, cfg *ApprovalQueueConfig)

MarkApprovalQueueTool marks a tool name to require approval queue.

func NormalizeMode

func NormalizeMode(mode string) string

NormalizeMode converts aliases to canonical policy modes.

func RequiresApprovalQueue

func RequiresApprovalQueue(ctx context.Context, name string) bool

RequiresApprovalQueue reports whether a tool should be queued for approval.

func RewriteContainerDataSourceRefs

func RewriteContainerDataSourceRefs(c types.Container, nameMap map[string]string) types.Container

RewriteContainerDataSourceRefs returns a copy of the container with every dataSourceRef rewritten according to the provided name mapping. Keys are original names; values are transformed names.

func ValidateExecution

func ValidateExecution(ctx context.Context, p *Policy, name string, args map[string]interface{}) error

ValidateExecution checks whether a tool execution is permitted by policy. Returns nil when allowed; otherwise an explanatory error.

func WithApprovalQueueState

func WithApprovalQueueState(ctx context.Context) context.Context

WithApprovalQueueState ensures a mutable approval-queue state exists in context.

func WithPolicy

func WithPolicy(ctx context.Context, p *Policy) context.Context

WithPolicy attaches policy to context.

Types

type ActivationSpec

type ActivationSpec struct {
	// Kind selects the activation mode: "history" or "tool_call".
	Kind string `yaml:"kind,omitempty" json:"kind,omitempty"`
	// Scope controls how many recorded calls are considered when kind==history:
	//  - "last" (default): only the most recent matching call is used
	//  - "all": aggregate data from all matching calls in the turn
	Scope string `yaml:"scope,omitempty" json:"scope,omitempty"`
	// Optional explicit tool to invoke when kind==tool_call. When omitted,
	// match.service/method may be used as a fallback by the consumer.
	Service string                 `yaml:"service,omitempty" json:"service,omitempty"`
	Method  string                 `yaml:"method,omitempty" json:"method,omitempty"`
	Args    map[string]interface{} `yaml:"args,omitempty" json:"args,omitempty"`
}

type ApprovalQueueConfig

type ApprovalQueueConfig struct {
	Enabled            bool
	TitleSelector      string
	DataSourceSelector string
	UIURI              string
}

func ApprovalQueueFor

func ApprovalQueueFor(ctx context.Context, name string) (*ApprovalQueueConfig, bool)

ApprovalQueueFor returns the approval queue config for a tool.

type AskFunc

type AskFunc func(ctx context.Context, name string, args map[string]interface{}, p *Policy) bool

AskFunc is invoked when policy.Mode==ModeAsk. It should return true to approve the call, false to reject. It can optionally mutate the policy (for example to switch to auto mode after user confirmation).

type ContextMatcher

type ContextMatcher interface {
	MatchDefinitionWithContext(ctx context.Context, pattern string) []*llm.ToolDefinition
}

ContextMatcher is an optional extension for registries that can evaluate tool pattern matches using request-scoped context.

type DataFeed

type DataFeed struct {
	Name        string      `json:"name" yaml:"name"`
	Data        interface{} `json:"data" yaml:"data"`
	RawSelector string      `json:"rawSelector" yaml:"rawSelector"`
}

DataFeed carries a resolved value and the raw selector used to obtain it. The type of Data is intentionally interface{} to support both object and collection values (e.g., a map with explanation/steps or a []map rows list).

type DataSource

type DataSource struct {
	types.DataSource `yaml:",inline"`
	Source           string `json:"source" yaml:"source"`
	Name             string `json:"name" yaml:"name"`
}

func (*DataSource) HasSource

func (d *DataSource) HasSource() bool

type DataSources

type DataSources map[string]*DataSource

func (DataSources) FeedDataSource

func (s DataSources) FeedDataSource() (*DataSource, error)

func (DataSources) Normalize

func (s DataSources) Normalize() map[string]*types.DataSource

Normalize returns normalized datasourcse

func (DataSources) Transform

func (s DataSources) Transform(hash string) (map[string]*types.DataSource, map[string]string)

Transform returns a normalized map of DataSources with keys suffixed by the provided hash, and a mapping from original name -> transformed name. Any internal DataSourceRef fields that reference other data sources are also rewritten using the mapping.

type Feed

type Feed struct {
	ID string `json:"id" yaml:"id"`

	// Data holds resolved data blocks keyed by data-source or container name.
	Data DataFeed `json:"dataFeed" yaml:"dataFeed"`

	// UI carries a renderable container definition for Forge-based UIs.
	UI *types.Container `json:"ui" yaml:"ui"`

	// DataSources defines UI data sources
	DataSources map[string]*types.DataSource `yaml:"dataSources,omitempty" json:"dataSources,omitempty"`

	Invoked bool `json:"-" yaml:"-"`
}

Feed describes a single matched rule and its extracted data. It is used as the payload for tool feeds rendered by the UI.

type FeedSpec

type FeedSpec struct {
	ID          string          `yaml:"id,omitempty" json:"id,omitempty"`
	Title       string          `yaml:"title,omitempty" json:"title,omitempty"`
	Priority    int             `yaml:"priority,omitempty" json:"priority,omitempty"`
	Match       MatchSpec       `yaml:"match" json:"match"`
	Activation  ActivationSpec  `yaml:"activation" json:"activation"`
	DataSources DataSources     `yaml:"dataSource,omitempty" json:"dataSource,omitempty"`
	UI          types.Container `yaml:"ui" json:"ui"`
}

func (*FeedSpec) InvokeServiceMethod

func (f *FeedSpec) InvokeServiceMethod() (string, string)

InvokeServiceMethod returns the effective (service, method) to invoke for this spec, preferring Activation overrides and falling back to Match when empty.

func (*FeedSpec) ShallInvokeTool

func (f *FeedSpec) ShallInvokeTool() bool

ShallInvokeTool indicates whether this spec should trigger a direct tool invocation.

func (*FeedSpec) ShallUseHistory

func (f *FeedSpec) ShallUseHistory() bool

ShallUseHistory indicates whether this spec should evaluate history (default when kind is empty) or explicitly when kind==history.

type FeedSpecs

type FeedSpecs []*FeedSpec

FeedSpecs is a convenience slice alias for helpers.

func (FeedSpecs) Index

func (s FeedSpecs) Index() map[mcpname.Name]*FeedSpec

func (FeedSpecs) MatchSpec

func (s FeedSpecs) MatchSpec() []MatchSpec

MatchSpec collects all MatchSpec entries in declaration order.

func (FeedSpecs) Matches

func (s FeedSpecs) Matches(name mcpname.Name) bool

Matches reports whether any spec matches the provided canonical tool name.

type Handler

type Handler func(ctx context.Context, args map[string]interface{}) (string, error)

Handler executes a tool call and returns its textual result.

type MatchSpec

type MatchSpec struct {
	Service string `yaml:"service,omitempty" json:"service,omitempty"`
	Method  string `yaml:"method,omitempty" json:"method,omitempty"`
}

func (MatchSpec) Matches

func (m MatchSpec) Matches(name mcpname.Name) bool

Matches compares against a canonical tool name. It supports simple wildcards: "*" in Service or Method matches any value.

func (*MatchSpec) Name

func (m *MatchSpec) Name() mcpname.Name

type Policy

type Policy struct {
	Mode      string   // ask, auto or deny
	AllowList []string // optional set of allowed tools (empty => all)
	BlockList []string // optional set of blocked tools
	Ask       AskFunc  // optional callback when Mode==ask
}

Policy controls runtime behaviour of tool execution.

func FromContext

func FromContext(ctx context.Context) *Policy

FromContext retrieves policy from context; may be nil.

func (*Policy) IsAllowed

func (p *Policy) IsAllowed(name string) bool

IsAllowed checks whether a tool name is permitted by Allow/Block lists.

type PolicyError

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

PolicyError represents a tool execution rejection caused by approval policy.

func (*PolicyError) Error

func (e *PolicyError) Error() string

type Registry

type Registry interface {
	// Definitions returns the merged list of available tool definitions.
	Definitions() []llm.ToolDefinition

	//MatchDefinition matches tool definition based on pattern
	MatchDefinition(pattern string) []*llm.ToolDefinition

	// GetDefinition fetches the definition for the given tool name. The second
	// result value indicates whether the definition exists.
	GetDefinition(name string) (*llm.ToolDefinition, bool)

	// MustHaveTools converts a set of patterns into the LLM toolkit slice used by
	// generation prompts.
	MustHaveTools(patterns []string) ([]llm.Tool, error)

	// Execute invokes the given tool with the supplied arguments and returns
	// its textual result.
	Execute(ctx context.Context, name string, args map[string]interface{}) (string, error)

	// SetDebugLogger attaches a writer that receives every executed tool call
	// for debugging.
	SetDebugLogger(w io.Writer)

	// Initialize allows registry implementations to perform optional
	// one-time discovery or warm-up (e.g., preload MCP servers/tools).
	// Implementations should be idempotent. Callers may safely ignore it.
	Initialize(ctx context.Context)
}

Registry defines the minimal interface required by the rest of the code-base. Previous consumers used a concrete *Registry struct; moving to an interface allows alternative implementations (remote catalogues, mocks, etc.) while retaining backward-compatibility.

func NewDefaultRegistry

func NewDefaultRegistry(mgr *manager.Manager) (Registry, error)

NewDefaultRegistry constructs the default MCP-backed tool registry with built-ins.

func WithConversation

func WithConversation(inner Registry, convID string) Registry

WithConversation returns a Registry that guarantees ctx carries convID for every Execute call. All other methods delegate to the underlying registry.

type Source

type Source struct {
	Service string `json:"service" yaml:"service"`
	Method  string `json:"method" yaml:"method"`
}

Source identifies the tool that produced the output observed by the rule.

type TimeoutResolver

type TimeoutResolver interface {
	ToolTimeout(name string) (time.Duration, bool)
}

TimeoutResolver may be implemented by registries that can suggest per-tool execution timeouts. The returned duration should be >0 to take effect; the boolean indicates whether a suggestion is available for the given name.

Jump to

Keyboard shortcuts

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