toolcall

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package toolcall defines composable tool providers for AI agents.

This package provides a layered tool composition system for AI agent file, finding, and history operations. Tools are composed using generics: Empty -> Worktree -> Finding -> History.

Callback types (WorktreeCallbacks, FindingCallbacks, etc.) are defined in the toolcall/callbacks subpackage. This separation allows packages that only need callback types to avoid importing AI SDK dependencies.

Tool Composition

Tools are composed by wrapping callback structs in generic wrappers:

// Callbacks hold the actual implementation functions
wt := callbacks.WorktreeCallbacks{
	ReadFile: func(ctx context.Context, path string) (string, error) { ... },
	WriteFile: func(ctx context.Context, path, content string, mode os.FileMode) error { ... },
}
fc := callbacks.FindingCallbacks{
	GetDetails: func(ctx context.Context, kind callbacks.FindingKind, id string) (string, error) { ... },
	GetLogs: func(ctx context.Context, kind callbacks.FindingKind, id string) (string, error) { ... },
}

hc := callbacks.HistoryCallbacks{
	ListCommits: func(ctx context.Context, offset, limit int) (callbacks.CommitListResult, error) { ... },
	GetFileDiff: func(ctx context.Context, path, start, end string, offset int64, limit int) (callbacks.FileDiffResult, error) { ... },
}

// Compose tools: Empty -> Worktree -> Finding -> History
tools := toolcall.NewHistoryTools(
	toolcall.NewFindingTools(
		toolcall.NewWorktreeTools(toolcall.EmptyTools{}, wt),
		fc,
	),
	hc,
)

Tool Providers

Providers generate tool definitions for specific AI backends (Claude, Gemini):

provider := toolcall.NewFindingToolsProvider[*Response, toolcall.WorktreeTools[toolcall.EmptyTools]](
	toolcall.NewWorktreeToolsProvider[*Response, toolcall.EmptyTools](
		toolcall.NewEmptyToolsProvider[*Response](),
	),
)

claudeTools := provider.ClaudeTools(tools)
googleTools := provider.GoogleTools(tools)

Callback Sources

Factory functions for callbacks are provided by other packages:

  • WorktreeCallbacks: clonemanager.WorktreeCallbacks(worktree)
  • FindingCallbacks: session.FindingCallbacks()
  • HistoryCallbacks: clonemanager.HistoryCallbacks(repo, baseCommit)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func OptionalParam

func OptionalParam[T any](call ToolCall, name string, defaultValue T) (T, map[string]any)

OptionalParam extracts an optional parameter from the tool call args.

func Param

func Param[T any](call ToolCall, trace interface {
	BadToolCall(string, string, map[string]any, error)
}, name string) (T, map[string]any)

Param extracts a required parameter from the tool call args. On error, records a bad tool call on the trace and returns an error response.

func ParameterToMap added in v0.5.0

func ParameterToMap(p Parameter) map[string]any

ParameterToMap converts a Parameter to a JSON Schema property map suitable for use in provider-specific tool definitions (Claude, Gemini, OpenAI, MCP).

func Ptr added in v0.6.0

func Ptr[T any](v T) *T

Ptr returns a pointer to the given value. Commonly used to set Destructive and OpenWorld fields on ToolAnnotations, which use *bool to distinguish "explicitly false" from "unset (default true)".

func SchemaToMap added in v0.5.0

func SchemaToMap(s *Schema) map[string]any

SchemaToMap converts a Schema to the map[string]any JSON Schema representation. Returns nil for a nil schema. A false schema (FalseSchema) returns nil; callers that need to emit the JSON boolean false should check s.False before calling (see schemaToAny).

Types

type Definition

type Definition struct {
	Name        string
	Description string
	Parameters  []Parameter

	// Annotations describes behavioral hints about this tool. When non-nil,
	// these are forwarded to MCP clients that support tool annotations.
	Annotations *ToolAnnotations

	// OutputSchema is an optional JSON Schema describing the tool's response.
	// Used by MCP's Tool.OutputSchema field.
	OutputSchema *Schema

	// InputSchemaDefs holds the "$defs" map from the top-level input schema.
	// Real-world MCP servers (e.g. Google Cloud Run, GKE) use "$defs" and
	// "$ref" to express shared sub-schemas; this field preserves them so they
	// survive a round-trip through extractParameters → mcpTool.
	InputSchemaDefs map[string]*Schema

	// InputSchemaDescription is the "description" field on the top-level input
	// schema object. It is distinct from Description (the tool's own description)
	// and typically contains the proto message description.
	InputSchemaDescription string

	// InputSchemaExtensions holds any top-level input schema keywords that are
	// not otherwise modelled (e.g. "$schema" meta-schema declaration used by
	// Linear and other non-Google MCP servers).
	InputSchemaExtensions map[string]any
}

Definition describes a tool's schema (name, description, parameters).

