Skip to content

Set per-tool policy: timeouts, caps, ordering and strict input

View as Markdown

Trailing options on weft.Tool set policy for that tool alone. weft.Timeout, weft.MaxResultBytes, weft.StrictInput, weft.Sequential and weft.WrapTools also work on weft.New, where they set the default for every tool; on a tool they override that default. Use them when one tool is slower, larger, riskier or more order-sensitive than the rest.

A tool with its own deadline, and one that lifts the agent’s, in toolpolicy/main.go:

toolpolicy/main.go
slow := weft.Tool("inventory", "Check stock levels.",
func(ctx context.Context, in orderInput) (string, error) {
select {
case <-time.After(time.Second): // a hung backend
return "in stock", nil
case <-ctx.Done(): // honour ctx: the deadline cancels it
return "", ctx.Err()
}
},
weft.Timeout(20*time.Millisecond), // this tool's own deadline
)
report := weft.Tool("report", "Build the monthly report.",
func(ctx context.Context, in orderInput) (string, error) {
time.Sleep(30 * time.Millisecond) // longer than the agent default
return "report ready", nil
},
weft.Timeout(0), // lifts the agent's default for this tool alone
)
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "inventory", Args: `{"order_id":"1234"}`},
wefttest.Call{Name: "report", Args: `{"order_id":"1234"}`},
),
wefttest.Say("Inventory timed out; the report is ready."),
), slow, report, weft.Timeout(10*time.Millisecond)) // the default for every other tool

toolpolicy/main.go on GitHub

The agent’s Timeout(10*time.Millisecond) covers every tool without its own. inventory gets 20 ms; report gets none.

The loop resolves each call’s policy when it dispatches it: the tool’s own value when set, else the agent’s. Every policy failure becomes a tool result the model reads, never a run error: a timed-out call is IsError: true and its siblings keep running (rule 1). The result cap is applied last, over every outcome.

OptionKindOn NewOn a tool
Timeout(d)PolicyOptiondefault deadline; none by defaultthis tool’s deadline; Timeout(0) lifts the default
MaxResultBytes(n)PolicyOptiondefault cap, 64 KiBthis tool’s cap; MaxResultBytes(0) removes it
StrictInput()PolicyOptionevery toolthis tool
Sequential()PolicyOptionevery call one at a timea barrier: this call runs alone
WrapTools(mw...)PolicyOptionwraps every callwraps this tool, inside the agent’s chain
PromptSnippet(text)ToolOption—system-prompt lines for this tool
RequireApproval()ToolOption—parks the call (approvals)
Replay(p)ToolOption—the side-effect class for re-runs (replay)
Origin(name)ToolOption—the tools record’s source

A weft.ToolOption configures one tool at definition time. A weft.PolicyOption is both an Option and a ToolOption: accepted by New and by Tool, the agent default on one and the override on the other. weft.ToolOptions composes several into one value, applied in order, so a package of policy travels under one name:

toolpolicy/main.go
// A package of per-tool policy under one name.
backend := weft.ToolOptions(
weft.Timeout(5*time.Second),
weft.MaxResultBytes(4096),
weft.StrictInput(),
)
// Middleware on one tool runs inside the agent's chain.
tag := func(next weft.ToolCaller) weft.ToolCaller {
return func(ctx context.Context, call weft.ToolCallPart) (string, error) {
out, err := next(ctx, call)
return "[cache] " + out, err
}
}
lookup := weft.Tool("lookup", "Look up an order.",
func(_ context.Context, in orderInput) (string, error) {
return "order " + in.OrderID + " has shipped", nil
},
backend, weft.WrapTools(tag), weft.Origin("orders-plugin"),
)

toolpolicy/main.go on GitHub

The manifest records both levels: a tool that overrides a default carries its own timeout, max_result_bytes, strict_input, sequential, require_approval, replay_policy and prompt_snippet keys, and a tool without options renders without them (Describe your agents in weft.json). The package example is ExampleToolOptions.

Timeout(d) on a tool is that tool’s deadline. The handler’s ctx carries it; when it expires the loop records an error result the model sees and moves on:

tool "inventory" timed out after 20ms

The loop abandons the handler’s goroutine at the deadline, so a handler must honour ctx to release what it holds (rule 9). On New, Timeout(d) is the default for every tool without its own, and non-positive values are ignored there. On a tool, Timeout(0) removes the agent’s default for that tool alone; the manifest records it as "timeout": "0s". Without any Timeout, only the run’s ctx bounds a call.

MaxResultBytes(n) caps one tool result’s text at n bytes. The agent default is 64 KiB. The loop cuts on a rune boundary and appends a marker naming the bytes the model did not receive, so it knows the output is partial (rule 8):

toolpolicy/main.go
logs := weft.Tool("logs", "Read the service logs.",
func(context.Context, orderInput) (string, error) {
return strings.Repeat("x", 40), nil
},
weft.MaxResultBytes(16), // cap this tool at 16 bytes
)
invoice := weft.Tool("invoice", "Render the invoice.",
func(context.Context, orderInput) (string, error) {
return strings.Repeat("y", 40), nil
},
weft.MaxResultBytes(0), // this tool's output always arrives whole
)
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "logs", Args: `{"order_id":"1234"}`},
wefttest.Call{Name: "invoice", Args: `{"order_id":"1234"}`},
),
wefttest.Say("done"),
), logs, invoice, weft.MaxResultBytes(8)) // the agent default for other tools

toolpolicy/main.go on GitHub

logs (error: false): xxxxxxxxxxxxxxxx
…[truncated 24 bytes]

The cap applies to successes, failures and panics alike. MaxResultBytes(0) removes the cap: on New for every tool, on a tool for that tool alone, as invoice shows. Negative values are ignored. agt.CallTool returns uncapped output and applies no timeout: both are run policy, applied by the loop.

Under any parallelism, a step’s tools start in call order. Sequential() on a tool is a barrier: the dispatcher lets every in-flight call of the step finish, runs this call alone, then resumes the step’s parallelism for the calls after it:

toolpolicy/main.go
write := weft.Tool("write_ledger", "Append to the ledger.",
func(ctx context.Context, _ orderInput) (string, error) {
log("write_ledger runs")
return "written", nil
},
weft.Sequential(), // a barrier: in-flight calls finish, this one runs alone
)
check := weft.Tool("check_ledger", "Verify the ledger.",
func(ctx context.Context, _ orderInput) (string, error) {
call, _ := weft.CallFromContext(ctx)
log(call.CallID + " starts")
time.Sleep(10 * time.Millisecond)
log(call.CallID + " ends")
return "verified", nil
})
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`},
wefttest.Call{Name: "write_ledger", Args: `{"order_id":"1"}`},
wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`},
),
wefttest.Say("done"),
), write, check, weft.Parallelism(4))

toolpolicy/main.go on GitHub

order: call_1 starts, call_1 ends, write_ledger runs, call_3 starts, call_3 ends

Results stay in call order either way. When the run’s parallelism is 1 (Sequential() or Parallelism(1), on New or per run), the loop sets ModelRequest.SequentialTools, so adapters that can ask the provider not to emit parallel batches do. A barrier on one tool does not set it. The package example is ExampleSequential.

By default an argument field the input struct does not declare is ignored, the encoding/json default: models add stray keys, and a rejection costs a round trip. StrictInput() rejects them as an ErrInvalidToolInput result naming the field:

