ahvn.tool package

class ahvn.tool.ToolSpec(*args, **kwargs)[源代码]

基类:object

A specification wrapper for tools that can be used with LLMs.

ToolSpec can be used as a decorator to convert functions into tool specifications:

示例

>>> @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)[源代码]

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.

__init__()[源代码]
property name
property binded
property input_schema
property params
property output_schema
async aexec(**kwargs)[源代码]

Execute the tool asynchronously with the provided keyword arguments, returning the full structured content.

参数:

**kwargs -- The keyword arguments to pass to the tool.

返回:

ToolResult. The full structured content.

exec(**kwargs)[源代码]

Execute the tool synchronously with the provided keyword arguments, returning the full structured content.

参数:

**kwargs -- The keyword arguments to pass to the tool

返回:

ToolResult. The full structured content.

async acall(**kwargs)[源代码]

Execute the tool asynchronously with the provided keyword arguments, returning the main output value.

参数:

**kwargs -- The keyword arguments to pass to the tool

返回:

Any. The main output value.

call(**kwargs)[源代码]

Execute the tool synchronously with the provided keyword arguments, returning the main output value.

参数:

**kwargs -- The keyword arguments to pass to the tool

返回:

Any. The main output value.

available()[源代码]

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.

返回:

True if connected to an MCP server, False otherwise.

For local tools (from_function), always returns True.

返回类型:

bool

示例

>>> 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)[源代码]

Create a ToolSpec from a Python function.

参数:
  • 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.

返回:

An instance of ToolSpec wrapping the provided function.

返回类型:

ToolSpec

classmethod from_mcp(tool, examples=None, *args, **kwargs)[源代码]

Create a ToolSpec from an MCP Tool.

参数:
  • 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.

返回:

An instance of ToolSpec wrapping the provided MCP tool.

返回类型:

ToolSpec

async classmethod from_client(client, tool_name, examples=None, *args, **kwargs)[源代码]

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.

参数:
  • 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).

返回:

An instance of ToolSpec wrapping the remote tool.

返回类型:

ToolSpec

抛出:
  • ValueError -- If the specified tool is not found on the server.

  • RuntimeError -- If the client is not connected.

示例

>>> 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)[源代码]

Create a ToolSpec from a code snippet.

参数:
  • 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.

返回:

An instance of ToolSpec wrapping the function defined in the provided code.

返回类型:

ToolSpec

bind(param, state_key=None, default=None)[源代码]

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.

参数:
  • 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.

返回:

The ToolSpec instance (for chaining).

返回类型:

ToolSpec

unbind(param)[源代码]

Unbind a parameter from its state key.

参数:

param (str) -- The parameter name to unbind.

返回:

The ToolSpec instance (for chaining).

返回类型:

ToolSpec

clone()[源代码]
返回类型:

ToolSpec

to_fastmcp()[源代码]
返回类型:

Tool

to_mcp()[源代码]
返回类型:

Tool

to_jsonschema(**kwargs)[源代码]
property docstring

Generate and return a synthesized docstring from the tool specification.

返回:

The synthesized docstring in Google style format.

返回类型:

str

property code

Generate a complete Python function definition with synthesized docstring.

返回:

The complete function code including signature, docstring, and placeholder body.

返回类型:

str

to_function()[源代码]

Return a function that behaves like ToolSpec.__call__ but has the same signature as the string produced by ToolSpec.code.

返回:

The generated function.

返回类型:

Callable

signature(**kwargs)[源代码]

Generate a tool function call signature with provided keyword arguments (and default values for missing arguments).

参数:

**kwargs -- The keyword arguments to include in the function call signature.

返回:

The function call signature as a string.

返回类型:

str

to_prompt()[源代码]
to_ukf()[源代码]
ahvn.tool.reg_toolspec(func=None, examples=None, parse_docstring=True, *args, **kwargs)[源代码]

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.

参数:
  • 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.

返回:

The decorated function with tool metadata attached.

返回类型:

Callable

示例

```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[源代码]

基类:object

A 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.

示例

```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)[源代码]

Called when a subclass is created. Scans for decorated methods and stores their metadata.

toolspec(name)[源代码]
返回类型:

ToolSpec

参数:

name (str)

to_toolspecs()[源代码]

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.

返回:

A named list of ToolSpec instances for all decorated methods.

返回类型:

Dict[ToolSpec]

list_toolspecs()[源代码]

List the names of all methods decorated with @reg_toolspec.

返回:

A list of method names that are registered as tools.

返回类型:

List[str]

Subpackages

Submodules