Tools

Tools

Expose Python functions as executable capabilities for your MCP clients.

Tools are the core primitives that let an LLM reach outside its training data: query a database, hit an API, crunch numbers, or open a file. In Hyperia, a tool is just a Python function decorated with @mcp.tool() and surfaced through the Model Context Protocol.


What are Tools?

When an LLM decides to call a tool:

  1. It sends a request containing parameters that match the tool’s input schema.

  2. Hyperia validates those parameters against your function signature (types, constraints, defaults).

  3. Your function executes with the validated inputs.

  4. The result is returned to the LLM, which can use it to craft its next response.

That single loop enables powerful behaviours—calculations, searches, side‑effects—well beyond what the model “knows” natively.


The @tool Decorator

Creating a tool is as simple as decorating a function:

from hyperia import Hyperia

mcp = Hyperia(name="CalculatorServer")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Adds two numbers."""
    return a + b

When registered, Hyperia automatically:

  • Uses the function name (add) as the tool name.

  • Uses the docstring as the description.

  • Generates a JSON input schema from type hints.

  • Handles validation and error reporting.

Note Variadic signatures (*args, **kwargs) are not supported—Hyperia must know every parameter to build a complete schema.


Parameter Basics

Type Annotations

Type hints are required for robust schemas and validation.

Rich Metadata with Annotated + Field

Use Annotated to attach Pydantic Field metadata—descriptions, ranges, regex, etc.—without polluting the default value column:

You can embed Field as the default value, but Annotated keeps type hints clear:


Supported Types

Hyperia supports nearly every Pydantic‑compatible type. A non‑exhaustive list:

Category
Examples
Notes

Basic scalars

int, float, str, bool

Binary

bytes

Raw bytes (Base64 handled manually)

Date/Time

datetime, date, timedelta

ISO‑8601 strings auto‑parsed

Collections

list[int], dict[str, float], set[str], tuple[int, int]

Nested combos allowed

Optional / Union

`int

None, str

Constrained

Literal["A", "B"], Enum

Value whitelists

Paths

Path

Auto‑converted from str

UUIDs

UUID

Auto‑converted

Pydantic models

User

Full validation & nested schemas

See Parameter Types below for deep dives and examples.


Optional Arguments

Standard Python rules apply: parameters without defaults are required; those with defaults (or | None) are optional.


Advanced Decorator Metadata

Override auto‑inferred values or add tags:

  • name – Explicit tool identifier exposed via MCP.

  • description – Overrides docstring for LLM visibility.

  • tags – Arbitrary strings clients may use for grouping or filtering.


Async vs Sync Tools

Hyperia is fully async‑aware:

Use async def whenever your tool performs blocking I/O (HTTP, DB, file access) to keep the event loop responsive.


Return Values

Hyperia serialises return values automatically:

Return Type
MCP Content

str

TextContent

dict, list, BaseModel

JSON‑serialised TextContent

bytes

Base64‑encoded BlobResourceContents

hyperia.Image helper

ImageContent

None

No content

Other types are coerced to str if possible.


Error Handling

If a tool fails, raise any Python exception or hyperia.ToolError.

  • Standard exceptions → logged; generic error sent to client.

  • ToolError → message forwarded, letting the LLM reason about the cause.


Tool Annotations

Add advisory metadata (does not consume LLM tokens) via annotations=:

Annotation
Type
Default
Purpose

title

string

UI‑friendly label

readOnlyHint

bool

False

Indicates no state change

destructiveHint

bool

True

If changes are irreversible

idempotentHint

bool

False

Repeat calls ⇒ same effect

openWorldHint

bool

True

Touches external systems


Accessing MCP Context

Inject a Context‑typed param to tap logging, resources, sampling, progress, etc.

See the Context chapter for the full API.


Server Behaviour Controls

Duplicate Tool Names

Configure via on_duplicate_tools= at server creation:

Options: "warn" (default), "error", "replace", "ignore".

Removing Tools Dynamically

Legacy JSON Parsing

Set HYPERIA_TOOL_ATTEMPT_PARSE_JSON_ARGS=1 to re‑enable old behaviour that auto‑parsed stringified JSON args. Default is off for strict validation.


Deep‑Dive: Parameter Types

Hyperia leans on Pydantic for validation and coercion. Highlights below—see linked sections for more.

Built‑in Scalars

Strings like "42" are coerced to int where appropriate.

Date & Time

Collections

Union / Optional

Constrained Literals & Enums

Binary Data

Raw bytes or base64 strings (decoded manually):

Paths & UUIDs

Pydantic Models


Field‑Level Validation Examples

Hyperia returns clear validation errors if input fails constraints.

Last updated