Typed Tools
A Gojent tool is a typed Go function paired with metadata (tool.Spec) implementing the tool.Tool interface. tool.New and tool.MustNew generate a JSON Schema directly from your Go input struct and validate model-supplied arguments before your handler ever runs.
Define a typed tool
Specify input and output types via tool.Config[In, Out] and pass it to tool.New (returns an error) or tool.MustNew (panics on invalid configuration, suited for startup wiring):
package main
import (
"context"
"fmt"
"log"
"github.com/ijaidev/gojent/core/tool"
)
type SearchInput struct {
Query string `json:"query" description:"Search query"`
Limit int `json:"limit,omitempty" description:"Maximum results, 1-20"`
Scope string `json:"scope,omitempty" enum:"docs,code,all" description:"Search scope"`
}
type SearchResult struct {
Title string `json:"title"`
URL string `json:"url"`
}
func main() {
search, err := tool.New(tool.Config[SearchInput, SearchResult]{
ID: "search",
Description: "Search the knowledge base.",
Annotations: tool.Annotations{ReadOnly: true, Idempotent: true},
Execute: func(_ context.Context, in SearchInput) (SearchResult, error) {
return SearchResult{Title: "Result for " + in.Query, URL: "https://example.com"}, nil
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(search.Spec().Name)
}
Supported struct tags and custom validation
Struct tags on In drive schema generation:
jsonsets the JSON property name, and,omitemptymarks the property optional (requiredotherwise).descriptionbecomes the JSON Schemadescriptionshown to the model.enumconstrains accepted values, for exampleenum:"low,medium,high".
If your input type implements tool.Validator (Validate() error), the runtime invokes Validate() after JSON decoding and schema validation and before calling Execute. When targeting providers that enforce strict JSON Schemas, configure both Config.Strict: true (marks the tool specification strict) and Config.SchemaOptions: []tool.SchemaOption{tool.WithStrictSchema(true)} (emits a strict JSON Schema with additionalProperties: false and all properties required).
Runtime execution guarantees
When an agent invokes tools, the runtime enforces five isolation and scheduling guarantees:
- Pre-handler validation: Explicit JSON arguments (including
{}) are validated against the generated JSON Schema before decoding; mismatches returntool.ErrInvalidInputto the model and yourExecutehandler never runs. Empty ornullarguments mean “no arguments” and skip schema validation (passing the zero value ofIn), so implementtool.Validatorwhen a field must be rejected even if the model sendsnullor empty arguments—Validate()always runs beforeExecute. - Bounded parallel execution: Tools default to
tool.ExecutionParallel, allowing contiguous parallel-safe tool calls in the same assistant message to run concurrently up toMaxParallelTools(agent.DefaultMaxParallelToolsis8; set1viaagent.Config.MaxParallelToolsoragent.WithMaxParallelToolsto force sequential execution). Calls markedtool.ExecutionSequentialact as ordering barriers, and every result is recorded in exact original call order. - Panic and cancellation containment: Panics inside a tool handler are recovered and surfaced as tool errors rather than crashing the process. Context cancellation and timeouts are reported cleanly.
- Default tool timeout: Each tool call is bounded by
agent.DefaultToolTimeout(2 minutes) whenToolTimeoutis zero. Override it onagent.Config.ToolTimeoutor per run withagent.WithToolTimeout; set a negative duration to disable the timeout. Wrap long-running orchestration or subagent tools withagent.WithoutDefaultToolTimeoutto exempt them from the default tool timeout while preserving enclosingBudget.MaxDurationand context cancellation. - Atomic persistence: Tool results are grouped into one user message (
llm.ToolResultsMessage) and persisted together with the assistant tool-call message in a singleStore.Appendcall.
Side-effect annotations
tool.Annotations describes a tool’s behavioral side effects so an agent.Policy or agent.Approver can gate execution without inspecting the tool implementation:
type Annotations struct {
ReadOnly bool // does not mutate state
Destructive bool // may delete or overwrite data
Idempotent bool // repeating the call has the same effect
OpenWorld bool // talks to an unbounded external system
}
Keep annotations honest—for example, mark read/search tools ReadOnly: true, Idempotent: true and file-mutating or shell tools Destructive: true. See Policies & Approvals for gating on annotations.
Results and multimodal output
Returning any typed Out struct makes it available both as structured Result.Data and as JSON text for the model. To return files, images, audio, or custom llm.Part slices, return tool.Result (or use tool.NewFileResult):
package main
import (
"context"
"fmt"
"github.com/ijaidev/gojent/core/llm"
"github.com/ijaidev/gojent/core/tool"
)
func main() {
readPreview := tool.MustNew(tool.Config[struct{}, tool.Result]{
ID: "read_preview",
Description: "Return a rendered preview part.",
Annotations: tool.Annotations{ReadOnly: true},
Execute: func(_ context.Context, _ struct{}) (tool.Result, error) {
return tool.Result{
Content: []llm.Part{llm.NewTextPart("rendered")},
}, nil
},
})
fmt.Println(readPreview.Spec().Name)
}
Explore ready-made filesystem, exec, web, and task tools in Ready-Made Tools, or inspect the full API on pkg.go.dev.