type EmptyTools

type EmptyTools struct{}

EmptyTools is the base tools type with no callbacks. Use this as the foundation when composing tool stacks.

type FindingTools

type FindingTools[T any] struct {
	callbacks.FindingCallbacks
	// contains filtered or unexported fields
}

FindingTools wraps a base tools type and adds finding callbacks.

func NewFindingTools

func NewFindingTools[T any](base T, cb callbacks.FindingCallbacks) FindingTools[T]

NewFindingTools creates a FindingTools wrapping the given base tools.

type HistoryTools

type HistoryTools[T any] struct {
	callbacks.HistoryCallbacks
	// contains filtered or unexported fields
}

HistoryTools wraps a base tools type and adds history callbacks.

func NewHistoryTools

func NewHistoryTools[T any](base T, cb callbacks.HistoryCallbacks) HistoryTools[T]

NewHistoryTools creates a HistoryTools wrapping the given base tools.

type Parameter

type Parameter struct {
	Name        string
	Type        string // "string"|"integer"|"boolean"|"number"|"array"|"object"|"null"
	Description string
	Required    bool

	// Items is the element schema for array-type parameters (Type=="array").
	Items *Schema
	// Properties defines named sub-schemas for object-type parameters (Type=="object").
	Properties map[string]*Schema
	// PropertyRequired lists property names that are required within an
	// object-type parameter. Distinct from Required, which controls whether
	// the parameter itself must be present in the tool call.
	PropertyRequired []string
	// AdditionalProperties constrains extra properties on an object parameter.
	// Use FalseSchema() to disallow all additional properties.
	AdditionalProperties *Schema
	// Enum restricts the parameter to a fixed set of allowed values.
	Enum []any

	// Numeric constraints.
	Minimum          *float64
	Maximum          *float64
	ExclusiveMinimum *float64
	ExclusiveMaximum *float64
	MultipleOf       *float64

	// String constraints.
	MinLength *int
	MaxLength *int
	Pattern   string

	// Schema metadata.
	Title      string
	Default    any
	Deprecated bool
	Format     string

	// Schema composition.
	OneOf []*Schema
	AnyOf []*Schema
	AllOf []*Schema
	Not   *Schema

	// Ref is a JSON Schema "$ref" value (e.g. "#/$defs/MyType"). When set,
	// other fields may still be present alongside it (JSON Schema allows
	// sibling keywords next to $ref in draft 2019-09+).
	Ref string

	// ReadOnly marks the parameter as read-only (JSON Schema "readOnly").
	ReadOnly bool
	// WriteOnly marks the parameter as write-only (JSON Schema "writeOnly").
	WriteOnly bool

	// Extensions holds vendor-specific extension keywords (e.g. "x-google-identifier").
	// Keys should begin with "x-" per JSON Schema convention.
	Extensions map[string]any
}

Parameter describes a single tool parameter.

The four scalar types ("string", "integer", "boolean", "number") are fully backward-compatible: existing tool definitions compile and run unchanged. The additional fields (Items, Properties, Enum, etc.) enable complex JSON Schema types such as arrays, objects, enums, and schema composition.

type Schema added in v0.5.0

type Schema struct {
	Type        string
	Description string
	Title       string
	Format      string

	// Object fields.
	Properties           map[string]*Schema
	Required             []string // required property names within this object schema
	AdditionalProperties *Schema  // use FalseSchema() to disallow additional properties
	// Defs holds "$defs" named sub-schemas. Typically used at the top level of
	// an input schema to define reusable types referenced via $ref.
	Defs map[string]*Schema

	// Array fields.
	Items *Schema

	// Enum restricts values to a fixed set.
	Enum []any

	// Numeric constraints.
	Minimum          *float64
	Maximum          *float64
	ExclusiveMinimum *float64
	ExclusiveMaximum *float64
	MultipleOf       *float64

	// String constraints.
	MinLength *int
	MaxLength *int
	Pattern   string

	// Schema metadata.
	Default    any
	Deprecated bool
	ReadOnly   bool
	WriteOnly  bool

	// Ref is a JSON Schema "$ref" value (e.g. "#/$defs/MyType").
	Ref string

	// Extensions holds vendor-specific extension keywords (e.g. "x-google-identifier").
	Extensions map[string]any

	// Schema composition.
	OneOf []*Schema
	AnyOf []*Schema
	AllOf []*Schema
	Not   *Schema

	// False represents the JSON Schema boolean false schema (matches nothing).
	// Use FalseSchema() rather than setting this field directly. It is used
	// primarily for AdditionalProperties to disallow any extra properties.
	False bool
}

Schema represents a JSON Schema definition used for nested type descriptions within a Parameter — for example, the element schema of an array (Items), property schemas of an object (Properties), or composition schemas (OneOf, AnyOf, AllOf).

func FalseSchema added in v0.5.0

func FalseSchema() *Schema

