ahvn.tool package¶
- class ahvn.tool.ToolSpec(*args, **kwargs)[source]¶
Bases:
objectA specification wrapper for tools that can be used with LLMs.
ToolSpec can be used as a decorator to convert functions into tool specifications:
Example
>>> @ToolSpec(name="add", description="Add two numbers") ... def add(a: int, b: int) -> int: ... return a + b >>> result = add(a=3, b=5) # Still works as a function 8 >>> llm.tooluse("Add 3 and 5", tools=[add]) # Works as a tool
- static __new__(cls, *args, **kwargs)[source]¶
Create a new ToolSpec instance or return a decorator.
When called with keyword arguments (e.g., @ToolSpec(name=”add”)), returns a decorator that creates a ToolSpec from the decorated function.
When called with no arguments, returns a normal ToolSpec instance.
- property name¶
- property binded¶
- property input_schema¶
- property params¶
- property output_schema¶
- async aexec(**kwargs)[source]¶
Execute the tool asynchronously with the provided keyword arguments, returning the full structured content.
- Parameters:
**kwargs – The keyword arguments to pass to the tool.
- Returns:
ToolResult. The full structured content.
- exec(**kwargs)[source]¶
Execute the tool synchronously with the provided keyword arguments, returning the full structured content.
- Parameters:
**kwargs – The keyword arguments to pass to the tool
- Returns:
ToolResult. The full structured content.
- async acall(**kwargs)[source]¶
Execute the tool asynchronously with the provided keyword arguments, returning the main output value.
- Parameters:
**kwargs – The keyword arguments to pass to the tool
- Returns:
Any. The main output value.
- call(**kwargs)[source]¶
Execute the tool synchronously with the provided keyword arguments, returning the main output value.
- Parameters:
**kwargs – The keyword arguments to pass to the tool
- Returns:
Any. The main output value.
- available()[source]¶
Check if this ToolSpec has an active MCP client connection.
This is useful for ToolSpecs created via from_client() to verify the connection is still active before attempting remote calls.
- Returns:
- True if connected to an MCP server, False otherwise.
For local tools (from_function), always returns True.
- Return type:
Example
>>> spec = await ToolSpec.from_client(client, "add") >>> if spec.available(): ... result = await spec.acall(a=3, b=7)
- classmethod from_function(func, examples=None, parse_docstring=True, *args, **kwargs)[source]¶
Create a ToolSpec from a Python function.
- Parameters:
func (Callable) – The Python function or callable class instance to convert into a tool. If a class instance with a __call__ method is provided, that method will be used.
examples (Optional[Iterable[ExperienceType]], optional) – Example usages of the tool. Defaults to None.
parse_docstring (bool, optional) – Whether to parse the function’s docstring for description. Defaults to True.
*args – Additional positional arguments to pass to FastMCPTool.from_function.
**kwargs – Additional keyword arguments to pass to FastMCPTool.from_function.
- Returns:
An instance of ToolSpec wrapping the provided function.
- Return type:
- classmethod from_mcp(tool, examples=None, *args, **kwargs)[source]¶
Create a ToolSpec from an MCP Tool.
- Parameters:
tool (Union[MCPTool, FastMCPTool]) – The MCP Tool to convert into a ToolSpec.
examples (Optional[Iterable[ExperienceType]], optional) – Example usages of the tool. Defaults to None.
*args – Additional positional arguments to pass to FastMCPTool.from_tool.
**kwargs – Additional keyword arguments to pass to FastMCPTool.from_tool.
- Returns:
An instance of ToolSpec wrapping the provided MCP tool.
- Return type:
- async classmethod from_client(client, tool_name, examples=None, *args, **kwargs)[source]¶
Create a ToolSpec from a FastMCP Client by retrieving a tool from an MCP server.
This method connects to an MCP server via the provided client, retrieves the specified tool’s definition, and creates a ToolSpec that can call the remote tool.
- Parameters:
client – FastMCP Client instance (must be within an async context manager).
tool_name (str) – The name of the tool to retrieve from the server.
examples (Optional[Iterable[ExperienceType]], optional) – Example usages of the tool. Defaults to None.
*args – Additional positional arguments (ignored for client-based tools).
**kwargs – Additional keyword arguments (ignored for client-based tools).
- Returns:
An instance of ToolSpec wrapping the remote tool.
- Return type:
- Raises:
ValueError – If the specified tool is not found on the server.
RuntimeError – If the client is not connected.
Example
>>> from fastmcp import FastMCP, Client >>> server = FastMCP("test") >>> @server.tool() >>> def add(a: int, b: int = 5) -> int: ... return a + b >>> client = Client(server) >>> async with client: ... spec = await ToolSpec.from_client(client, "add") ... result = spec.call(a=3, b=7) ... print(result) # 10
- classmethod from_code(code, func_name=None, env=None, examples=None, *args, **kwargs)[source]¶
Create a ToolSpec from a code snippet.
- Parameters:
code (str) – The code snippet containing the function definition.
func_name (Optional[str], optional) – The name of the function to extract from the code. Defaults to None. If None, and only one callable is found, that function will be used. Notice that func_name is NOT the same as name, which will be used as the function name in the tool spec. func_name only helps to identify which function to use from the code snippet, it does NOT affect the tool spec.
env (Optional[Dict], optional) – The environment in which to execute the code. Defaults to None.
examples (Optional[Iterable[ExperienceType]], optional) – Example usages of the tool. Defaults to None.
*args – Additional positional arguments to pass to FastMCPTool.from_function.
**kwargs – Additional keyword arguments to pass to FastMCPTool.from_function.
- Returns:
An instance of ToolSpec wrapping the function defined in the provided code.
- Return type:
- bind(param, state_key=None, default=None)[source]¶
Bind a parameter to a state key (and a value if the key is not present). The benefit of using a state instead of a direct value is that the state can be updated externally, and the tool will always use the latest value from the state.
- Parameters:
param (str) – The parameter name to bind.
state_key (Optional[str]) – The dot-separated state key path to bind the parameter to. It supports nested keys using dot notation (e.g., “user.age”). If None, the parameter name will be used as the state key. Defaults to None.
default (
Optional[Any]) – The default value if the state key is not present. Defaults to None.
- Returns:
The ToolSpec instance (for chaining).
- Return type:
- property docstring¶
Generate and return a synthesized docstring from the tool specification.
- Returns:
The synthesized docstring in Google style format.
- Return type:
- property code¶
Generate a complete Python function definition with synthesized docstring.
- Returns:
The complete function code including signature, docstring, and placeholder body.
- Return type:
- to_function()[source]¶
Return a function that behaves like ToolSpec.__call__ but has the same signature as the string produced by ToolSpec.code.
- Returns:
The generated function.
- Return type:
Callable
- ahvn.tool.reg_toolspec(func=None, examples=None, parse_docstring=True, *args, **kwargs)[source]¶
Decorator to mark a method as a tool that should be registered as a ToolSpec.
This decorator can be used with or without arguments: - @reg_toolspec - @reg_toolspec(parse_docstring=True, description=”Custom description”)
The ToolSpec is created when to_toolspecs() is called on an instance.
- Parameters:
func (Optional[Callable], optional) – The function to decorate. If None, returns a partial decorator. Defaults to None.
examples (Optional[Iterable[ExperienceType]], optional) – Example usages of the tool. Defaults to None.
parse_docstring (bool, optional) – Whether to parse the function’s docstring for description. Defaults to True.
*args – Additional positional arguments to pass to FastMCPTool.from_function.
**kwargs – Additional keyword arguments to pass to FastMCPTool.from_function.
- Returns:
The decorated function with tool metadata attached.
- Return type:
Callable
Example
```python class MyKLBase(ToolRegistry):
@reg_toolspec(parse_docstring=True) def search(self, query: str) -> str:
“””Search for items.
- Args:
query: The search query string.
- Returns:
str: The search results.
“”” return f”Results for: {query}”
- class ahvn.tool.ToolRegistry[source]¶
Bases:
objectA mixin class that provides tool registration and management capabilities.
This class uses __init_subclass__ to automatically detect and register methods decorated with @reg_toolspec during class definition, storing the metadata for later ToolSpec creation.
The @reg_toolspec decorator is automatically available as a class method on any subclass.
Example
```python class MyCustomKLBase(KLBase):
@reg_toolspec(parse_docstring=True) def search(self, query: str) -> str:
“””Search for items.
- Args:
query: The search query string.
- Returns:
str: The search results.
“”” return f”Results for: {query}”
# ToolSpecs are created when to_toolspecs() is called kb = MyCustomKLBase() tools = kb.to_toolspecs() # Creates and returns ToolSpec instances ```
- classmethod __init_subclass__(**kwargs)[source]¶
Called when a subclass is created. Scans for decorated methods and stores their metadata.
- to_toolspecs()[source]¶
Collect all methods decorated with @reg_toolspec and convert them to ToolSpec instances.
This method creates ToolSpec instances from the registered tool metadata, binding ‘self’ to each tool so they can be called as instance methods.
- Returns:
A named list of ToolSpec instances for all decorated methods.
- Return type:
Dict[ToolSpec]
Subpackages¶
Submodules¶
- ahvn.tool.base module
ToolSpecToolSpec.__new__()ToolSpec.__init__()ToolSpec.nameToolSpec.bindedToolSpec.input_schemaToolSpec.paramsToolSpec.output_schemaToolSpec.aexec()ToolSpec.exec()ToolSpec.acall()ToolSpec.call()ToolSpec.available()ToolSpec.from_function()ToolSpec.from_mcp()ToolSpec.from_client()ToolSpec.from_code()ToolSpec.bind()ToolSpec.unbind()ToolSpec.clone()ToolSpec.to_fastmcp()ToolSpec.to_mcp()ToolSpec.to_jsonschema()ToolSpec.docstringToolSpec.codeToolSpec.to_function()ToolSpec.signature()ToolSpec.to_prompt()ToolSpec.to_ukf()
- ahvn.tool.mixin module