tools

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package tools defines runtime-facing tool metadata and helpers.

This file defines the opt-in idempotency metadata used by planners to decide whether repeated tool calls can be safely de-duplicated across a transcript.

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: json.Marshal,
	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

This section is empty.

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.

When a tool is idempotent for a given scope, orchestration layers may treat repeated calls with identical arguments as redundant and avoid executing them.

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

const (
	// IdempotencyScopeTranscript indicates the tool is idempotent across a run
	// transcript: identical calls may be dropped once a successful result exists
	// in the transcript.
	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 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) 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 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 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.
	//
	// This is intended for tools whose result is the user-facing terminal output
	// (for example, a final report renderer) and should not be followed by extra
	// model narration.
	TerminalRun 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.

Jump to

Keyboard shortcuts

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