FalseSchema returns a sentinel Schema that serializes as the JSON Schema boolean false (matches nothing). Use for AdditionalProperties to disallow any additional properties in an object schema.

type Tool

type Tool[Resp any] struct {
	Def     Definition
	Handler func(ctx context.Context, call ToolCall, trace *agenttrace.Trace[Resp], result *Resp) map[string]any
}

Tool defines a tool once with a single handler that works with any provider.

type ToolAnnotations added in v0.5.0

type ToolAnnotations struct {
	// ReadOnly indicates the tool does not modify any state. Defaults to false.
	ReadOnly bool
	// Destructive indicates the tool may cause irreversible changes (e.g. delete).
	// Nil means unset; the MCP default is true (assume destructive unless stated).
	Destructive *bool
	// Idempotent indicates repeated calls with the same arguments have the same
	// effect as a single call. Defaults to false.
	Idempotent bool
	// OpenWorld indicates the tool may interact with external systems beyond
	// the immediate context (e.g. web searches, external APIs).
	// Nil means unset; the MCP default is true (assume open-world unless stated).
	OpenWorld *bool
}

ToolAnnotations describes behavioral hints about a tool. These map directly to the MCP protocol's tool annotation fields and help clients display appropriate warnings and take appropriate precautions before invoking a tool.

ReadOnly and Idempotent are plain bool because the MCP spec defines their absent/nil default as false. Destructive and OpenWorld are *bool because the MCP spec defines their absent/nil default as true — a nil pointer means "unset, assume true", while a pointer to false means "explicitly not destructive/open-world". Proxies must preserve nil to avoid silently downgrading tools that are destructive or open-world by default.

type ToolCall

type ToolCall struct {
	ID   string
	Name string
	Args map[string]any
}

ToolCall is a provider-independent representation of a tool call.

type ToolProvider

type ToolProvider[Resp, CB any] interface {
	// Tools returns unified tool definitions that work with any provider.
	Tools(ctx context.Context, cb CB) (map[string]Tool[Resp], error)
}

ToolProvider defines tools for an agent. Implementations return provider-independent tool definitions. Compose providers by wrapping: Empty -> Worktree -> Finding. Conversion to SDK-specific types happens downstream in the metaagent layer.

func NewEmptyToolsProvider

func NewEmptyToolsProvider[Resp any]() ToolProvider[Resp, EmptyTools]

NewEmptyToolsProvider returns a ToolProvider that provides no tools. Use this as the base when composing tool provider stacks.

func NewFindingToolsProvider

func NewFindingToolsProvider[Resp, T any](base ToolProvider[Resp, T]) ToolProvider[Resp, FindingTools[T]]

NewFindingToolsProvider creates a provider that adds finding tools (get_finding_details, search_finding_logs, read_finding_logs) on top of the base provider's tools. The finding tools are only added if the corresponding callbacks are available.

func NewHistoryToolsProvider

func NewHistoryToolsProvider[Resp, T any](base ToolProvider[Resp, T]) ToolProvider[Resp, HistoryTools[T]]

NewHistoryToolsProvider creates a provider that adds history tools (list_commits, get_file_diff) on top of the base provider's tools.

func NewWorktreeToolsProvider

func NewWorktreeToolsProvider[Resp, T any](base ToolProvider[Resp, T]) ToolProvider[Resp, WorktreeTools[T]]

NewWorktreeToolsProvider creates a provider that adds worktree tools on top of the base provider's tools.

type WorktreeTools

type WorktreeTools[T any] struct {
	callbacks.WorktreeCallbacks
	// contains filtered or unexported fields
}

WorktreeTools wraps a base tools type and adds worktree callbacks.

func NewWorktreeTools

func NewWorktreeTools[T any](base T, cb callbacks.WorktreeCallbacks) WorktreeTools[T]

NewWorktreeTools creates a WorktreeTools wrapping the given base tools.

Directories

Path Synopsis
Package callbacks provides lightweight callback types for AI agent tool operations.
Package callbacks provides lightweight callback types for AI agent tool operations.
Package claudetool provides utilities for handling tool calls in Claude AI applications.
Package claudetool provides utilities for handling tool calls in Claude AI applications.
Package googletool provides utilities for handling function calls in Google Gemini AI applications.
Package googletool provides utilities for handling function calls in Google Gemini AI applications.
Package openaistool converts unified toolcall.Tool definitions into OpenAI-compatible openai.ChatCompletionToolParam metadata for use with the [openaiexecutor].
Package openaistool converts unified toolcall.Tool definitions into OpenAI-compatible openai.ChatCompletionToolParam metadata for use with the [openaiexecutor].
Package params provides shared parameter extraction and error formatting utilities used by both Claude and Google tool implementations.
Package params provides shared parameter extraction and error formatting utilities used by both Claude and Google tool implementations.

Jump to

Keyboard shortcuts

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