# 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):

```go
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:

- `json` sets the JSON property name, and `,omitempty` marks the property optional (`required` otherwise).
- `description` becomes the JSON Schema `description` shown to the model.
- `enum` constrains accepted values, for example `enum:"low,medium,high"`.

If your input type implements [`tool.Validator`](https://pkg.go.dev/github.com/ijaidev/gojent/core/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:

1. **Pre-handler validation:** Explicit JSON arguments (including `{}`) are validated against the generated JSON Schema before decoding; mismatches return `tool.ErrInvalidInput` to the model and your `Execute` handler never runs. Empty or `null` arguments mean "no arguments" and skip schema validation (passing the zero value of `In`), so implement [`tool.Validator`](https://pkg.go.dev/github.com/ijaidev/gojent/core/tool#Validator) when a field must be rejected even if the model sends `null` or empty arguments—`Validate()` always runs before `Execute`.
2. **Bounded parallel execution:** Tools default to `tool.ExecutionParallel`, allowing contiguous parallel-safe tool calls in the same assistant message to run concurrently up to `MaxParallelTools` (`agent.DefaultMaxParallelTools` is `8`; set `1` via `agent.Config.MaxParallelTools` or `agent.WithMaxParallelTools` to force sequential execution). Calls marked `tool.ExecutionSequential` act as ordering barriers, and every result is recorded in exact original call order.
3. **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.
4. **Default tool timeout:** Each tool call is bounded by `agent.DefaultToolTimeout` (**2 minutes**) when `ToolTimeout` is zero. Override it on `agent.Config.ToolTimeout` or per run with `agent.WithToolTimeout`; set a negative duration to disable the timeout. Wrap long-running orchestration or subagent tools with `agent.WithoutDefaultToolTimeout` to exempt them from the default tool timeout while preserving enclosing `Budget.MaxDuration` and context cancellation.
5. **Atomic persistence:** Tool results are grouped into one user message (`llm.ToolResultsMessage`) and persisted together with the assistant tool-call message in a single `Store.Append` call.

## 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:

```go no-compile
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](/docs/core/policies) 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`):

```go
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](/docs/modules/tools), or inspect the full API on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/tool).
