---
title: 'Set per-tool policy: timeouts, caps, ordering and strict input'
description: Give one tool its own deadline, result cap, sequential barrier, strict argument check, prompt snippet or middleware with trailing options on weft.Tool.
url: https://weftgo.dev/docs/guides/tool-policy/
type: how-to
sources:
  - 'weft/core/tool.go:73-108 (ToolOption, ToolOptions, PolicyOption), 499-537 (Timeout, StrictInput), 551-580 (WrapTools on a tool), 582-595 (PromptSnippet), 635-642 (Origin: the tools record''s source and weft.tool.origin; local, subagent, mcp:<server> or mcp), 710-714 (OriginDetail)'
  - 'weft/core/tool.go:192-221 (decodeInput: StrictInput is DisallowUnknownFields; required is not checked); scratch proof (docs a10 fix): a StrictInput tool called with {} ran with zero values, and {"x":1} was refused as unknown field "x"'
  - weft/core/agent.go:228-244 (Sequential), 526-535 (MaxResultBytes)
  - 'weft/core/loop.go:493 (SequentialTools: parallelism == 1), 1280 (the barrier), 1662-1675 (composeSystem), 1802-1865 (callTool: per-tool policy over the agent''s; strict at 1627), 1978-1981 (the timeout text), 2205-2222 (capResultN: the marker)'
  - weft/core/loop.go:1687-1706 (Agent.CallTool applies no cap or timeout)
  - weft/core/tool.go:719-766 (ReplayPolicy, ReplayNever, ReplaySafe, Replay, ToolDef.ReplayPolicy)
  - weft/core/manifest.go:210-215 (replay_policy only for safe), 110-135 (the manifest's per-tool policy keys), 221-230 (timeout "0s")
  - weft/AGENTS.md:32-45 (block 1), 77-78 (block 2), rules 8 and 9
  - weft/README.md:130-140 (Per-tool policy)
  - weft/CHANGELOG.md:2969, 6634, 6659, 6687
  - weft/example_test.go:510 (ExamplePromptSnippet), 527 (ExampleSequential), 749 (ExampleToolOptions)
  - weft/core/request_test.go:1283 (ExampleOrigin)
  - docs-site/examples/toolpolicy/main.go, main_test.go TestToolPolicy, TestCapIsOnEveryOutcome, TestStrictOnAgent, TestTimeoutDoesNotFailRun
---

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

Trailing options on [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) set policy for that tool alone. [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout), [`weft.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes), [`weft.StrictInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StrictInput), [`weft.Sequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) and [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go)

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

## 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](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). 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](https://weftgo.dev/docs/guides/approvals/)) |
| `Replay(p)` | `ToolOption` | — | the side-effect class for re-runs ([replay](https://weftgo.dev/docs/observe/playground/replay/)) |
| `Origin(name)` | `ToolOption` | — | the tools record's source |

## Combine per-tool options

A [`weft.ToolOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOption) configures one tool at definition time. A [`weft.PolicyOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) composes several into one value, applied in order, so a package of policy travels under one name:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go)

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](https://weftgo.dev/docs/guides/manifest/)). The package example is [`ExampleToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolOptions).

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

```text
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](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). 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

`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](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)):

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) returns uncapped output and applies no timeout: both are run policy, applied by the loop.

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

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Sequential).

## 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) result naming the field:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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?](https://weftgo.dev/docs/concepts/tools/#edge-cases-in-schemas-and-arguments) shows the pointer-and-`ModelRetry` check.

## Attach prompt lines to a tool

[`weft.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go)

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

Only advertised tools contribute, so a tool a [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) function or `OnlyTools` removes takes its snippet with it. Empty snippets add nothing. [`ToolDef.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.PromptSnippet) reports a tool's text, empty when unset, and the manifest records it. The package example is [`ExamplePromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PromptSnippet).

## Name a tool's origin

[`weft.Origin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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](https://weftgo.dev/docs/guides/mcp/#mcp-identity)). [`weft.OriginDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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](#combine-per-tool-options) tags `lookup` as `orders-plugin`; the core example [`ExampleOrigin`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Origin) reads the record back.

## Mark a tool safe to re-run

[`weft.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Replay) sets a tool's side-effect class, a [`weft.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayPolicy), for re-runs of a recorded conversation (a playground experiment, a replay fixture). [`weft.ReplayNever`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#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](https://weftgo.dev/docs/observe/playground/replay/).

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

```text
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](https://weftgo.dev/docs/guides/middleware/) covers both seams.

## Complete example

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

```go title="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)
	}
}
```

[toolpolicy/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/toolpolicy/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/toolpolicy) · run it from `docs-site/examples`:

```sh
go run ./toolpolicy
go test ./toolpolicy
```

```text
== 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
```

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

## See also

- [How do tools work?](https://weftgo.dev/docs/concepts/tools/)
- [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/)
- [Define tools at runtime: RawTool and ToolSource](https://weftgo.dev/docs/guides/dynamic-tools/)
- [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)
- [Describe your agents in weft.json](https://weftgo.dev/docs/guides/manifest/)

Symbols used: [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.ToolOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOption) · [`weft.PolicyOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PolicyOption) · [`weft.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolOptions) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes) · [`weft.StrictInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StrictInput) · [`weft.Sequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) · [`weft.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PromptSnippet) · [`ToolDef.PromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.PromptSnippet) · [`weft.Origin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Origin) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Replay) · [`weft.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayPolicy) · [`weft.ReplaySafe`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplaySafe) · [`weft.ReplayNever`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReplayNever) · [`ToolDef.ReplayPolicy`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#ToolDef.ReplayPolicy) · [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.ErrInvalidToolInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidToolInput) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ToolOptions) · [`ExampleSequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Sequential) · [`ExamplePromptSnippet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-PromptSnippet) · [`ExampleOrigin`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Origin)
