Skip to content

How do tools work?

View as Markdown

weft.Tool turns a Go function into a tool the model can call. The input struct’s json and jsonschema tags become the tool’s JSON Schema; the function’s return value becomes the result the model sees, a string as it is and anything else as JSON.

Two tools in concepts/tools.go take the same input and return different types:

concepts/tools.go
status = weft.Tool("order_status", "Report an order's status in words.",
func(ctx context.Context, in OrderQuery) (string, error) {
return "order " + in.OrderID + " has shipped", nil // a string is sent verbatim
})
lookup = weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in OrderQuery) (Order, error) {
return Order{ID: in.OrderID, Status: "shipped"}, nil // anything else is sent as JSON
})

concepts/tools.go on GitHub

The model reads order 1234 has shipped from the first and {"id":"1234","status":"shipped"} from the second.

A tool is a *weft.ToolDef. Each step, the loop advertises the agent’s tools to the model by name, description and input schema. When the model calls one, the loop decodes the call’s JSON arguments into the input struct, runs the handler with a context that identifies the call, and puts the rendered result on the step’s tool message. A failure in decoding or running a call is a result too, not a run error: see Tool errors are data. The exceptions are malformed calls and tool sets: an empty or repeated call id or an empty tool name fails the run with ErrModelContract (see the edge cases below), and a ToolSource snapshot with a nil tool or a duplicate name fails it with ErrNilTool or ErrDuplicateTool.

weft.Tool(name, description, fn, opts...) infers its two type parameters from fn’s signature, func(ctx context.Context, in In) (Out, error), so the compiler checks the handler’s shape and nothing is written twice. The shape mirrors the official Go MCP SDK’s AddTool[In, Out], so a weft tool can be served over MCP without an adapter layer (Use MCP both ways).

What the model sees as the result depends on Out:

  • A string is sent verbatim. The tool has no output schema.
  • Any other type is sent as its json.Marshal encoding, and the tool’s OutputSchema is reflected from that type.

The model never sees OutputSchema: no first-party provider adapter sends it, and the request record’s tool catalog (and its hash) covers the name, description and input schema only. Two readers outside the loop use it. weft.Manifest writes it as the tool’s output_schema in weft.json. mcp.AddTools and mcp.Serve list it as the MCP tool’s outputSchema and return the result’s JSON as structuredContent too; a result that is not JSON is then an isError result. In the other direction, mcp.Tools records an object output schema the server sends.

In must be a struct or a pointer to one, because providers and MCP require an object at the top of a tool schema. An empty name, a nil function or a non-struct input panics when Tool is called.

The ToolDef it returns has four exported fields: Name, Description, InputSchema and OutputSchema. A ToolDef can be changed until it is registered. Tools are options: passing one to weft.New registers a deep copy, so later changes to your value never reach the agent.

Options after the handler set that tool’s policy: weft.Timeout, weft.MaxResultBytes, weft.StrictInput, weft.Sequential, weft.RequireApproval and more, covered in Set per-tool policy. weft.ToolOptions composes several of them into one named value, applied in order, with nil entries ignored.

toolDef.Invoke(ctx, args) runs a tool directly with raw JSON arguments: it decodes them into the input type, calls the handler and returns the text the model would see. A decode failure returns an error wrapping ErrInvalidToolInput. Invoke applies the tool’s own StrictInput setting; timeouts and result caps are run policy, applied only by the loop.

The package example ExampleTool prints a derived schema. Tools defined outside Go source, with an explicit schema, use weft.RawTool: see Define tools at runtime.

A weft.Schema is the subset of JSON Schema (draft 2020-12) weft derives from an input struct. Its shape tracks what the Go MCP SDK derives through Google’s jsonschema-go, so tools cross to MCP without conversion. Its fields are Type, Format, Description, Properties, AdditionalProperties, Required and Items.

The derivation, field by field:

  • The json tag names the property; a field tagged "-" is skipped; an untagged field uses its Go name.
  • The jsonschema tag is the property’s description.
  • A field is required unless it is a pointer or tagged omitempty.
  • The ,string tag option types a scalar field as string, its quoted wire form.

Types map like this:

