---
title: 'Define tools at runtime: RawTool and ToolSource'
description: Register a tool from a JSON Schema with weft.RawTool and ParseSchema, or serve a tool list that changes during a run with weft.ToolSource.
url: https://weftgo.dev/docs/guides/dynamic-tools/
type: how-to
sources:
  - weft/core/tool.go:403-435 (RawTool), 18-25 (frozen at New), 524-532 (StrictInput does not reach RawTool)
  - weft/core/schema.go:42-75 (ParseSchema)
  - 'weft/google/convert.go:354-381 (genaiSchema: keywords genai.Schema lacks are dropped); weft/google/model_test.go:278-306 (enum kept, oneOf dropped)'
  - weft/core/agent.go:778-841 (ToolSource, effectiveTools, dispatchTools, validateSnapshot), 902-911 (Agent.Tools)
  - weft/core/errors.go:98-109 (ErrDuplicateTool, ErrNilTool)
  - 'scratch proof (weft v0.17.0): OnlyTools("lookup") and a ToolSource without it each gave ErrNoOutput with the NO_SUCH_TOOL result; OnlyTools("lookup", "submit_output") and a source appending agt.Tools()''s submit_output each decoded the value'
  - weft/core/loop.go:473 (one snapshot per step), 544-554 (a PrepareStep result validated by the same rule), 1687-1706 (CallTool fetches its own snapshot)
  - weft/core/manifest.go:244-252 (no source for a RawTool)
  - weft/AGENTS.md:49-52 (block 1b), rule 1
  - weft/CHANGELOG.md:6220, 6455, 6563, 6572
  - docs-site/examples/dynamictools/main.go, main_test.go TestDynamicTools, TestRawToolNilSchema, TestParseSchemaRejectsNonObject, TestManifestKeepsStaticSet
---

# Define tools at runtime: RawTool and ToolSource

[`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) defines a tool from an explicit schema instead of a Go struct; its handler receives the model's arguments as raw JSON. [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) replaces the agent's tool list with a function the loop calls once per step (plus once when a resume runs approved calls, and once per manual `CallTool`), for a registry that changes while the agent runs. Use the first for tools defined outside Go source (plugin manifests, gateways, MCP remotes), the second when the set of tools is not known at `New`.

A tool whose schema arrives as bytes, in `dynamictools/main.go`:

```go title="dynamictools/main.go"
schema, err := weft.ParseSchema(json.RawMessage(pluginSchema))
if err != nil {
	return err // invalid JSON, or a top level that is not an object
}
export := weft.RawTool("export_report", "Export the monthly report.", schema,
	func(ctx context.Context, args json.RawMessage) (string, error) {
		var in struct {
			Format string `json:"format"`
		}
		if err := json.Unmarshal(args, &in); err != nil {
			return "", err // validation is the handler's job
		}
		if in.Format != "pdf" && in.Format != "csv" {
			return "", fmt.Errorf("format %q is not pdf or csv", in.Format)
		}
		return "exported as " + in.Format, nil
	})
```

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

The model sees the schema as written, `enum` included, and the handler checks its own input.

## How it works

`weft.Tool` reflects a schema from the input struct and decodes the arguments into it. `RawTool` skips both: you hand it a [`*weft.Schema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Schema), and the handler gets the bytes. Everything else is the same tool: it runs through the `WrapTools` chain, takes per-tool options such as `Timeout` and `MaxResultBytes`, and its errors are results the model reads.

A `ToolSource` changes where the loop finds tools, not how it runs them. At each step the loop calls the function once; a resume that runs approved calls fetches once more before step 0, and each manual `agt.CallTool` fetches its own snapshot. That one per-step snapshot is what the step advertises and what its calls dispatch against, so what the model was shown is exactly what runs. Without a source, the list given to `New` is the only source of tools.

## Register a tool from a JSON Schema

[`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) reads a JSON Schema document into a `*Schema`. It fills the structured fields it knows, such as `Type`, `Properties` and `Required`, so the manifest and any reader that walks the tree see them. It also keeps the document's own bytes, which [`Schema.MarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Schema.MarshalJSON) re-emits. A keyword the `Schema` type cannot hold, such as `enum`, `oneOf` or `$ref`, still reaches the model on the openai and anthropic adapters:

```text
schema sent: {"properties":{"format":{"description":"the export format","enum":["pdf","csv"],"type":"string"}},"required":["format"],"type":"object"}
property type: string
```

The google adapter is narrower: it sends only the keywords Gemini's schema type has, so `enum` survives but `oneOf`, `$ref` and others are dropped without an error. [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/#import-tools) lists what it keeps and drops; on Gemini, validate those constraints in the handler.

The top level must be an object, because providers and MCP require one. Invalid JSON, trailing data or a non-object top level return an error naming the problem, at import rather than at the first model call. The structured view is lenient: a keyword whose shape `Schema` cannot hold, such as a type array `["string","null"]`, leaves that field zero and is not an error.

The handler receives the arguments verbatim: no unmarshalling and no `ErrInvalidToolInput`. Validation belongs to it, and an error it returns is an error result the model reads:

```text
step 0 (error: true): format "xml" is not pdf or csv
step 1 (error: false): exported as csv
```

A nil schema becomes the empty object schema, so the tool accepts any object. `StrictInput` has no effect on a `RawTool`. `RawTool` panics on an empty name or a nil handler, as `Tool` does. The manifest records no `source` line for it, because the definition is not in Go source. `mcp.Tools` builds its imported tools this way ([Use MCP both ways](https://weftgo.dev/docs/guides/mcp/)).

## Serve tools that change during a run

Pass `ToolSource` a function that returns the current list. Its owner synchronizes it; the agent stays immutable, because the source is a value:

```go title="dynamictools/main.go"
reg := &registry{}
reg.Add(weft.Tool("install_billing", "Install the billing plugin.",
	func(context.Context, struct{}) (string, error) {
		reg.Add(refund) // callable from the next step's fetch
		return "billing plugin installed", nil
	}))
agt := weft.New(model(), weft.ToolSource(reg.Tools))
```

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

The model calls `refund` and `install_billing` in step 0. `refund` is not in step 0's snapshot, so it fails as unknown, even though `install_billing` adds it during that step. Step 1 fetches again and the call runs:

```text
step 0 refund (error: true): NO_SUCH_TOOL: no tool named "refund"
step 0 install_billing (error: false): billing plugin installed
step 1 refund (error: false): refunded 1234
agent.Tools(): 0
```

A tool registered mid-step becomes callable on the next step's fetch. The sequential barrier and dispatch use the same snapshot as the advertisement, so a source that changes mid-step cannot produce a tool that was advertised and then not found. [`agt.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) fetches its own snapshot on each call.

The source replaces the static list; it does not add to it. Tools passed to `New` beside a `ToolSource` are not advertised. [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) and `weft.Manifest` keep reporting that static construction-time set, which is why the output prints `0`: a manifest describes the code, not the registry behind a source. Per-run rules still apply to the snapshot: `OnlyTools` narrows it, and `ParkAllExcept` and `ParkSource` match a source's tools by name like any other.

## Handle a malformed snapshot

`New` panics on a duplicate tool name or a nil `*ToolDef`. A snapshot is built at run time, so the same mistakes fail the run instead, with [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) or [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool):

```go title="dynamictools/main.go"
dup := weft.New(wefttest.Script(wefttest.Say("never")),
	weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, lookup} }))
_, err := dup.Generate(ctx, weft.Prompt("Where is order 1234?"))
fmt.Fprintln(w, errors.Is(err, weft.ErrDuplicateTool), err)

withNil := weft.New(wefttest.Script(wefttest.Say("never")),
	weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, nil} }))
_, err = withNil.Generate(ctx, weft.Prompt("Where is order 1234?"))
fmt.Fprintln(w, errors.Is(err, weft.ErrNilTool), err)
```

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

```text
true weft: run failed at step 0: weft: duplicate tool name from tool source: "lookup"
true weft: run failed at step 0: weft: nil tool in tool source snapshot: entry 1
```

Both are run errors, a [`*weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) with the partial transcript on `.Result`, and match with `errors.Is` ([rule 1](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). The run fails rather than silently dropping the second tool or advertising a nil every adapter would dereference. `agt.CallTool` returns the same errors, and the tool list a [`PrepareStep`](https://weftgo.dev/docs/guides/prepare-step/) function returns is checked by the same rule.

## Complete example

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

```go title="dynamictools/main.go"
// Command dynamictools runs the examples of the guide "Define tools at
// runtime: RawTool and ToolSource": go run ./dynamictools. Every model is
// scripted with wefttest, so it runs offline.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"sync"

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

// pluginSchema is a tool schema that arrives as bytes, for example from a
// plugin manifest. The enum is a keyword weft.Schema has no field for.
const pluginSchema = `{
  "type": "object",
  "properties": {
    "format": {"type": "string", "enum": ["pdf", "csv"], "description": "the export format"}
  },
  "required": ["format"]
}`

// rawTool defines a tool from an explicit schema and raw arguments.
func rawTool(ctx context.Context, w io.Writer) error {
	schema, err := weft.ParseSchema(json.RawMessage(pluginSchema))
	if err != nil {
		return err // invalid JSON, or a top level that is not an object
	}
	export := weft.RawTool("export_report", "Export the monthly report.", schema,
		func(ctx context.Context, args json.RawMessage) (string, error) {
			var in struct {
				Format string `json:"format"`
			}
			if err := json.Unmarshal(args, &in); err != nil {
				return "", err // validation is the handler's job
			}
			if in.Format != "pdf" && in.Format != "csv" {
				return "", fmt.Errorf("format %q is not pdf or csv", in.Format)
			}
			return "exported as " + in.Format, nil
		})
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "export_report", Args: `{"format":"xml"}`}),
		wefttest.ToolCalls(wefttest.Call{Name: "export_report", Args: `{"format":"csv"}`}),
		wefttest.Say("Exported."),
	)
	agt := weft.New(model, export)
	res, err := agt.Generate(ctx, weft.Prompt("Export the report."))
	if err != nil {
		return err
	}
	sent, err := json.Marshal(model.Requests()[0].Tools[0].InputSchema)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "schema sent:", compact(sent))
	fmt.Fprintln(w, "property type:", schema.Properties["format"].Type)
	for _, s := range res.Steps[:2] {
		r := s.Results[0]
		fmt.Fprintf(w, "step %d (error: %t): %s\n", s.Index, r.IsError, r.Content)
	}
	return nil
}

