tools

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tools defines runtime-facing tool metadata and helpers.

This file defines opt-in idempotency metadata for planners and orchestrators. The runtime does not implement replay suppression or result caching.

Package tools exposes shared tool metadata and codec types used by generated code.

Index

Constants

This section is empty.

Variables

View Source
var AnyJSONCodec = JSONCodec[any]{
	ToJSON: func(value any) ([]byte, error) {
		return json.Marshal(value)
	},
	FromJSON: func(data []byte) (any, error) {
		if len(data) == 0 {
			return nil, nil
		}
		var out any
		if err := json.Unmarshal(data, &out); err != nil {
			return nil, err
		}
		return out, nil
	},
}

AnyJSONCodec is a pre-built codec for the `any` type. It uses standard JSON marshaling/unmarshaling and is suitable for integrations where the concrete type is not known at compile time.

Functions

func ValidateJSONSchema added in v2.1.0

func ValidateJSONSchema(schema []byte, value any) error

ValidateJSONSchema validates a JSON-compatible value against a JSON Schema document. Local references resolve against the supplied document; external references fail closed.

Types

type BoundsSpec

type BoundsSpec struct {
	// Paging optionally describes cursor-based pagination for this bounded tool.
	Paging *PagingSpec
}

BoundsSpec describes the runtime-owned bounds contract for a tool.

type ConfirmationSpec

type ConfirmationSpec struct {
	// Title is an optional title shown in the confirmation UI (when supported).
	Title string
	// PromptTemplate is rendered with the tool payload to produce the prompt.
	PromptTemplate string
	// DeniedResultTemplate is rendered with the tool payload to produce JSON for
	// the denied tool result. The rendered JSON must decode with the tool result
	// codec so consumers observe a schema-compliant tool_result.
	DeniedResultTemplate string
}

ConfirmationSpec declares the confirmation protocol for a tool. It is emitted by loom-mcp codegen when a tool uses Confirmation in the DSL.

Confirmation uses a runtime-owned confirmation transport (typically an ask_question-style external interaction) to obtain an approve/deny decision from a human operator. Tool authors only configure templates and optional display title; the runtime owns how confirmation is requested and how the decision is delivered back to the run.

type FieldIssue

type FieldIssue struct {
	Field      string
	Constraint string
	// Optional extras for richer UIs and retry hints; not all are populated by the codecs.
	Allowed []string
	MinLen  *int
	MaxLen  *int
	Pattern string
	Format  string
}

FieldIssue represents a single validation issue for a payload. Constraint values follow goa error kinds: missing_field, invalid_enum_value, invalid_format, invalid_pattern, invalid_range, invalid_length, invalid_field_type. Generated tool codecs return []FieldIssue from ValidationError.Issues().

type IdempotencyScope

type IdempotencyScope string

IdempotencyScope declares the semantic scope in which a tool call is considered idempotent.

A scope is a semantic declaration only. Consumers that implement replay must define canonical argument equality, success-only reuse, and failure behavior.

Default: tools are not idempotent across a transcript unless explicitly tagged.

const (
	// IdempotencyScopeTranscript indicates the tool is idempotent across a run
	// transcript. It does not enable built-in duplicate suppression.
	IdempotencyScopeTranscript IdempotencyScope = "transcript"

	// TagIdempotencyTranscript is the design-time tag emitted into ToolSpec.Tags
	// when a tool is declared idempotent across a transcript.
	TagIdempotencyTranscript = "loom-mcp.idempotency=transcript"
)

func IdempotencyScopeFromTags

func IdempotencyScopeFromTags(tags []string) (IdempotencyScope, bool, error)

IdempotencyScopeFromTags returns the idempotency scope declared in tags.

Contract:

  • The idempotency tag appears at most once. Multiple tags are a design bug.
  • Unknown idempotency values are a design bug and are returned as errors.

type Ident

type Ident string

Ident is the strong type for globally unique tool identifiers. Tool IDs are canonical strings of the form "toolset.tool" (e.g., "helpers.search", "weather.get_forecast"). This format is consistent across all loom-mcp surfaces: planners, hooks, streams, policies, and generated code.

Using Ident instead of raw strings provides:

  • Type safety: prevents accidental mixing with session IDs, run IDs, etc.
  • Documentation: call sites show intent (tool vs. arbitrary string)
  • Provider agnosticism: platform adapters handle format translation

Generated code produces typed Ident constants for each tool:

// In generated specs package
const ToolSearch tools.Ident = "helpers.search"

// Usage
if call.Name == specs.ToolSearch { ... }

Platform adapters (Bedrock, OpenAI) are responsible for translating between canonical Idents and platform-specific formats. For example, Bedrock requires underscores instead of dots, so the adapter maps "helpers.search" to "helpers_search" on outbound calls and reverses the mapping on inbound tool calls. User code never needs to handle these transformations.

const RecallContext Ident = "runtime.recall_context"