Go typeSchema
string, []bytestring
boolboolean
any integer typeinteger
float32, float64number
slice, arrayarray, with Items
map[K]Vobject, with AdditionalProperties typing the values; map[string]any stays a bare object
structobject, with Properties and Required
time.Timestring with format: date-time
pointerthe pointed-to type’s schema; the field becomes optional
interface, func, chanunconstrained (an empty schema)

The RefundRequest struct in concepts/tools.go uses most of these:

concepts/tools.go
refund := weft.Tool("refund_order", "Refund an order.",
func(ctx context.Context, in RefundRequest) (string, error) { return "refunded", nil })
b, err := json.MarshalIndent(refund.InputSchema, "", " ")
if err != nil {
return err
}
fmt.Fprintln(w, string(b))

concepts/tools.go on GitHub

{
"type": "object",
"properties": {
"credits": {
"type": "object",
"additionalProperties": {
"type": "integer"
}
},
"lines": {
"type": "array",
"description": "line numbers to refund; all when empty",
"items": {
"type": "integer"
}
},
"order_id": {
"type": "string",
"description": "the order to refund"
},
"reason": {
"type": "string",
"description": "why the customer wants a refund"
}
},
"required": [
"order_id"
]
}

reason is a *string, so it is optional without omitempty. credits is a map[string]int, so its values are typed. The OpenAI and Anthropic adapters send additionalProperties; the Google adapter drops it, because Gemini’s schema subset has no such field. The boolean form additionalProperties: false cannot be expressed.

Schema.MarshalJSON emits a schema that came from weft.ParseSchema (an MCP server’s input schema, a plugin manifest) byte for byte, so keywords the struct cannot hold, such as enum or oneOf, still reach the model on the openai and anthropic adapters. The google adapter drops every keyword Gemini’s schema type lacks, oneOf and $ref among them; Use MCP both ways has the table of what it keeps. A reflected schema marshals as the plain struct.

The derivation follows encoding/json, so the schema never advertises a field the decoder will not fill:

  • Embedded structs contribute their fields to the enclosing object with encoding/json’s dominance rules. A name claimed at a shallower embedding depth wins over a deeper one. At equal depth, exactly one json-tagged claim wins over untagged ones; any other tie cancels the name, which encoding/json also drops.
  • Two fields of one struct claiming one JSON name panic when the tool is built, at any named nesting depth: one of them could never receive a value. Inside an embedded struct the same collision drops the name instead, as encoding/json does.
  • An embedded pointer to an unexported struct type panics: encoding/json cannot decode into it, so its fields would be advertised and unreachable.
  • Recursive types are cut at the recursion: the nested occurrence is an unconstrained value.
  • time.Duration is an integer counting nanoseconds, as encoding/json encodes it. Prefer a string field for durations a model writes.

The loop is as strict with what the model sends:

  • Arguments must be exactly one JSON value. Trailing data after the arguments object ({"a":1} {"a":2}) is an INVALID_INPUT result, with or without StrictInput. Empty or null arguments decode as {}.
  • A tool-call id repeated within one step fails the run with ErrModelContract, like an empty id: results and approval decisions key on the id. Ids may repeat across steps.
  • A required field may be absent. The loop checks types, not presence: nothing compares the arguments with the schema’s required list, and no adapter asks the provider to enforce the schema. A field the model leaves out decodes to its zero value ("", 0, false, nil), and the handler runs. StrictInput does not change this: it refuses fields the struct does not declare, never missing ones.

Where absent and zero mean different things, as with a refund amount or a bool decision, make the field a pointer and check it in the handler. Return weft.ModelRetry so the model repairs the call. The model reads RETRY: amount is required and calls again; the retries count against MaxModelRetries. A pointer field is also optional in the schema, so say in its jsonschema description that the model must send it. weft.Output[T]’s submit_output decodes the same way: see Get structured output.

Inside a handler, weft.CallFromContext(ctx) reports which call is running, as a weft.Call:

FieldWhat it holds
RunIDThe run the call belongs to.
StepThe zero-based index of the step that requested it.
CallIDThe provider’s call identifier.
NameThe tool name.
ApprovedTrue when the call was parked at the approval boundary and now runs under an Approve decision.

