Set per-tool policy: timeouts, caps, ordering and strict input
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:
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 toolThe agent’s Timeout(10*time.Millisecond) covers every tool without its own. inventory gets 20 ms; report gets none.
How it works
Section titled “How it works”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.
| Option | Kind | On New | On a tool |
|---|---|---|---|
Timeout(d) | PolicyOption | default deadline; none by default | this tool’s deadline; Timeout(0) lifts the default |
MaxResultBytes(n) | PolicyOption | default cap, 64 KiB | this tool’s cap; MaxResultBytes(0) removes it |
StrictInput() | PolicyOption | every tool | this tool |
Sequential() | PolicyOption | every call one at a time | a barrier: this call runs alone |
WrapTools(mw...) | PolicyOption | wraps every call | wraps 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 |
Combine per-tool options
Section titled “Combine per-tool options”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:
// 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"),)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.
Set a timeout
Section titled “Set a timeout”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 20msThe 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.
Cap a tool’s result
Section titled “Cap a tool’s result”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):
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 toolslogs (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.
Run a tool alone
Section titled “Run a tool alone”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:
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))order: call_1 starts, call_1 ends, write_ledger runs, call_3 starts, call_3 endsResults 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.
Reject undeclared arguments
Section titled “Reject undeclared arguments”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:
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)refund (error: true): INVALID_INPUT: tool "refund": unknown field "amount": not in the schemaretry: refunded 1234The 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.
Attach prompt lines to a tool
Section titled “Attach prompt lines to a tool”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:
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)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.
Name a tool’s origin
Section titled “Name a tool’s origin”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.
Mark a tool safe to re-run
Section titled “Mark a tool safe to re-run”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.
Wrap one tool with middleware
Section titled “Wrap one tool with middleware”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 shippedPanic 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.
Complete example
Section titled “Complete example”toolpolicy/main.go runs each region against a scripted model:
// 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 on GitHub · run it from docs-site/examples:
go run ./toolpolicygo test ./toolpolicy== timeoutsinventory (error: true): tool "inventory" timed out after 20msreport (error: false): report ready== result caplogs (error: false): xxxxxxxxxxxxxxxx…[truncated 24 bytes]invoice (error: false): yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy== sequentialcheck_ledger (error: false): verifiedwrite_ledger (error: false): writtencheck_ledger (error: false): verifiedorder: call_1 starts, call_1 ends, write_ledger runs, call_3 starts, call_3 ends== strict inputrefund (error: true): INVALID_INPUT: tool "refund": unknown field "amount": not in the schemaretry: refunded 1234== prompt snippetsystem sent: "You are a support agent.\n\nCite the article you used."snippet: "Cite the article you used."== composed policylookup (error: false): [cache] order 1234 has shippedBest practices & gotchas
Section titled “Best practices & gotchas”- 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
Sequentialwhen it writes shared state. Other tools keep running in parallel; only the barrier is serialized. (Source:weft/core/agent.go:233-243,ExampleSequential) - Use
StrictInputwhere 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 appliesStrictInputand the middleware, not run policy. (Source:weft/core/loop.go:1687-1697)
See also
Section titled “See also”- How do tools work?
- Add behaviour with middleware
- Define tools at runtime: RawTool and ToolSource
- Require human approval for a tool
- Describe your agents in weft.json
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