Tools¶
Define the functions an agent can call — the @tool decorator,
execution strategies, and JSON Schema generation.
For the concepts, start with Tools.
Decorator¶
The primary entry point — wrap a Python function and you get a Tool
the agent can call. Parameters are introspected from the type hints
and the JSON Schema is generated automatically.
tool ¶
tool(fn: Callable[P, R] | None = None, *, name: str | None = None, description: str | None = None, idempotent: bool = False, labels: Iterable[str] | None = None, sandbox: SandboxSpec | ToolSandbox | str | bool | None = None, deferred: bool = False, emits_progress: bool = False) -> Tool | Callable[[Callable[P, R]], Tool]
Decorator to create a tool from a function.
Usage
@tool def search(query: str) -> str: '''Search the knowledge base.''' return "results..."
@tool(name="custom_name", description="Custom description") def my_tool(x: int) -> int: return x * 2
@tool(idempotent=True) def open_incident(alert_id: str, severity: str) -> dict: '''Open an incident — safe to mark idempotent because repeated calls for the same alert would open duplicate incidents, which we never want.''' ...
@tool(sandbox=True, labels={"code-exec"}) def run_snippet(source: str) -> dict: '''Evaluate a snippet — runs in an isolated box, never in the host process. Self-contained: imports live inside the body.''' import ast return {"parsed": ast.dump(ast.parse(source))}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[P, R] | None
|
The function to wrap |
None
|
name
|
str | None
|
Override tool name (defaults to function name) |
None
|
description
|
str | None
|
Override description (defaults to docstring) |
None
|
idempotent
|
bool
|
If True, the ReAct loop deduplicates calls with matching (name, arguments) within a single agent run. Prevents duplicate side-effects when a model re-issues a tool call it has already made this turn. |
False
|
labels
|
Iterable[str] | None
|
Policy-matching labels the tool declares; matched against
:class: |
None
|
sandbox
|
SandboxSpec | ToolSandbox | str | bool | None
|
Run the tool in an isolated box instead of the host
process. |
None
|
emits_progress
|
bool
|
Stream the progress this tool reports with
:func: |
False
|
Returns:
| Type | Description |
|---|---|
Tool | Callable[[Callable[P, R]], Tool]
|
Tool instance |
Source code in .sdk/src/tulip/tools/decorator.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | |
Tool ¶
Bases: BaseModel
A tool that can be called by agents.
Created via the @tool decorator.
idempotent
class-attribute
instance-attribute
¶
When True, the ReAct loop deduplicates calls: if the model emits the same (tool_name, arguments) combination that has already been executed earlier in the current agent run, the prior result is reused and the tool function is not invoked again. Use for tools that either have side-effects you don't want duplicated (bookings, transfers, writes) or whose output is stable across the run (config/date lookups).
labels
class-attribute
instance-attribute
¶
Policy-matching labels this tool declares (e.g. {"code-exec"}).
Matched against :class:~tulip.control.policy.ControlPolicy label sets
such as require_sandbox_for by governance hooks like
:class:~tulip.tools.sandbox.SandboxEnforcerHook.
sandbox
class-attribute
instance-attribute
¶
When set, :meth:execute ships the function's source into the
configured sandbox and runs it there — the host process never executes
the body. The function must be self-contained: synchronous, imports
inside its body, JSON-serializable arguments and return value, and no
ctx/context parameter. See :mod:tulip.tools.sandbox.
deferred
class-attribute
instance-attribute
¶
When True, the tool's schema is NOT sent to the model until it is
activated — the model reaches it through the tool_search builtin
(auto-registered when any deferred tool exists). Deferral is a context
economy: only visibility changes. The tool is registered, gated, and
policy-matched exactly as an eager tool; activating it adds its schema
to the next model call, nothing more (#177).
native
class-attribute
instance-attribute
¶
Provider-native definitions of this tool, keyed by adapter
("anthropic", "openai_responses"). An adapter that finds its key
sends that definition instead of the function schema; the others keep
using :attr:parameters. Keys starting with _ are directives to the
adapter (a beta header, a request option) and are never sent as part of
the tool. See :mod:tulip.tools.computer.
emits_progress
class-attribute
instance-attribute
¶
When True, the agent runtime streams progress this tool reports
(:func:tulip.tools.context.report_progress, or an MCP server's
notifications/progress) as live
:class:~tulip.core.events.ToolProgressEvent s while the call runs.
Tools created from an MCP server set it.
output_schema
class-attribute
instance-attribute
¶
JSON Schema of the structured content the tool returns, when it
declares one (an MCP tool's outputSchema). Informational: it is not
sent to the model and does not change how the result is handled.
func
property
¶
Alias for :attr:fn. Some samples and downstream code reach
for .func (the LangChain/LangGraph idiom); keep both names
pointed at the same underlying callable so users don't have to
write getattr(t, 'fn', None) or getattr(t, 'func', t).
execute
async
¶
Execute the tool with given arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
ToolContext | None
|
Optional tool context (injected if function accepts it) |
None
|
**kwargs
|
Any
|
Tool arguments |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Tool result |
Source code in .sdk/src/tulip/tools/decorator.py
to_openai_schema ¶
Get OpenAI-compatible tool schema.
A tool with :attr:native definitions carries them under a top-level
native key for the adapters that understand it.
Source code in .sdk/src/tulip/tools/decorator.py
__call__ ¶
Direct invocation of the tool.
A sandboxed tool is sandboxed here too — direct calls are not a bypass. The recovered (JSON round-tripped) value is returned raw, mirroring a plain function call.
Source code in .sdk/src/tulip/tools/decorator.py
Tool context¶
Inject per-call context (the agent's state, custom metadata, the
hook orchestrator) into a tool by declaring a ToolContext parameter.
ToolContext ¶
Bases: BaseModel
Context passed to tools during execution.
Provides access to agent state, metadata, and utilities.
get_metadata ¶
Get a metadata value (ephemeral metadata included).
Source code in .sdk/src/tulip/tools/context.py
Registry¶
The agent's compiled tool collection. Built once during
Agent.__init__; mutating config.tools directly afterwards has no
effect (use Agent.add_tool / add_tools instead).
ToolRegistry ¶
Bases: BaseModel
Registry for managing available tools.
Handles tool registration, lookup, and schema generation.
activated
class-attribute
instance-attribute
¶
Names of deferred tools whose schemas have been surfaced to the model
(via tool_search or :meth:activate). Deferral is visibility only:
an unactivated deferred tool is still registered, still executable, and
still gated — it just costs no context until the model asks for it.
register ¶
register_many ¶
unregister ¶
get ¶
get_or_raise ¶
Get a tool by name, raising if not found.
Source code in .sdk/src/tulip/tools/registry.py
list_tools ¶
to_openai_schemas ¶
Schemas for the tools the model may currently see.
Eager tools always; deferred tools only once activated. This is the single choke point the run loop reads, so deferral needs no loop changes — an unactivated deferred tool simply never reaches the request payload (#177).
Source code in .sdk/src/tulip/tools/registry.py
deferred_pending ¶
Deferred tools whose schemas the model has not been shown yet.
activate ¶
Surface a deferred tool's schema to subsequent model calls.
Activation changes visibility and nothing else — gating, labels and
sandbox requirements ride on the Tool object and were in force the
whole time. Raises KeyError for an unknown name; activating an
eager or already-active tool is a no-op.
Source code in .sdk/src/tulip/tools/registry.py
search ¶
Rank deferred, not-yet-activated tools against a keyword query.
Deliberately boring lexical scoring (token overlap on name and description, substring bonus): deterministic, offline, and cheap — the model supplies the intelligence; this just narrows the catalog.
Source code in .sdk/src/tulip/tools/registry.py
__contains__ ¶
__len__ ¶
Executors¶
The strategy the agent uses to run a batch of tool calls. The default
is ConcurrentExecutor (parallel up to max_concurrency);
SequentialExecutor runs them one at a time for tools that share
non-thread-safe state.
ToolExecutor ¶
Bases: BaseModel, ABC
Base class for tool execution strategies.
Subclasses implement different execution patterns (sequential, concurrent, rate-limited, etc.)
execute
abstractmethod
async
¶
execute(tool_calls: list[ToolCall], registry: ToolRegistry, ctx_factory: ToolContextFactory | None = None) -> list[ToolResult]
Execute a batch of tool calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[ToolCall]
|
Tool calls to execute |
required |
registry
|
ToolRegistry
|
Tool registry to look up tools |
required |
ctx_factory
|
ToolContextFactory | None
|
Optional factory for creating tool contexts |
None
|
Returns:
| Type | Description |
|---|---|
list[ToolResult]
|
List of tool results |
Source code in .sdk/src/tulip/tools/executor.py
execute_streaming
async
¶
execute_streaming(tool_calls: list[ToolCall], registry: ToolRegistry, ctx_factory: ToolContextFactory | None = None) -> AsyncIterator[tuple[int, ToolResult]]
Yield (input_index, result) as each tool call completes.
The default implementation falls back to :meth:execute and yields
in input order — fine for executors with no useful streaming
semantics (sequential, single-shot rate-limited). Concurrent
executors override this to stream results in completion order.
Breaking out of the consumer async for (or raising inside its
body) must cancel any tasks the executor has in flight. Concrete
implementations are responsible for that guarantee — the runtime
loop relies on it for interrupt-driven sibling cancellation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[ToolCall]
|
Tool calls to execute. |
required |
registry
|
ToolRegistry
|
Tool registry to look up tools. |
required |
ctx_factory
|
ToolContextFactory | None
|
Optional factory for creating tool contexts. |
None
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[tuple[int, ToolResult]]
|
Tuples of |
AsyncIterator[tuple[int, ToolResult]]
|
for concurrent executors, input order for sequential ones. |
Source code in .sdk/src/tulip/tools/executor.py
ConcurrentExecutor ¶
Bases: ToolExecutor
Execute tools concurrently with optional concurrency limit.
execute
async
¶
execute(tool_calls: list[ToolCall], registry: ToolRegistry, ctx_factory: ToolContextFactory | None = None) -> list[ToolResult]
Execute tools concurrently.
Source code in .sdk/src/tulip/tools/executor.py
execute_streaming
async
¶
execute_streaming(tool_calls: list[ToolCall], registry: ToolRegistry, ctx_factory: ToolContextFactory | None = None) -> AsyncIterator[tuple[int, ToolResult]]
Yield (input_index, result) in completion order.
Fan out one asyncio.Task per tool call (bounded by
max_concurrency via a shared semaphore). Results land on a
queue as they finish; the consumer iterates the queue and sees
events in completion order. If the consumer breaks early or
raises inside the async for body, the finally cancels
every still-in-flight task — that's how the runtime loop
propagates an interrupt to siblings.
We deliberately use create_task + a stop-marker pattern
instead of asyncio.TaskGroup: TaskGroup blocks __aexit__
on every task finishing, which deadlocks the streaming consumer
when a producer is cancelled (the cancelled task never puts on
the queue, so the consumer's queue.get() blocks forever).
The per-task finally here unconditionally posts a
stop-marker so the consumer always learns when each task is
done, even on cancellation.
Source code in .sdk/src/tulip/tools/executor.py
SequentialExecutor ¶
Bases: ToolExecutor
Execute tools one at a time.
execute
async
¶
execute(tool_calls: list[ToolCall], registry: ToolRegistry, ctx_factory: ToolContextFactory | None = None) -> list[ToolResult]
Execute tools sequentially.
Source code in .sdk/src/tulip/tools/executor.py
execute_streaming
async
¶
execute_streaming(tool_calls: list[ToolCall], registry: ToolRegistry, ctx_factory: ToolContextFactory | None = None) -> AsyncIterator[tuple[int, ToolResult]]
Yield (input_index, result) per call as it finishes.
Sequential execution means input order == completion order; this impl exists so the runtime loop can treat both executors through the same streaming interface. Breaking from the consumer simply stops further calls — there are no siblings to cancel.
Source code in .sdk/src/tulip/tools/executor.py
Schema generation¶
JSON Schema generation from Python type hints / Pydantic models —
used by the @tool decorator but also callable directly when you
need a schema for an external system (e.g. an MCP server).
generate_schema ¶
Generate OpenAI-compatible tool schema from a function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[..., Any]
|
The function to generate schema for |
required |
description
|
str | None
|
Override description (uses docstring if not provided) |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Tool schema in OpenAI function format |
Source code in .sdk/src/tulip/tools/schema.py
pydantic_to_json_schema ¶
Built-in tools¶
get_today_date ¶
Return today's date plus common reference points for date arithmetic.
Call this whenever the user mentions a relative or partial date ("tomorrow", "next Monday", "in ten days", "April 20") so you can convert to an explicit YYYY-MM-DD before calling a date-sensitive tool.
Returns:
| Type | Description |
|---|---|
dict
|
A dict with: |
dict
|
|
dict
|
|
dict
|
|
dict
|
|
dict
|
|
dict
|
|