Use it for audit lines, progress that must name its call, or the call’s part of an idempotency key. The call id alone is not a key: a later turn may reuse it, so add the session and what the call acts on (Make an approved tool idempotent):

concepts/tools.go
return weft.Tool("who_calls", "Report which call this is.",
func(ctx context.Context, in OrderQuery) (string, error) {
call, ok := weft.CallFromContext(ctx)
if !ok {
return "", errors.New("who_calls: not called by the agent loop")
}
return fmt.Sprintf("run=%s step=%d call=%s tool=%s",
call.RunID, call.Step, call.CallID, call.Name), nil
})

concepts/tools.go on GitHub

In the complete example this tool prints run=run-1 step=0 call=call_3 tool=who_calls. The second return value is false when the context did not come from the agent loop, for example under a direct Invoke. Tool middleware passes verified values to a handler the same way, on the context: see Add behaviour with middleware.

agt.CallTool(ctx, call) dispatches one tool call by name the way the loop does, through the agent’s WrapTools chain and the tool’s own, with StrictInput applied at both levels. It returns the text the model would see. It is the seam for code that dispatches calls itself:

concepts/tools.go
out, err := agt.CallTool(ctx, weft.ToolCallPart{
ID: "manual-1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`),
})
fmt.Fprintln(w, "CallTool:", out, err)
_, err = agt.CallTool(ctx, weft.ToolCallPart{ID: "manual-2", Name: "refund_order"})
fmt.Fprintln(w, "unknown tool is ErrNoSuchTool:", errors.Is(err, weft.ErrNoSuchTool))
out, err = lookup.Invoke(ctx, json.RawMessage(`{"order_id":"5678"}`))
fmt.Fprintln(w, "Invoke:", out, err)

concepts/tools.go on GitHub

Unlike the loop, CallTool does not turn failures into results or apply run policy:

  • An unknown name returns an error wrapping ErrNoSuchTool; arguments that do not decode, one wrapping ErrInvalidToolInput; a RequireApproval tool, one wrapping ErrApprovalRequired.
  • Handler errors, middleware errors and panics come back to the caller as they are.
  • Timeout and MaxResultBytes are not applied. Those are the run policies the package example ExampleToolOptions bundles with weft.ToolOptions; only the loop enforces them.

Called from inside a tool handler, the dispatched call is a call of its own. Its handler’s CallFromContext reports its own id and name, in the dispatching call’s run and step. An approval the outer call ran under does not carry over: a RequireApproval tool still returns ErrApprovalRequired.

concepts/tools.go runs the three tools in one step, prints the derived schema, and dispatches calls by hand:

concepts/tools.go
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
// OrderQuery is the input of the order tools below.
type OrderQuery struct {
OrderID string `json:"order_id" jsonschema:"the order to look up"`
}
// Order is lookup_order's result; a non-string result reaches the model
// as JSON.
type Order struct {
ID string `json:"id"`
Status string `json:"status"`
}
// RefundRequest shows how Go types map onto the derived schema.
type RefundRequest struct {
OrderID string `json:"order_id" jsonschema:"the order to refund"`
Lines []int `json:"lines,omitempty" jsonschema:"line numbers to refund; all when empty"`
Reason *string `json:"reason" jsonschema:"why the customer wants a refund"`
Credits map[string]int `json:"credits,omitempty"`
}
// orderTools defines two tools with one input type and two result types.
func orderTools() (status, lookup *weft.ToolDef) {
status = weft.Tool("order_status", "Report an order's status in words.",
func(ctx context.Context, in OrderQuery) (string, error) {
return "order " + in.OrderID + " has shipped", nil // a string is sent verbatim
})
lookup = weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in OrderQuery) (Order, error) {
return Order{ID: in.OrderID, Status: "shipped"}, nil // anything else is sent as JSON
})
return status, lookup
}
// printSchema prints the input schema weft derives for RefundRequest.
func printSchema(w io.Writer) error {
refund := weft.Tool("refund_order", "Refund an order.",
func(ctx context.Context, in RefundRequest) (string, error) { return "refunded", nil })
b, err := json.MarshalIndent(refund.InputSchema, "", " ")
if err != nil {
return err
}
fmt.Fprintln(w, string(b))
return nil
}
// whoCalls is a tool that reports the call it is serving.
func whoCalls() *weft.ToolDef {
return weft.Tool("who_calls", "Report which call this is.",
func(ctx context.Context, in OrderQuery) (string, error) {
call, ok := weft.CallFromContext(ctx)
if !ok {
return "", errors.New("who_calls: not called by the agent loop")
}
return fmt.Sprintf("run=%s step=%d call=%s tool=%s",
call.RunID, call.Step, call.CallID, call.Name), nil
})
}
// callByHand dispatches tool calls without a run.
func callByHand(ctx context.Context, w io.Writer, agt *weft.Agent, lookup *weft.ToolDef) error {
out, err := agt.CallTool(ctx, weft.ToolCallPart{
ID: "manual-1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`),
})
fmt.Fprintln(w, "CallTool:", out, err)
_, err = agt.CallTool(ctx, weft.ToolCallPart{ID: "manual-2", Name: "refund_order"})
fmt.Fprintln(w, "unknown tool is ErrNoSuchTool:", errors.Is(err, weft.ErrNoSuchTool))
out, err = lookup.Invoke(ctx, json.RawMessage(`{"order_id":"5678"}`))
fmt.Fprintln(w, "Invoke:", out, err)
return nil
}
// demoTools runs the three tools in one step, prints the schema, and
// dispatches calls by hand.
func demoTools(ctx context.Context, w io.Writer) error {
status, lookup := orderTools()
model := wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "order_status", Args: `{"order_id":"1234"}`},
wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`},
wefttest.Call{Name: "who_calls", Args: `{"order_id":"1234"}`},
),
wefttest.Say("Order 1234 has shipped."),
)
agt := weft.New(model, status, lookup, whoCalls())
res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
for _, r := range res.Steps[0].Results {
fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content)
}
fmt.Fprintln(w, "order_status has an output schema:", status.OutputSchema != nil)
fmt.Fprintln(w, "lookup_order has an output schema:", lookup.OutputSchema != nil)
if err := printSchema(w); err != nil {
return err
}
return callByHand(ctx, w, agt, lookup)
}

View concepts/tools.go on GitHub

Run it from docs-site/examples:

Terminal window
go run ./concepts tools
go test ./concepts
order_status → order 1234 has shipped
lookup_order → {"id":"1234","status":"shipped"}
who_calls → run=run-1 step=0 call=call_3 tool=who_calls
order_status has an output schema: false
lookup_order has an output schema: true
{ … the schema above … }
CallTool: {"id":"1234","status":"shipped"} <nil>
unknown tool is ErrNoSuchTool: true
Invoke: {"id":"5678","status":"shipped"} <nil>
  • Return a string when the result is prose. A string reaches the model without JSON quotes; a struct is marshalled. (Source: weft/docs/adr/0003-tool-contract.md, weft/core/tool.go:174-181)
  • Write a jsonschema description on every field the model fills. It is the only per-field guidance the model gets. (Source: weft/core/schema.go:366-368)
  • Make optional fields pointers or omitempty. Every other field is required in the schema the model sees. (Source: weft/core/schema.go:188-190)
  • Do not rely on required to reject a call. It is advertised to the model, not checked: an omitted field reaches the handler as its zero value. Use a pointer field and return weft.ModelRetry when it is nil. (Source: weft/core/tool.go:192-221; weft/core/errors.go:203-214)
  • Honour ctx in handlers. A timed-out handler’s goroutine is abandoned, not stopped; only ctx tells it to give up. (Source: AGENTS.md rule 9, weft/core/tool.go:499-508)
  • Do not expect CallTool to be recorded. It never produces a span; outside a run nothing records it. (Source: weft/core/loop.go:1686-1705, CHANGELOG 0.8.0)

Symbols used: weft.Tool · weft.ToolDef · ToolDef.Invoke · weft.Schema · Schema.MarshalJSON · weft.ParseSchema · weft.RawTool · weft.Call · weft.CallFromContext · Agent.CallTool · weft.ToolCallPart · weft.ToolOptions · weft.ErrNoSuchTool · weft.ErrInvalidToolInput · weft.ErrApprovalRequired · weft.New · weft.RunID · wefttest.Script