Documentation
¶
Overview ¶
Package tools provides the tool-calling infrastructure: descriptors, a registry that executes them, and the built-in executors.
The package contains:
- A tool descriptor registry with JSON Schema validation of arguments and results
- Mock executors (static and template-based)
- An HTTP executor for live API calls, with request and response mapping
- Exec and server executors that run tools as subprocesses
- An MCP executor that calls tools on MCP servers
- Argument coercion for common model mistakes, such as "10" for an integer
Tools load from YAML or JSON files with Registry.LoadToolFromBytes, or are registered directly with Registry.Register.
Index ¶
- Constants
- Variables
- func CallIDFromContext(ctx context.Context) string
- func ClassifyError(err error) types.ToolErrorType
- func ConsentDeclinedMessage(toolName, strategy string) string
- func ContentTypeToMediaType(contentType string) string
- func DecodeArgsExtras(args json.RawMessage, typed any, knownKeys ...string) (map[string]any, error)
- func ErrorResult(id, name string, err error) types.MessageToolResult
- func FormatResultText(raw json.RawMessage) string
- func IsBinaryContentType(contentType string, acceptTypes []string) bool
- func IsImplicitTool(name string) bool
- func IsSystemTool(name string) bool
- func MatchToolPattern(pattern, name string) bool
- func MergeExtrasIntoMetadata(target, extras map[string]any) map[string]any
- func ParseToolName(name string) (namespace, localName string)
- func QualifyToolName(namespace, localName string) string
- func ReadMultimodalResponse(resp *http.Response, aggregateSize *atomic.Int64, maxAggregateSize int64) (json.RawMessage, []types.ContentPart, error)
- func RedactFields(data []byte, fields []string) []byte
- func ResolveMockParts(parts []types.ContentPart) ([]types.ContentPart, error)
- func TruncateResultText(toolName, content string, maxSize int) string
- func WithCallID(ctx context.Context, id string) context.Context
- func WithMCPRegistry(ctx context.Context, reg mcp.Registry) context.Context
- type A2AAuthConfig
- type A2AConfig
- type A2ARetryConfig
- type A2ASkillFilter
- type ApprovalChecker
- type ApprovalGate
- type AsyncCallExecutor
- type AsyncToolExecutor
- type CallExecutor
- type ClientConfig
- type Coercion
- type ConsentConfig
- type DefaultRequestMapper
- func (m *DefaultRequestMapper) BuildBody(bodyArgs map[string]any, jmespathExpr string) (json.RawMessage, error)
- func (m *DefaultRequestMapper) PartitionArgs(args map[string]any, cfg *RequestMapping, urlTemplate string) (query, header, body map[string]any)
- func (m *DefaultRequestMapper) RenderHeaders(templates map[string]string, args map[string]any) (map[string]string, error)
- func (m *DefaultRequestMapper) RenderURL(urlTemplate string, args map[string]any) (string, error)
- type DefaultResponseMapper
- type DeferringExecutor
- type ErrToolsPending
- type ExecConfig
- type ExecExecutor
- func (e *ExecExecutor) Execute(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, error)
- func (e *ExecExecutor) ExecuteAsync(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (*ToolExecutionResult, error)
- func (e *ExecExecutor) Name() string
- type Executor
- type FileToolResponseRepository
- type HTTPConfig
- type HTTPExecutor
- func (e *HTTPExecutor) AggregateResponseSize() int64
- func (e *HTTPExecutor) Execute(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, error)
- func (e *HTTPExecutor) ExecuteMultimodal(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, []types.ContentPart, error)
- func (e *HTTPExecutor) Name() string
- func (e *HTTPExecutor) ResetAggregateSize()
- type HostExtras
- type InMemoryToolResponseRepository
- type MCPExecutor
- func (e *MCPExecutor) Execute(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, error)
- func (e *MCPExecutor) ExecuteMultimodal(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, []types.ContentPart, error)
- func (e *MCPExecutor) Name() string
- type MockScriptedExecutor
- func (e *MockScriptedExecutor) Execute(_ context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, error)
- func (e *MockScriptedExecutor) ExecuteMultimodal(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, []types.ContentPart, error)
- func (e *MockScriptedExecutor) Name() string
- type MockStaticExecutor
- func (e *MockStaticExecutor) Execute(_ context.Context, descriptor *ToolDescriptor, _ json.RawMessage) (json.RawMessage, error)
- func (e *MockStaticExecutor) ExecuteMultimodal(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, []types.ContentPart, error)
- func (e *MockStaticExecutor) Name() string
- type MockToolErrorConfig
- type MockToolResponseConfig
- type ModelResult
- type ModelResultOptions
- type MultimodalConfig
- type MultimodalExecutor
- type PendingToolExecution
- type PendingToolInfo
- type Registry
- func (r *Registry) AdmitSettled(toolName string, admit func() error) error
- func (r *Registry) AdmitSettledRelease(toolName string, admit func() error) (release func(), err error)
- func (r *Registry) CheckResult(toolName string, content json.RawMessage, parts []types.ContentPart) (*ToolExecutionResult, error)
- func (r *Registry) Child(opts ...RegistryOption) *Registry
- func (r *Registry) Execute(ctx context.Context, toolName string, args json.RawMessage) (*ToolResult, error)
- func (r *Registry) ExecuteAsync(ctx context.Context, toolName string, args json.RawMessage) (*ToolExecutionResult, error)
- func (r *Registry) ExecuteAsyncAdmitted(ctx context.Context, toolName string, args json.RawMessage, admit func() error) (*ToolExecutionResult, error)
- func (r *Registry) ExecuteCall(ctx context.Context, call ToolCall) (*ToolResult, error)
- func (r *Registry) ExecuteCallAsyncAdmitted(ctx context.Context, call ToolCall, admit func() error) (*ToolExecutionResult, error)
- func (r *Registry) Fork() *Registry
- func (r *Registry) Get(name string) *ToolDescriptor
- func (r *Registry) GetByNamespace(ns string) []*ToolDescriptor
- func (r *Registry) GetTool(name string) (*ToolDescriptor, error)
- func (r *Registry) GetTools() map[string]*ToolDescriptor
- func (r *Registry) GetToolsByNames(names []string) ([]*ToolDescriptor, error)
- func (r *Registry) IterateTools(fn func(name string, tool *ToolDescriptor))
- func (r *Registry) List() []string
- func (r *Registry) LoadToolFromBytes(filename string, data []byte) error
- func (r *Registry) MaxToolResultSize() int
- func (r *Registry) Register(descriptor *ToolDescriptor) error
- func (r *Registry) RegisterExecutor(executor Executor)
- func (r *Registry) RegisterLocal(descriptor *ToolDescriptor) error
- func (r *Registry) Unregister(name string) bool
- func (r *Registry) UnregisterLocal(name string) bool
- type RegistryOption
- type RepositoryToolExecutor
- func (e *RepositoryToolExecutor) Execute(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, error)
- func (e *RepositoryToolExecutor) ExecuteCall(ctx context.Context, descriptor *ToolDescriptor, call ToolCall) (json.RawMessage, []types.ContentPart, error)
- func (e *RepositoryToolExecutor) Name() string
- type RequestMapper
- type RequestMapping
- type ResponseMapper
- type ResponseMapping
- type SchemaValidator
- func (sv *SchemaValidator) CacheLen() int
- func (sv *SchemaValidator) CoerceArgs(descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, []Coercion, error)
- func (sv *SchemaValidator) CoerceResult(descriptor *ToolDescriptor, result json.RawMessage) (json.RawMessage, []Coercion, error)
- func (sv *SchemaValidator) ValidateArgs(descriptor *ToolDescriptor, args json.RawMessage) error
- func (sv *SchemaValidator) ValidateResult(descriptor *ToolDescriptor, result json.RawMessage) error
- type ServerExecutor
- type ToolCall
- type ToolConfig
- type ToolDescriptor
- type ToolErrorData
- type ToolExecutionResult
- type ToolExecutionStatus
- type ToolRepository
- type ToolResponseData
- type ToolResponseRepository
- type ToolResult
- type ValidationError
Examples ¶
Constants ¶
const ( // DefaultToolTimeout is the default execution timeout applied to tools // that don't specify their own TimeoutMs. 30 seconds accommodates HTTP-calling // tools and other network-dependent operations. DefaultToolTimeout = 30000 // DefaultMaxToolResultSize is the maximum allowed size (in bytes) of a // tool result's text. The provider stage truncates results that exceed it. DefaultMaxToolResultSize = 1 * 1024 * 1024 // 1 MB )
const ( DeclineStrategyFallback = "fallback" DeclineStrategyError = "error" DeclineStrategyRetry = "retry" )
Decline strategy constants for ConsentConfig.DeclineStrategy.
const ( // DefaultMaxAggregateSize is the default limit, in bytes, on the response // bytes an HTTPExecutor reads across all its calls (50MB). DefaultMaxAggregateSize = 50 * 1024 * 1024 )
Default configuration values for HTTP tool execution.
const DefaultMaxSchemaCacheSize = 128
DefaultMaxSchemaCacheSize is the maximum number of compiled JSON schemas held in the validator cache. When full the least-recently-used entry is evicted.
const NamespaceSep = "__"
NamespaceSep is the separator used in qualified tool names. Example: "a2a__weather_agent__get_forecast"
Variables ¶
var ( // ErrToolNotFound is returned when a requested tool is not found in the registry. ErrToolNotFound = errors.New("tool not found") // ErrToolNameRequired is returned when registering a tool without a name. ErrToolNameRequired = errors.New("tool name is required") // ErrToolDescriptionRequired is returned when registering a tool without a description. ErrToolDescriptionRequired = errors.New("tool description is required") // ErrInputSchemaRequired is returned when registering a tool without an input schema. ErrInputSchemaRequired = errors.New("input schema is required") // ErrOutputSchemaRequired is returned when registering a tool without an output schema. ErrOutputSchemaRequired = errors.New("output schema is required") // ErrInvalidToolMode is returned when a tool has an invalid mode. ErrInvalidToolMode = errors.New("mode must be 'mock', 'live', 'local', 'mcp', 'client', or a registered executor name") // ErrMockExecutorOnly is returned when a non-mock tool is passed to a mock executor. ErrMockExecutorOnly = errors.New("executor can only execute mock tools") // ErrMCPExecutorOnly is returned when a non-mcp tool is passed to an MCP executor. ErrMCPExecutorOnly = errors.New("MCP executor can only execute mcp tools") // ErrToolTimeout is returned when a tool execution exceeds its configured timeout. ErrToolTimeout = errors.New("tool execution timed out") )
Sentinel errors for tool operations.
var ErrAggregateResponseSizeExceeded = fmt.Errorf("aggregate HTTP response size limit exceeded")
ErrAggregateResponseSizeExceeded is returned when the cumulative response size across all HTTP tool calls exceeds the configured maximum.
var ErrRateLimitExceeded = fmt.Errorf("tool rate limit exceeded")
ErrRateLimitExceeded is the error reported when a tool call exceeds its per-minute rate limit. Registry.Execute reports its message in ToolResult.Error and Registry.ExecuteAsync in ToolExecutionResult.Error; neither returns it.
var ErrTemplatedURLHost = errors.New(
"http tool URL templates may use arguments in the path and query, not the scheme or host")
ErrTemplatedURLHost is returned for an HTTP tool whose URL template puts an argument in the scheme or host.
var ErrURLDotSegment = errors.New(`http tool URL path has a "." or ".." segment`)
ErrURLDotSegment is returned by DefaultRequestMapper.RenderURL when the rendered path has a "." or ".." segment. Escaping cannot neutralize a value that is a whole dot segment, and a server resolving it would serve a different path from the one the template names.
Functions ¶
func CallIDFromContext ¶
CallIDFromContext extracts the tool call ID from the context. Returns an empty string if no call ID is set.
func ClassifyError ¶ added in v2.22.0
func ClassifyError(err error) types.ToolErrorType
ClassifyError is the class of a tool call's error: a validation error when err wraps a *ValidationError, an execution error otherwise.
func ConsentDeclinedMessage ¶ added in v2.17.0
ConsentDeclinedMessage is the tool result text that tells the model the user declined consent for toolName, worded for the decline strategy: fallback asks for an alternative approach, retry for a different approach, and error (or any other value) reports the denial. PromptArena's consent simulation uses the same text.
func ContentTypeToMediaType ¶
ContentTypeToMediaType maps an HTTP Content-Type to a types.ContentPart Type string.
func DecodeArgsExtras ¶
DecodeArgsExtras decodes raw tool args twice: once into the executor's typed struct, and once into a generic map so any keys NOT named in knownKeys can be returned to the caller for routing into the output's Metadata bag.
Hosts use sdk.WithToolDescriptorOverride to extend a capability tool's InputSchema with deployment-specific top-level fields. Without this helper, the executor's typed Unmarshal would drop those fields silently. With it, the executor can keep its strict typing AND let unknown args flow through as metadata extras.
knownKeys must list every top-level JSON key the executor's typed struct owns; passing the wrong list causes typed fields to be duplicated into extras (annoying but harmless — typed values still win when merged).
Returns an empty map (not nil) when args contains no extras, so callers can merge unconditionally without nil checks. Returns nil + nil when args is empty or "null" — both mean "no args at all".
func ErrorResult ¶ added in v2.22.0
func ErrorResult(id, name string, err error) types.MessageToolResult
ErrorResult is the tool result the model is given for call id of tool name that failed with err: "Error: <err>" as its text, err as its error, and err's class (ClassifyError). The provider stage answers a failed call with it, and the SDK answers a result a host settled outside the turn with it when the result cannot be prepared.
func FormatResultText ¶ added in v2.22.0
func FormatResultText(raw json.RawMessage) string
FormatResultText is a JSON tool result as the model is given it: a string unquoted, an object or array indented, any other value as written (numbers keep their exact digits, null reads null). The empty string reads "" (two quote characters), as does no result at all: an empty text block is rejected by some providers. Text that is not JSON is returned as it is.
func IsBinaryContentType ¶
IsBinaryContentType returns true if the Content-Type indicates a binary response that should be handled as multimodal content rather than JSON. If acceptTypes is non-empty, only those specific types match. Otherwise, common image/audio/video prefixes are checked.
func IsImplicitTool ¶
IsImplicitTool reports whether a system tool is auto-surfaced to every prompt without an allowed_tools entry. Capability tools (a2a, workflow, memory, skill, image/video mediagen) are implicitly available. MCP tools are system-namespaced but must be listed explicitly in allowed_tools (or matched by an mcp__<server>__* wildcard), so they are excluded here.
func IsSystemTool ¶
IsSystemTool returns true if name belongs to a known system namespace.
func MatchToolPattern ¶
MatchToolPattern reports whether a tool name matches an allowed_tools entry. An entry ending in "*" is a prefix match (the text before "*" is treated as a literal prefix), so "mcp__memory__*" matches every tool from the "memory" MCP server and "mcp__*" matches every MCP tool. Any other entry is an exact match.
func MergeExtrasIntoMetadata ¶
MergeExtrasIntoMetadata copies extras into target, leaving any keys already present in target untouched. This implements the "typed-fields-win" conflict rule: if both the typed `metadata` arg and a passthrough extra have the same key, the typed value (already in target) wins.
If target is nil and extras is non-empty, returns a fresh map; otherwise mutates target in place and returns it. Returns nil when both are empty.
func ParseToolName ¶
ParseToolName splits a qualified tool name on the first NamespaceSep. "a2a__weather__forecast" → ("a2a", "weather__forecast") "get_weather" → ("", "get_weather") "" → ("", "")
func QualifyToolName ¶
QualifyToolName joins a namespace and local name with NamespaceSep. ("mcp", "fs__read") → "mcp__fs__read" ("", "get_weather") → "get_weather"
func ReadMultimodalResponse ¶
func ReadMultimodalResponse( resp *http.Response, aggregateSize *atomic.Int64, maxAggregateSize int64, ) (json.RawMessage, []types.ContentPart, error)
ReadMultimodalResponse reads a binary HTTP response and returns it as a ContentPart with base64-encoded data. It enforces per-response and aggregate size limits.
func RedactFields ¶
RedactFields replaces the value of each listed top-level key of a JSON object with "[REDACTED]". Keys that are absent are ignored. Data that is not a JSON object is returned unchanged.
func ResolveMockParts ¶
func ResolveMockParts(parts []types.ContentPart) ([]types.ContentPart, error)
ResolveMockParts processes a slice of ContentPart, resolving any file_path references in MediaContent to base64-encoded data. URL references and already-encoded data are passed through unchanged.
func TruncateResultText ¶ added in v2.22.0
TruncateResultText cuts content to at most maxSize bytes, never inside a character, and appends a note saying so when it is longer, logging the cut under toolName. A maxSize of zero or less leaves content as it is.
func WithCallID ¶
WithCallID returns a new context that carries the tool call ID. This is set by the pipeline before executing a tool so that executors can access the provider-assigned call ID.
func WithMCPRegistry ¶
WithMCPRegistry attaches an MCP registry to the context. The MCPExecutor reads this on each Execute and routes via that registry, falling back to the executor's configured registry when absent.
Use this to give each concurrent run its own per-run MCP registry (typically a Fork of the engine's parent registry) so that session-scoped servers registered under the same name (e.g. "sandbox") resolve to different URLs without collision.
Types ¶
type A2AAuthConfig ¶
type A2AAuthConfig struct {
Scheme string `json:"scheme" yaml:"scheme"` // e.g. "Bearer", "Basic"
// Token is the static token value. Excluded from JSON serialization to prevent leaks.
Token string `json:"-" yaml:"token,omitempty"`
TokenEnv string `json:"token_env,omitempty" yaml:"token_env,omitempty"` // Env var containing the token
}
A2AAuthConfig defines authentication for an A2A agent connection.
type A2AConfig ¶
type A2AConfig struct {
AgentURL string `json:"agent_url" yaml:"agent_url"`
SkillID string `json:"skill_id" yaml:"skill_id"`
TimeoutMs int `json:"timeout_ms,omitempty" yaml:"timeout_ms,omitempty"`
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
HeadersFromEnv []string `json:"headers_from_env,omitempty" yaml:"headers_from_env,omitempty"`
Auth *A2AAuthConfig `json:"auth,omitempty" yaml:"auth,omitempty"`
// RetryPolicy overrides the executor's retry policy for this agent, field
// by field; see A2ARetryConfig.
RetryPolicy *A2ARetryConfig `json:"retry,omitempty" yaml:"retry,omitempty"`
SkillFilter *A2ASkillFilter `json:"skill_filter,omitempty" yaml:"skill_filter,omitempty"`
}
A2AConfig defines configuration for A2A agent tool execution
type A2ARetryConfig ¶
type A2ARetryConfig struct {
MaxRetries int `json:"max_retries,omitempty" yaml:"max_retries,omitempty"`
InitialDelayMs int `json:"initial_delay_ms,omitempty" yaml:"initial_delay_ms,omitempty"`
MaxDelayMs int `json:"max_delay_ms,omitempty" yaml:"max_delay_ms,omitempty"`
}
A2ARetryConfig defines per-agent retry policy overrides. Set on an A2AConfig, each non-zero field replaces the A2A executor's own value for that agent, and a zero field keeps it: MaxRetries is the number of retries after the first attempt (negative: none), InitialDelayMs and MaxDelayMs the backoff in milliseconds. An executor built not to retry (a2a.WithNoRetry) ignores it.
type A2ASkillFilter ¶
type A2ASkillFilter struct {
Allowlist []string `json:"allowlist,omitempty" yaml:"allowlist,omitempty"`
Blocklist []string `json:"blocklist,omitempty" yaml:"blocklist,omitempty"`
}
A2ASkillFilter controls which skills from an A2A agent are exposed to the LLM.
func (*A2ASkillFilter) IncludesSkill ¶
func (f *A2ASkillFilter) IncludesSkill(skillID string) bool
IncludesSkill returns true if the given skill ID passes the filter.
type ApprovalChecker ¶
type ApprovalChecker func(ctx context.Context, callID, name string, args map[string]any) *PendingToolInfo
ApprovalChecker decides whether a tool call must be held for external approval (human-in-the-loop) before execution. It returns a non-nil PendingToolInfo to hold the call pending, or nil to let it execute normally. It is consulted per tool call before execution; a nil checker is a no-op. The context is the tool-execution context, so a checker that persists the held call (e.g. to a durable store) honors cancellation and deadlines.
type ApprovalGate ¶ added in v2.20.0
type ApprovalGate func(ctx context.Context, callID, name string, args map[string]any) (*PendingToolInfo, error)
ApprovalGate is an ApprovalChecker that can also refuse a call. It returns a non-nil PendingToolInfo to hold the call pending, nil to let it execute, or an error to refuse it: a refused call does not execute, and the model is given the error as the call's result. A gate that cannot record a hold (its store is unavailable, for example) returns an error rather than nil, so the call fails closed instead of running unapproved.
type AsyncCallExecutor ¶ added in v2.22.0
type AsyncCallExecutor interface {
Executor
// ExecuteCallAsync may return immediately with a pending status.
ExecuteCallAsync(ctx context.Context, descriptor *ToolDescriptor, call ToolCall) (*ToolExecutionResult, error)
}
AsyncCallExecutor is the call-taking form of AsyncToolExecutor: it receives the whole call, caller included, and may return ToolStatusPending. On the registry's async paths it is preferred over AsyncToolExecutor. An executor that implements AsyncToolExecutor and CallExecutor but not this interface is given ExecuteAsync on the async paths (so it can still suspend a call, but without the caller) and ExecuteCall on the synchronous ones.
type AsyncToolExecutor ¶
type AsyncToolExecutor interface {
Executor // Still implements the basic Executor interface
// ExecuteAsync may return immediately with a pending status
ExecuteAsync(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (*ToolExecutionResult, error)
}
AsyncToolExecutor is a tool that can return pending status instead of blocking. Tools that require human approval or external async operations should implement this.
type CallExecutor ¶ added in v2.22.0
type CallExecutor interface {
Executor
// ExecuteCall runs call and returns the JSON result and optional content parts.
ExecuteCall(
ctx context.Context, descriptor *ToolDescriptor, call ToolCall,
) (json.RawMessage, []types.ContentPart, error)
}
CallExecutor extends Executor with an entry point that receives the whole call: its name, the provider's call ID, the arguments and the caller the conversation acts for. The registry prefers it over ExecuteMultimodal and Execute. call.Args are the arguments after the registry coerced them toward the input schema and validated them.
type ClientConfig ¶
type ClientConfig struct {
Consent *ConsentConfig `json:"consent,omitempty" yaml:"consent,omitempty"`
TimeoutMs int `json:"timeout_ms,omitempty" yaml:"timeout_ms,omitempty"`
Categories []string `json:"categories,omitempty" yaml:"categories,omitempty"`
// ValidateOutput checks a result the caller supplies for a deferred call
// (SendToolResult in the SDK) against the tool's OutputSchema. A result
// that does not match reaches the model as a failed call. Results from a
// registered handler are checked against the schema either way.
ValidateOutput bool `json:"validate_output,omitempty" yaml:"validate_output,omitempty"`
}
ClientConfig defines configuration for client-side tool execution. Tools with mode "client" are fulfilled by the SDK caller's device (e.g., GPS, camera, contacts, biometrics).
type ConsentConfig ¶
type ConsentConfig struct {
// Required declares that the tool needs the user's permission before it
// runs. It is a host-declared setting: the runtime and SDK do not ask for
// consent and do not block the call. The SDK passes it through on the
// tool descriptor (ClientToolRequest.Descriptor and the conversation's
// tool registry) for the host to act on.
Required bool `json:"required" yaml:"required"`
Message string `json:"message,omitempty" yaml:"message,omitempty"`
// DeclineStrategy tells the model how to proceed when the user declines:
// "error", "fallback" or "retry" (the DeclineStrategy* constants). It is a
// declarative setting whose handling is up to the host. When it is set,
// the SDK's Conversation.RejectClientTool answers the call with
// ConsentDeclinedMessage for the strategy, followed by the caller's
// reason, so the model sees what PromptArena's consent simulation gives
// it. When it is empty, the rejection text is unchanged.
DeclineStrategy string `json:"decline_strategy,omitempty" yaml:"decline_strategy,omitempty"`
}
ConsentConfig defines consent requirements for client-side tools. These are declarative tool settings: asking for consent and acting on the answer is the host's job. Message is surfaced to the host (the SDK's ClientToolRequest.ConsentMsg and pending client tool).
type DefaultRequestMapper ¶
type DefaultRequestMapper struct{}
DefaultRequestMapper is the built-in implementation of RequestMapper. It uses text/template for URL/header interpolation and JMESPath for body reshaping.
func (*DefaultRequestMapper) BuildBody ¶
func (m *DefaultRequestMapper) BuildBody(bodyArgs map[string]any, jmespathExpr string) (json.RawMessage, error)
BuildBody produces the JSON body from args, optionally reshaped via JMESPath.
func (*DefaultRequestMapper) PartitionArgs ¶
func (m *DefaultRequestMapper) PartitionArgs( args map[string]any, cfg *RequestMapping, urlTemplate string, ) (query, header, body map[string]any)
PartitionArgs splits tool arguments into query parameters and body fields. The header bucket is always empty: headers come from RequestMapping.HeaderParams templates. Arguments consumed by URL templates and header templates, listed in Exclude, or routed to the query are left out of the body. With a nil cfg every argument goes to the body.
func (*DefaultRequestMapper) RenderHeaders ¶
func (m *DefaultRequestMapper) RenderHeaders( templates map[string]string, args map[string]any, ) (map[string]string, error)
RenderHeaders applies text/template substitution to header value templates.
func (*DefaultRequestMapper) RenderURL ¶
RenderURL applies Go text/template substitution to a URL string. Template variables like {{.user_id}} are replaced with values from args.
Every value is escaped for where it lands, so an argument cannot change the request's path or query: values before the template's first literal "?" or "#" are escaped with url.PathEscape, and values after it with url.QueryEscape. A rendered path with a "." or ".." segment fails with ErrURLDotSegment.
type DefaultResponseMapper ¶
type DefaultResponseMapper struct{}
DefaultResponseMapper is the built-in implementation of ResponseMapper. It uses JMESPath for response extraction and reshaping.
func (*DefaultResponseMapper) MapResponse ¶
func (m *DefaultResponseMapper) MapResponse( response json.RawMessage, jmespathExpr string, ) (json.RawMessage, error)
MapResponse applies a JMESPath expression to extract or reshape a JSON response.
type DeferringExecutor ¶ added in v2.22.0
type DeferringExecutor interface {
Defer(tool *ToolDescriptor, call ToolCall) (*ToolExecutionResult, bool)
}
DeferringExecutor is implemented by an executor that can defer a call without running it, for the host to settle later, as a client tool with no handler does. ExecuteCallAsyncAdmitted and ExecuteAsyncAdmitted ask Defer first: when it returns true, its result (status ToolStatusPending) is returned as the call's, the executor does not run, and neither the admit gate nor the registry's rate limit counts the call; both count it when the host settles it (AdmitSettled). The deferred calls of one round therefore never take each other's room. Defer is given the call with its coerced, validated arguments, and must decide and build the pending result from one look at its own state, so a call it does not defer is run (and counted) normally.
type ErrToolsPending ¶
type ErrToolsPending struct {
Pending []PendingToolExecution
}
ErrToolsPending is returned by the provider stage when one or more tool calls returned ToolStatusPending. The pipeline should suspend: completed tool results are still returned alongside this error so they can be appended to the message history.
func IsErrToolsPending ¶
func IsErrToolsPending(err error) (*ErrToolsPending, bool)
IsErrToolsPending checks whether err is or wraps an *ErrToolsPending.
func (*ErrToolsPending) Error ¶
func (e *ErrToolsPending) Error() string
type ExecConfig ¶
type ExecConfig struct {
Command string `json:"command" yaml:"command"`
Runtime string `json:"runtime,omitempty" yaml:"runtime,omitempty"` // "exec" (default) or "server"
Args []string `json:"args,omitempty" yaml:"args,omitempty"`
// Env lists the names of the environment variables passed to the exec
// subprocess. When it is empty the subprocess inherits the full environment.
Env []string `json:"env,omitempty" yaml:"env,omitempty"`
TimeoutMs int `json:"timeout_ms,omitempty" yaml:"timeout_ms,omitempty"`
}
ExecConfig defines configuration for exec subprocess tool execution. The runtime spawns the command per invocation, passing tool arguments as JSON on stdin and reading the result from stdout.
type ExecExecutor ¶
type ExecExecutor struct{}
ExecExecutor runs tool invocations as one-shot subprocesses. The tool arguments are written as JSON to stdin; the subprocess result is read from stdout. Stderr output is captured and logged on failure.
Security: Trust Boundary ¶
The command and arguments executed by ExecExecutor come from pack files (tool definitions) and runtime config files (YAML manifests). These config files are the trust boundary: commands are not sandboxed, validated, or restricted in any way, which keeps the executor maximally flexible.
Pack files and runtime config files MUST come from trusted sources. Untrusted or unreviewed packs should never be loaded, as they can execute arbitrary commands with the privileges of the host process.
func (*ExecExecutor) Execute ¶
func (e *ExecExecutor) Execute( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, error)
Execute runs the tool as a one-shot subprocess.
Execute is the synchronous path, which has no way to suspend a call, so a subprocess that answers {"pending": ...} is an error here. The pipeline calls ExecuteAsync, where a pending answer suspends the call.
func (*ExecExecutor) ExecuteAsync ¶ added in v2.17.0
func (e *ExecExecutor) ExecuteAsync( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (*ToolExecutionResult, error)
ExecuteAsync runs the tool as a one-shot subprocess and reports a {"pending": ...} answer as ToolStatusPending, on the same path client and other async tools use: the pipeline suspends the call and the caller resolves it later.
func (*ExecExecutor) Name ¶
func (e *ExecExecutor) Name() string
Name returns the executor name used for mode-based routing.
type Executor ¶
type Executor interface {
Execute(ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage) (json.RawMessage, error)
Name() string
}
Executor interface defines how tools are executed
type FileToolResponseRepository ¶
type FileToolResponseRepository struct {
// contains filtered or unexported fields
}
FileToolResponseRepository implements ToolResponseRepository from a scenario's configured tool responses. It answers only for calls whose context key equals its scenario ID.
func NewFileToolResponseRepository ¶
func NewFileToolResponseRepository( scenarioID string, toolResponses map[string][]MockToolResponseConfig, ) *FileToolResponseRepository
NewFileToolResponseRepository creates a repository from scenario tool responses. This is typically used by Arena to provide tool mocking from YAML scenarios.
func (*FileToolResponseRepository) GetToolResponse ¶
func (r *FileToolResponseRepository) GetToolResponse( toolName string, args map[string]any, contextKey string, ) (*ToolResponseData, error)
GetToolResponse implements ToolResponseRepository. It returns the first configured response for the tool whose CallArgs all appear, with deeply equal values, in args. Numbers compare by value at any depth, so int, float64 and json.Number forms of 42 are equal. An entry with no CallArgs matches any call. It returns nil when the context key is not the scenario ID or nothing matches.
type HTTPConfig ¶
type HTTPConfig struct {
// URL is the endpoint. It may contain Go template references to tool
// arguments in the path and query, but not in the scheme or host.
URL string `json:"url" yaml:"url"`
// Method is the HTTP method. It defaults to POST.
Method string `json:"method" yaml:"method"`
// HeadersFromEnv lists headers to set from environment variables, each
// entry in the form "Header-Name=ENV_VAR_NAME". A variable that is unset or
// empty sets no header.
HeadersFromEnv []string `json:"headers_from_env,omitempty" yaml:"headers_from_env,omitempty"`
// TimeoutMs bounds the request, in milliseconds. 0 sets no limit here.
TimeoutMs int `json:"timeout_ms" yaml:"timeout_ms"`
// Redact lists top-level keys of a JSON object response whose values are
// replaced with "[REDACTED]" before the result is returned.
Redact []string `json:"redact,omitempty" yaml:"redact,omitempty"`
// Headers are literal headers set on every request.
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
// Request/response mapping configuration
Request *RequestMapping `json:"request,omitempty" yaml:"request,omitempty"`
Response *ResponseMapping `json:"response,omitempty" yaml:"response,omitempty"`
// Multimodal response handling
Multimodal *MultimodalConfig `json:"multimodal,omitempty" yaml:"multimodal,omitempty"`
}
HTTPConfig defines configuration for live HTTP tool execution
type HTTPExecutor ¶
type HTTPExecutor struct {
// RequestMapper customizes how tool args map to HTTP requests.
// If nil, DefaultRequestMapper is used.
RequestMapper RequestMapper
// ResponseMapper customizes how HTTP responses map to tool results.
// If nil, DefaultResponseMapper is used.
ResponseMapper ResponseMapper
// PreRequest, if set, is called with every request after it is built
// (URL rendered, headers applied) and before it is sent. It may modify the
// request, for example to add a freshly refreshed auth token or a
// signature. An error it returns fails the tool call and nothing is sent.
PreRequest func(req *http.Request) error
// contains filtered or unexported fields
}
HTTPExecutor executes tools that make HTTP calls based on pack configuration. It reads the HTTPConfig from the tool descriptor and makes the appropriate HTTP request. It tracks cumulative response sizes and rejects calls once the aggregate limit is reached.
For GET/HEAD/DELETE requests, tool arguments are encoded as URL query parameters. For POST/PUT/PATCH requests, tool arguments are sent as a JSON request body.
Custom RequestMapper and ResponseMapper implementations can be injected to override URL templating, argument partitioning, body building, header rendering, and response reshaping.
func NewHTTPExecutor ¶
func NewHTTPExecutor() *HTTPExecutor
NewHTTPExecutor creates a new HTTP executor with the default HTTP client and default aggregate response size limit.
func NewHTTPExecutorWithClient ¶
func NewHTTPExecutorWithClient(client *http.Client) *HTTPExecutor
NewHTTPExecutorWithClient creates a new HTTP executor with a custom HTTP client. This is useful for testing or when custom transport configuration is needed.
func NewHTTPExecutorWithMaxAggregate ¶
func NewHTTPExecutorWithMaxAggregate(maxAggregate int64) *HTTPExecutor
NewHTTPExecutorWithMaxAggregate creates a new HTTP executor with a custom aggregate response size limit. Use 0 or a negative value to disable.
func (*HTTPExecutor) AggregateResponseSize ¶
func (e *HTTPExecutor) AggregateResponseSize() int64
AggregateResponseSize returns the cumulative response size consumed so far.
func (*HTTPExecutor) Execute ¶
func (e *HTTPExecutor) Execute( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, error)
Execute performs an HTTP request based on the tool descriptor's HTTPConfig. A non-2xx status is an error that includes the response body. A response that is not JSON is returned wrapped as {"result": "<body>"}. Redaction runs before response mapping.
func (*HTTPExecutor) ExecuteMultimodal ¶
func (e *HTTPExecutor) ExecuteMultimodal( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, []types.ContentPart, error)
ExecuteMultimodal performs an HTTP request and returns multimodal content parts when the response is a binary type (image, audio, video). For JSON responses, it falls back to the standard Execute path with no content parts.
func (*HTTPExecutor) Name ¶
func (e *HTTPExecutor) Name() string
Name returns the executor name used for registration.
func (*HTTPExecutor) ResetAggregateSize ¶
func (e *HTTPExecutor) ResetAggregateSize()
ResetAggregateSize resets the cumulative response size counter to zero.
type HostExtras ¶
HostExtras carries top-level fields from a tool invocation's args that fell outside the executor's typed schema. Populated by capability executors when sdk.WithToolDescriptorOverride extends a built-in tool's InputSchema with deployment-specific fields, so the LLM-supplied extension data reaches the host callback that receives the executor's typed record.
Contract:
- The runtime writes this map exactly once per call, at the executor's arg-decode step (via DecodeArgsExtras). Any other write site inside PromptKit is a bug.
- The host reads it from whichever typed record carries it (e.g. *workflow.TransitionResult inside an OnCommit callback).
- The field is named HostExtras, not Metadata, to keep this channel distinct from a record's first-class metadata (which has its own domain semantics — see Memory.Metadata, Message.Metadata).
Do not use HostExtras as a general-purpose bag for PromptKit-internal state. If the runtime needs to carry something on a typed record, add a typed field.
type InMemoryToolResponseRepository ¶
type InMemoryToolResponseRepository struct {
// contains filtered or unexported fields
}
InMemoryToolResponseRepository implements ToolResponseRepository using in-memory storage. This is useful for SDK unit tests and programmatic configuration of tool responses.
func NewInMemoryToolResponseRepository ¶
func NewInMemoryToolResponseRepository() *InMemoryToolResponseRepository
NewInMemoryToolResponseRepository creates a new in-memory tool response repository.
func (*InMemoryToolResponseRepository) AddResponse ¶
func (r *InMemoryToolResponseRepository) AddResponse(contextKey, toolName string, response *ToolResponseData)
AddResponse adds a tool response for a specific context and tool name. This method supports simple responses where argument matching is not needed.
func (*InMemoryToolResponseRepository) GetToolResponse ¶
func (r *InMemoryToolResponseRepository) GetToolResponse( toolName string, args map[string]any, contextKey string, ) (*ToolResponseData, error)
GetToolResponse implements ToolResponseRepository. For simplicity, this implementation only matches by tool name and context, not by arguments. For argument-based matching, use FileToolResponseRepository or implement a custom repository.
type MCPExecutor ¶
type MCPExecutor struct {
// contains filtered or unexported fields
}
MCPExecutor executes tools using MCP (Model Context Protocol) servers. The configured registry is used as a default; callers can attach a per-call registry override via WithMCPRegistry to give each concurrent run its own MCP routing without sharing tool-to-server mappings.
Timeouts come from the caller's context (the tool registry applies the descriptor's TimeoutMs) and from the server's own request timeout (ServerConfig.TimeoutMs); the executor adds none of its own.
func NewMCPExecutor ¶
func NewMCPExecutor(registry mcp.Registry) *MCPExecutor
NewMCPExecutor creates a new MCP executor
func (*MCPExecutor) Execute ¶
func (e *MCPExecutor) Execute( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, error)
Execute executes a tool using an MCP server. Images and audio in the result are included in the JSON as content blocks; ExecuteMultimodal returns them as content parts instead.
func (*MCPExecutor) ExecuteMultimodal ¶ added in v2.10.0
func (e *MCPExecutor) ExecuteMultimodal( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, []types.ContentPart, error)
ExecuteMultimodal executes a tool using an MCP server, returning images and audio from the result as content parts the model can see.
type MockScriptedExecutor ¶
type MockScriptedExecutor struct{}
MockScriptedExecutor executes tools using templated mock data
func NewMockScriptedExecutor ¶
func NewMockScriptedExecutor() *MockScriptedExecutor
NewMockScriptedExecutor creates a new scripted mock executor
func (*MockScriptedExecutor) Execute ¶
func (e *MockScriptedExecutor) Execute( _ context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, error)
Execute executes a tool using templated mock data
func (*MockScriptedExecutor) ExecuteMultimodal ¶
func (e *MockScriptedExecutor) ExecuteMultimodal( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, []types.ContentPart, error)
ExecuteMultimodal executes a scripted mock tool and returns both JSON result and content parts. The JSON result is rendered via Go templates; MockParts (if present) are resolved identically to MockStaticExecutor (file_path → base64, URLs passed through).
func (*MockScriptedExecutor) Name ¶
func (e *MockScriptedExecutor) Name() string
Name returns the executor name
type MockStaticExecutor ¶
type MockStaticExecutor struct{}
MockStaticExecutor executes tools using static mock data
func NewMockStaticExecutor ¶
func NewMockStaticExecutor() *MockStaticExecutor
NewMockStaticExecutor creates a new static mock executor
func (*MockStaticExecutor) Execute ¶
func (e *MockStaticExecutor) Execute( _ context.Context, descriptor *ToolDescriptor, _ json.RawMessage, ) (json.RawMessage, error)
Execute executes a tool using static mock data
func (*MockStaticExecutor) ExecuteMultimodal ¶
func (e *MockStaticExecutor) ExecuteMultimodal( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, []types.ContentPart, error)
ExecuteMultimodal executes a tool and returns both JSON result and content parts. When MockParts are configured on the descriptor, file_path references in media content are resolved to base64 data, and URL references are passed through as-is.
func (*MockStaticExecutor) Name ¶
func (e *MockStaticExecutor) Name() string
Name returns the executor name
type MockToolErrorConfig ¶
MockToolErrorConfig represents an error configuration.
type MockToolResponseConfig ¶
type MockToolResponseConfig struct {
CallArgs map[string]any `yaml:"call_args"`
Result any `yaml:"result,omitempty"`
Error *MockToolErrorConfig `yaml:"error,omitempty"`
}
MockToolResponseConfig represents a single tool response configuration.
type ModelResult ¶ added in v2.22.0
type ModelResult struct {
// Text is the result's text: the formatted JSON, or the joined text parts.
Text string
// Parts holds a multimodal result's parts (text and media, in order); nil
// for a text-only result.
Parts []types.ContentPart
}
ModelResult is a completed tool result as the model is given it.
func BuildModelResult ¶ added in v2.22.0
func BuildModelResult( raw json.RawMessage, parts []types.ContentPart, opts ModelResultOptions, ) (ModelResult, error)
BuildModelResult prepares a completed tool result for the model: the one place a result's formatting, rewriting and size limit are applied, for a call the pipeline ran and for one a caller resolved. A result with parts is its parts, each text part rewritten and capped and media parts kept in place; otherwise it is raw formatted as text. The error is Rewrite's.
type ModelResultOptions ¶ added in v2.22.0
type ModelResultOptions struct {
// ToolName names the tool in the truncation log.
ToolName string
// MaxSize is the size limit in bytes for each text; zero or less is no limit
// (the registry's MaxToolResultSize).
MaxSize int
// Rewrite, when set, rewrites each text before the size limit applies.
Rewrite func(string) (string, error)
// Unformatted takes a text result's raw content as its text, as it is,
// instead of formatting it (FormatResultText).
Unformatted bool
}
ModelResultOptions says how a completed tool result is prepared for the model.
type MultimodalConfig ¶
type MultimodalConfig struct {
// Enabled activates Content-Type-based detection of binary responses.
Enabled bool `json:"enabled" yaml:"enabled"`
// AcceptTypes lists the MIME types the tool may return (e.g. "image/png", "audio/wav").
// If empty, common image/audio/video types are auto-detected.
AcceptTypes []string `json:"accept_types,omitempty" yaml:"accept_types,omitempty"`
}
MultimodalConfig configures multimodal response handling for HTTP tools.
type MultimodalExecutor ¶
type MultimodalExecutor interface {
Executor
// ExecuteMultimodal returns both the JSON result and optional content parts.
ExecuteMultimodal(
ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage,
) (json.RawMessage, []types.ContentPart, error)
}
MultimodalExecutor extends Executor with support for returning multimodal content parts. Executors that can return images, audio, or other non-text content should implement this.
type PendingToolExecution ¶
type PendingToolExecution struct {
CallID string `json:"call_id"`
ToolName string `json:"tool_name"`
Args map[string]any `json:"args"`
// RawArgs are the call's arguments exactly as the model sent them, which
// Args decodes.
RawArgs json.RawMessage `json:"raw_args,omitempty"`
PendingInfo *PendingToolInfo `json:"pending_info,omitempty"`
ToolResult types.MessageToolResult `json:"tool_result"`
}
PendingToolExecution captures a single tool call that returned ToolStatusPending.
type PendingToolInfo ¶
type PendingToolInfo struct {
// Reason for pending (e.g., "requires_approval", "waiting_external_api")
Reason string `json:"reason"`
// Human-readable description
Message string `json:"message"`
// Tool details (for middleware to use in notifications)
ToolName string `json:"tool_name"`
Args json.RawMessage `json:"args"`
// Optional: expiration, callback URL, etc.
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CallbackURL string `json:"callback_url,omitempty"`
// Arbitrary metadata for custom middleware
Metadata map[string]any `json:"metadata,omitempty"`
}
PendingToolInfo describes a tool call awaiting external input or approval.
func (PendingToolInfo) MarshalJSON ¶
func (p PendingToolInfo) MarshalJSON() ([]byte, error)
MarshalJSON normalizes the pending tool call's args (empty -> {}).
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages tool descriptors and provides access to executors. All map access is protected by mu (RWMutex) for safe concurrent use.
The registry is the single store of descriptors. A repository handed to NewRegistryWithRepository is read once, at construction; every later Register, Unregister, Get and List acts on the registry alone, so what Unregister removes stays removed.
Example ¶
ExampleRegistry shows registering a tool descriptor and executing it via the static mock executor — no network or live backend required. This is the same registry/executor pair Arena uses to run assertions against canned tool responses.
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/tools"
)
func main() {
reg := tools.NewRegistry()
_ = reg.Register(&tools.ToolDescriptor{
Name: "get_weather",
Mode: "mock",
MockResult: json.RawMessage(`{"temp_f":72}`),
})
result, err := tools.NewMockStaticExecutor().Execute(context.Background(), reg.Get("get_weather"), nil)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(result))
}
Output: {"temp_f":72}
func NewRegistry ¶
func NewRegistry(opts ...RegistryOption) *Registry
NewRegistry creates an empty tool registry.
func NewRegistryWithRepository ¶
func NewRegistryWithRepository(repo ToolRepository, opts ...RegistryOption) *Registry
NewRegistryWithRepository creates a tool registry preloaded with every descriptor the repository lists. The repository is not retained.
func (*Registry) AdmitSettled ¶ added in v2.22.0
AdmitSettled admits a deferred call to toolName (one its executor returned ToolStatusPending for) when the host settles it: it counts the call under the registry's rate limit (WithRateLimit) and, when admit is not nil, calls admit under the limit's lock, as ExecuteAsyncAdmitted does for a call it runs. Over the registry's limit it returns an error wrapping ErrRateLimitExceeded; if admit refuses, its error, and the registry does not count the call. A deferred call is counted by the registry's limit only here, never when it is dispatched.
func (*Registry) AdmitSettledRelease ¶ added in v2.22.0
func (r *Registry) AdmitSettledRelease(toolName string, admit func() error) (release func(), err error)
AdmitSettledRelease is AdmitSettled, also returning release, which takes the registry's count of the call back: for a settled call whose result is then never used (its turn was abandoned). release is nil when the call is refused. It does not take back what admit counted.
func (*Registry) CheckResult ¶ added in v2.22.0
func (r *Registry) CheckResult( toolName string, content json.RawMessage, parts []types.ContentPart, ) (*ToolExecutionResult, error)
CheckResult holds content (and parts), a result produced for a call to toolName outside the registry, to the checks ExecuteCallAsync applies to an executor's result: coerced toward and validated against the tool's output schema, unless the tool is in mcp mode or the result carries media. A result that fails is reported as status ToolStatusFailed with the error text a call the registry runs reports; one that passes as ToolStatusComplete with the content to use. An unknown tool returns an error.
It is for a host that runs a call itself, such as a held call it approved, so its result is held to the same contract as one the registry ran.
func (*Registry) Child ¶ added in v2.3.0
func (r *Registry) Child(opts ...RegistryOption) *Registry
Child returns a registry that shares this one's tool DESCRIPTORS but owns its own EXECUTORS.
Executors are keyed by name, one per name, and several hold per-conversation state, so conversations must not share them. Descriptors are data, and a host that passes a registry in with WithToolRegistry reads it back to inspect and override the tool set. So Register and Unregister act on the parent, and only RegisterExecutor stays local to the child.
Executor lookup falls through to the parent only for names the child never registered, so a host's own custom executor is still used. Descriptor lookup is live, not a snapshot: a tool registered on the parent after the child was created is visible to the child.
Child is nil-receiver safe: a nil parent yields a standalone registry, so a caller can write reg = hostRegistry.Child() without checking whether the host supplied one. The child takes the parent's default timeout, result size limit and rate limiter, and options passed to Child override them.
func (*Registry) Execute ¶
func (r *Registry) Execute( ctx context.Context, toolName string, args json.RawMessage, ) (*ToolResult, error)
Execute runs a tool with the given arguments. It is ExecuteCall for a call with no ID and no caller.
func (*Registry) ExecuteAsync ¶
func (r *Registry) ExecuteAsync( ctx context.Context, toolName string, args json.RawMessage, ) (*ToolExecutionResult, error)
ExecuteAsync is Execute for executors that may suspend a call. If the tool's executor implements AsyncToolExecutor, the result can have status ToolStatusPending; otherwise the call runs synchronously. Failures are reported as status ToolStatusFailed with a nil error, as for Execute.
func (*Registry) ExecuteAsyncAdmitted ¶ added in v2.17.0
func (r *Registry) ExecuteAsyncAdmitted( ctx context.Context, toolName string, args json.RawMessage, admit func() error, ) (*ToolExecutionResult, error)
ExecuteAsyncAdmitted is ExecuteAsync with an admission gate. admit, when not nil, is called once the call has passed every check of its own (the tool exists, its arguments are valid, it has an executor, and the registry's rate limit allows it), immediately before the executor runs. If admit returns an error, the executor does not run, the registry's rate limit does not count the call, and that error is returned unchanged. A call that fails one of the registry's checks never reaches admit, and neither does one its executor defers (DeferringExecutor): that call is admitted, and counted by the registry's rate limit, when the host settles it (AdmitSettled). A call an executor defers only once it runs has its count under the registry's rate limit taken back then.
func (*Registry) ExecuteCall ¶ added in v2.22.0
ExecuteCall runs a tool call. It coerces the call's arguments toward the input schema, validates them, applies the rate limit, and runs the executor the tool's mode selects, under the tool's TimeoutMs. An executor that implements CallExecutor is given the call with the coerced arguments, so it sees the call ID and the caller. An unknown tool, invalid arguments, or a missing executor return an error. An executor failure, a timeout, a rate-limit refusal, or a result that fails the output schema is reported in ToolResult.Error with a nil error. Results of tools in mcp mode are not validated against the output schema. The result's ID is the call's ID.
func (*Registry) ExecuteCallAsyncAdmitted ¶ added in v2.22.0
func (r *Registry) ExecuteCallAsyncAdmitted( ctx context.Context, call ToolCall, admit func() error, ) (*ToolExecutionResult, error)
ExecuteCallAsyncAdmitted is ExecuteAsyncAdmitted for a whole call, so the executor can see its ID and caller. The executor is given the call with its coerced, validated arguments through the first entry point it implements: AsyncCallExecutor's ExecuteCallAsync, AsyncToolExecutor's ExecuteAsync (which can suspend the call but does not see the call or its caller), then the synchronous entry points in the order ExecuteCall uses (CallExecutor, MultimodalExecutor, Executor).
func (*Registry) Fork ¶
Fork returns a child Registry that snapshots the parent's tool descriptors and executors at the moment of the call. After Fork the child and parent are independent: descriptors and executors registered on the child do not leak to the parent (and vice versa).
Use this to give each concurrent run its own per-run dispatch state: a per-run MCPExecutor wired to a per-run mcp.Registry, plus per-run MCP tool descriptors discovered from session-scoped sources, without colliding with other runs that share the engine's parent Registry.
Memory cost is two shallow map copies; descriptor and executor values are pointer-typed so the underlying objects are shared.
func (*Registry) Get ¶
func (r *Registry) Get(name string) *ToolDescriptor
Get retrieves a tool descriptor by name, or nil when none is registered.
func (*Registry) GetByNamespace ¶
func (r *Registry) GetByNamespace(ns string) []*ToolDescriptor
GetByNamespace returns all tool descriptors in the given namespace.
func (*Registry) GetTool ¶
func (r *Registry) GetTool(name string) (*ToolDescriptor, error)
GetTool retrieves a tool descriptor by name.
func (*Registry) GetTools ¶
func (r *Registry) GetTools() map[string]*ToolDescriptor
GetTools returns all loaded tool descriptors. The returned map is a shallow copy (safe to iterate/delete keys), but the *ToolDescriptor pointers are shared with the registry. Callers must not mutate the returned descriptors.
func (*Registry) GetToolsByNames ¶
func (r *Registry) GetToolsByNames(names []string) ([]*ToolDescriptor, error)
GetToolsByNames returns tool descriptors for the specified names
func (*Registry) IterateTools ¶
func (r *Registry) IterateTools(fn func(name string, tool *ToolDescriptor))
IterateTools calls fn for each loaded tool descriptor while holding the read lock. This avoids the map copy that GetTools performs, which matters when the registry is large and the caller only needs to inspect each tool once (e.g. building a provider tool list). The callback must not call back into the Registry.
func (*Registry) LoadToolFromBytes ¶
LoadToolFromBytes loads a tool descriptor from raw bytes data. A filename ending in .yaml or .yml selects the YAML parser, which requires the Kubernetes manifest form (apiVersion, kind: Tool, metadata, spec); any other filename selects JSON. The descriptor must have a name, description, input schema, output schema and a valid mode, or an error is returned. A TimeoutMs of 0 is replaced with the registry default. The filename is used for the parser choice and in error messages.
func (*Registry) MaxToolResultSize ¶
MaxToolResultSize returns the configured maximum tool result size in bytes.
func (*Registry) Register ¶
func (r *Registry) Register(descriptor *ToolDescriptor) error
Register adds a tool descriptor to the registry, replacing any descriptor of the same name, and sets its Namespace from its name. Unlike LoadToolFromBytes, it does not check the descriptor's required fields. On a registry made with Child, the descriptor is registered on the parent.
func (*Registry) RegisterExecutor ¶
RegisterExecutor registers a tool executor under its Executor.Name.
A registry holds exactly one executor per name, so registering a second one under a name already taken replaces the first. Two owners that share a registry, typically two conversations, would each expect their own executor to serve their tool calls, and the later registration would take over the earlier one's calls along with whatever per-conversation state its executor holds.
RegisterExecutor logs the replacement at Warn. Give each conversation its own executors with Registry.Child. A nil executor is ignored.
func (*Registry) RegisterLocal ¶ added in v2.22.0
func (r *Registry) RegisterLocal(descriptor *ToolDescriptor) error
RegisterLocal registers a descriptor on this registry alone: unlike Register, never on the parent of a registry made with Child, so it is invisible to the parent and to the parent's other children. Get, GetTool and tool execution resolve it, after every descriptor the registry and its parent chain hold, so one registered there under the same name, even later, wins over it. List, GetTools, IterateTools and GetByNamespace do not include it. It replaces a local descriptor of the same name, and sets its Namespace from its name.
It is for a descriptor that belongs to one conversation's run, such as a tool an application offers the model at runtime.
func (*Registry) Unregister ¶
Unregister removes a tool descriptor by name. Returns true if a descriptor was removed, false if none was registered.
The workflow runtime uses it when a state machine transitions into a terminal state, to remove the previous state's workflow__transition descriptor so the model cannot call it against a dead state. Safe to call concurrently with Get/List.
Removal is final for every read path: Get, GetTool and List all read the same store. There is no repository fallback that restores the descriptor. On a registry made with Child, the descriptor is removed from the parent.
func (*Registry) UnregisterLocal ¶ added in v2.22.0
UnregisterLocal removes a descriptor RegisterLocal registered, and reports whether there was one.
type RegistryOption ¶
type RegistryOption func(*Registry)
RegistryOption configures a Registry during construction.
func WithDefaultTimeout ¶
func WithDefaultTimeout(ms int) RegistryOption
WithDefaultTimeout sets the default timeout (in milliseconds) applied to tools that don't declare their own TimeoutMs. Pass 0 to disable timeouts by default.
func WithMaxToolResultSize ¶
func WithMaxToolResultSize(bytes int) RegistryOption
WithMaxToolResultSize sets the maximum allowed size (in bytes) of a tool result's text, which the provider stage enforces by truncating. Pass 0 to disable size checking.
func WithRateLimit ¶
func WithRateLimit(maxCallsPerMinute int) RegistryOption
WithRateLimit sets a per-tool rate limit (maximum calls per minute). Pass 0 to disable rate limiting (the default).
type RepositoryToolExecutor ¶
type RepositoryToolExecutor struct {
// contains filtered or unexported fields
}
RepositoryToolExecutor wraps existing tool executors to provide repository-backed mock responses with fallback to real execution. A base executor that implements CallExecutor is given the whole call, caller included; any other base runs Execute. This enables deterministic tool testing while maintaining the ability to fall back to real tool execution when needed.
func NewRepositoryToolExecutor ¶
func NewRepositoryToolExecutor( baseExecutor Executor, repo ToolResponseRepository, contextKey string, ) *RepositoryToolExecutor
NewRepositoryToolExecutor creates a new repository-backed tool executor. The executor will first check the repository for configured responses, and fall back to the base executor if no match is found.
func (*RepositoryToolExecutor) Execute ¶
func (e *RepositoryToolExecutor) Execute( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, error)
Execute executes a tool, first checking the repository for mock responses. If a matching response is found in the repository, it returns that response. Otherwise, it falls back to the base executor for real execution.
func (*RepositoryToolExecutor) ExecuteCall ¶ added in v2.22.0
func (e *RepositoryToolExecutor) ExecuteCall( ctx context.Context, descriptor *ToolDescriptor, call ToolCall, ) (json.RawMessage, []types.ContentPart, error)
ExecuteCall implements CallExecutor: a repository response for the call's arguments, else the base executor's run of the call. A base that implements CallExecutor is given the whole call, its caller included; any other base runs Execute, exactly as through Execute. The wrapper never suspends a call and never returns content parts, whatever the base implements.
func (*RepositoryToolExecutor) Name ¶
func (e *RepositoryToolExecutor) Name() string
Name returns the executor name with repository suffix.
type RequestMapper ¶
type RequestMapper interface {
// RenderURL applies path parameter substitution to the URL template.
RenderURL(urlTemplate string, args map[string]any) (string, error)
// PartitionArgs splits tool arguments into query, header, and body buckets
// based on the mapping configuration.
PartitionArgs(args map[string]any, cfg *RequestMapping, urlTemplate string) (query, header, body map[string]any)
// BuildBody produces the JSON request body from the body arguments.
// If a JMESPath body_mapping is configured, it reshapes the args.
BuildBody(bodyArgs map[string]any, jmespathExpr string) (json.RawMessage, error)
// RenderHeaders applies template interpolation to header values.
RenderHeaders(templates map[string]string, args map[string]any) (map[string]string, error)
}
RequestMapper maps tool arguments to HTTP request components. Implementations can customize URL templating, argument partitioning, and body building.
type RequestMapping ¶
type RequestMapping struct {
// QueryParams lists argument keys to route as URL query parameters.
QueryParams []string `json:"query_params,omitempty" yaml:"query_params,omitempty"`
// HeaderParams maps HTTP header names to Go text/template strings
// that interpolate tool arguments. E.g. {"Authorization": "Bearer {{.token}}"}.
HeaderParams map[string]string `json:"header_params,omitempty" yaml:"header_params,omitempty"`
// BodyMapping is a JMESPath expression to reshape the body arguments
// before sending. Only applies to POST/PUT/PATCH requests.
BodyMapping string `json:"body_mapping,omitempty" yaml:"body_mapping,omitempty"`
// Exclude lists argument keys to omit from the request entirely.
// Keys consumed by URL path templates and header templates are
// automatically excluded from the body.
Exclude []string `json:"exclude,omitempty" yaml:"exclude,omitempty"`
// StaticQuery injects fixed query parameters into every request.
// These are not part of the LLM's input schema — they control
// API behavior (e.g. result count, language, format).
StaticQuery map[string]string `json:"static_query,omitempty" yaml:"static_query,omitempty"`
// StaticHeaders injects fixed headers into every request.
// Unlike header_params, these are literal values, not templates.
StaticHeaders map[string]string `json:"static_headers,omitempty" yaml:"static_headers,omitempty"`
// StaticBody injects fixed fields into the JSON request body.
// Only applies to POST/PUT/PATCH. Merged with LLM-provided body fields.
StaticBody map[string]any `json:"static_body,omitempty" yaml:"static_body,omitempty"`
}
RequestMapping configures how LLM tool arguments are mapped to HTTP request components.
type ResponseMapper ¶
type ResponseMapper interface {
// MapResponse applies a JMESPath expression to reshape the response JSON.
MapResponse(response json.RawMessage, jmespathExpr string) (json.RawMessage, error)
}
ResponseMapper maps HTTP response bodies to tool results. Implementations can customize response extraction and reshaping.
type ResponseMapping ¶
type ResponseMapping struct {
// BodyMapping is a JMESPath expression to extract or reshape the response JSON.
BodyMapping string `json:"body_mapping,omitempty" yaml:"body_mapping,omitempty"`
}
ResponseMapping configures how HTTP response bodies are mapped to tool results.
type SchemaValidator ¶
type SchemaValidator struct {
// contains filtered or unexported fields
}
SchemaValidator handles JSON schema validation for tool inputs and outputs. It maintains an LRU cache of compiled schemas bounded by maxCacheSize.
func NewSchemaValidator ¶
func NewSchemaValidator() *SchemaValidator
NewSchemaValidator creates a new schema validator with the default cache size.
func NewSchemaValidatorWithSize ¶
func NewSchemaValidatorWithSize(maxSize int) *SchemaValidator
NewSchemaValidatorWithSize creates a new schema validator with the given maximum cache size. If maxSize <= 0 it defaults to DefaultMaxSchemaCacheSize.
func (*SchemaValidator) CacheLen ¶
func (sv *SchemaValidator) CacheLen() int
CacheLen returns the number of entries in the schema cache. Exported for testing and monitoring.
func (*SchemaValidator) CoerceArgs ¶
func (sv *SchemaValidator) CoerceArgs( descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, []Coercion, error)
CoerceArgs normalises LLM tool arguments to match the types declared in the tool's input schema. Weak LLMs produce a variety of non-conformant output:
- null for optional fields (Ollama, Llama)
- empty strings for non-string optional fields (GPT-3.5, small models)
- string-encoded numbers/booleans ("10", "true", "0.8")
- bare strings instead of arrays ("preference" instead of ["preference"])
- wrong enum case ("escalate" instead of "Escalate")
- whitespace around enum values ("Escalate ")
- "yes"/"no" for booleans, integer 1/0 for booleans
- "5.0" string for integer fields
All normalisation happens here, before ValidateArgs, keeping the schema validator strict and tool executors simple.
func (*SchemaValidator) CoerceResult ¶
func (sv *SchemaValidator) CoerceResult( descriptor *ToolDescriptor, result json.RawMessage, ) (json.RawMessage, []Coercion, error)
CoerceResult attempts to coerce simple type mismatches in tool results.
A result that validates is returned as-is. Otherwise validation is re-attempted after a round-trip through JSON, which normalizes whitespace and encoding. It does not convert types (for example string to number), and the returned Coercion slice is always nil.
func (*SchemaValidator) ValidateArgs ¶
func (sv *SchemaValidator) ValidateArgs(descriptor *ToolDescriptor, args json.RawMessage) error
ValidateArgs validates tool arguments against the descriptor's input schema and returns a *ValidationError of type "args_invalid" when they do not conform. Nil, empty or null args are validated as an empty object. A descriptor with no input schema, or a schema with a $ref to an external document, is not validated.
func (*SchemaValidator) ValidateResult ¶
func (sv *SchemaValidator) ValidateResult(descriptor *ToolDescriptor, result json.RawMessage) error
ValidateResult validates a tool result against the descriptor's output schema and returns a *ValidationError of type "result_invalid" when it does not conform. The same skip rules as ValidateArgs apply.
type ServerExecutor ¶
type ServerExecutor struct {
// contains filtered or unexported fields
}
ServerExecutor runs tool invocations against a long-running subprocess. The subprocess stays alive across multiple calls and communicates via JSON-RPC 2.0 over stdin/stdout (one JSON object per line).
Each tool gets its own subprocess, started lazily on first invocation and restarted if it has exited. Requests to one process may be in flight concurrently; responses are matched to requests by JSON-RPC id.
Security: Trust Boundary ¶
The command and arguments that start server processes come from pack files (tool definitions) and runtime config files (YAML manifests). These config files are the trust boundary: commands are not sandboxed, validated, or restricted in any way, which keeps the executor maximally flexible.
Pack files and runtime config files MUST come from trusted sources. Untrusted or unreviewed packs should never be loaded, as they can execute arbitrary commands with the privileges of the host process.
func (*ServerExecutor) Close ¶
func (e *ServerExecutor) Close() error
Close terminates all managed server processes.
func (*ServerExecutor) Execute ¶
func (e *ServerExecutor) Execute( ctx context.Context, descriptor *ToolDescriptor, args json.RawMessage, ) (json.RawMessage, error)
Execute sends a JSON-RPC request to the tool's server process and returns the result.
func (*ServerExecutor) Name ¶
func (e *ServerExecutor) Name() string
Name returns the executor name used for mode-based routing.
type ToolCall ¶
type ToolCall struct {
Name string `json:"name"`
Args json.RawMessage `json:"args"`
ID string `json:"id"` // Provider-specific call ID
// Caller is who the conversation acts for, as the host set it with
// sdk.WithCaller. The zero value means none was set. PromptKit hands it to
// the host's executor (CallExecutor) and otherwise never reads, persists,
// logs or emits it; it is not serialized.
Caller types.Caller `json:"-"`
}
ToolCall represents a tool invocation request
func (ToolCall) MarshalJSON ¶
MarshalJSON normalizes the tool call's args (empty -> {}).
type ToolConfig ¶
type ToolConfig struct {
APIVersion string `json:"apiVersion" yaml:"apiVersion"`
Kind string `json:"kind" yaml:"kind"`
Metadata metav1.ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
Spec ToolDescriptor `json:"spec" yaml:"spec"`
}
ToolConfig represents a K8s-style tool configuration manifest
func (*ToolConfig) FunctionName ¶ added in v2.7.0
func (c *ToolConfig) FunctionName() string
FunctionName is the name the LLM calls the tool by: spec.name when set, otherwise metadata.name. metadata.name is a resource name, where hyphens are conventional, so it cannot always be a function name.
type ToolDescriptor ¶
type ToolDescriptor struct {
Name string `json:"name" yaml:"name"`
Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
Description string `json:"description" yaml:"description"`
InputSchema json.RawMessage `json:"input_schema" yaml:"input_schema"` // JSON Schema Draft-07
OutputSchema json.RawMessage `json:"output_schema" yaml:"output_schema"` // JSON Schema Draft-07
Mode string `json:"mode" yaml:"mode"` // mock|live|local|mcp|client|<executor name>
TimeoutMs int `json:"timeout_ms" yaml:"timeout_ms"`
// Static mock data (in-memory)
MockResult json.RawMessage `json:"mock_result,omitempty" yaml:"mock_result,omitempty"`
// Multimodal mock parts (text, image, audio, etc.)
MockParts []types.ContentPart `json:"mock_parts,omitempty" yaml:"mock_parts,omitempty"`
// Template for dynamic mocks (inline or file)
MockTemplate string `json:"mock_template,omitempty" yaml:"mock_template,omitempty"`
MockResultFile string `json:"mock_result_file,omitempty" yaml:"mock_result_file,omitempty"`
MockTemplateFile string `json:"mock_template_file,omitempty" yaml:"mock_template_file,omitempty"`
// Labels are optional key-value pairs propagated to events, metrics, and traces.
// Use for dynamic dimensions like handler type, service tier, or team ownership.
// These appear as additional Prometheus metric labels and OTel span attributes.
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
HTTPConfig *HTTPConfig `json:"http,omitempty" yaml:"http,omitempty"` // Live HTTP configuration
A2AConfig *A2AConfig `json:"a2a,omitempty" yaml:"a2a,omitempty"` // A2A agent configuration
ClientConfig *ClientConfig `json:"client,omitempty" yaml:"client,omitempty"` // Client-side execution configuration
ExecConfig *ExecConfig `json:"exec,omitempty" yaml:"exec,omitempty"` // Exec subprocess configuration
// Declaration is the pack's definition of this tool, so a
// host's executor can apply its own policy to action_scope and
// extensions. It is a copy, never the loaded pack, and is read-only: it
// may be shared by every conversation opened from one PackTemplate. Nil
// means the pack does not declare the tool: a capability, MCP or
// discovered tool, or a handler with no pack entry. How to treat an
// undeclared tool is the host's decision. PromptKit never reads it.
Declaration *packspec.Tool `json:"-" yaml:"-"`
// Agent is the pack's definition of the agent member this tool calls,
// set on A2A tools resolved from the pack's own agents (a read-only copy,
// like Declaration). Nil for every other tool, including A2A tools discovered
// from a remote agent card.
Agent *packspec.AgentDef `json:"-" yaml:"-"`
}
ToolDescriptor represents a normalized tool definition
func (ToolDescriptor) MarshalJSON ¶
func (d ToolDescriptor) MarshalJSON() ([]byte, error)
MarshalJSON normalizes the descriptor's schemas (empty -> {}).
type ToolErrorData ¶
type ToolErrorData struct {
Type string `json:"type"` // Error type/category
Message string `json:"message"` // Error message
}
ToolErrorData represents an error response for tool execution.
type ToolExecutionResult ¶
type ToolExecutionResult struct {
Status ToolExecutionStatus `json:"status"`
Content json.RawMessage `json:"content,omitempty"`
Parts []types.ContentPart `json:"parts,omitempty"`
Error string `json:"error,omitempty"`
// Present when Status == ToolStatusPending
PendingInfo *PendingToolInfo `json:"pending_info,omitempty"`
}
ToolExecutionResult includes status and optional pending information
type ToolExecutionStatus ¶
type ToolExecutionStatus string
ToolExecutionStatus represents whether a tool completed or needs external input
const ( // ToolStatusComplete indicates the tool finished executing ToolStatusComplete ToolExecutionStatus = "complete" // ToolStatusPending indicates the tool is waiting for external input (e.g., human approval) ToolStatusPending ToolExecutionStatus = "pending" // ToolStatusFailed indicates the tool execution failed ToolStatusFailed ToolExecutionStatus = "failed" )
type ToolRepository ¶
type ToolRepository interface {
LoadTool(name string) (*ToolDescriptor, error)
ListTools() ([]string, error)
SaveTool(descriptor *ToolDescriptor) error
}
ToolRepository is the source a registry is LOADED from at construction: NewRegistryWithRepository copies every descriptor it lists into the registry and does not consult it again. It is a loader, not a store: pack content is immutable for a session, so there is nothing to re-read and nothing to write back.
type ToolResponseData ¶
type ToolResponseData struct {
Result any `json:"result,omitempty"` // Successful response data
Error *ToolErrorData `json:"error,omitempty"` // Error response
}
ToolResponseData represents a configured tool response with optional error.
type ToolResponseRepository ¶
type ToolResponseRepository interface {
// GetToolResponse retrieves a mock response for a tool execution.
// Returns nil if no matching response is configured (not an error).
GetToolResponse(toolName string, args map[string]any, contextKey string) (*ToolResponseData, error)
}
ToolResponseRepository defines the interface for repositories that can provide mock tool responses based on tool name, arguments, and context.
type ToolResult ¶
type ToolResult struct {
Name string `json:"name"`
ID string `json:"id"` // Matches ToolCall.ID
Result json.RawMessage `json:"result"`
Parts []types.ContentPart `json:"parts,omitempty"`
LatencyMs int64 `json:"latency_ms"`
Error string `json:"error,omitempty"`
}
ToolResult represents the result of a tool execution
func (ToolResult) MarshalJSON ¶
func (r ToolResult) MarshalJSON() ([]byte, error)
MarshalJSON normalizes the tool result payload (empty -> {}).
type ValidationError ¶
type ValidationError struct {
Type string `json:"type"` // "args_invalid" | "result_invalid" | "policy_violation"
Tool string `json:"tool"`
Detail string `json:"detail"`
Path string `json:"path,omitempty"`
}
ValidationError represents a tool validation failure
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface
Source Files
¶
- arg_equal.go
- args_passthrough.go
- child_registry.go
- context.go
- error_result.go
- errors.go
- exec_executor.go
- executors.go
- host_extras.go
- http_executor.go
- http_mapping.go
- http_multimodal.go
- mcp_executor.go
- rate_limiter.go
- raw_message_marshal.go
- registry.go
- repository_executor.go
- result_text.go
- server_executor.go
- types.go
- validator.go