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

基类:BaseUKF

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

  1. Cannot access internal function state: They execute remotely via

    client.call_tool(), with no access to local variables or closures.

  2. Cannot be serialized to code: No function source code is available,

    only the API schema.

  3. Require active server connection: Must maintain connection to the

    original MCP server for execution.

  4. 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:
  1. Bind values may be arbitrary Python objects (not serializable)

  2. Serialized schemas already reflect the bound parameters

  3. Client-side ToolSpec doesn't need original binds

Recommended Composers:
docstring:

Generates formatted tool documentation from schemas. Examples: ``` Add two numbers

Args:

a (int): First number b (int): Second number (defaults to 5)

Returns:

int: Sum of a and b

```

示例

>>> # 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)
参数:
type_default: ClassVar[str] = 'tool'
available(client=None)[源代码]

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.

参数:

client -- Optional FastMCP Client instance. If provided, checks this client. If None, attempts to create client from stored config.

返回:

True if client appears ready to connect, False otherwise.

返回类型:

bool

示例

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

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.

参数:
  • tool_spec (ToolSpec) -- The ToolSpec to serialize.

  • name (str, optional) -- UKF name. Defaults to tool name.

  • client_config (Dict, optional) -- Client connection configuration. If None, defaults to {"type": "inmemory"}.

  • **updates -- Additional keyword arguments to update the ToolUKFT attributes.

返回:

New ToolUKFT instance with serialized tool information.

返回类型:

ToolUKFT

示例

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

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.

参数:

client -- Optional FastMCP Client instance. If None, attempts to create client from stored client_config. Must be within async context manager if provided.

返回:

Restored ToolSpec with remote execution capability.

返回类型:

ToolSpec

抛出:

示例

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

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.

参数:

client -- Optional FastMCP Client instance. If None, attempts to create client from stored client_config.

返回:

Restored ToolSpec with automatic connection management.

返回类型:

ToolSpec

抛出:
  • 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).

示例

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

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

参数:
  • client -- FastMCP Client instance (must be within async context manager).

  • tool_name (str) -- Name of the tool to fetch from server.

  • name (str, optional) -- UKF name. Defaults to tool_name.

  • client_config (Dict, optional) -- Client connection configuration.

  • **updates -- Additional keyword arguments to update the ToolUKFT attributes.

返回:

New ToolUKFT instance with tool information from server.

返回类型:

ToolUKFT

示例

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

参数:
  • self (BaseModel) -- The BaseModel instance.

  • context (Any) -- The context.

返回类型:

None

ahvn.ukf.templates.basic.tool.docstring_composer(kl, **kwargs)[源代码]

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

参数:
  • kl (BaseUKF) -- Knowledge object containing tool schema data.

  • **kwargs -- Additional composition parameters (ignored).

返回:

Synthesized docstring in Google style format.

返回类型:

str

示例

>>> 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: ..."