ahvn.ukf.templates.basic.tool module¶
- class ahvn.ukf.templates.basic.tool.ToolUKFT(*, name, notes='', short_description='', description='', type='general', version='v0.1.0', version_notes='', variant='default', variant_notes='', content='', content_resources=<factory>, content_composers=<factory>, source='unknown', parents=<factory>, creator='unknown', owner='unknown', workspace='unknown', collection='general', tags=<factory>, synonyms=<factory>, triggers=<factory>, priority=0, related=<factory>, auths=<factory>, timefluid=False, timestamp=<factory>, last_verified=<factory>, expiration=-1, inactive_mark=False, metadata=<factory>, profile=<factory>)[source]¶
Bases:
BaseUKFTool class for serializing and transferring MCP server-client tool definitions.
ToolUKFT enables server-client-based tool definitions to be stored, transferred, and restored across systems. It serializes all tool metadata (schemas, examples, client connection config) while the actual execution happens via MCP client connections.
IMPORTANT: Only server-client-based MCP tools are supported to become UKFT.
ToolUKFT is designed for tools that are served through MCP servers and accessed via FastMCP clients. It CANNOT serialize: - Regular Python functions (use ToolSpec.from_function() directly) - Local function-based tools with internal state - Tools with non-serializable closures or dependencies
Limitations of restored tools (from to_tool/to_atool):
Compared to tools created via ToolSpec.from_function(), client-based tools: 1. Cannot be further bound: Binding requires access to the original function
signature and implementation, which is only available server-side.
- Cannot access internal function state: They execute remotely via
client.call_tool(), with no access to local variables or closures.
- Cannot be serialized to code: No function source code is available,
only the API schema.
- Require active server connection: Must maintain connection to the
original MCP server for execution.
- Limited introspection: Only schema information is available, no
implementation details.
However, client-based tools DO support: - Full schema information (parameters, output types, descriptions) - Example execution patterns - Both sync and async execution - Connection status checking
To support binding for UKFT tools, the recommended approach is: - Create different ToolUKFT instances for each binding configuration - Store the binded ToolUKFT instances separately or as variants
UKF Type: tool
- Recommended Components of content_resources:
tool_name (str): The name of the tool.
description (str): Detailed tool description.
input_schema (Dict): JSON Schema for input parameters (with binds applied).
output_schema (Dict): JSON Schema for output structure.
examples (List[Dict], optional): Example usage cases.
- client_config (Dict, optional): Client connection configuration.
type (str): Connection type (“http”, “stdio”, “inmemory”)
url (str, optional): URL for HTTP connections
script_path (str, optional): Python file path for stdio
env (Dict, optional): Environment variables for stdio
command (str, optional): DEPRECATED, use script_path instead
server (FastMCP, optional): Server instance for inmemory (cannot be serialized)
- Note: state and binds are NOT serialized because:
Bind values may be arbitrary Python objects (not serializable)
Serialized schemas already reflect the bound parameters
Client-side ToolSpec doesn’t need original binds
- Recommended Composers:
Example
>>> # Server side: Serialize ToolSpec to UKFT >>> tool_spec = ToolSpec.from_function(add_function) >>> tool_ukft = ToolUKFT.from_toolspec( ... tool_spec, ... client_config={"type": "http", "url": "http://server/mcp"} ... ) >>> >>> # Transfer UKFT (e.g., save to database, send over network) >>> serialized = tool_ukft.model_dump_json() >>> >>> # Client side: Restore ToolSpec (client auto-created from config) >>> tool_ukft = ToolUKFT.model_validate_json(serialized) >>> tool_spec = await tool_ukft.to_atool() # No client needed! >>> result = await tool_spec.acall(a=3, b=7) >>> >>> # Or pass explicit client >>> client = Client(...) >>> async with client: ... tool_spec = await tool_ukft.to_atool(client) ... result = await tool_spec.acall(a=3, b=7)
- Parameters:
name (UKFMediumTextType)
notes (UKFMediumTextType)
short_description (UKFMediumTextType)
description (UKFMediumTextType)
type (UKFShortTextType)
version (UKFShortTextType)
version_notes (UKFMediumTextType)
variant (UKFShortTextType)
variant_notes (UKFMediumTextType)
content (UKFLongTextType)
content_resources (UKFJsonType)
content_composers (UKFJsonType)
source (UKFShortTextType)
parents (UKFJsonType)
creator (UKFShortTextType)
owner (UKFShortTextType)
workspace (UKFShortTextType)
collection (UKFShortTextType)
tags (UKFTagsType)
synonyms (UKFSynonymsType)
triggers (UKFJsonType)
priority (UKFIntegerType)
related (UKFRelatedType)
auths (UKFAuthsType)
timefluid (UKFBooleanType)
timestamp (UKFTimestampType)
last_verified (UKFTimestampType)
expiration (UKFDurationType)
inactive_mark (UKFBooleanType)
metadata (UKFJsonType)
profile (UKFJsonType)
- available(client=None)[source]¶
Check if a client connection can be established to the tool’s server.
This attempts to create a client from the stored config and check basic connectivity requirements. It does not guarantee the tool exists on the server.
- Parameters:
client – Optional FastMCP Client instance. If provided, checks this client. If None, attempts to create client from stored config.
- Returns:
True if client appears ready to connect, False otherwise.
- Return type:
Example
>>> tool_ukft = ToolUKFT.model_validate_json(serialized) >>> if tool_ukft.available(): ... tool_spec = await tool_ukft.to_atool()
- classmethod from_toolspec(tool_spec, name=None, client_config=None, **updates)[source]¶
Create a ToolUKFT by serializing a ToolSpec (server-side).
This method captures all serializable information from a ToolSpec. The key insight: we serialize the BINDED tool (tool_spec.binded) which already has parameter bindings applied, avoiding the need to serialize potentially non-serializable bind values.
- Parameters:
- Returns:
New ToolUKFT instance with serialized tool information.
- Return type:
Example
>>> tool_spec = ToolSpec.from_function(my_function) >>> tool_ukft = ToolUKFT.from_toolspec( ... tool_spec, ... client_config={"type": "http", "url": "http://server/mcp"} ... ) >>> print(tool_ukft.text("docstring"))
- async to_atool(client=None)[source]¶
Restore a ToolSpec from ToolUKFT with a client connection (async version).
This method reconstructs a fully functional ToolSpec using: 1. Stored schemas for API documentation (binds already applied) 2. Provided client (or auto-created from config) for remote execution via client.call_tool() 3. Restored examples
Note: Binds and state are not restored because they’re already baked into the stored schemas. The serialized schemas already reflect the bound parameters.
- Parameters:
client – Optional FastMCP Client instance. If None, attempts to create client from stored client_config. Must be within async context manager if provided.
- Returns:
Restored ToolSpec with remote execution capability.
- Return type:
- Raises:
ValueError – If tool is not found on the server.
NotImplementedError – If client_config uses inmemory transport (requires explicit client).
Example
>>> # Auto-create client from config >>> tool_ukft = ToolUKFT.model_validate_json(serialized_data) >>> async with tool_ukft.to_atool() as tool_spec: ... result = await tool_spec.acall(x=5, y=3) >>> >>> # Or provide explicit client >>> client = Client("http://server/mcp") >>> async with client: ... tool_spec = await tool_ukft.to_atool(client) ... result = await tool_spec.acall(x=5, y=3)
- to_tool(client=None)[source]¶
Restore a ToolSpec from ToolUKFT with a client connection (sync version).
This is a synchronous wrapper that creates a ToolSpec which manages client connections automatically for each call. The client connection is established and closed for each tool execution.
Note: This is less efficient than async mode which can reuse connections. Prefer async mode (to_atool) when possible.
- Parameters:
client – Optional FastMCP Client instance. If None, attempts to create client from stored client_config.
- Returns:
Restored ToolSpec with automatic connection management.
- Return type:
- Raises:
ValueError – If tool is not found on the server.
RuntimeError – If called from within an async context (use to_atool instead).
NotImplementedError – If client_config uses inmemory transport (requires explicit client).
Example
>>> # Auto-create client from config >>> tool_ukft = ToolUKFT.model_validate_json(serialized_data) >>> # Sync usage (NOT in async context) >>> tool_spec = tool_ukft.to_tool() >>> result = tool_spec.call(x=5, y=3) # Auto-connects per call >>> >>> # Or provide explicit client >>> client = Client("http://server/mcp") >>> tool_spec = tool_ukft.to_tool(client) >>> result = tool_spec.call(x=5, y=3)
- async classmethod from_client(client, tool_name, name=None, client_config=None, **updates)[source]¶
Create a ToolUKFT by fetching and serializing a tool from an MCP server.
This is a convenience method that combines: 1. Fetching tool definition via client 2. Creating ToolSpec 3. Serializing to ToolUKFT
- Parameters:
- Returns:
New ToolUKFT instance with tool information from server.
- Return type:
Example
>>> client = Client("http://server/mcp") >>> async with client: ... tool_ukft = await ToolUKFT.from_client( ... client, "add", ... client_config={"type": "http", "url": "http://server/mcp"} ... )
- model_config = {'validate_assignment': True, 'validate_default': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)¶
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- ahvn.ukf.templates.basic.tool.docstring_composer(kl, **kwargs)[source]¶
Compose tool documentation from stored schemas.
This composer generates a formatted docstring for a tool based on its stored input and output schemas, providing complete API documentation without needing the actual function code.
- Recommended Knowledge Types:
ToolUKFT
- Parameters:
kl (BaseUKF) – Knowledge object containing tool schema data.
**kwargs – Additional composition parameters (ignored).
- Returns:
Synthesized docstring in Google style format.
- Return type:
Example
>>> kl.content_resources = { ... "tool_name": "add", ... "description": "Add two numbers", ... "input_schema": {"properties": {"a": {"type": "integer"}, ...}}, ... "output_schema": {"properties": {"result": {"type": "integer"}}} ... } >>> docstring_composer(kl) "Add two numbers\n\nArgs:\n a (int): ...\n\nReturns:\n int: ..."