How @tool turns a typed Python function into a tool schema, which types are supported, how to describe parameters, and when to use parameters= or strict=.
Tools
A tool is a plain Python function decorated with @tool(). Dendrux reads the signature, type hints, and docstring once, at decoration time, and stores the result on a ToolDef. The function stays callable as normal.
from typing import Literal
from dendrux import tool
@tool()
async def show(kind: Literal["chart", "table"], title: str | None = None) -> str:
"""Render a chart or table in the UI.
Args:
kind: Which widget to render.
title: Optional heading shown above the widget.
"""
return f"rendered {kind}"The tool's description is the full docstring. The arguments schema is generated from the type hints.
Decorator options
Supported parameter types
Nested types compose. For example, list[Node] where Node is a BaseModel becomes an array of typed objects.
A parameter is required when it has no default and is not Optional. Defaults must be JSON-serializable and are emitted as "default".
Some types are rejected at decoration time with a TypeError that names the parameter:
- Unions other than
T | None, for examplestr | int LiteralorEnumvalues of mixed types, for exampleLiteral["a", 1]dictwith non-strkeys- Recursive models, dataclasses, or TypedDicts, because they cannot be inlined
- Any other custom class
For any of these, pass the schema yourself with parameters=.
Arguments are validated and coerced (0.5.0). A
BaseModelparameter receives the model instance, anEnumparameter receives the member, and values are converted to the annotated types. See How arguments are checked. Before 0.5.0 these arrived as plain JSON values (dict, raw value) and you had to validate them yourself.
Malformed arguments never reach your tool. If the model's arguments are not valid JSON, the call is rejected before parameter validation with
code: "invalid_json". The model sees the parse error and retries; the run does not fail, and the raw arguments are never persisted. See Tool argument validation.
Parameter descriptions
There are two ways to describe a parameter. If both are present for the same parameter, Annotated wins.
Annotated metadata: use either a pydantic Field(description=...) or a plain string.
from typing import Annotated
from pydantic import Field
@tool()
async def search(
query: Annotated[str, Field(description="Full-text search query")],
limit: Annotated[int, "Maximum number of results"] = 10,
) -> list[str]:
"""Search the catalog."""
...Google-style docstring Args: section: Dendrux reads lines of the form name: text and name (type): text. Indented continuation lines are joined to the line above. Entries for names that are not parameters are ignored. The docstring itself stays unchanged as the tool's description.
How arguments are checked
For a local @tool, each call goes through these steps in order, and a failure at any step returns an error to the model instead of running your function:
- The arguments string is parsed as JSON (
code: "invalid_json"on failure). deny=is applied.- PII placeholders are restored, if your PII guardrail and
restore=mode allow it for this tool. - The arguments are validated against the tool's JSON Schema. Integral floats such as
3.0are accepted forinteger. - They are coerced to the annotated types:
3.0becomes3, a dict becomes theBaseModel, dataclass orTypedDict, a string becomes theEnummember, an ISO 8601 string becomes adatetime, andField(...)constraints (ge,le,min_length,max_length,patternand so on) are enforced. The constraints also appear as keywords in the generated schema. max_calls_per_runis checked.before_toolruns.- If approval is needed, the run pauses.
- Your function runs.
Validation happens before the approval pause, so a person is never asked to approve a call that could not have run.
What a reviewer sees, and what runs. Your function is called with objects built from the coerced arguments, and before_tool receives real values in process. The approval view (approval.requested and any stored or displayed approval) carries the arguments exactly as the model sent them: after JSON parsing, in placeholder form when PII redaction is on, before coercion, and without injected defaults. Coercion is deterministic, so the approved arguments decide what runs.
from pydantic import BaseModel, Field
class Address(BaseModel):
city: str
zip: str = Field(pattern=r"^\d{5}$")
@tool()
async def ship(order_id: int, to: Address) -> str:
"""Ship an order."""
return f"{order_id} -> {to.city}" # `to` is an Address, not a dictDetails:
- Error messages name the field and the constraint that failed, never the value, so personal data cannot flow back to the model provider through an error. Dictionary keys and unknown argument names are not echoed either: a key shows as
<key>, and an unexpected top-level argument is reported as a count with the list of valid arguments (ship has 1 unknown argument. Valid arguments: order_id, to). A few Pydantic messages that quote the input (a bad discriminator tag, UUID, base64 or embedded JSON) are replaced with fixed text. - Arguments that cannot be stored are refused before any hook, approval or execution, for known, unknown and client tools alike: a string or key holding NUL or a lone surrogate, a non-finite number, or a structure too large to persist returns
code: "invalid_params"to the model. The message names the tool and the rule, never the content. - A tool whose own argument schema is malformed (for example
requiredthat is not a list of strings, includingrequired: null) returnscode: "invalid_tool_schema"instead of raising. The log line names the tool, not the schema. MCP tools with such a schema are skipped at discovery (see MCP). *argsand**kwargsare left out of the generated schema.- A tool with an explicit
parameters=schema keeps JSON Schema validation only. There is no coercion, and your function receives the plain JSON values. - MCP tools and client tools are not coerced: their arguments and results are unchanged from 0.4.
- Tool schemas are part of the prompt, so adding constraint keywords can change a prompt-cache key once, on the first request after you upgrade.
Timeouts and the thread pool
timeout_seconds bounds each server tool call. How a timeout behaves depends on whether the call had started:
Sync tools (plain def functions) run on one process-wide, bounded thread pool, created on first use. Size it with DENDRUX_TOOL_THREADS (default 32). Limit what one Agent can occupy with Agent(tool_threads=8) (default 8), so one agent or tenant cannot starve the others. Pool threads are daemon threads: a hung sync tool never blocks interpreter exit, but its side effect may be cut off at exit.
A sync tool that has timed out cannot be killed; it keeps its thread until it returns. Dendrux counts these and reports them in a log line and as zombie_threads on the tool.completed event. dendrux.tool_pool_stats() returns a snapshot (max_threads, threads, busy, queued, zombies) so you can export it as a gauge; restart the process if zombies keeps growing toward max_threads. Async tools are cancelled at the timeout.
Waiting calls are bounded too. Each Agent runs at most tool_threads tool calls at once, and at most 256 more may wait for a slot. A call that arrives when the queue is full is not started: the model gets a retryable code: "tool_pool_saturated" result and the tool never runs, so a burst of calls cannot build an unbounded backlog. Change the bound for the process with the DENDRUX_TOOL_QUEUE_LIMIT environment variable (a positive integer, read the first time a call has to wait). There is no Agent argument for it in 0.5.
If a parallel batch ends the run (a failure that stops the run), the async siblings are cancelled and recorded as cancelled; sibling sync tools that had already started are recorded with an unknown outcome.
Result size limits
A tool result larger than Limits.max_tool_result_bytes (1 MiB by default) is replaced before it is stored or sent to the model. A JSON result becomes {"error": "result too large", "code": "size_limit", "bytes": N}; a plain string result is truncated with a marker. The same cap applies to local, MCP and client-submitted results.
from dendrux import Agent, Limits
Agent(provider=provider, prompt="...", tools=[export_csv],
limits=Limits(max_tool_result_bytes=8 * 1024 * 1024))Return a summary, a count, or a file reference from the tool and let the model ask for more, rather than raising the cap. The other limits (max_input_bytes, max_metadata_bytes, max_notes_per_run) are on the Agent page.
Explicit schema: parameters=
When the generated schema does not fit, pass your own JSON Schema. Generation is skipped entirely and the schema is stored as given. The root must be a dict with "type": "object".
@tool(parameters={
"type": "object",
"properties": {"value": {"anyOf": [{"type": "string"}, {"type": "number"}]}},
"required": ["value"],
})
async def record(value) -> str:
"""Record a value."""
...Strict mode
@tool(strict=True) opts the tool into strict tool calling: OpenAI strict function calling and Anthropic strict tool use. With strict mode on, the provider constrains the model's arguments to the schema.
The schema is normalized once, at decoration time, and stored on ToolDef.parameters, so every provider sees the same schema:
- Every object gets
additionalProperties: false. - Every property becomes required.
Optionalparameters are already nullable, so the model can still passnull. - A parameter that has a non-
Nonedefault, such aslimit: int = 10, also becomes required. The model must then supply a value, and the default appears only as a"default"hint in the schema.
On the wire:
OpenAI strict mode requires every object to declare its properties. If a strict tool has a free-form dict or dict[str, T] parameter, the decorator raises TypeError. Use a BaseModel, dataclass, or TypedDict instead.
strict=True combines with parameters=: your explicit schema is normalized the same way. The decorator also rejects a free-form object under draft-7 definitions, the same as under $defs.
Strict mode on Anthropic
On Anthropic, Dendrux sends "strict": true and a per-request copy of the schema adapted to Anthropic's strict subset. ToolDef.parameters is not changed. Non-strict tools are sent exactly as before, byte for byte, so prompt caching is not affected.
The adapted copy:
- Gets
additionalProperties: falseon every object. - Keeps what the grammar can enforce:
enum,const,$ref, optional fields,minLength,maxLength, simplepatterns,minItemsof 0 or 1, and the standardformats (date-time,date,time,duration,email,hostname,uri,ipv4,ipv6,uuid). - Moves what Anthropic rejects into the field's
description, so the model still sees it: numeric bounds (minimum,maximum,exclusiveMinimum,exclusiveMaximum),multipleOf,maxItems,minItemsabove 1,uniqueItems, uncommonformats, and advanced regex features such as lookaround. A bound likeField(ge=1)becomes the text "Must be >= 1." in the description.
A constraint that was moved into the description is a hint to the model, not a grammar rule. If it matters, check it in your function.
Anthropic limits one request to 20 strict tools, 24 optional parameters and 16 union-typed parameters (X | None, anyOf) across all strict tools. Dendrux counts these in tool order. A tool is sent non-strict, with the reason logged on dendrux.llm.anthropic, when it:
- would go over a limit;
- has a free-form
dict, a tuple, anAnyfield or a recursive model.
A strict tool that is sent non-strict logs a WARNING once per tool name, then DEBUG.
If Anthropic still rejects a strict schema (its grammar compiler has size and regex limits that cannot be checked in advance), Dendrux retries that request once with every strict tool sent as before. It logs a WARNING and keeps sending that tool non-strict for the rest of the process. The retry applies to any HTTP 400 on a request that carried a strict tool; other errors are raised unchanged.
To turn strict mode off for a provider, pass strict=False:
from dendrux.llm.anthropic import AnthropicProvider
provider = AnthropicProvider(model="claude-sonnet-4-6", strict=False)Then tools and structured output are sent exactly as in 0.4.0. Use it when you point ANTHROPIC_BASE_URL at a gateway that rejects the strict field.
Data retention. Strict mode sends your tool schemas to Anthropic's grammar compiler, which caches them for up to 24 hours since last use. That cache is separate from prompts and responses, which keep their usual zero-data-retention and HIPAA handling. Do not put sensitive data such as PHI in property names, enum or const values, or patterns. If your schemas may contain it, use AnthropicProvider(..., strict=False). See Anthropic's strict tool use and structured outputs pages, under "Data retention".
Apps that already used @tool(strict=True) with Anthropic see one prompt-cache miss after upgrading to 0.4.1, because the tool payload now carries strict and the adapted schema.
When the model calls a tool that does not exist
The call does not run. The model gets a failed tool result that lists what it can call:
Unknown tool: bash. Available tools: read_file, write_fileNames are sorted and capped at 50, then , … and N more. If no tools were offered, the text is Unknown tool: bash. No tools are available. The Unknown tool: <name> prefix is stable. The rejection is recorded with code: "unknown_tool" on the result and the tool.completed event, and happens before before_tool and approval, so neither sees it. A name too long to store is not echoed back.
MCP tools
Tools discovered from MCP servers do not go through @tool. Their server-provided inputSchema is passed to the model unchanged, and strict mode does not apply to them.