Tools API Reference
Complete API reference for creating and managing tools in AA Kit.
Import Statement
from aakit import tool, async_tool, ToolRegistry, create_tool, validate_toolTool Decorator
Decorator for creating MCP-compatible tools from functions
@tool
@tool(
description: str = None,
parameters: Dict[str, Any] = None,
returns: str = None,
examples: List[str] = None,
tags: List[str] = None,
rate_limit: RateLimit = None,
cache: bool = True,
timeout: int = None
)Decorator to convert a function into an MCP tool
Parameters
description(str)- Tool description for the agentparameters(Dict[str, Any])- Parameter schema overridereturns(str)- Description of return valueexamples(List[str])- Usage examplestags(List[str])- Tool categorization tagsrate_limit(RateLimit)- Tool-specific rate limitingcache(bool)- Enable result cachingtimeout(int)- Execution timeout in secondsExample
@tool(
description="Search for information on the web",
returns="List of search results with titles and snippets",
tags=["search", "web"],
cache=True,
timeout=30
)
async def web_search(query: str, max_results: int = 5) -> List[Dict]:
"""
Search the web for information.
Args:
query: Search query string
max_results: Maximum number of results to return
Returns:
List of search results
"""
# Implementation here
return resultsTool Functions
Utility functions for working with tools
create_tool
def create_tool(
func: Callable,
name: str = None,
description: str = None,
**kwargs
) -> MCPToolCreate a tool from a function programmatically
Parameters
func(Callable)- The function to convertname(str)- Override the tool namedescription(str)- Tool description**kwargs(dict)- Additional tool configurationExample
def my_function(x: int) -> int:
return x * 2
tool = create_tool(
my_function,
name="doubler",
description="Doubles the input value"
)validate_tool
def validate_tool(tool: Union[Callable, MCPTool]) -> ValidationResultValidate a tool's schema and implementation
Parameters
tool(Union[Callable, MCPTool])- Tool to validateExample
result = validate_tool(my_tool)
if not result.is_valid:
print(f"Validation errors: {result.errors}")tool_from_openapi
def tool_from_openapi(
spec_url: str,
operation_id: str,
**kwargs
) -> MCPToolCreate a tool from an OpenAPI specification
Parameters
spec_url(str)- URL or path to OpenAPI specoperation_id(str)- Operation ID to convert**kwargs(dict)- Additional configurationExample
tool = tool_from_openapi(
"https://api.example.com/openapi.json",
"searchProducts"
)Tool Schema
Schema generation and manipulation
generate_schema
def generate_schema(func: Callable) -> Dict[str, Any]Generate MCP schema from function signature
Parameters
func(Callable)- Function to analyzeExample
def calculate(x: float, y: float, operation: str = "add") -> float:
"""Perform a calculation."""
pass
schema = generate_schema(calculate)
print(schema)
# Output: {
# "name": "calculate",
# "description": "Perform a calculation",
# "inputSchema": {
# "type": "object",
# "properties": {
# "x": {"type": "number"},
# "y": {"type": "number"},
# "operation": {"type": "string", "default": "add"}
# },
# "required": ["x", "y"]
# }
# }merge_schemas
def merge_schemas(base: Dict, override: Dict) -> DictMerge tool schemas with overrides
Parameters
base(Dict)- Base schemaoverride(Dict)- Override schemaExample
base_schema = generate_schema(my_func)
custom_schema = {
"properties": {
"x": {"description": "First number", "minimum": 0}
}
}
final_schema = merge_schemas(base_schema, custom_schema)Tool Registry
Managing collections of tools
ToolRegistry
class ToolRegistry:
def __init__(self, namespace: str = None)Registry for organizing and discovering tools
Parameters
namespace(str)- Optional namespace for toolsExample
registry = ToolRegistry("math_tools")
@registry.register
@tool(description="Add two numbers")
def add(x: float, y: float) -> float:
return x + y
# List all tools
tools = registry.list_tools()
# Get specific tool
add_tool = registry.get_tool("add")
# Export as MCP catalog
catalog = registry.to_mcp_catalog()discover_tools
def discover_tools(
module: Union[str, ModuleType],
pattern: str = "*"
) -> List[MCPTool]Automatically discover tools in a module
Parameters
module(Union[str, ModuleType])- Module to scanpattern(str)- Name pattern to matchExample
# Discover all tools in a module
import my_tools
tools = discover_tools(my_tools)
# Discover tools matching pattern
math_tools = discover_tools("my_tools", pattern="calc_*")Async Tools
Working with asynchronous tools
async_tool
@async_tool(
max_concurrency: int = None,
queue_size: int = None,
**kwargs
)Decorator for async tools with concurrency control
Parameters
max_concurrency(int)- Maximum concurrent executionsqueue_size(int)- Maximum queue size**kwargs(dict)- Additional tool configurationExample
@async_tool(
max_concurrency=5,
description="Fetch data from API"
)
async def fetch_data(url: str) -> dict:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()Tool Composition
Combining multiple tools
compose_tools
def compose_tools(
tools: List[MCPTool],
name: str,
description: str,
composition_type: str = "sequential"
) -> MCPToolCreate a composite tool from multiple tools
Parameters
tools(List[MCPTool])- Tools to composename(str)- Name for composite tooldescription(str)- Description of compositioncomposition_type(str)- sequential, parallel, or conditionalExample
# Create a pipeline tool
pipeline = compose_tools(
[fetch_tool, process_tool, save_tool],
name="data_pipeline",
description="Fetch, process, and save data",
composition_type="sequential"
)
# Use in agent
agent = Agent(
name="data_agent",
tools=[pipeline]
)Type Definitions
MCPTool
class MCPTool:
name: str
description: str
inputSchema: Dict[str, Any]
func: Callable
metadata: Dict[str, Any]
async def execute(self, arguments: Dict) -> Any:
"""Execute the tool with given arguments"""
def to_mcp_schema(self) -> Dict:
"""Convert to MCP tool schema"""
def validate_arguments(self, arguments: Dict) -> ValidationResult:
"""Validate arguments against schema"""ToolParameter
class ToolParameter:
name: str
type: str # "string", "number", "boolean", "object", "array"
description: Optional[str]
required: bool = True
default: Any = None
enum: Optional[List[Any]] = None
minimum: Optional[float] = None
maximum: Optional[float] = None
pattern: Optional[str] = NoneValidationResult
class ValidationResult:
is_valid: bool
errors: List[str]
warnings: List[str]
suggestions: List[str]Complete Example
from aakit import tool, async_tool, ToolRegistry, Agent
import aiohttp
from typing import List, Dict, Optional
from datetime import datetime
# Create a tool registry
registry = ToolRegistry("web_tools")
@registry.register
@tool(
description="Search the web for information",
returns="List of search results",
examples=[
"web_search('python tutorials')",
"web_search('machine learning', max_results=10)"
],
tags=["web", "search"],
cache=True
)
async def web_search(
query: str,
max_results: int = 5,
language: str = "en"
) -> List[Dict[str, str]]:
"""
Search the web and return relevant results.
Args:
query: The search query
max_results: Maximum number of results to return
language: Language code for results
Returns:
List of dictionaries containing title, url, and snippet
"""
# Simulated search results
results = []
for i in range(max_results):
results.append({
"title": f"Result {i+1} for {query}",
"url": f"https://example.com/{i+1}",
"snippet": f"Content about {query}..."
})
return results
@registry.register
@async_tool(
description="Extract content from a webpage",
max_concurrency=3,
timeout=30
)
async def extract_content(url: str) -> Dict[str, str]:
"""Extract main content from a webpage."""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
html = await response.text()
# Content extraction logic here
return {
"title": "Page Title",
"content": "Main content...",
"published": datetime.now().isoformat()
}
@registry.register
@tool(
description="Summarize text content",
parameters={
"text": {
"type": "string",
"description": "Text to summarize",
"maxLength": 10000
},
"max_length": {
"type": "integer",
"description": "Maximum summary length",
"default": 200,
"minimum": 50,
"maximum": 500
}
}
)
def summarize(text: str, max_length: int = 200) -> str:
"""Create a concise summary of the provided text."""
# Simple summarization (in practice, use NLP)
words = text.split()[:max_length]
return " ".join(words) + "..."
# Compose tools into a research pipeline
from aakit import compose_tools
research_pipeline = compose_tools(
[web_search, extract_content, summarize],
name="research_pipeline",
description="Search, extract, and summarize web content",
composition_type="sequential"
)
# Create an agent with the tools
agent = Agent(
name="research_assistant",
instruction="You help users research topics by searching and summarizing web content",
model="gpt-4",
tools=registry.get_all_tools() + [research_pipeline]
)
# Tool validation
from aakit import validate_tool
for tool_name, tool_func in registry.items():
result = validate_tool(tool_func)
if result.is_valid:
print(f"✓ {tool_name} is valid")
else:
print(f"✗ {tool_name} has errors: {result.errors}")
# Export tools for MCP
mcp_catalog = registry.to_mcp_catalog()
print(f"Exported {len(mcp_catalog['tools'])} tools to MCP format")Tool Best Practices
Do's
- • Provide clear descriptions
- • Use type hints for all parameters
- • Include docstrings with examples
- • Validate inputs thoroughly
- • Handle errors gracefully
- • Make tools focused and specific
Don'ts
- • Don't create overly complex tools
- • Don't ignore error handling
- • Don't hardcode sensitive data
- • Don't mix multiple concerns
- • Don't skip input validation
- • Don't use blocking I/O in async tools
MCP Tool Schema
{
"name": "web_search",
"description": "Search the web for information",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
},
"max_results": {
"type": "integer",
"description": "Maximum number of results to return",
"default": 5,
"minimum": 1,
"maximum": 50
},
"language": {
"type": "string",
"description": "Language code for results",
"default": "en",
"enum": ["en", "es", "fr", "de", "ja"]
}
},
"required": ["query"]
}
}Next Steps
Continue to the Memory API reference to learn about memory backends.
Continue to Memory API →