strands.tools.decorator
¶
Tool decorator for SDK.
This module provides the @tool decorator that transforms Python functions into SDK Agent tools with automatic metadata extraction and validation.
The @tool decorator performs several functions:
- Extracts function metadata (name, description, parameters) from docstrings and type hints
- Generates a JSON schema for input validation
- Handles two different calling patterns:
- Standard function calls (func(arg1, arg2))
- Tool use calls (agent.my_tool(param1="hello", param2=123))
- Provides error handling and result formatting
- Works with both standalone functions and class methods
Example
from strands import Agent, tool
@tool
def my_tool(param1: str, param2: int = 42) -> dict:
'''
Tool description - explain what it does.
#Args:
param1: Description of first parameter.
param2: Description of second parameter (default: 42).
#Returns:
A dictionary with the results.
'''
result = do_something(param1, param2)
return {
"status": "success",
"content": [{"text": f"Result: {result}"}]
}
agent = Agent(tools=[my_tool])
agent.tool.my_tool(param1="hello", param2=123)
JSONSchema = dict
module-attribute
¶
Type alias for JSON Schema dictionaries.
P = ParamSpec('P')
module-attribute
¶
R = TypeVar('R')
module-attribute
¶
T = TypeVar('T', bound=(Callable[..., Any]))
module-attribute
¶
ToolGenerator = AsyncGenerator[Any, None]
module-attribute
¶
Generator of tool events with the last being the tool result.
logger = logging.getLogger(__name__)
module-attribute
¶
AgentTool
¶
Bases: ABC
Abstract base class for all SDK tools.
This class defines the interface that all tool implementations must follow. Each tool must provide its name, specification, and implement a stream method that executes the tool's functionality.
Source code in strands/types/tools.py
218 219 220 221 222 223 224 225 226 227 228 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 | |
is_dynamic
property
¶
Whether the tool was dynamically loaded during runtime.
Dynamic tools may have different lifecycle management.
Returns:
| Type | Description |
|---|---|
bool
|
True if loaded dynamically, False otherwise. |
supports_hot_reload
property
¶
Whether the tool supports automatic reloading when modified.
Returns:
| Type | Description |
|---|---|
bool
|
False by default. |
tool_name
abstractmethod
property
¶
The unique name of the tool used for identification and invocation.
tool_spec
abstractmethod
property
¶
Tool specification that describes its functionality and parameters.
tool_type
abstractmethod
property
¶
The type of the tool implementation (e.g., 'python', 'javascript', 'lambda').
Used for categorization and appropriate handling.
__init__()
¶
Initialize the base agent tool with default dynamic state.
Source code in strands/types/tools.py
227 228 229 | |
get_display_properties()
¶
Get properties to display in UI representations of this tool.
Subclasses can extend this to include additional properties.
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Dictionary of property names and their string values. |
Source code in strands/types/tools.py
295 296 297 298 299 300 301 302 303 304 305 306 | |
mark_dynamic()
¶
Mark this tool as dynamically loaded.
Source code in strands/types/tools.py
291 292 293 | |
stream(tool_use, invocation_state, **kwargs)
abstractmethod
¶
Stream tool events and return the final result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_use
|
ToolUse
|
The tool use request containing tool ID and parameters. |
required |
invocation_state
|
dict[str, Any]
|
Caller-provided kwargs that were passed to the agent when it was invoked (agent(), agent.invoke_async(), etc.). |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Yields:
| Type | Description |
|---|---|
ToolGenerator
|
Tool events with the last being the tool result. |
Source code in strands/types/tools.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
DecoratedFunctionTool
¶
Bases: AgentTool, Generic[P, R]
An AgentTool that wraps a function that was decorated with @tool.
This class adapts Python functions decorated with @tool to the AgentTool interface. It handles both direct function calls and tool use invocations, maintaining the function's original behavior while adding tool capabilities.
The class is generic over the function's parameter types (P) and return type (R) to maintain type safety.
Source code in strands/tools/decorator.py
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 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 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 | |
supports_hot_reload
property
¶
Check if this tool supports automatic reloading when modified.
Returns:
| Type | Description |
|---|---|
bool
|
Always true for function-based tools. |
tool_name
property
¶
Get the name of the tool.
Returns:
| Type | Description |
|---|---|
str
|
The tool name as a string. |
tool_spec
property
¶
Get the tool specification.
Returns:
| Type | Description |
|---|---|
ToolSpec
|
The tool specification dictionary containing metadata for Agent integration. |
tool_type
property
¶
Get the type of the tool.
Returns:
| Type | Description |
|---|---|
str
|
The string "function" indicating this is a function-based tool. |
__call__(*args, **kwargs)
¶
Call the original function with the provided arguments.
This method enables the decorated function to be called directly with its original signature, preserving the normal function call behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
args
|
Positional arguments to pass to the function. |
()
|
**kwargs
|
kwargs
|
Keyword arguments to pass to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
R
|
The result of the original function call. |
Source code in strands/tools/decorator.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 | |
__get__(instance, obj_type=None)
¶
Descriptor protocol implementation for proper method binding.
This method enables the decorated function to work correctly when used as a class method. It binds the instance to the function call when accessed through an instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
Any
|
The instance through which the descriptor is accessed, or None when accessed through the class. |
required |
obj_type
|
Optional[Type]
|
The class through which the descriptor is accessed. |
None
|
Returns:
| Type | Description |
|---|---|
DecoratedFunctionTool[P, R]
|
A new DecoratedFunctionTool with the instance bound to the function if accessed through an instance, |
DecoratedFunctionTool[P, R]
|
otherwise returns self. |
Example
class MyClass:
@tool
def my_tool():
...
instance = MyClass()
# instance of DecoratedFunctionTool that works as you'd expect
tool = instance.my_tool
Source code in strands/tools/decorator.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | |
__init__(tool_name, tool_spec, tool_func, metadata)
¶
Initialize the decorated function tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_name
|
str
|
The name to use for the tool (usually the function name). |
required |
tool_spec
|
ToolSpec
|
The tool specification containing metadata for Agent integration. |
required |
tool_func
|
Callable[P, R]
|
The original function being decorated. |
required |
metadata
|
FunctionToolMetadata
|
The FunctionToolMetadata object with extracted function information. |
required |
Source code in strands/tools/decorator.py
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | |
get_display_properties()
¶
Get properties to display in UI representations.
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Function properties (e.g., function name). |
Source code in strands/tools/decorator.py
651 652 653 654 655 656 657 658 659 660 | |
stream(tool_use, invocation_state, **kwargs)
async
¶
Stream the tool with a tool use specification.
This method handles tool use streams from a Strands Agent. It validates the input, calls the function, and formats the result according to the expected tool result format.
Key operations:
- Extract tool use ID and input parameters
- Validate input against the function's expected parameters
- Call the function with validated input
- Format the result as a standard tool result
- Handle and format any errors that occur
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_use
|
ToolUse
|
The tool use specification from the Agent. |
required |
invocation_state
|
dict[str, Any]
|
Caller-provided kwargs that were passed to the agent when it was invoked (agent(), agent.invoke_async(), etc.). |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Yields:
| Type | Description |
|---|---|
ToolGenerator
|
Tool events with the last being the tool result. |
Source code in strands/tools/decorator.py
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 | |
FunctionToolMetadata
¶
Helper class to extract and manage function metadata for tool decoration.
This class handles the extraction of metadata from Python functions including:
- Function name and description from docstrings
- Parameter names, types, and descriptions
- Return type information
- Creation of Pydantic models for input validation
The extracted metadata is used to generate a tool specification that can be used by Strands Agent to understand and validate tool usage.
Source code in strands/tools/decorator.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 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 | |
__init__(func, context_param=None)
¶
Initialize with the function to process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
The function to extract metadata from. Can be a standalone function or a class method. |
required |
context_param
|
str | None
|
Name of the context parameter to inject, if any. |
None
|
Source code in strands/tools/decorator.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | |
extract_metadata()
¶
Extract metadata from the function to create a tool specification.
This method analyzes the function to create a standardized tool specification that Strands Agent can use to understand and interact with the tool.
The specification includes:
- name: The function name (or custom override)
- description: The function's docstring description (excluding Args)
- inputSchema: A JSON schema describing the expected parameters
Returns:
| Type | Description |
|---|---|
ToolSpec
|
A dictionary containing the tool specification. |
Source code in strands/tools/decorator.py
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 | |
inject_special_parameters(validated_input, tool_use, invocation_state)
¶
Inject special framework-provided parameters into the validated input.
This method automatically provides framework-level context to tools that request it through their function signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validated_input
|
dict[str, Any]
|
The validated input parameters (modified in place). |
required |
tool_use
|
ToolUse
|
The tool use request containing tool invocation details. |
required |
invocation_state
|
dict[str, Any]
|
Caller-provided kwargs that were passed to the agent when it was invoked (agent(), agent.invoke_async(), etc.). |
required |
Source code in strands/tools/decorator.py
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |
validate_input(input_data)
¶
Validate input data using the Pydantic model.
This method ensures that the input data meets the expected schema before it's passed to the actual function. It converts the data to the correct types when possible and raises informative errors when not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_data
|
dict[str, Any]
|
A dictionary of parameter names and values to validate. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with validated and converted parameter values. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input data fails validation, with details about what failed. |
Source code in strands/tools/decorator.py
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 | |
InterruptException
¶
Bases: Exception
Exception raised when human input is required.
Source code in strands/interrupt.py
32 33 34 35 36 37 | |
__init__(interrupt)
¶
Set the interrupt.
Source code in strands/interrupt.py
35 36 37 | |
ToolContext
dataclass
¶
Bases: _Interruptible
Context object containing framework-provided data for decorated tools.
This object provides access to framework-level information that may be useful for tool implementations.
Attributes:
| Name | Type | Description |
|---|---|---|
tool_use |
ToolUse
|
The complete ToolUse object containing tool invocation details. |
agent |
Any
|
The Agent or BidiAgent instance executing this tool, providing access to conversation history, model configuration, and other agent state. |
invocation_state |
dict[str, Any]
|
Caller-provided kwargs that were passed to the agent when it was invoked (agent(), agent.invoke_async(), etc.). |
Note
This class is intended to be instantiated by the SDK. Direct construction by users is not supported and may break in future versions as new fields are added.
Source code in strands/types/tools.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
ToolInterruptEvent
¶
Bases: TypedEvent
Event emitted when a tool is interrupted.
Source code in strands/types/_events.py
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
interrupts
property
¶
The interrupt instances.
tool_use_id
property
¶
The id of the tool interrupted.
__init__(tool_use, interrupts)
¶
Set interrupt in the event payload.
Source code in strands/types/_events.py
346 347 348 | |
ToolResult
¶
Bases: TypedDict
Result of a tool execution.
Attributes:
| Name | Type | Description |
|---|---|---|
content |
list[ToolResultContent]
|
List of result content returned by the tool. |
status |
ToolResultStatus
|
The status of the tool execution ("success" or "error"). |
toolUseId |
str
|
The unique identifier of the tool use request that produced this result. |
Source code in strands/types/tools.py
87 88 89 90 91 92 93 94 95 96 97 98 | |
ToolResultEvent
¶
Bases: TypedEvent
Event emitted when a tool execution completes.
Source code in strands/types/_events.py
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 | |
tool_result
property
¶
Final result from the completed tool execution.
tool_use_id
property
¶
The toolUseId associated with this result.
__init__(tool_result)
¶
Initialize with the completed tool result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_result
|
ToolResult
|
Final result from the tool execution |
required |
Source code in strands/types/_events.py
278 279 280 281 282 283 284 | |
ToolSpec
¶
Bases: TypedDict
Specification for a tool that can be used by an agent.
Attributes:
| Name | Type | Description |
|---|---|---|
description |
str
|
A human-readable description of what the tool does. |
inputSchema |
JSONSchema
|
JSON Schema defining the expected input parameters. |
name |
str
|
The unique name of the tool. |
outputSchema |
NotRequired[JSONSchema]
|
Optional JSON Schema defining the expected output format. Note: Not all model providers support this field. Providers that don't support it should filter it out before sending to their API. |
Source code in strands/types/tools.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
ToolStreamEvent
¶
Bases: TypedEvent
Event emitted when a tool yields sub-events as part of tool execution.
Source code in strands/types/_events.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
tool_use_id
property
¶
The toolUseId associated with this stream.
__init__(tool_use, tool_stream_data)
¶
Initialize with tool streaming data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_use
|
ToolUse
|
The tool invocation producing the stream |
required |
tool_stream_data
|
Any
|
The yielded event from the tool execution |
required |
Source code in strands/types/_events.py
305 306 307 308 309 310 311 312 | |
ToolUse
¶
Bases: TypedDict
A request from the model to use a specific tool with the provided input.
Attributes:
| Name | Type | Description |
|---|---|---|
input |
Any
|
The input parameters for the tool. Can be any JSON-serializable type. |
name |
str
|
The name of the tool to invoke. |
toolUseId |
str
|
A unique identifier for this specific tool use request. |
Source code in strands/types/tools.py
52 53 54 55 56 57 58 59 60 61 62 63 64 | |
tool(func=None, description=None, inputSchema=None, name=None, context=False)
¶
tool(__func: Callable[P, R]) -> DecoratedFunctionTool[P, R]
tool(
description: Optional[str] = None,
inputSchema: Optional[JSONSchema] = None,
name: Optional[str] = None,
context: bool | str = False,
) -> Callable[
[Callable[P, R]], DecoratedFunctionTool[P, R]
]
Decorator that transforms a Python function into a Strands tool.
This decorator seamlessly enables a function to be called both as a regular Python function and as a Strands tool. It extracts metadata from the function's signature, docstring, and type hints to generate an OpenAPI-compatible tool specification.
When decorated, a function:
- Still works as a normal function when called directly with arguments
- Processes tool use API calls when provided with a tool use dictionary
- Validates inputs against the function's type hints and parameter spec
- Formats return values according to the expected Strands tool result format
- Provides automatic error handling and reporting
The decorator can be used in two ways:
- As a simple decorator: @tool
- With parameters: @tool(name="custom_name", description="Custom description")
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Optional[Callable[P, R]]
|
The function to decorate. When used as a simple decorator, this is the function being decorated. When used with parameters, this will be None. |
None
|
description
|
Optional[str]
|
Optional custom description to override the function's docstring. |
None
|
inputSchema
|
Optional[JSONSchema]
|
Optional custom JSON schema to override the automatically generated schema. |
None
|
name
|
Optional[str]
|
Optional custom name to override the function's name. |
None
|
context
|
bool | str
|
When provided, places an object in the designated parameter. If True, the param name defaults to 'tool_context', or if an override is needed, set context equal to a string to designate the param name. |
False
|
Returns:
| Type | Description |
|---|---|
Union[DecoratedFunctionTool[P, R], Callable[[Callable[P, R]], DecoratedFunctionTool[P, R]]]
|
An AgentTool that also mimics the original function when invoked |
Example
@tool
def my_tool(name: str, count: int = 1) -> str:
# Does something useful with the provided parameters.
#
# Parameters:
# name: The name to process
# count: Number of times to process (default: 1)
#
# Returns:
# A message with the result
return f"Processed {name} {count} times"
agent = Agent(tools=[my_tool])
agent.my_tool(name="example", count=3)
# Returns: {
# "toolUseId": "123",
# "status": "success",
# "content": [{"text": "Processed example 3 times"}]
# }
Example with parameters
@tool(name="custom_tool", description="A tool with a custom name and description", context=True)
def my_tool(name: str, count: int = 1, tool_context: ToolContext) -> str:
tool_id = tool_context["tool_use"]["toolUseId"]
return f"Processed {name} {count} times with tool ID {tool_id}"
Source code in strands/tools/decorator.py
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 | |