func compact(b []byte) string {
	var v any
	if err := json.Unmarshal(b, &v); err != nil {
		return string(b)
	}
	out, _ := json.Marshal(v)
	return string(out)
}

// registry is a tool list that changes while an agent runs: plugins
// installed mid-run, servers polled per step. Its owner synchronizes it.
type registry struct {
	mu    sync.Mutex
	tools []*weft.ToolDef
}

func (r *registry) Tools() []*weft.ToolDef {
	r.mu.Lock()
	defer r.mu.Unlock()
	return append([]*weft.ToolDef(nil), r.tools...)
}

func (r *registry) Add(t *weft.ToolDef) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.tools = append(r.tools, t)
}

type orderInput struct {
	OrderID string `json:"order_id" jsonschema:"the order"`
}

// toolSource re-reads the registry each step.
func toolSource(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 })
	reg := &registry{}
	reg.Add(weft.Tool("install_billing", "Install the billing plugin.",
		func(context.Context, struct{}) (string, error) {
			reg.Add(refund) // callable from the next step's fetch
			return "billing plugin installed", nil
		}))
	agt := weft.New(model(), weft.ToolSource(reg.Tools))
	res, err := agt.Generate(ctx, weft.Prompt("Refund order 1234."))
	if err != nil {
		return err
	}
	for _, s := range res.Steps {
		for _, r := range s.Results {
			fmt.Fprintf(w, "step %d %s (error: %t): %s\n", s.Index, r.Name, r.IsError, r.Content)
		}
	}
	fmt.Fprintln(w, "agent.Tools():", len(agt.Tools()))
	return nil
}