RecallContext is the runtime-owned tool for discovery and reads of hidden model-visible conversation evidence within an authorized checkpoint chain.

const ToolUnavailable Ident = "runtime.tool_unavailable"

ToolUnavailable is a runtime-owned tool used to represent model tool calls whose requested tool name is not registered for the run.

Provider adapters and runtimes rewrite unknown tool calls to this identifier to preserve a valid tool_use → tool_result handshake even when models hallucinate tool names. The tool returns a structured error and a retry hint instructing the model to select from the advertised tool list.

func (Ident) Ident added in v2.1.0

func (id Ident) Ident() Ident

Ident returns the identifier so Ident satisfies Named.

func (Ident) String

func (id Ident) String() string

String returns the string representation of the identifier. Useful for logging, error messages, and JSON serialization where the raw string is needed.

func (Ident) Tool

func (id Ident) Tool() string

Tool returns the tool name component of the identifier (the part after the last dot). For "helpers.search", this returns "search". Returns an empty string if the identifier is empty.

func (Ident) Toolset

func (id Ident) Toolset() string

Toolset returns the toolset component of the identifier (the part before the last dot). For "helpers.search", this returns "helpers". Returns an empty string if the identifier has no dot separator.

type JSONCodec

type JSONCodec[T any] struct {
	// ToJSON encodes the value into canonical JSON.
	ToJSON func(T) ([]byte, error)
	// FromJSON decodes the JSON payload into the typed value.
	FromJSON func([]byte) (T, error)
}

JSONCodec serializes and deserializes strongly typed values to and from JSON.

type Named added in v2.1.0

type Named interface {
	Ident() Ident
}

Named identifies a tool without requiring its payload or result types.

type PagingSpec

type PagingSpec struct {
	// CursorField is the name of the optional String field in the tool payload
	// used to request subsequent pages.
	CursorField string
	// NextCursorField is the canonical field name for the next-page cursor in
	// the projected result contract. Runtimes populate it from
	// planner.ToolResult.Bounds.NextCursor when present.
	NextCursorField string
}

PagingSpec describes cursor-based pagination for a bounded tool. Field names refer to the payload/result contract projected by BoundedResult, not necessarily to fields authored on the semantic Go result type.

type ResultRefs added in v2.1.0

type ResultRefs struct {
	// Parts addresses runtime-owned recall attachments; ordinary tools must not set it.
	Parts runstore.Hash `json:"parts,omitzero"`
	// Result addresses the full canonical result JSON eligible for model access.
	Result runstore.Hash
	// ServerData addresses the server-only sidecar; never expose it to a model.
	ServerData runstore.Hash
	// Payload addresses the executed payload, including injected server-only values.
	// Neither this hash nor its content may enter model-facing messages.
	Payload runstore.Hash
}

ResultRefs addresses content committed in the root run scope before a result enters workflow state. Tool activities, inline tools, adapted child outputs, and externally provided results populate these references. Empty hashes mean no corresponding stored content. Error-only and structural results have no eligible result reference; Payload is populated only by tool activities.

type SchemaValidationError added in v2.1.0

type SchemaValidationError struct {
	Path    string
	Message string
	Value   any
}

SchemaValidationError represents a validation error with structured details.

func (*SchemaValidationError) Error added in v2.1.0

func (e *SchemaValidationError) Error() string

Error formats the validation error with its instance path when present.

type SchemaValidationErrors added in v2.1.0

type SchemaValidationErrors struct {
	Errors []*SchemaValidationError
}

SchemaValidationErrors collects multiple validation errors.

func (*SchemaValidationErrors) Add added in v2.1.0

func (e *SchemaValidationErrors) Add(path, message string, value any)

Add appends one validation failure to the collection.

func (*SchemaValidationErrors) Error added in v2.1.0

func (e *SchemaValidationErrors) Error() string

Error joins the collected validation failures into one message.

func (*SchemaValidationErrors) HasErrors added in v2.1.0

func (e *SchemaValidationErrors) HasErrors() bool

HasErrors reports whether the collection contains validation failures.

type ServerDataAudience

type ServerDataAudience string

ServerDataAudience declares who a server-data payload is intended for.

Audience is a routing contract for downstream consumers (timeline projection, UI renderers, persistence sinks). It is not sent to model providers.

const (
	// AudienceTimeline indicates the payload is persisted and eligible for UI rendering.
	AudienceTimeline ServerDataAudience = "timeline"
	// AudienceInternal indicates the payload is an internal tool-composition attachment.
	AudienceInternal ServerDataAudience = "internal"
	// AudienceEvidence indicates the payload carries provenance references.
	AudienceEvidence ServerDataAudience = "evidence"
)

type ServerDataSpec

