---
title: Add behaviour with middleware (the two seams)
description: Wrap the model with weft.WrapModel and every tool call with weft.WrapTools; the first middleware listed is the outermost, and package mw holds the reference set.
url: https://weftgo.dev/docs/guides/middleware/
type: how-to
sources:
  - 'W11-auditA2-fix, v0.20.2: weft/core/layers.go:154-170 (toolNames keyed by the closure''s code pointer; the last name wins), 172-190 (funcInfo reads it when the manifest is built)'
  - 'weft/core/layers.go:331-390 (Masked: the kind order), 1-130 (the three levels; MiddlewareInfo: Name, Params, Source in the import-path form, Opaque; the Describe convention; the Unwrap walk), 260-290 (ToolReporter.Denied, Masked), 365-420 (RepairInfo, Reporter.Repair)'
  - weft/core/mw/retry.go:140, weft/core/mw/model.go:73, 318, weft/core/mw/repairjson.go:36 (Describe on Retry, Fallback, Log, RepairJSON)
  - 'weft/otel/options.go:169-198 (DevDetail: the layer spans, the repair original 4 KiB, weft.panic 16 KiB, off by default, the dev gate and its WARN, Local and Studio with content on, LoggerProvider and the second chain)'
  - 'weft/core/layers.go:150-240 (v0.20.2: NameToolMiddleware, funcInfo, closureSource, isClosure; a named function by its name and import-path source; a closure as func@<dir>/<file>:<line>, that place its source; independent of inlining); weft/core/mw/tool.go:25-28 (mw.Allow named through it)'
  - docs-site/examples/middleware/onion.go (mw-names, mw-report; TestOnionNames, run against ../weft-rc020b through a scratch go.work)
  - 'weft/CHANGELOG.md:35 (0.20.0: the middleware onion recorded), 71 (0.20.0 breaking: the manifest hash), 74 (weft.attempt.layer retry)'
  - weft/AGENTS.md:94-101 (block 2), rule 10
  - weft/README.md:149-180 (The two seams)
  - weft/docs/adr/0006-seams.md:19-58 (Decision), 85-88 (reference middleware)
  - weft/core/agent.go:246-253 (ModelMiddleware), 265-271 (WrapModel), 273-283 (InfoOf), 285-304 (Unwrap)
  - weft/core/tool.go:539-549 (ToolCaller, ToolMiddleware), 569-580 (WrapTools)
  - weft/core/mw/doc.go:1-38
  - weft/core/mw/tool.go:25-43 (Allow), 53 (Audit), 104-158 (MapErrors, passThrough)
  - weft/core/mw/model.go:304-331 (Log)
  - weft/mw/facade.go:49 (Log), 166 (Allow), 176 (Audit), 186 (MapErrors)
  - weft/core/wefttest/conform.go:15-31 (ConformInfo, ConformInfoT)
  - weft/example_test.go:300 (ExampleWrapModel), 327 (ExampleWrapTools), 357 (ExampleWrapTools_context)
  - weft/mw/example_test.go:59 (ExampleAllow), 77 (ExampleMapErrors), 97 (ExampleLog), 149 (ExampleAudit), Example_rateLimitMiddleware
  - weft/CHANGELOG.md:6597, 6644, 6648
  - docs-site/examples/middleware/seams.go, middleware_test.go TestDemos, TestToolChainOrder, TestLogRequestsKeepsModelInfo
  - 'v0.20.2: weft/core/model.go:149-167 (ModelRequest: per-request copies of the slices, Content and Params'' values; part bytes shared); weft/core/mw/retry.go:109-111, weft/core/mw/model.go:31-33 (each attempt its own copy); docs-site/examples/middleware/params.go (mw-params), params_test.go TestCapTemperature'
  - 'v0.20.2: weft/core/layers.go:41-55 (MiddlewareInfo: Params carry configuration only, never a secret or a closure''s captured value), 277-299 (ToolReporter: the last report of a kind wins; outside a loop-dispatched call, Agent.CallTool included, a no-op), 312-316 (Denied reaches weft.tool.denied_by when the call ends in an error); weft/core/agent.go:649-652 (the manifest hash on every run); weft/studio/manifests.go:13, 40 (GET /api/manifests/{hash})'
---

# Add behaviour with middleware (the two seams)

Behaviour you add to a run attaches at two seams. [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) wraps the agent's model, so middleware sees every request the loop sends; [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) wraps every tool call the loop dispatches. In both, the first middleware listed is the outermost, and package [`mw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw) ships the reference set.