// model scripts: refund before it is installed, install, refund again.
func model() weft.Model {
	return wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`},
			wefttest.Call{Name: "install_billing", Args: `{}`},
		),
		wefttest.ToolCalls(wefttest.Call{Name: "refund", Args: `{"order_id":"1234"}`}),
		wefttest.Say("Refunded."),
	)
}

// badSnapshot shows the two malformed snapshots.
func badSnapshot(ctx context.Context, w io.Writer) error {
	lookup := weft.Tool("lookup", "Look up an order.",
		func(_ context.Context, in orderInput) (string, error) { return "shipped", nil })
	dup := weft.New(wefttest.Script(wefttest.Say("never")),
		weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, lookup} }))
	_, err := dup.Generate(ctx, weft.Prompt("Where is order 1234?"))
	fmt.Fprintln(w, errors.Is(err, weft.ErrDuplicateTool), err)

	withNil := weft.New(wefttest.Script(wefttest.Say("never")),
		weft.ToolSource(func() []*weft.ToolDef { return []*weft.ToolDef{lookup, nil} }))
	_, err = withNil.Generate(ctx, weft.Prompt("Where is order 1234?"))
	fmt.Fprintln(w, errors.Is(err, weft.ErrNilTool), err)
	return nil
}

func run(ctx context.Context, w io.Writer) error {
	steps := []struct {
		title string
		fn    func(context.Context, io.Writer) error
	}{
		{"raw tool", rawTool},
		{"tool source", toolSource},
		{"bad snapshot", badSnapshot},
	}
	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)
	}
}
```

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

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

```sh
go run ./dynamictools
go test ./dynamictools
```

```text
== raw tool
schema sent: {"properties":{"format":{"description":"the export format","enum":["pdf","csv"],"type":"string"}},"required":["format"],"type":"object"}
property type: string
step 0 (error: true): format "xml" is not pdf or csv
step 1 (error: false): exported as csv
== tool source
step 0 refund (error: true): NO_SUCH_TOOL: no tool named "refund"
step 0 install_billing (error: false): billing plugin installed
step 1 refund (error: false): refunded 1234
agent.Tools(): 0
== bad snapshot
true weft: run failed at step 0: weft: duplicate tool name from tool source: "lookup"
true weft: run failed at step 0: weft: nil tool in tool source snapshot: entry 1
```

## Best practices & gotchas

- **Validate arguments in a `RawTool` handler.** The loop does not decode them and `StrictInput` does not apply. (Source: `weft/core/tool.go:403-410`)
- **Parse foreign schemas with `ParseSchema`, not by hand.** It keeps the bytes whole, so keywords `Schema` has no field for reach the model on openai and anthropic. On google, `oneOf`, `$ref` and the other keywords Gemini lacks are dropped ([the table](https://weftgo.dev/docs/guides/mcp/#import-tools)). (Source: `weft/core/schema.go:42-58`, CHANGELOG 0.2.0, `weft/google/convert.go:354-381`)
- **Return a copy of the list from a source, under the owner's lock.** Synchronization and freshness belong to the source's owner. (Source: `weft/core/agent.go:786-787`)
- **Put every tool in the source when you use one.** The source replaces the static list for advertising and dispatch. (Source: `weft/core/agent.go:802-809`)
- **Return `submit_output` from the source of an `Output[T]` agent.** It is not added for you: a source that leaves it out makes the model's submission read `NO_SUCH_TOOL: no tool named "submit_output"`, and `GenerateAs` returns `ErrNoOutput`. Append the `submit_output` entry of `agt.Tools()`, which reports it beside a source. (Source: `weft/core/agent.go:802-809, 902-911`; [structured output](https://weftgo.dev/docs/guides/structured-output/#best-practices--gotchas))
- **Change the tool list deliberately.** `ToolSource` and `PrepareStep` are the two knobs that can break a prompt-cache prefix. (Source: `weft/core/agent.go:174-175`)
- **Do not expect a mutation after `New` to reach the agent.** Registered tools are deep-copied at `New`; `Agent.Tools` returns copies. (Source: `weft/core/tool.go:22-25`, CHANGELOG 0.2.0)

## See also

- [How do tools work?](https://weftgo.dev/docs/concepts/tools/)
- [Use MCP both ways](https://weftgo.dev/docs/guides/mcp/)
- [Rewrite the request each step (PrepareStep)](https://weftgo.dev/docs/guides/prepare-step/)
- [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/)
- [Describe your agents in weft.json](https://weftgo.dev/docs/guides/manifest/)

Symbols used: [`weft.RawTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawTool) · [`weft.ParseSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParseSchema) · [`weft.Schema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Schema) · [`Schema.MarshalJSON`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Schema.MarshalJSON) · [`weft.ToolSource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolSource) · [`weft.ToolDef`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolDef) · [`weft.ErrDuplicateTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrDuplicateTool) · [`weft.ErrNilTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrNilTool) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`Agent.Tools`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Tools) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Manifest) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
