Define tools at runtime: RawTool and ToolSource
weft.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 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:
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 })The model sees the schema as written, enum included, and the handler checks its own input.
How it works
Section titled “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, 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
Section titled “Register a tool from a JSON Schema”weft.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 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:
schema sent: {"properties":{"format":{"description":"the export format","enum":["pdf","csv"],"type":"string"}},"required":["format"],"type":"object"}property type: stringThe 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 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:
step 0 (error: true): format "xml" is not pdf or csvstep 1 (error: false): exported as csvA 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).
Serve tools that change during a run
Section titled “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:
reg := ®istry{}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))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:
step 0 refund (error: true): NO_SUCH_TOOL: no tool named "refund"step 0 install_billing (error: false): billing plugin installedstep 1 refund (error: false): refunded 1234agent.Tools(): 0A 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 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 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
Section titled “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 or weft.ErrNilTool:
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)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 1Both are run errors, a *weft.RunError with the partial transcript on .Result, and match with errors.Is (rule 1). 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 function returns is checked by the same rule.
Complete example
Section titled “Complete example”dynamictools/main.go runs each region against a scripted model:
// 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 := ®istry{} 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) }}View on GitHub · run it from docs-site/examples:
go run ./dynamictoolsgo test ./dynamictools== raw toolschema sent: {"properties":{"format":{"description":"the export format","enum":["pdf","csv"],"type":"string"}},"required":["format"],"type":"object"}property type: stringstep 0 (error: true): format "xml" is not pdf or csvstep 1 (error: false): exported as csv== tool sourcestep 0 refund (error: true): NO_SUCH_TOOL: no tool named "refund"step 0 install_billing (error: false): billing plugin installedstep 1 refund (error: false): refunded 1234agent.Tools(): 0== bad snapshottrue 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 1Best practices & gotchas
Section titled “Best practices & gotchas”- Validate arguments in a
RawToolhandler. The loop does not decode them andStrictInputdoes not apply. (Source:weft/core/tool.go:403-410) - Parse foreign schemas with
ParseSchema, not by hand. It keeps the bytes whole, so keywordsSchemahas no field for reach the model on openai and anthropic. On google,oneOf,$refand the other keywords Gemini lacks are dropped (the table). (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_outputfrom the source of anOutput[T]agent. It is not added for you: a source that leaves it out makes the model’s submission readNO_SUCH_TOOL: no tool named "submit_output", andGenerateAsreturnsErrNoOutput. Append thesubmit_outputentry ofagt.Tools(), which reports it beside a source. (Source:weft/core/agent.go:802-809, 902-911; structured output) - Change the tool list deliberately.
ToolSourceandPrepareStepare the two knobs that can break a prompt-cache prefix. (Source:weft/core/agent.go:174-175) - Do not expect a mutation after
Newto reach the agent. Registered tools are deep-copied atNew;Agent.Toolsreturns copies. (Source:weft/core/tool.go:22-25, CHANGELOG 0.2.0)
See also
Section titled “See also”- How do tools work?
- Use MCP both ways
- Rewrite the request each step (PrepareStep)
- Set per-tool policy
- Describe your agents in weft.json
Symbols used: weft.RawTool · weft.ParseSchema · weft.Schema · Schema.MarshalJSON · weft.ToolSource · weft.ToolDef · weft.ErrDuplicateTool · weft.ErrNilTool · weft.RunError · Agent.Tools · Agent.CallTool · weft.Manifest · weft.Tool · weft.New · wefttest.Script