Both seams on one agent, in `middleware/seams.go`:

```go title="middleware/seams.go"
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
	func(_ context.Context, _ struct{}) (string, error) {
		fmt.Fprintln(w, "handler: lookup_order")
		return "shipped", nil
	},
	weft.WrapTools(trace(w, "tool")), // this tool only, inside the agent's chain
)
agt := weft.New(
	wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup_order"}),
		wefttest.Say("It has shipped."),
	),
	weft.WrapModel(logRequests(w)),
	weft.WrapTools(trace(w, "outer"), trace(w, "inner")), // first listed = outermost
	lookup,
)
_, err := agt.Generate(ctx, weft.Prompt("Where is my order?"))
```

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

`logRequests` prints a line per model request. The three `trace` middleware print before and after the rest of the chain, which shows the order a call takes:

```text
model request: 1 messages, 1 tools
outer: before lookup_order
inner: before lookup_order
tool: before lookup_order
handler: lookup_order
tool: after lookup_order
inner: after lookup_order
outer: after lookup_order
model request: 3 messages, 1 tools
```

## The two seams

Each seam is a function from the next link to a new one, the shape `net/http` routers such as chi use:

| Seam | Option | Middleware type | Wraps |
|---|---|---|---|
| Model | `weft.WrapModel(mw...)` | [`weft.ModelMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelMiddleware): `func(next weft.Model) weft.Model` | every model call the loop makes |
| Tool | `weft.WrapTools(mw...)` | [`weft.ToolMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolMiddleware): `func(next weft.ToolCaller) weft.ToolCaller` | every tool call the loop and [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) dispatch |

`WrapModel(a, b)` calls `a(b(model))`; `WrapTools(a, b)` runs `a(b(call))`. A later `WrapModel` or `WrapTools` option appends inward. Nil entries are ignored. The model chain is built once, at `weft.New`.

`WrapTools` works on a tool too: passed to `weft.Tool`, it wraps that tool alone, inside the agent's chain. A tool call goes through, in order: the agent's middleware, the tool's own middleware, then the base, which resolves the tool, checks `RequireApproval`, decodes the arguments and runs the handler.