type ServerDataSpec struct {
	// Kind identifies the server-data kind.
	Kind string
	// Audience declares who this server-data payload is intended for.
	//
	// Allowed values:
	//   - "timeline": persisted and eligible for UI rendering and transcript export
	//   - "internal": tool-composition attachment; not persisted or rendered
	//   - "evidence": provenance references; persisted separately from timeline cards
	Audience ServerDataAudience
	// Description describes what an observer sees when this payload is rendered.
	Description string
	// Type describes the schema and JSON codec for this server-data payload.
	Type TypeSpec
}

ServerDataSpec describes one server-only payload emitted alongside a tool result. Server data is never sent to model providers.

type ToolSpec

type ToolSpec struct {
	// Name is the globally unique tool identifier (`toolset.tool`).
	Name Ident
	// Service identifies the Goa service that declared the tool.
	Service string
	// Toolset is the toolset registration identifier used for routing.
	// It is typically the DSL toolset name.
	Toolset string
	// Description provides human-readable context for planners and tooling.
	Description string
	// Tags carries optional metadata labels used by policy or UI layers.
	Tags []string
	// Meta carries arbitrary design-time metadata attached to the tool via DSL.
	//
	// Meta is intended for downstream consumers (policy engines, UIs, orchestration
	// layers) that need structured tool annotations without requiring runtime
	// design introspection. Code generation emits Meta only when present.
	Meta map[string][]string
	// TerminalRun indicates that once this tool executes in a run, the runtime
	// terminates the run immediately after publishing the tool result(s), without
	// requesting a follow-up planner PlanResume/finalization turn. Terminal tools
	// must also be bookkeeping tools.
	TerminalRun bool
	// Bookkeeping indicates that the tool records control-plane state without
	// consuming the run-level MaxToolCalls budget. Successful bookkeeping results
	// do not reset recovery turns or independently schedule another planner turn.
	Bookkeeping bool
	// KeepResultInContext preserves whole results during context clearing.
	KeepResultInContext bool

	// IsAgentTool indicates this tool is implemented by an agent (agent-as-tool).
	// When true, the runtime executes the tool by starting the provider agent as a
	// child workflow from within the parent workflow loop. Set by codegen when
	// processing Exports blocks.
	IsAgentTool bool
	// AgentID is the fully qualified agent identifier (e.g., "service.agent_name").
	// Only set when IsAgentTool is true.
	AgentID string
	// Bounds declares the runtime-owned bounded-result contract for this tool.
	// When non-nil, runtimes require explicit planner.ToolResult.Bounds metadata
	// on successful executions and project the canonical bounded fields back
	// into encoded result JSON, result previews, and stream/hook payloads
	// without inspecting tool-specific semantics.
	Bounds *BoundsSpec
	// ServerData enumerates server-only payloads emitted alongside the tool
	// result. Server data is never sent to model providers.
	//
	// Each entry declares the schema and codec for the item data payload
	// (`toolregistry.ServerDataItem.Data`) so runtimes and consumers can decode
	// and validate it without runtime design introspection.
	ServerData []*ServerDataSpec
	// ResultReminder is an optional system reminder injected into the
	// conversation after the tool result is returned. It provides backstage
	// guidance to the model about how to interpret or present the result
	// (for example, "The user sees a rendered graph of this data"). The
	// runtime wraps this text in <system-reminder> tags.
	ResultReminder string
	// Confirmation configures design-time confirmation requirements for this tool.
	// When set, runtimes may request explicit out-of-band user confirmation before
	// executing the tool. Runtime configuration can override or extend this policy.
	Confirmation *ConfirmationSpec
	// Payload describes the request schema for the tool.
	Payload TypeSpec
	// Result describes the response schema for the tool.
	Result TypeSpec
}

ToolSpec enumerates the metadata and JSON codecs for a tool.

type TypeSpec

type TypeSpec struct {
	// Name is the Go identifier associated with the type.
	Name string
	// Schema contains the JSON schema definition rendered at code generation time.
	Schema []byte
	// ExampleJSON optionally contains a canonical example JSON document for this
	// type. When present on payload types, runtimes and planners can surface it
	// in retry hints or await-clarification prompts to guide callers toward a
	// schema-compliant shape.
	ExampleJSON []byte
	// ExampleInput is an optional parsed example payload. When present, it is a
	// JSON-object example represented as a map and can be attached to retry hints
	// without runtime JSON unmarshaling.
	ExampleInput map[string]any
	// Codec serializes and deserializes values matching the type.
	Codec JSONCodec[any]
}

TypeSpec describes the payload or result schema for a tool.

type TypedTool added in v2.1.0

type TypedTool[P, R any] struct {
	Name    Ident
	Payload JSONCodec[P]
	Result  JSONCodec[R]
}

TypedTool describes a tool's identifier and its typed JSON codecs.

func (TypedTool[P, R]) Ident added in v2.1.0

func (t TypedTool[P, R]) Ident() Ident

Ident returns the canonical identifier of the tool.

Jump to

Keyboard shortcuts

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