---
title: Tag runs with metadata
description: Attach tenant, user or request ids to every span and record of a run with weft.Metadata or weft.WithMetadata, and read them back with weft.MetadataFromContext.
url: https://weftgo.dev/docs/guides/metadata/
type: how-to
sources:
  - weft/core/metadata.go:10-20 (limits), 22-46 (Metadata), 60-72 (WithMetadata), 112-114 (MetadataFromContext), 122-135 (mergeMetadata order)
  - weft/core/observe.go:1407-1429 (metadataAttrs, the semconv mirrors), 277-284 (weft.metadata.dropped on invoke_agent)
  - weft/AGENTS.md:130-132 (block 3), 180 (weft.approval.actor), 211-213 (block 6)
  - weft/example_test.go:965 (ExampleMetadata)
  - weft/core/example_test.go:1222 (ExampleWithMetadata)
  - weft/core/metadata_test.go:61 (TestMetadataInheritedAndOverlaidBySubagentRun), 97 (TestMetadataLimits), 140 (TestMetadataCapKeepsWeftKeys)
  - weft/core/metadata_empty_test.go:17 (TestMetadataEmptyValueRemovesInherited), 92-128 (TestMetadataEmptyValueFreesSlotAtCap)
  - weft/core/metadata.go:132-134 (removals apply before any addition), 143-150 (the removal pass runs first)
  - weft/CHANGELOG.md:432-435 (at the 64-key cap a run's removals apply before its additions)
  - weft/scope/scope.go:40, 70 (scope.Header stamps weft.page_url)
  - weft/CHANGELOG.md:422, 886, 3227, 4806, 4813
  - docs-site/examples/metadata/main.go, main_test.go TestMetadata, TestOptionWinsOverContext, TestEmptyValueRemoves, TestNoMetadataIsNil
---

# Tag runs with metadata

[`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) attaches caller key/value pairs to one run: every span and every record of the run carries them, and so do the runs of its subagents. [`weft.WithMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithMetadata) puts the same pairs on a context, for every run started under it. [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) reads the merged pairs back. Metadata is reporting only: it changes nothing the model sees.

Tag a run in `metadata/main.go`:

```go title="metadata/main.go"
res, err := agt.Generate(ctx,
	weft.Prompt("Where is order 1234?"),
	weft.Metadata(map[string]string{"tenant": "acme", "enduser.id": "u_42"}),
	weft.Metadata(map[string]string{"request.id": "req_7"}), // several options merge; a later key wins
)
```

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

The pairs are on the run's `invoke_agent` span, its `chat` and `execute_tool` spans, and its records, so a trace backend can group or filter by tenant. The package example is [`ExampleMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Metadata).

## Metadata

`Metadata` is a run option. Several `Metadata` options merge in order, and a later key wins. The pairs ride the run's context, so anything that receives that context can read them with `MetadataFromContext`: a `weft.Tap`, an `OnRunEnd` observer, a tool handler, or a subagent's child run.

```go title="metadata/main.go"
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
	func(ctx context.Context, in LookupInput) (string, error) {
		tenant := weft.MetadataFromContext(ctx)["tenant"] // the run's pairs, in the handler
		return "order " + in.OrderID + " of " + tenant + " has shipped", nil
	})
agt := weft.New(model, lookup,
	weft.Tap(func(ctx context.Context, ev weft.Event) {
		if _, ok := ev.(weft.RunStart); ok {
			md := weft.MetadataFromContext(ctx)
			fmt.Fprintln(w, "run start: tenant =", md["tenant"], "user =", md["enduser.id"])
		}
	}),
)
```

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

`MetadataFromContext` returns a copy of the pairs in force: the run's own merged over its ancestors'. It returns nil when there are none.

Keys under `weft.` are the weft modules' namespace by convention. `weft/thread` stamps `weft.session.id` and `weft.turn` on every turn's run, and `weft.public_id` when the session has one, and an approval resume can name its decider with `weft.approval.actor`. The core does not police the prefix. Two keys also get the OpenTelemetry mirrors that backends group on: `weft.session.id` is repeated as `gen_ai.conversation.id` and `session.id`, and `enduser.id` as `user.id`. A run started on a tool call's context, such as a subagent's child run, also carries `weft.parent.run.id` and `weft.parent.call.id` on its `invoke_agent` span, beside the run's `weft.version` and, for a named agent, `weft.manifest.hash`.

### Inherit and remove pairs

A [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent)'s child run inherits the parent's pairs, because they travel on the tool call's context. An empty value means "none": it is never stored, and it removes the key the run would otherwise inherit, from its parent run or from a `WithMetadata` context.

```go title="metadata/main.go"
researcher := weft.New(wefttest.Script(wefttest.Say("notes"), wefttest.Say("notes")), weft.Name("researcher"), childTap)
lead := weft.New(wefttest.Script(
	wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}),
	wefttest.Say("done"),
), weft.Subagent("research", "Research a topic.", researcher))
_, err := lead.Generate(ctx, weft.Prompt("Brief me."),
	weft.Metadata(map[string]string{"tenant": "acme", "weft.session.id": "s_01"}))
if err != nil {
	return err
}
// A run that is not the enclosing session's work says so with "":
_, err = researcher.Generate(weft.WithMetadata(ctx, map[string]string{"tenant": "acme", "weft.session.id": "s_01"}),
	weft.Prompt("Standalone."),
	weft.Metadata(map[string]string{"weft.session.id": ""}))
```

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

The first child run prints `weft.session.id="s_01"`. The second run reads an empty string because the key is gone: `TestEmptyValueRemoves` checks that the key is absent, not empty. `weft/thread` uses this to stamp `weft.public_id` as `""` on a session that has none, so a turn started inside another session's tool handler never reads as that session's.

### Limits

Metadata rides every span and record, so it is identity, not a payload:

| Limit | Value |
|---|---|
| Keys per run | 64 |
| Key length | 128 bytes |
| Value length | 1024 bytes |

An entry over a limit, or with an empty key, is dropped, never truncated, and counted on the run's `invoke_agent` span as `weft.metadata.dropped`. An empty value is a removal and is not counted. Removals apply before additions: a key an empty value removes frees its slot first, so at 64 inherited keys a run that removes one and adds one keeps the new key, whatever the two keys' sort order. At the key cap the `weft.` keys are kept first, then the rest in sorted key order, so a large tag set never costs a run its session identity.

## Context metadata

`WithMetadata(ctx, kv)` returns a copy of `ctx` that carries `kv` for every run started under it. Use it where the code that learns a fact is not the code that calls `Generate`: `net/http` middleware that knows the tenant or the page before the handler runs.

```go title="metadata/main.go"
tag := func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		ctx := weft.WithMetadata(r.Context(), map[string]string{
			"tenant": r.Header.Get("X-Tenant"),
			"region": "eu-west",
		})
		next.ServeHTTP(rw, r.WithContext(ctx))
	})
}
chat := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
	// The handler passes no metadata option: the run reads the context's pairs.
	res, err := agt.Generate(r.Context(), weft.Prompt(r.FormValue("q")))
	if err != nil {
		http.Error(rw, err.Error(), http.StatusBadGateway)
		return
	}
	fmt.Fprint(rw, res.Text())
})
handler := tag(chat)
```

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

The handler passes no metadata option, and the run still reads `tenant` and `region`. The rules match `Metadata`:

- Pairs merge over any the context already carries, a later key winning, under the same limits.
- A run's own `Metadata` options win over the context's pairs.
- A subagent's child run inherits them as it inherits the parent's.
- An entry over a limit is dropped and counted on each run started under the returned context; that run's children start from zero.

This is how [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) stamps the request's page as `weft.page_url` on every run its handler starts. The package example is [`ExampleWithMetadata`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-WithMetadata).

## Complete example

`metadata/main.go` tags a run, stamps pairs from HTTP middleware, shows inheritance and removal, and drops an over-long value:

```go title="metadata/main.go"
// Command metadata runs the examples of the guide "Tag runs with
// metadata": go run ./metadata. Every model is scripted with wefttest,
// so it runs offline; swap in a provider adapter for a real one.
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"

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

// perRun tags one run and reads the pairs back in a tap and in a tool.
func perRun(ctx context.Context, w io.Writer) error {
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
		wefttest.Say("Order 1234 has shipped."),
	)
	type LookupInput struct {
		OrderID string `json:"order_id" jsonschema:"the order to look up"`
	}
	lookup := weft.Tool("lookup_order", "Look up an order by ID.",
		func(ctx context.Context, in LookupInput) (string, error) {
			tenant := weft.MetadataFromContext(ctx)["tenant"] // the run's pairs, in the handler
			return "order " + in.OrderID + " of " + tenant + " has shipped", nil
		})
	agt := weft.New(model, lookup,
		weft.Tap(func(ctx context.Context, ev weft.Event) {
			if _, ok := ev.(weft.RunStart); ok {
				md := weft.MetadataFromContext(ctx)
				fmt.Fprintln(w, "run start: tenant =", md["tenant"], "user =", md["enduser.id"])
			}
		}),
	)

	res, err := agt.Generate(ctx,
		weft.Prompt("Where is order 1234?"),
		weft.Metadata(map[string]string{"tenant": "acme", "enduser.id": "u_42"}),
		weft.Metadata(map[string]string{"request.id": "req_7"}), // several options merge; a later key wins
	)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "tool saw:", res.Steps[0].Results[0].Content)
	return nil
}

// fromRequest stamps metadata in net/http middleware, before the
// handler starts a run.
func fromRequest(ctx context.Context, w io.Writer) error {
	agt := weft.New(wefttest.Script(wefttest.Say("ok")),
		weft.Tap(func(ctx context.Context, ev weft.Event) {
			if _, ok := ev.(weft.RunStart); ok {
				md := weft.MetadataFromContext(ctx)
				fmt.Fprintln(w, "run start: tenant =", md["tenant"], "region =", md["region"])
			}
		}))
	tag := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			ctx := weft.WithMetadata(r.Context(), map[string]string{
				"tenant": r.Header.Get("X-Tenant"),
				"region": "eu-west",
			})
			next.ServeHTTP(rw, r.WithContext(ctx))
		})
	}
	chat := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		// The handler passes no metadata option: the run reads the context's pairs.
		res, err := agt.Generate(r.Context(), weft.Prompt(r.FormValue("q")))
		if err != nil {
			http.Error(rw, err.Error(), http.StatusBadGateway)
			return
		}
		fmt.Fprint(rw, res.Text())
	})
	handler := tag(chat)

	req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/chat?q=hello", nil)
	req.Header.Set("X-Tenant", "acme")
	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, req)
	fmt.Fprintln(w, "response:", rec.Code, rec.Body.String())
	return nil
}

// inherit shows a Subagent's child run inheriting the pairs, and an
// empty value removing one.
func inherit(ctx context.Context, w io.Writer) error {
	childTap := weft.Tap(func(ctx context.Context, ev weft.Event) {
		if _, ok := ev.(weft.RunStart); ok {
			md := weft.MetadataFromContext(ctx)
			fmt.Fprintf(w, "child run: tenant=%q weft.session.id=%q\n", md["tenant"], md["weft.session.id"])
		}
	})
	researcher := weft.New(wefttest.Script(wefttest.Say("notes"), wefttest.Say("notes")), weft.Name("researcher"), childTap)
	lead := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}),
		wefttest.Say("done"),
	), weft.Subagent("research", "Research a topic.", researcher))
	_, err := lead.Generate(ctx, weft.Prompt("Brief me."),
		weft.Metadata(map[string]string{"tenant": "acme", "weft.session.id": "s_01"}))
	if err != nil {
		return err
	}
	// A run that is not the enclosing session's work says so with "":
	_, err = researcher.Generate(weft.WithMetadata(ctx, map[string]string{"tenant": "acme", "weft.session.id": "s_01"}),
		weft.Prompt("Standalone."),
		weft.Metadata(map[string]string{"weft.session.id": ""}))
	return err
}

// limits shows an over-long value dropped, never truncated.
func limits(ctx context.Context, w io.Writer) error {
	var got map[string]string
	agt := weft.New(wefttest.Script(wefttest.Say("ok")),
		weft.Tap(func(ctx context.Context, ev weft.Event) {
			if _, ok := ev.(weft.RunStart); ok {
				got = weft.MetadataFromContext(ctx)
			}
		}))
	_, err := agt.Generate(ctx, weft.Prompt("hi"), weft.Metadata(map[string]string{
		"tenant": "acme",
		"notes":  strings.Repeat("x", 1025), // over the 1024-byte value limit
	}))
	if err != nil {
		return err
	}
	_, kept := got["notes"]
	fmt.Fprintf(w, "keys kept: %d, notes kept: %t\n", len(got), kept)
	return nil
}

func run(ctx context.Context, w io.Writer) error {
	steps := []struct {
		title string
		fn    func(context.Context, io.Writer) error
	}{
		{"per run", perRun},
		{"from the request", fromRequest},
		{"inherited", inherit},
		{"limits", limits},
	}
	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)
	}
}
```

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

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

```sh
go run ./metadata
go test ./metadata
```

```text
== per run
run start: tenant = acme user = u_42
tool saw: order 1234 of acme has shipped
== from the request
run start: tenant = acme region = eu-west
response: 200 ok
== inherited
child run: tenant="acme" weft.session.id="s_01"
child run: tenant="acme" weft.session.id=""
== limits
keys kept: 1, notes kept: false
```

## Best practices & gotchas

- **Put identity in metadata, not content.** Pairs ride every span and record, and the limits drop anything over 1024 bytes without truncating it. (Source: `weft/core/metadata.go:10-20`, `TestMetadataLimits`)
- **Read the drop counter when a key is missing.** A dropped pair leaves no trace except `weft.metadata.dropped` on the run's `invoke_agent` span. (Source: `weft/core/metadata.go:37-43`)
- **Remove an inherited key with `""`, not by omitting it.** A child run inherits every pair it does not override; only an empty value removes one. (Source: `TestMetadataEmptyValueRemovesInherited`, CHANGELOG 0.15.1)
- **Do not rely on metadata to change behaviour.** It is reporting only; the model never sees it. Use [run options](https://weftgo.dev/docs/guides/run-options/) to change what a run does. (Source: `weft/core/metadata.go:70-71`)
- **Leave the `weft.` prefix to weft's modules.** Those keys are kept first under the cap because they carry a run's session identity. (Source: `TestMetadataCapKeepsWeftKeys`, CHANGELOG 0.8.0)

## See also

- [Observe a run without changing it](https://weftgo.dev/docs/guides/observers/): the taps that read metadata
- [Change an agent's configuration for one run](https://weftgo.dev/docs/guides/run-options/)
- [The record contract](https://weftgo.dev/docs/reference/record-contract/)
- [Sessions and traces in Studio](https://weftgo.dev/docs/observe/studio/sessions-and-traces/)

Symbols used: [`weft.Metadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Metadata) · [`weft.WithMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithMetadata) · [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Prompt) · [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`ExampleMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Metadata) · [`ExampleWithMetadata`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-WithMetadata)