Two seams is the whole set. Observation is a third thing, [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap), which sees every event and changes nothing. A third seam needs an ADR. To see where each phase of a step and a tool call sits around the seams, read [`docs/life-of-a-call.md`](https://github.com/weftgo/weft/blob/v0.20.2/docs/life-of-a-call.md).

## Model middleware

A `ModelMiddleware` returns a `weft.Model` that wraps `next`. It sees each [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) as the loop built it, after `PrepareStep`, and every event the inner model yields. It may log, retry, substitute or rewrite:

```go title="middleware/seams.go"
// logRequests is a ModelMiddleware: it prints a line for every request
// the loop sends, then streams the inner model's reply unchanged.
func logRequests(w io.Writer) weft.ModelMiddleware {
	return func(next weft.Model) weft.Model { return requestLogger{next: next, w: w} }
}

type requestLogger struct {
	next weft.Model
	w    io.Writer
}

func (m requestLogger) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	fmt.Fprintf(m.w, "model request: %d messages, %d tools\n", len(req.Messages), len(req.Tools))
	return m.next.Stream(ctx, req)
}

// Info and Unwrap forward the inner model's identity and declare it.
func (m requestLogger) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m requestLogger) Unwrap() weft.Model   { return m.next }
```

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

**A middleware may rewrite its own request.** Each request carries its own copies of the slices, of each message's `Content`, and of `Params`' values. `mw.Retry` and `mw.Fallback` hand each attempt a fresh copy. So a write such as `*req.Params.Temperature` holds for that attempt alone. Nothing leaks to the agent, the run option, the caller's variable, a later step or the next attempt:

```go title="middleware/params.go"
// capTemperature is a ModelMiddleware that writes the request's own
// temperature: since 0.18.1 each request, and each mw.Retry or
// mw.Fallback attempt, carries its own copy of Params' values, so the
// write reaches neither the agent, the run option, the caller's
// variable, a later step nor the next attempt.
func capTemperature(limit float64) weft.ModelMiddleware {
	return func(next weft.Model) weft.Model { return tempCap{next: next, limit: limit} }
}

type tempCap struct {
	next  weft.Model
	limit float64
}

func (m tempCap) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	if t := req.Params.Temperature; t != nil && *t > m.limit {
		*t = m.limit // this request's copy; the bytes inside parts stay read-only
	}
	return m.next.Stream(ctx, req)
}

func (m tempCap) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m tempCap) Unwrap() weft.Model   { return m.next }
```

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

`TestCapTemperature` runs it inside `mw.Retry` with a temperature of 0.9: both tries are sent 0.5, and the caller's variable still reads 0.9. The bytes inside parts (`Args`, `Data`) stay shared and read-only.

Forward the inner model's identity with [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf), so `RunStart.Model` and the manifest still name the provider. Declare the wrapped model with an `Unwrap` method, so a caller can walk the chain with [`weft.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap). A middleware that returns a nil `Model` panics at `New`. The package example [`ExampleWrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-WrapModel) is the same shape.

## Tool middleware

A [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) takes a call and returns the result text the model will see, or an error. A `ToolMiddleware` wraps one and may act before `next` (deny, decorate `ctx`, log), after it (map errors, audit), or instead of it:

```go title="middleware/seams.go"
// trace is a ToolMiddleware that prints before and after the rest of the
// chain runs.
func trace(w io.Writer, name string) weft.ToolMiddleware {
	return func(next weft.ToolCaller) weft.ToolCaller {
		return func(ctx context.Context, call weft.ToolCallPart) (string, error) {
			fmt.Fprintf(w, "%s: before %s\n", name, call.Name)
			out, err := next(ctx, call)
			fmt.Fprintf(w, "%s: after %s\n", name, call.Name)
			return out, err
		}
	}
}
```

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

What the middleware returns decides what the model sees:

- **A string and nil** is the result.
- **A `*weft.ToolError`** gives the model a code: `&weft.ToolError{Code: "DENIED", Message: "this agent is read-only"}` reads `DENIED: this agent is read-only`.
- **Any other error** is rendered as its text, exactly as a handler error would be.
- **An error wrapping `weft.ErrApprovalRequired`** is the one non-result: the call parks on `RunResult.Pending`. See [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/).

A middleware panic is a `tool "x" panicked: …` result, never a run error: panic containment sits outside the chain. So does `weft.Timeout`, which bounds the whole chain. An unknown tool still runs the agent's chain, so `mw.Allow` and `mw.Audit` see the attempt, before the base returns `NO_SUCH_TOOL`. The package example [`ExampleWrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-WrapTools) denies every `delete_` tool.

## Pass facts on the context

Middleware that verifies something (a user, a tenant, a quota) puts it on `ctx` before calling `next`. The handler reads it back through a typed accessor, the same shape as [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext):

```go title="middleware/seams.go"
// The accessor pair: only this package can put a user on a context.
type user struct{ Name string }

type userKey struct{}

func withUser(ctx context.Context, u user) context.Context {
	return context.WithValue(ctx, userKey{}, u)
}

func userFrom(ctx context.Context) (user, bool) {
	u, ok := ctx.Value(userKey{}).(user)
	return u, ok
}

// authenticate verifies the caller before next and puts the user on ctx.
func authenticate(lookup func(ctx context.Context) (user, error)) weft.ToolMiddleware {
	return func(next weft.ToolCaller) weft.ToolCaller {
		return func(ctx context.Context, call weft.ToolCallPart) (string, error) {
			u, err := lookup(ctx)
			if err != nil {
				return "", &weft.ToolError{Code: "UNAUTHENTICATED", Message: "sign in first", Err: err}
			}
			return next(withUser(ctx, u), call)
		}
	}
}

// myOrders reads the verified user back; it never trusts the arguments
// for who is calling.
var myOrders = weft.Tool("my_orders", "List the caller's orders.",
	func(ctx context.Context, _ struct{}) (string, error) {
		u, ok := userFrom(ctx)
		if !ok {
			return "", weft.Errorf("UNAUTHENTICATED", "no user on the call")
		}
		return "orders for " + u.Name + ": 1234, 5678", nil
	})
```

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

With a verified user, `my_orders` returns `orders for ada: 1234, 5678`. When the lookup fails, the middleware never calls `next` and the model reads `UNAUTHENTICATED: sign in first`; the cause stays on `ToolError.Err` for logs. Put only verified data on the context, and derive business values in the handler after decoding. The package example is [`ExampleWrapTools_context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-WrapTools-Context).

## Reference middleware

Package `mw` holds small, dependency-free middleware for both seams. Copy one, compose them, or write your own:

| Middleware | Seam | What it does |
|---|---|---|
| [`mw.Allow(permit)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) | tool | Runs a call only when `permit(call)` is true |
| [`mw.Audit(logger)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Audit) | tool | One Info line per call |
| [`mw.MapErrors(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MapErrors) | tool | Shapes handler errors before the model sees them |
| [`mw.Log(logger)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Log) | model | One Debug line before and one after each model call |
| [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry), [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback), [`mw.FallbackWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#FallbackWhen) | model | Retry with backoff, then fail over: [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) |
| [`mw.RepairJSON`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RepairJSON) | model | Closes a truncated or fenced tool-call argument object once: [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/) |

The tool trio together, with `mw.Log` on the model:

```go title="middleware/seams.go"
permit := func(c weft.Call) bool { return !strings.HasPrefix(c.Name, "delete_") }
agt := weft.New(model,
	weft.WrapModel(mw.Log(logger)), // Debug: one line before and one after each model call
	weft.WrapTools(
		mw.Audit(logger),  // observation: one Info line per call, with the cause
		mw.Allow(permit),  // decision: DENIED: tool "x" is not allowed
		mw.MapErrors(nil), // shaping: plain errors → INTERNAL: tool "x" failed
	),
	lookup, query, deleteOrder,
)
res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Status, report, then delete 1234."))
```

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

The order follows the godoc's: observation outermost, then the decision, then shaping. `mw.Audit` outside `mw.Allow` logs denied calls too. On the model seam the godoc's order is `mw.Log`, `mw.Fallback`, `mw.Retry`, `mw.RepairJSON`, outermost first. `mw` ships no rate limiter, because `golang.org/x/time` would be its first dependency; [`Example_rateLimitMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-package-RateLimitMiddleware) builds one from the standard library.

### Allow

`mw.Allow(permit)` gates every call on a predicate over its [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call). A denied call never runs: the model reads `DENIED: tool "delete_order" is not allowed` and the loop moves on, with no retry and no prompt. A nil `permit` allows every call. Outside the loop (`Agent.CallTool` with a bare `ctx`) the `Call` is built from the call part alone. `Allow` is a fixed policy; a decision deferred to a person is [approval](https://weftgo.dev/docs/guides/approvals/). Package example: [`ExampleAllow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Allow).

### Audit

`mw.Audit(logger)` logs one line per call at Info level, on `slog.Default` when `logger` is nil: run, step, call id, tool, duration, and the outcome. A failed call's line carries the model-visible text as `err` and, for a `*weft.ToolError` with a cause, the cause as `cause`. Under the agent's `weft.Content(false)` neither text is logged, only `err_bytes` (the text's length) and the `ToolError` code. Audit changes nothing. Package example: [`ExampleAudit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Audit).

### Log

`mw.Log(logger)` writes a Debug line before each model call (provider, model, message and tool counts) and one after it (stop reason, usage, tool-call count, duration). Placed outermost it sees the outcome of retries and fallbacks; placed innermost, each attempt. A nil `logger` means `slog.Default`. Package example: [`ExampleLog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Log).

### Map errors

`mw.MapErrors(fn)` shapes handler errors in one place. A `*weft.ToolError`, a context error and `ErrApprovalRequired` pass through untouched; every other error goes through `fn`. With a nil `fn`, the default hides the text (database messages, stack fragments) behind `INTERNAL: tool "query" failed` and keeps the original as the `ToolError`'s cause, where `mw.Audit` and `errors.As` still find it. When `fn` returns nil, the original error stands. Package example: [`ExampleMapErrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-MapErrors).

## Check middleware keeps model info

[`wefttest.ConformInfo(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfo) returns nil when model middleware `m` forwards the inner model's identity unchanged, and an error otherwise, showing the `Info` it got and the one it wanted. The error names the function's Go type, `core.ModelMiddleware`, not which middleware failed, so call it once per middleware. [`wefttest.ConformInfoT`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfoT) is the test-helper form. Add one line to your middleware's tests, from `middleware/middleware_test.go`:

```go title="middleware/middleware_test.go"
// The convention, checked: logRequests forwards the inner model's
// identity, so RunStart.Model and the manifest still name the provider.
func TestLogRequestsKeepsModelInfo(t *testing.T) {
	wefttest.ConformInfoT(t, logRequests(&bytes.Buffer{}))
}
```

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

## The onion in the record

Since 0.20.0 the record says which middleware wrapped a call and what each layer decided, at three levels. All of it reports only: nothing here changes a call, a retry, a denial or a result.

**The manifest lists the chain.** Each agent's manifest names its `model_middleware` and `tool_middleware` outer to inner, with a tool's own middleware under the tool. It also lists the hooks the agent has: `prepare_step`, `tap`, `on_run_end` and `tool_source`. Each entry is `{name, params?, source?, opaque?}`, a [`weft.MiddlewareInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MiddlewareInfo).

A model layer may describe itself with an optional `Describe() weft.MiddlewareInfo` method. `mw.Retry` reports its budget and delays, `mw.Fallback` its backups, `mw.Log` and `mw.RepairJSON` their names. Any other model layer is named by its type, and the walk goes inward through `Unwrap`. A layer without `Unwrap` ends the walk and is marked `opaque`, so the chain never reads shorter than it is without saying so.

Put only configuration in `Describe()`'s `Params`: counts, durations, model names. Never put a secret or a closure's captured value there. The manifest is hashed into every run's `weft.manifest.hash`, and Studio serves it whole at `GET /api/manifests/{hash}`.

A tool middleware is a function, so it is named by what the function is:

```go title="middleware/onion.go"
agt := weft.New(wefttest.Script(), weft.Name("payments"),
	weft.WrapTools(
		mw.Allow(func(weft.Call) bool { return true }), // "mw.Allow", no source
		budget, // "<package>.budget" ("main.budget" in a command), source "<import path>/onion.go:17"
		func(next weft.ToolCaller) weft.ToolCaller { return next }, // "func@middleware/onion.go:38", that place its source
	))
b, err := weft.Manifest(agt)
```

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

| Tool middleware | `name` | `source` |
|---|---|---|
| weft's own (`mw.Allow`, `mw.Audit`, `mw.MapErrors`) | its name, registered with [`weft.NameToolMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#NameToolMiddleware) | none |
| a named function or method | its package-qualified name, such as `main.budget` in a command | its position, such as `github.com/x/app/budget.go:17` |
| a closure | `func@<dir>/<file>:<line>`, where it is written, such as `func@app/main.go:42`; Studio's layer drawer shows it as `main.go:42` | the same place, `app/main.go:42` |

Wrap your own constructor's closure in `weft.NameToolMiddleware(name, mw)` to give it a name instead. The name belongs to the function literal, not to one closure of it: every closure of that literal shares it, and a later call for the same literal replaces it, in agents already built too. A constructor that names each closure from its argument (`"limit:"+name`) leaves every agent's manifest with the last name it was called with. `weft.manifest.hash` is computed once, at `New`, so an agent built before that last call keeps its old hash on every run while `weft.Manifest(a)` now holds the new name and hashes differently: its runs no longer match its own manifest, and they read stale against a registration or `weft.json` made later. Give each distinct name its own literal, or keep the name constant. The names do not depend on what the compiler inlined or on the Go version. A named function's `source` is one form on every machine: the defining package's import path, the file's base name and the line, never an absolute path. A closure's is its directory's name and file. Because the manifest lists the onion, adding or removing middleware changes `weft.manifest.hash` ([The manifest hash](https://weftgo.dev/docs/guides/manifest/#the-manifest-hash)). [`ExampleMiddlewareInfo`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-MiddlewareInfo) prints one.

**The spans say what a layer decided.** A tool middleware tells the call's `execute_tool` span through [`weft.ToolReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolReportFromContext)`(ctx)`, a [`ToolReporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolReporter):

```go title="middleware/onion.go"
// budget refuses wire_money and says so on the call's execute_tool span
// (weft.tool.denied_by "budget"). Reporting changes nothing the model sees.
func budget(next weft.ToolCaller) weft.ToolCaller {
	return func(ctx context.Context, call weft.ToolCallPart) (string, error) {
		if call.Name == "wire_money" {
			weft.ToolReportFromContext(ctx).Denied("budget")
			return "", &weft.ToolError{Code: weft.CodeDenied, Message: "over budget"}
		}
		return next(ctx, call)
	}
}
```

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

| Reporter call | Span attribute | Set by |
|---|---|---|
| `Denied(by)` | `weft.tool.denied_by` | `mw.Allow` reports `allow`; a deny grant on a resume `grant` (with `weft.grant.id`), else `approval` |
| `Masked(original)` | `weft.tool.error_masked` | `mw.MapErrors`: the hidden error's kind, never its text. The kind is the first of: an `ErrorKind() string` method, a context error's name, an `ErrorType()` method, a `ToolError`'s code, a standard sentinel through `errors.Is` (`io.EOF`, `fs.ErrNotExist`), else the error's Go type. Studio and the devtools panel read a plain error's type (`*errors.errorString`) as "plain error" and an `errors.Join` or two-`%w` error's as "joined errors"; the attribute keeps the type. A mapping that only wraps reports nothing |

Three rules bound these reports. `Denied(by)` reaches the span only when the call then ends in an error. The last report of a kind wins. Outside a loop-dispatched call, `Agent.CallTool` included, `ToolReportFromContext` returns a reporter that discards every report.

A model middleware that rewrites a call's arguments reports it with [`Reporter.Repair`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Repair) and a [`weft.RepairInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RepairInfo) (`CallID`, `Kind`, `Original`, `Repaired`): the step's `chat` span gets a `weft.repair` event and the call `weft.tool.args_repaired`. `mw.RepairJSON` does this, with the kinds `fence`, `unterminated`, `fence+unterminated` and `trim`. `mw.Retry` marks the requests it sent again with `weft.attempt.layer` `retry` ([Report attempts](https://weftgo.dev/docs/guides/retries-and-fallback/#report-attempts)). The examples [`ExampleToolReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ToolReportFromContext) and [`ExampleReporter_Repair`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Reporter.Repair) show both.

**Development detail shows every layer.** [`otel.DevDetail()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#DevDetail) adds one `layer <name>` span per `WrapModel` or `WrapTools` layer per call, named as the manifest names the layer. The spans nest outer to inner under the call's `chat` or `execute_tool` span. Each carries `weft.layer.name`, `weft.layer.kind` (`model` or `tool`), `weft.layer.index` (0 the outermost) and `error.type` where the layer returned an error. The `weft.repair` event then carries the original arguments, capped at 4 KiB. A contained tool or middleware panic's stack rides its `execute_tool` span as a `weft.panic` event, capped at 16 KiB. It is off by default: a span per layer is 2 to 6 more spans per call. Like `RawBodies` it takes effect only behind the development gate (`WEFT_ENV=dev`, or `otel.DevMode()`); otherwise `Start` logs `otel: DevDetail ignored: …`. Only the Local and Studio destinations with content on receive it ([Record provider wire bodies](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only)).

Pass the pipeline's logger provider to the agent with `weft.LoggerProvider(p.LoggerProvider())`, or rely on `Install`'s global registration. With the option the agent knows the level at `New` and builds the layer boundaries into its one model chain. Through the global provider it cannot: the first run builds a second chain, so your `WrapModel` constructors run twice and a stateful middleware holds two states. [`ExampleDevDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-DevDetail) shows it.

Studio draws all three in the run page's "what wrapped this call" ([Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/#what-wrapped-this-call)).

## Complete example

`middleware/seams.go` runs the chain-order demo, the context accessor with a good and a failed lookup, and the reference middleware on three parallel calls:

```go title="middleware/seams.go"
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"iter"
	"log/slog"
	"slices"
	"strings"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/mw"
	"github.com/weftgo/weft/wefttest"
)

// logRequests is a ModelMiddleware: it prints a line for every request
// the loop sends, then streams the inner model's reply unchanged.
func logRequests(w io.Writer) weft.ModelMiddleware {
	return func(next weft.Model) weft.Model { return requestLogger{next: next, w: w} }
}

type requestLogger struct {
	next weft.Model
	w    io.Writer
}

func (m requestLogger) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	fmt.Fprintf(m.w, "model request: %d messages, %d tools\n", len(req.Messages), len(req.Tools))
	return m.next.Stream(ctx, req)
}

// Info and Unwrap forward the inner model's identity and declare it.
func (m requestLogger) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m requestLogger) Unwrap() weft.Model   { return m.next }

// trace is a ToolMiddleware that prints before and after the rest of the
// chain runs.
func trace(w io.Writer, name string) weft.ToolMiddleware {
	return func(next weft.ToolCaller) weft.ToolCaller {
		return func(ctx context.Context, call weft.ToolCallPart) (string, error) {
			fmt.Fprintf(w, "%s: before %s\n", name, call.Name)
			out, err := next(ctx, call)
			fmt.Fprintf(w, "%s: after %s\n", name, call.Name)
			return out, err
		}
	}
}

// seamOrder runs one tool call through two agent middleware and one tool
// middleware, and one model call through logRequests.
func seamOrder(ctx context.Context, w io.Writer) error {
	lookup := weft.Tool("lookup_order", "Look up an order by ID.",
		func(_ context.Context, _ struct{}) (string, error) {
			fmt.Fprintln(w, "handler: lookup_order")
			return "shipped", nil
		},
		weft.WrapTools(trace(w, "tool")), // this tool only, inside the agent's chain
	)
	agt := weft.New(
		wefttest.Script(
			wefttest.ToolCalls(wefttest.Call{Name: "lookup_order"}),
			wefttest.Say("It has shipped."),
		),
		weft.WrapModel(logRequests(w)),
		weft.WrapTools(trace(w, "outer"), trace(w, "inner")), // first listed = outermost
		lookup,
	)
	_, err := agt.Generate(ctx, weft.Prompt("Where is my order?"))
	return err
}

// The accessor pair: only this package can put a user on a context.
type user struct{ Name string }

type userKey struct{}

func withUser(ctx context.Context, u user) context.Context {
	return context.WithValue(ctx, userKey{}, u)
}

func userFrom(ctx context.Context) (user, bool) {
	u, ok := ctx.Value(userKey{}).(user)
	return u, ok
}

// authenticate verifies the caller before next and puts the user on ctx.
func authenticate(lookup func(ctx context.Context) (user, error)) weft.ToolMiddleware {
	return func(next weft.ToolCaller) weft.ToolCaller {
		return func(ctx context.Context, call weft.ToolCallPart) (string, error) {
			u, err := lookup(ctx)
			if err != nil {
				return "", &weft.ToolError{Code: "UNAUTHENTICATED", Message: "sign in first", Err: err}
			}
			return next(withUser(ctx, u), call)
		}
	}
}

// myOrders reads the verified user back; it never trusts the arguments
// for who is calling.
var myOrders = weft.Tool("my_orders", "List the caller's orders.",
	func(ctx context.Context, _ struct{}) (string, error) {
		u, ok := userFrom(ctx)
		if !ok {
			return "", weft.Errorf("UNAUTHENTICATED", "no user on the call")
		}
		return "orders for " + u.Name + ": 1234, 5678", nil
	})

// contextFacts runs my_orders once with a verified user and once with a
// failed lookup.
func contextFacts(ctx context.Context, w io.Writer) error {
	for _, lookup := range []func(context.Context) (user, error){
		func(context.Context) (user, error) { return user{Name: "ada"}, nil },
		func(context.Context) (user, error) { return user{}, errors.New("session expired") },
	} {
		agt := weft.New(wefttest.Script(
			wefttest.ToolCalls(wefttest.Call{Name: "my_orders"}),
			wefttest.Say("Done."),
		), myOrders, weft.WrapTools(authenticate(lookup)))
		res, err := agt.Generate(ctx, weft.Prompt("Show my orders."))
		if err != nil {
			return err
		}
		fmt.Fprintln(w, "my_orders →", res.Steps[0].Results[0].Content)
	}
	return nil
}

// referenceSet runs the reference tool middleware together.
func referenceSet(ctx context.Context, w io.Writer) error {
	// Drop the time and duration attributes so the output is stable.
	stable := func(_ []string, a slog.Attr) slog.Attr {
		if a.Key == slog.TimeKey || a.Key == "dur" {
			return slog.Attr{}
		}
		return a
	}
	var logs strings.Builder
	logger := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: stable}))

	lookup := weft.Tool("lookup_order", "Look up an order by ID.",
		func(_ context.Context, _ struct{}) (string, error) { return "shipped", nil })
	query := weft.Tool("query", "Run a report query.",
		func(_ context.Context, _ struct{}) (string, error) {
			return "", errors.New("pq: SSL is not enabled on the server")
		})
	deleteOrder := weft.Tool("delete_order", "Delete an order.",
		func(_ context.Context, _ struct{}) (string, error) { return "deleted", nil })
	model := wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{ID: "c1", Name: "lookup_order"},
			wefttest.Call{ID: "c2", Name: "query"},
			wefttest.Call{ID: "c3", Name: "delete_order"},
		),
		wefttest.Say("Order shipped; the report and the delete failed."),
	)

	permit := func(c weft.Call) bool { return !strings.HasPrefix(c.Name, "delete_") }
	agt := weft.New(model,
		weft.WrapModel(mw.Log(logger)), // Debug: one line before and one after each model call
		weft.WrapTools(
			mw.Audit(logger),  // observation: one Info line per call, with the cause
			mw.Allow(permit),  // decision: DENIED: tool "x" is not allowed
			mw.MapErrors(nil), // shaping: plain errors → INTERNAL: tool "x" failed
		),
		lookup, query, deleteOrder,
	)
	res, err := agt.Generate(ctx, weft.RunID("run-1"), weft.Prompt("Status, report, then delete 1234."))
	if err != nil {
		return err
	}
	for _, r := range res.Steps[0].Results {
		fmt.Fprintf(w, "%s → %s\n", r.Name, r.Content)
	}
	// The calls ran in parallel, so their audit lines are sorted by call id.
	var audit []string
	for _, line := range strings.Split(strings.TrimSpace(logs.String()), "\n") {
		if strings.Contains(line, `msg="tool call"`) {
			audit = append(audit, line[strings.Index(line, "run="):])
		}
	}
	slices.Sort(audit)
	for _, line := range audit {
		fmt.Fprintln(w, "audit:", line)
	}
	return nil
}

// demoSeams is the middleware page's complete example.
func demoSeams(ctx context.Context, w io.Writer) error {
	for _, demo := range []func(context.Context, io.Writer) error{seamOrder, contextFacts, referenceSet} {
		if err := demo(ctx, w); err != nil {
			return err
		}
	}
	return nil
}
```

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

Run it from `docs-site/examples`:

```sh
go run ./middleware seams
go test ./middleware
```

```text
model request: 1 messages, 1 tools
outer: before lookup_order
inner: before lookup_order
tool: before lookup_order
handler: lookup_order
tool: after lookup_order
inner: after lookup_order
outer: after lookup_order
model request: 3 messages, 1 tools
my_orders → orders for ada: 1234, 5678
my_orders → UNAUTHENTICATED: sign in first
lookup_order → shipped
query → INTERNAL: tool "query" failed
delete_order → DENIED: tool "delete_order" is not allowed
audit: run=run-1 step=0 call=c1 tool=lookup_order result_bytes=7
audit: run=run-1 step=0 call=c2 tool=query err="INTERNAL: tool \"query\" failed" cause="pq: SSL is not enabled on the server"
audit: run=run-1 step=0 call=c3 tool=delete_order err="DENIED: tool \"delete_order\" is not allowed"
```

## Best practices & gotchas

- **List the outermost middleware first.** `WrapModel(a, b)` is `a(b(model))`; a later option appends inward. (Source: `weft/core/agent.go:265-271`, `weft/core/tool.go:569-580`)
- **Put `mw.Fallback` outside `mw.Retry`.** Then the primary is retried to exhaustion before the backup is tried; the reverse retries the whole fallback chain. (Source: `weft/core/mw/doc.go:15-19`)
- **Forward `Info` and declare `Unwrap` in model middleware.** Without `Info`, `RunStart.Model` and the manifest lose the provider; `wefttest.ConformInfoT` catches it. (Source: `weft/core/agent.go:246-253`, `weft/core/wefttest/conform.go:15-22`)
- **Decorate `ctx` only with what the middleware verified.** Handlers trust what an accessor returns; arguments come from the model. (Source: `weft/docs/adr/0006-seams.md:59-64`)
- **Observe events with `weft.Tap`; reach for observing middleware only at the seam.** A tap sees every event and changes nothing. Use `mw.Audit` or `mw.Log` when you need the call's context or its outcome where the call is made. (Source: AGENTS.md rule 10, `weft/core/mw/doc.go:23`, `weft/core/mw/tool.go:45-53`, `weft/core/mw/model.go:297-302`)
- **Expect parallel calls to log out of order.** Tool calls in one step run concurrently, so `mw.Audit` lines arrive in completion order; sort by call id when the order matters. (Source: `docs-site/examples/middleware/seams.go` referenceSet, AGENTS.md rule 3)

## See also

- [How do tools work?](https://weftgo.dev/docs/concepts/tools/)
- [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/)
- [Require human approval for a tool](https://weftgo.dev/docs/guides/approvals/)
- [Observe a run without changing it: Tap, OnRunEnd, OnMessages](https://weftgo.dev/docs/guides/observers/)
- [What is a Model? The provider contract](https://weftgo.dev/docs/concepts/models/)

Symbols used: [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.ModelMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelMiddleware) · [`weft.ToolMiddleware`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolMiddleware) · [`weft.ToolCaller`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCaller) · [`weft.ToolCallPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolCallPart) · [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) · [`weft.ErrApprovalRequired`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrApprovalRequired) · [`weft.Call`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Call) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`mw.Allow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Allow) · [`mw.Audit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Audit) · [`mw.MapErrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MapErrors) · [`mw.Log`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Log) · [`wefttest.ConformInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfo) · [`wefttest.ConformInfoT`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ConformInfoT) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
