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 src/locus/tools/decorator.py
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 383 | |
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:~locus.control.policy.ControlPolicy label sets
such as require_sandbox_for by governance hooks like
:class:~locus.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:locus.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:locus.tools.computer.
emits_progress
class-attribute
instance-attribute
¶
When True, the agent runtime streams progress this tool reports
(:func:locus.tools.context.report_progress, or an MCP server's
notifications/progress) as live
:class:~locus.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 src/locus/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 src/locus/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 src/locus/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).
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 src/locus/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 src/locus/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 src/locus/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 src/locus/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 src/locus/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 src/locus/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 src/locus/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 src/locus/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 src/locus/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 src/locus/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 src/locus/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
|
|
Source code in src/locus/tools/builtins.py
OCI tools¶
Agents that drive Oracle Cloud Infrastructure: use_oci runs a read-only
OCI CLI / SDK operation and describe_oci explains a resource. Both need
the oci extra. See the OCI tools notebook.
use_oci ¶
use_oci(service: str, client: str, operation: str, parameters: dict[str, Any] | None = None, compartment_id: str | None = None, region: str | None = None, profile: str = 'DEFAULT', auth_type: str = 'api_key', label: str = '', allow_mutations: bool = False) -> dict[str, Any]
Call any operation on any OCI service via the OCI Python SDK.
This is a single open-specification tool that dispatches to the full OCI control plane. Pick the service module, the client class inside it, the operation (SDK method name), and the parameters — the tool builds the right client with auth, invokes the method, and returns the serialized response.
Read-only by default. Mutating operations (anything that isn't a
list/get/head/summarize/preview/validate/test/search/describe/fetch/
compute_) are refused unless allow_mutations=True is passed
explicitly, or the LOCUS_USE_OCI_ALLOW_MUTATIONS=1 env var
is set. This is intentional — the model will sometimes pick a
mutating verb when a read would do.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
str
|
OCI service module under |
required |
client
|
str
|
Client class inside that module (CamelCase, ends in
|
required |
operation
|
str
|
SDK method name in snake_case — mirrors the REST
operation id. Examples: |
required |
parameters
|
dict[str, Any] | None
|
Keyword arguments to pass to the operation. For
list/get calls this is typically |
None
|
compartment_id
|
str | None
|
Convenience — if the operation accepts
|
None
|
region
|
str | None
|
OCI region (e.g. |
None
|
profile
|
str
|
|
'DEFAULT'
|
auth_type
|
str
|
One of |
'api_key'
|
label
|
str
|
Free-text hint describing the user-facing intent of the call. Surfaces in logs and traces — not sent to OCI. |
''
|
allow_mutations
|
bool
|
Explicit opt-in to run a write operation
(anything that isn't |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict with |
dict[str, Any]
|
|
dict[str, Any]
|
serialized response) or |
Examples:
List every compartment in a tenancy::
use_oci(
service="identity",
client="IdentityClient",
operation="list_compartments",
parameters={
"compartment_id": "ocid1.tenancy.oc1..xxx",
"compartment_id_in_subtree": True,
},
profile="DEFAULT",
)
Get one Autonomous Database::
use_oci(
service="database",
client="DatabaseClient",
operation="get_autonomous_database",
parameters={"autonomous_database_id": "ocid1.autonomousdatabase..."},
region="ca-toronto-1",
)
Free-form search across all resources in a compartment::
use_oci(
service="resource_search",
client="ResourceSearchClient",
operation="search_resources",
parameters={
"search_details": {
"type": "Structured",
"query": "query all resources where compartmentId = '...'",
}
},
)
Source code in src/locus/tools/oci.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | |
describe_oci ¶
describe_oci(service: str | None = None, client: str | None = None, operation: str | None = None) -> dict[str, Any]
Introspect the OCI Python SDK — discover services, clients, operations, params.
Use this before use_oci whenever you're unsure what shape the
call needs to take. It progressively zooms in:
- No args: list every service module under
oci.*(~190 of them). serviceonly: list every*Clientclass inside that service.service+client: list every operation (method) on that client, separated into read-only and mutating.service+client+operation: return the operation's parameter schema — name, type, required/optional, description — parsed from the OCI SDK docstring, plus a snippet of the human description and whether the operation is read-only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
str | None
|
Snake-case service module name (e.g. |
None
|
client
|
str | None
|
CamelCase client class name (e.g. |
None
|
operation
|
str | None
|
Snake-case operation name (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict whose shape depends on how deep you drilled. Always |
dict[str, Any]
|
includes |
Examples:
Discover all services::
describe_oci()
# {"status": "ok", "level": "services", "services": ["access_governance_cp", ...]}
Find clients in a service::
describe_oci(service="core")
# {"status": "ok", "level": "clients",
# "clients": ["BlockstorageClient", "ComputeClient", "VirtualNetworkClient"]}
See operation parameter schema::
describe_oci(
service="identity",
client="IdentityClient",
operation="list_compartments",
)
# {"status": "ok", "level": "operation",
# "read_only": True,
# "parameters": [
# {"name": "compartment_id", "type": "str", "required": True, ...},
# {"name": "compartment_id_in_subtree", "type": "bool", ...},
# ...
# ]}
Source code in src/locus/tools/oci.py
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 | |