toolpolicy/main.go
refund := weft.Tool("refund", "Refund an order.",
func(_ context.Context, in orderInput) (string, error) {
return "refunded " + in.OrderID, nil
},
weft.StrictInput(), // an undeclared field is an error result naming it
)
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234","amount":50}`}),
wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`}),
wefttest.Say("Refunded."),
), refund)

toolpolicy/main.go on GitHub

refund (error: true): INVALID_INPUT: tool "refund": unknown field "amount": not in the schema
retry: refunded 1234

The model reads the error and calls again without the field. Use it where an ignored field would be a silent misreading of the call: here, an amount the handler would drop. On New it applies to every tool, and a tool cannot opt out of an agent-level StrictInput. A weft.RawTool is unaffected: it receives the raw arguments.

StrictInput checks only for extra fields, never for missing ones. A required field the model leaves out still decodes to its zero value, with or without it: How do tools work? shows the pointer-and-ModelRetry check.

weft.PromptSnippet keeps a tool’s usage rules next to the tool. The loop appends the snippets of the tools it advertises to the agent’s instructions for every model call, one paragraph per tool in the order the step advertises them (registration order unless a PrepareStep function reorders them), separated by blank lines:

toolpolicy/main.go
search := weft.Tool("search", "Search the help centre.",
func(context.Context, orderInput) (string, error) { return "", nil },
weft.PromptSnippet("Cite the article you used."),
)
agt := weft.New(model, weft.Instructions("You are a support agent."), search)

toolpolicy/main.go on GitHub

system sent: "You are a support agent.\n\nCite the article you used."

Only advertised tools contribute, so a tool a PrepareStep function or OnlyTools removes takes its snippet with it. Empty snippets add nothing. ToolDef.PromptSnippet reports a tool’s text, empty when unset, and the manifest records it. The package example is ExamplePromptSnippet.

weft.Origin names where a tool came from, for the observability record only: it is the source of the tool on the run’s tools record and, since 0.20.0, for a tool that is not local, the weft.tool.origin attribute of each call’s execute_tool span. It changes nothing the model sees or the loop does. A tool is local by default; weft.Subagent sets subagent, and mcp.Tools sets mcp:<server> under mcp.Server(name), else mcp (MCP identity). weft.OriginDetail records the origin in parts beside it. Any other string is recorded verbatim, and the last Origin wins. The example under Combine per-tool options tags lookup as orders-plugin; the core example ExampleOrigin reads the record back.

weft.Replay sets a tool’s side-effect class, a weft.ReplayPolicy, for re-runs of a recorded conversation (a playground experiment, a replay fixture). weft.ReplayNever is the zero value and the default: an unannotated tool counts as never, so a re-run substitutes its call with the recorded result or parks it, and never fires it again silently. weft.ReplaySafe vouches that the call is idempotent and side-effect free, a read, so a re-run may execute it. Any other value counts as never. Like every tool option the last one wins, so Replay(ReplayNever) after a shared Replay(ReplaySafe) takes the vouching back. ToolDef.ReplayPolicy reports the class, and the manifest writes replay_policy only for safe. How a re-run uses it is in Replay a run from any step, with edits.

WrapTools on a tool wraps that tool alone, inside the agent’s chain: agent middleware, then tool middleware, then decode, then the handler. The first middleware listed is the outermost. In that example, tag prefixes lookup’s result:

lookup (error: false): [cache] order 1234 has shipped

Panic containment and timeouts sit outside the chain, so a panic in tool middleware is still an error result. Add behaviour with middleware covers both seams.

toolpolicy/main.go runs each region against a scripted model:

toolpolicy/main.go
// Command toolpolicy runs the examples of the guide "Set per-tool policy:
// timeouts, caps, ordering and strict input": go run ./toolpolicy. Every
// model is scripted with wefttest, so it runs offline.
package main
import (
"context"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
type orderInput struct {
OrderID string `json:"order_id" jsonschema:"the order to look up"`
}
// results prints every tool result of a run's first step.
func results(w io.Writer, res *weft.RunResult) {
for _, r := range res.Steps[0].Results {
fmt.Fprintf(w, "%s (error: %t): %s\n", r.Name, r.IsError, r.Content)
}
}
// timeouts: an agent default, a tool's own deadline, and a lifted one.
func timeouts(ctx context.Context, w io.Writer) error {
slow := weft.Tool("inventory", "Check stock levels.",
func(ctx context.Context, in orderInput) (string, error) {
select {
case <-time.After(time.Second): // a hung backend
return "in stock", nil
case <-ctx.Done(): // honour ctx: the deadline cancels it
return "", ctx.Err()
}
},
weft.Timeout(20*time.Millisecond), // this tool's own deadline
)
report := weft.Tool("report", "Build the monthly report.",
func(ctx context.Context, in orderInput) (string, error) {
time.Sleep(30 * time.Millisecond) // longer than the agent default
return "report ready", nil
},
weft.Timeout(0), // lifts the agent's default for this tool alone
)
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "inventory", Args: `{"order_id":"1234"}`},
wefttest.Call{Name: "report", Args: `{"order_id":"1234"}`},
),
wefttest.Say("Inventory timed out; the report is ready."),
), slow, report, weft.Timeout(10*time.Millisecond)) // the default for every other tool
res, err := agt.Generate(ctx, weft.Prompt("Check order 1234."))
if err != nil {
return err
}
results(w, res)
return nil
}
// resultCap: one tool capped small, one uncapped.
func resultCap(ctx context.Context, w io.Writer) error {
logs := weft.Tool("logs", "Read the service logs.",
func(context.Context, orderInput) (string, error) {
return strings.Repeat("x", 40), nil
},
weft.MaxResultBytes(16), // cap this tool at 16 bytes
)
invoice := weft.Tool("invoice", "Render the invoice.",
func(context.Context, orderInput) (string, error) {
return strings.Repeat("y", 40), nil
},
weft.MaxResultBytes(0), // this tool's output always arrives whole
)
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "logs", Args: `{"order_id":"1234"}`},
wefttest.Call{Name: "invoice", Args: `{"order_id":"1234"}`},
),
wefttest.Say("done"),
), logs, invoice, weft.MaxResultBytes(8)) // the agent default for other tools
res, err := agt.Generate(ctx, weft.Prompt("Show order 1234."))
if err != nil {
return err
}
results(w, res)
return nil
}
// sequential: a barrier tool runs alone; results stay in call order.
func sequential(ctx context.Context, w io.Writer) error {
var mu sync.Mutex
var order []string
log := func(s string) {
mu.Lock()
defer mu.Unlock()
order = append(order, s)
}
write := weft.Tool("write_ledger", "Append to the ledger.",
func(ctx context.Context, _ orderInput) (string, error) {
log("write_ledger runs")
return "written", nil
},
weft.Sequential(), // a barrier: in-flight calls finish, this one runs alone
)
check := weft.Tool("check_ledger", "Verify the ledger.",
func(ctx context.Context, _ orderInput) (string, error) {
call, _ := weft.CallFromContext(ctx)
log(call.CallID + " starts")
time.Sleep(10 * time.Millisecond)
log(call.CallID + " ends")
return "verified", nil
})
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(
wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`},
wefttest.Call{Name: "write_ledger", Args: `{"order_id":"1"}`},
wefttest.Call{Name: "check_ledger", Args: `{"order_id":"1"}`},
),
wefttest.Say("done"),
), write, check, weft.Parallelism(4))
res, err := agt.Generate(ctx, weft.Prompt("Record the payment."))
if err != nil {
return err
}
results(w, res)
fmt.Fprintln(w, "order:", strings.Join(order, ", "))
return nil
}
// strict: an undeclared argument field is rejected for one tool.
func strict(ctx context.Context, w io.Writer) error {
refund := weft.Tool("refund", "Refund an order.",
func(_ context.Context, in orderInput) (string, error) {
return "refunded " + in.OrderID, nil
},
weft.StrictInput(), // an undeclared field is an error result naming it
)
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234","amount":50}`}),
wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`}),
wefttest.Say("Refunded."),
), refund)
res, err := agt.Generate(ctx, weft.Prompt("Refund 50 on order 1234."))
if err != nil {
return err
}
results(w, res)
fmt.Fprintln(w, "retry:", res.Steps[1].Results[0].Content)
return nil
}
// snippet: usage rules composed into the system prompt.
func snippet(ctx context.Context, w io.Writer) error {
model := wefttest.Script(wefttest.Say("ok"))
search := weft.Tool("search", "Search the help centre.",
func(context.Context, orderInput) (string, error) { return "", nil },
weft.PromptSnippet("Cite the article you used."),
)
agt := weft.New(model, weft.Instructions("You are a support agent."), search)
if _, err := agt.Generate(ctx, weft.Prompt("How do refunds work?")); err != nil {
return err
}
fmt.Fprintf(w, "system sent: %q\n", model.LastRequest().System)
fmt.Fprintf(w, "snippet: %q\n", agt.Tools()[0].PromptSnippet())
return nil
}
// composed: a named policy and a tool's own middleware.
func composed(ctx context.Context, w io.Writer) error {
// A package of per-tool policy under one name.
backend := weft.ToolOptions(
weft.Timeout(5*time.Second),
weft.MaxResultBytes(4096),
weft.StrictInput(),
)
// Middleware on one tool runs inside the agent's chain.
tag := func(next weft.ToolCaller) weft.ToolCaller {
return func(ctx context.Context, call weft.ToolCallPart) (string, error) {
out, err := next(ctx, call)
return "[cache] " + out, err
}
}
lookup := weft.Tool("lookup", "Look up an order.",
func(_ context.Context, in orderInput) (string, error) {
return "order " + in.OrderID + " has shipped", nil
},
backend, weft.WrapTools(tag), weft.Origin("orders-plugin"),
)
agt := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{Name: "lookup", Args: `{"order_id":"1234"}`}),
wefttest.Say("Shipped."),
), lookup)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
return err
}
results(w, res)
return nil
}
func run(ctx context.Context, w io.Writer) error {
steps := []struct {
title string
fn func(context.Context, io.Writer) error
}{
{"timeouts", timeouts},
{"result cap", resultCap},
{"sequential", sequential},
{"strict input", strict},
{"prompt snippet", snippet},
{"composed policy", composed},
}
for _, s := range steps {
fmt.Fprintf(w, "== %s\n", s.title)
if err := s.fn(ctx, w); err != nil {
return fmt.Errorf("%s: %w", s.title, err)
}
}
return nil
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View toolpolicy/main.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./toolpolicy
go test ./toolpolicy
== timeouts
inventory (error: true): tool "inventory" timed out after 20ms
report (error: false): report ready
== result cap
logs (error: false): xxxxxxxxxxxxxxxx
…[truncated 24 bytes]
invoice (error: false): yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
== sequential
check_ledger (error: false): verified
write_ledger (error: false): written
check_ledger (error: false): verified
order: call_1 starts, call_1 ends, write_ledger runs, call_3 starts, call_3 ends
== strict input
refund (error: true): INVALID_INPUT: tool "refund": unknown field "amount": not in the schema
retry: refunded 1234
== prompt snippet
system sent: "You are a support agent.\n\nCite the article you used."
snippet: "Cite the article you used."
== composed policy
lookup (error: false): [cache] order 1234 has shipped
  • Honour ctx in every handler. A timeout abandons the handler’s goroutine; a handler that ignores ctx keeps running and holding resources. (Source: AGENTS.md rule 9, weft/core/tool.go:499-507)
  • Lift the cap only for output that must arrive whole. The 64 KiB default keeps a runaway tool from filling the context window. (Source: weft/core/agent.go:26-28, AGENTS.md rule 8)
  • Mark a tool Sequential when it writes shared state. Other tools keep running in parallel; only the barrier is serialized. (Source: weft/core/agent.go:233-243, ExampleSequential)
  • Use StrictInput where a dropped field changes meaning. The default is lenient on purpose. (Source: weft/core/tool.go:524-532)
  • Expect no cap or timeout from CallTool. Manual dispatch applies StrictInput and the middleware, not run policy. (Source: weft/core/loop.go:1687-1697)

Symbols used: weft.Tool · weft.ToolOption · weft.PolicyOption · weft.ToolOptions · weft.Timeout · weft.MaxResultBytes · weft.StrictInput · weft.Sequential · weft.WrapTools · weft.ToolCaller · weft.PromptSnippet · ToolDef.PromptSnippet · weft.Origin · weft.RequireApproval · weft.Replay · weft.ReplayPolicy · weft.ReplaySafe · weft.ReplayNever · ToolDef.ReplayPolicy · weft.RawTool · weft.ErrInvalidToolInput · weft.CallFromContext · Agent.CallTool · weft.Parallelism · wefttest.Script · ExampleToolOptions · ExampleSequential · ExamplePromptSnippet · ExampleOrigin