Skip to content

Helper Classes

Utility classes and helper functions that support the core functionality of the ToolRegistry library.

Parameter Models

Parameter validation and schema generation for tool functions. ArgModelBase dynamically creates Pydantic models from function signatures for runtime argument validation.

toolregistry.parameter_models

InvalidSignature

Bases: Exception

Exception raised when a function signature cannot be processed.

Attributes:

Name Type Description
message str

Explanation of the error.

warn_untyped_parameters

warn_untyped_parameters(func_name: str, parameters_schema: dict[str, Any], annotations: dict[str, Any], already_warned: set[str] | None = None) -> None

Warn when a parameter renders without a type in the JSON Schema.

An empty schema tells a schema-driven client nothing about what to send. The usual causes are a bare container that escaped normalization and an annotation the backend cannot express; both used to degrade silently. Any, object, and unannotated parameters are excluded because an unconstrained schema is the correct rendering for them.

Parameters:

Name Type Description Default
func_name str

Name used in the warning message.

required
parameters_schema dict[str, Any]

The final Tool.parameters schema.

required
annotations dict[str, Any]

Original resolved annotations, keyed by parameter name.

required
already_warned set[str] | None

Parameters whose annotation already produced a specific fallback warning; the generic diagnostic is skipped for them so one mistake does not produce two warnings.

None
Source code in src/toolregistry/parameter_models.py
def warn_untyped_parameters(
    func_name: str,
    parameters_schema: dict[str, Any],
    annotations: dict[str, Any],
    already_warned: set[str] | None = None,
) -> None:
    """Warn when a parameter renders without a type in the JSON Schema.

    An empty schema tells a schema-driven client nothing about what to send.
    The usual causes are a bare container that escaped normalization and an
    annotation the backend cannot express; both used to degrade silently.
    ``Any``, ``object``, and unannotated parameters are excluded because an
    unconstrained schema is the correct rendering for them.

    Args:
        func_name: Name used in the warning message.
        parameters_schema: The final ``Tool.parameters`` schema.
        annotations: Original resolved annotations, keyed by parameter name.
        already_warned: Parameters whose annotation already produced a
            specific fallback warning; the generic diagnostic is skipped for
            them so one mistake does not produce two warnings.
    """
    properties = parameters_schema.get("properties")
    if not isinstance(properties, dict):
        return
    skip = already_warned or set()
    for name, prop in properties.items():
        if name not in annotations or name in skip:
            continue
        annotation = annotations[name]
        if _is_any_like(annotation):
            continue
        untyped = _is_untyped_schema(prop)
        untyped_branch = isinstance(prop, dict) and any(
            _is_untyped_schema(branch)
            for keyword in ("anyOf", "oneOf")
            for branch in prop.get(keyword, [])
        )
        if untyped or untyped_branch:
            warnings.warn(
                f"Parameter '{name}' of '{func_name}' renders without a type "
                "in its JSON Schema, so schema-driven clients cannot build a "
                "valid value. Annotate the element type (for example "
                "list[float] instead of list).",
                UserWarning,
                stacklevel=3,
            )

Utilities

toolregistry.utils is the compatibility surface: it re-exports every helper that downstream packages import, so existing imports keep working. The implementations live next to their concern: tool-name normalization and the registration filter in toolregistry._names, base-URL HTTP clients and HttpClientConfig in toolregistry._http, and tool-result encoding in toolregistry._serialisation.

The admin panel's Python-source preview lists only functions defined in the module. Because toolregistry.utils is now a compatibility surface, previewing it no longer lists the moved functions; register those from toolregistry._names, toolregistry._http or toolregistry._serialisation.

toolregistry.utils

Shared helpers kept as the compatibility surface.

The implementations live next to their concern: tool-name rules in :mod:toolregistry._names, HTTP client glue in :mod:toolregistry._http, and result encoding in :mod:toolregistry._serialisation. Every name this module exported before the split is still importable here, so downstream packages and existing documentation keep working.

HttpClientConfig

HttpClientConfig(base_url: str, headers: dict[str, str] | None = None, timeout: float = 10.0, auth: tuple[str, str] | None = None, cookies: dict[str, str] | None = None, allow_private_hosts: bool = False, **extra_options: Any)

Container for HTTP client configuration.

Creates zero-dependency HTTP clients with base URL support, connection pooling, and both sync/async interfaces.

Parameters:

Name Type Description Default
base_url str

The base URL for the API. This is required.

required
headers dict[str, str] | None

Custom request headers. Default is None.

None
timeout float

Request timeout in seconds. Default is 10.0.

10.0
auth tuple[str, str] | None

Basic authentication credentials (username, password). Default is None.

None
cookies dict[str, str] | None

Initial cookies to send with requests. The underlying client maintains a persistent cookie jar — cookies from Set-Cookie response headers are accumulated across requests on the same persistent client. Default is None.

None
allow_private_hosts bool

Permit base_url to resolve to a loopback, link-local or private address. Defaults to False; set it for an API that runs on the same host or on a private network.

False
**extra_options Any

Additional client parameters (e.g. verify, proxy, pool_size, max_response_size). max_response_size defaults to :data:DEFAULT_MAX_TOOL_RESPONSE_BYTES (10 MiB); pass None to disable the cap.

{}
Source code in src/toolregistry/_http.py
def __init__(
    self,
    base_url: str,
    headers: dict[str, str] | None = None,
    timeout: float = 10.0,
    auth: tuple[str, str] | None = None,
    cookies: dict[str, str] | None = None,
    allow_private_hosts: bool = False,
    **extra_options: Any,
):
    self.base_url = base_url.rstrip("/")
    self.headers = headers or {}
    self.timeout = timeout
    self.auth = auth
    self.cookies = cookies
    self.allow_private_hosts = allow_private_hosts
    # A buffered tool response is capped by default; ``None`` disables it.
    # Keep extra_options untouched: it is part of the public state (and
    # pickled with the config), so the default is resolved here instead.
    self.max_response_size = extra_options.get(
        "max_response_size", DEFAULT_MAX_TOOL_RESPONSE_BYTES
    )
    self.extra_options = extra_options
    self._sync_client: _BaseUrlClient | None = None
    self._async_client: _BaseUrlAsyncClient | None = None

__getstate__

__getstate__() -> dict

Drop live HTTP clients before pickling.

The config (base_url, headers, timeout, auth, extra_options) is preserved. Live _sync_client / _async_client (holding thread locks and connection pools) are dropped. The worker process will recreate them lazily via get_persistent_client().

Source code in src/toolregistry/_http.py
def __getstate__(self) -> dict:
    """Drop live HTTP clients before pickling.

    The config (base_url, headers, timeout, auth, extra_options)
    is preserved.  Live ``_sync_client`` / ``_async_client``
    (holding thread locks and connection pools) are dropped.
    The worker process will recreate them lazily via
    ``get_persistent_client()``.
    """
    return {
        "base_url": self.base_url,
        "headers": self.headers,
        "timeout": self.timeout,
        "auth": self.auth,
        "cookies": self.cookies,
        "allow_private_hosts": self.allow_private_hosts,
        "max_response_size": self.max_response_size,
        "extra_options": self.extra_options,
    }

__setstate__

__setstate__(state: dict) -> None

Restore config; clients will be created lazily on first use.

Source code in src/toolregistry/_http.py
def __setstate__(self, state: dict) -> None:
    """Restore config; clients will be created lazily on first use."""
    self.base_url = state["base_url"]
    self.headers = state["headers"]
    self.timeout = state["timeout"]
    self.auth = state["auth"]
    self.cookies = state.get("cookies")
    self.allow_private_hosts = state.get("allow_private_hosts", False)
    # Default for a config pickled before the cap existed.
    self.max_response_size = state.get(
        "max_response_size", DEFAULT_MAX_TOOL_RESPONSE_BYTES
    )
    self.extra_options = state["extra_options"]
    self._sync_client = None
    self._async_client = None

close

close()

Close persistent clients (sync).

Only closes the sync client. Use close_async() to properly close the async client.

Source code in src/toolregistry/_http.py
def close(self):
    """Close persistent clients (sync).

    Only closes the sync client. Use ``close_async()`` to properly
    close the async client.
    """
    if self._sync_client:
        self._sync_client.close()
        self._sync_client = None

close_async async

close_async()

Close all persistent clients.

Source code in src/toolregistry/_http.py
async def close_async(self):
    """Close all persistent clients."""
    if self._async_client:
        await self._async_client.aclose()
        self._async_client = None
    if self._sync_client:
        self._sync_client.close()
        self._sync_client = None

ensure_base_url_allowed

ensure_base_url_allowed() -> None

Validate :attr:base_url on the calling thread.

Callers that build a client from a URL they did not choose can run this ahead of time. The decision is cached, so repeating it is cheap.

Raises:

Type Description
UnsafeAddressError

If the base URL uses a scheme the outbound policy does not accept, names no host, does not resolve, or resolves to a non-public address while :attr:allow_private_hosts is false.

Source code in src/toolregistry/_http.py
def ensure_base_url_allowed(self) -> None:
    """Validate :attr:`base_url` on the calling thread.

    Callers that build a client from a URL they did not choose can run
    this ahead of time.  The decision is cached, so repeating it is cheap.

    Raises:
        UnsafeAddressError: If the base URL uses a scheme the outbound
            policy does not accept, names no host, does not resolve, or
            resolves to a non-public address while
            :attr:`allow_private_hosts` is false.
    """
    validate_outbound_url(
        self.base_url,
        allow_private_hosts=self.allow_private_hosts,
    )

ensure_base_url_allowed_async async

ensure_base_url_allowed_async() -> None

Validate :attr:base_url without blocking the event loop.

Raises:

Type Description
UnsafeAddressError

If the base URL uses a scheme the outbound policy does not accept, names no host, does not resolve, resolution times out, or resolves to a non-public address while :attr:allow_private_hosts is false.

Source code in src/toolregistry/_http.py
async def ensure_base_url_allowed_async(self) -> None:
    """Validate :attr:`base_url` without blocking the event loop.

    Raises:
        UnsafeAddressError: If the base URL uses a scheme the outbound
            policy does not accept, names no host, does not resolve,
            resolution times out, or resolves to a non-public address
            while :attr:`allow_private_hosts` is false.
    """
    await validate_outbound_url_async(
        self.base_url,
        allow_private_hosts=self.allow_private_hosts,
    )

get_persistent_client

get_persistent_client(use_async: Literal[False] = False) -> _BaseUrlClient
get_persistent_client(use_async: Literal[True] = ...) -> _BaseUrlAsyncClient
get_persistent_client(use_async: bool = False)

Get or create a persistent client instance.

Unlike to_client(), this method reuses the same client across multiple calls, enabling HTTP connection pooling.

Parameters:

Name Type Description Default
use_async bool

Whether to return an async client.

False

Returns:

Type Description

A persistent _BaseUrlClient or _BaseUrlAsyncClient instance.

Source code in src/toolregistry/_http.py
def get_persistent_client(self, use_async: bool = False):
    """Get or create a persistent client instance.

    Unlike ``to_client()``, this method reuses the same client across
    multiple calls, enabling HTTP connection pooling.

    Args:
        use_async: Whether to return an async client.

    Returns:
        A persistent _BaseUrlClient or _BaseUrlAsyncClient instance.
    """
    if use_async:
        if self._async_client is None:
            self._async_client = self._make_client(use_async=True)
        return self._async_client
    else:
        if self._sync_client is None:
            self._sync_client = self._make_client(use_async=False)
        return self._sync_client

to_client

to_client(use_async: Literal[False]) -> _BaseUrlClient
to_client(use_async: Literal[True]) -> _BaseUrlAsyncClient
to_client(use_async: bool = False)

Create a new HTTP client instance.

Parameters:

Name Type Description Default
use_async bool

Whether to create an asynchronous client. Default is False.

False

Returns:

Type Description

A _BaseUrlClient or _BaseUrlAsyncClient wrapping the underlying

zero-dependency client with base URL support.

Source code in src/toolregistry/_http.py
def to_client(self, use_async: bool = False):
    """Create a new HTTP client instance.

    Args:
        use_async: Whether to create an asynchronous client. Default is False.

    Returns:
        A _BaseUrlClient or _BaseUrlAsyncClient wrapping the underlying
        zero-dependency client with base URL support.
    """
    return self._make_client(use_async=use_async)

with_base_url

with_base_url(base_url: str) -> HttpClientConfig

Return a copy of this config that points at base_url.

Headers, auth, timeout, cookies, the private-host policy, max_response_size and every extra client option are carried over. Live pooled clients are not: the copy starts without them. The original keeps its pools until the caller closes it.

Parameters:

Name Type Description Default
base_url str

The replacement base URL.

required

Returns:

Type Description
HttpClientConfig

A new config with the same settings and the new base URL.

Source code in src/toolregistry/_http.py
def with_base_url(self, base_url: str) -> HttpClientConfig:
    """Return a copy of this config that points at *base_url*.

    Headers, auth, timeout, cookies, the private-host policy,
    ``max_response_size`` and every extra client option are carried
    over.  Live pooled clients are not: the copy starts without them.
    The original keeps its pools until the caller closes it.

    Args:
        base_url: The replacement base URL.

    Returns:
        A new config with the same settings and the new base URL.
    """
    options = dict(self.extra_options)
    options["max_response_size"] = self.max_response_size
    return HttpClientConfig(
        base_url,
        headers=dict(self.headers),
        timeout=self.timeout,
        auth=self.auth,
        cookies=dict(self.cookies) if self.cookies is not None else None,
        allow_private_hosts=self.allow_private_hosts,
        **options,
    )

OpenAPIPathError

Bases: ValueError

A request path would leave the configured base origin.

Raised before a tool is built or a request is sent. It subclasses ValueError so existing callers keep working; the admin layer catches this type specifically so a path rejection is reported as a bad request instead of being confused with an internal fault.

ToolNameFilter

ToolNameFilter(include: str | list[str] | None = None, exclude: str | list[str] | None = None)

Include/exclude filter applied when registering remote tools.

Patterns are matched with :func:fnmatch.fnmatchcase against four spellings of each candidate name: the raw remote tool name (the name the source advertises, e.g. the MCP tool name or the OpenAPI operationId), the final post-namespace name (e.g. gh-list_issues), and the :func:normalize_tool_name form of each. A pattern therefore matches a tool when it matches any spelling, so bash-execute, bash_execute, hub-bash_execute, and hub_bash_execute all select the same tool.

include and exclude are mutually exclusive. None means the corresponding side is not filtered; an empty list matches nothing, so include=[] drops every tool. A bare string is treated as a single-pattern list, so a one-item JSON/YAML include: name is not mistaken for an iterable of characters.

Matching is case-sensitive (:func:fnmatch.fnmatchcase), unlike discover_tools / call_deferred, which fold case. Write patterns in the case the source advertises.

The normalized spelling is not unique. When a source advertises two names that normalize to the same string (for example x-y and x_y), a pattern written in that spelling selects both tools. Use the raw or post-namespace spelling to narrow to one of them.

Parameters:

Name Type Description Default
include str | list[str] | None

Names or glob patterns to keep. When given, a tool is kept only if one of its spellings matches a pattern.

None
exclude str | list[str] | None

Names or glob patterns to drop. When given, a tool is dropped if one of its spellings matches a pattern.

None

Raises:

Type Description
ValueError

If both include and exclude are given.

Source code in src/toolregistry/_names.py
def __init__(
    self,
    include: str | list[str] | None = None,
    exclude: str | list[str] | None = None,
) -> None:
    if include is not None and exclude is not None:
        raise ValueError(
            "include and exclude are mutually exclusive; pass only one."
        )
    self.include = _as_pattern_list(include)
    self.exclude = _as_pattern_list(exclude)

accepts

accepts(raw_name: str, namespaced_name: str) -> bool

Return whether a tool passes the filter.

Parameters:

Name Type Description Default
raw_name str

The remote tool name before namespace handling.

required
namespaced_name str

The final registered name (raw_name plus any namespace prefix).

required

Returns:

Type Description
bool

True if the tool should be registered, False if it must be

bool

dropped.

Source code in src/toolregistry/_names.py
def accepts(self, raw_name: str, namespaced_name: str) -> bool:
    """Return whether a tool passes the filter.

    Args:
        raw_name: The remote tool name before namespace handling.
        namespaced_name: The final registered name (``raw_name`` plus
            any namespace prefix).

    Returns:
        True if the tool should be registered, False if it must be
        dropped.
    """
    candidates = _name_spellings(raw_name, namespaced_name)
    if self.include is not None:
        return any(
            fnmatch.fnmatchcase(name, pattern)
            for pattern in self.include
            for name in candidates
        )
    if self.exclude is not None:
        return not any(
            fnmatch.fnmatchcase(name, pattern)
            for pattern in self.exclude
            for name in candidates
        )
    return True

warn_if_all_filtered_out

warn_if_all_filtered_out(*, total: int, accepted: int, source: str) -> None

Warn when an active filter leaves none of total candidates.

A filter that leaves nothing registered is almost always a configuration mistake: an empty list, a bare string, or a pattern spelled differently from the names the source advertises. Without this warning registration succeeds and silently produces an empty source.

Parameters:

Name Type Description Default
total int

Number of candidate tools the source offered.

required
accepted int

Number of candidates that passed this filter.

required
source str

Source label used in the message, e.g. "MCP".

required

Warns:

Type Description
UserWarning

If a filter is active, total is non-zero, and accepted is zero.

Source code in src/toolregistry/_names.py
def warn_if_all_filtered_out(
    self,
    *,
    total: int,
    accepted: int,
    source: str,
) -> None:
    """Warn when an active filter leaves none of *total* candidates.

    A filter that leaves nothing registered is almost always a
    configuration mistake: an empty list, a bare string, or a pattern
    spelled differently from the names the source advertises.  Without
    this warning registration succeeds and silently produces an empty
    source.

    Args:
        total: Number of candidate tools the source offered.
        accepted: Number of candidates that passed this filter.
        source: Source label used in the message, e.g. ``"MCP"``.

    Warns:
        UserWarning: If a filter is active, *total* is non-zero, and
            *accepted* is zero.
    """
    if self.include is None and self.exclude is None:
        return
    if total <= 0 or accepted > 0:
        return
    if self.include is not None:
        detail = f"include={self.include!r} matched none of {total} tool(s)"
    else:
        detail = f"exclude={self.exclude!r} excluded all {total} tool(s)"
    # Attribute the warning to the caller rather than the integration
    # internals; a fixed stacklevel cannot follow the async bridge.
    warn_at_user_frame(
        f"{source} registration filter {detail}; nothing was registered.",
        UserWarning,
    )

ToolResultJSONEncoder

Bases: JSONEncoder

JSON encoder for values returned by tools.

Projects common non-JSON-native Python values to a JSON-safe representation. json traverses containers itself, so this only needs to handle the leaf values it cannot serialize.

Handled values:

  • Enum members -> their .value
  • pathlib.Path -> str
  • Decimal / UUID -> str
  • datetime / date / time -> ISO 8601 string
  • bytes -> base64-encoded ASCII string
  • set / frozenset -> JSON array, ordered by repr so the encoding is reproducible across processes for orderable and mixed-type elements alike (tuples are native to JSON)
  • dataclass instances -> :func:dataclasses.asdict
  • Pydantic v2 models (model_dump), v1 models (dict), any object exposing a zero-argument to_dict -> dict, and array-like objects exposing tolist (numpy arrays, torch tensors) -> list

Whatever tolist returns is serialized by json normally, so a non-native element inside it is routed back through this encoder.

Non-finite floats (NaN, Infinity, -Infinity) are written as null. json would otherwise emit the bare constants, which are not valid JSON: JSON.parse, Go's encoding/json and serde all reject them, so a tool returning a metric computed from an empty set would produce a body a conforming client cannot read. FastAPI's encoder and the JSON spec's recommendation both use null.

Anything else has no JSON projection and raises TypeError.

default

default(o: Any) -> Any

Project o to JSON-native values, sanitising non-finite floats.

Source code in src/toolregistry/_serialisation.py
def default(self, o: Any) -> Any:
    """Project *o* to JSON-native values, sanitising non-finite floats."""
    return _replace_non_finite(self._project(o))

iterencode

iterencode(o: Any, _one_shot: bool = False)

Encode o after replacing non-finite floats with null.

Source code in src/toolregistry/_serialisation.py
def iterencode(self, o: Any, _one_shot: bool = False):  # noqa: ANN401
    """Encode *o* after replacing non-finite floats with ``null``."""
    return super().iterencode(_replace_non_finite(o), _one_shot)

HttpxClientConfig

HttpxClientConfig(*args: Any, **kwargs: Any) -> HttpClientConfig

Deprecated alias for HttpClientConfig.

.. deprecated:: Use HttpClientConfig instead. HttpxClientConfig will be removed in a future release.

Source code in src/toolregistry/_http.py
def HttpxClientConfig(*args: Any, **kwargs: Any) -> HttpClientConfig:
    """Deprecated alias for HttpClientConfig.

    .. deprecated::
        Use ``HttpClientConfig`` instead. ``HttpxClientConfig`` will be
        removed in a future release.
    """
    warnings.warn(
        "HttpxClientConfig is deprecated, use HttpClientConfig instead",
        DeprecationWarning,
        stacklevel=2,
    )
    return HttpClientConfig(*args, **kwargs)

compute_schema_hash

compute_schema_hash(parameters: dict[str, Any]) -> str

Compute a deterministic SHA-256 hex digest of a JSON Schema dict.

Parameters:

Name Type Description Default
parameters dict[str, Any]

The JSON Schema dict (typically Tool.parameters).

required

Returns:

Type Description
str

A 64-character lowercase hex string.

Source code in src/toolregistry/utils.py
def compute_schema_hash(parameters: dict[str, Any]) -> str:
    """Compute a deterministic SHA-256 hex digest of a JSON Schema dict.

    Args:
        parameters: The JSON Schema dict (typically ``Tool.parameters``).

    Returns:
        A 64-character lowercase hex string.
    """
    canonical = json.dumps(parameters, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()

encode_tool_result

encode_tool_result(result: Any, *, tool_name: str = '') -> str

Encode a tool result to a string suitable for the wire.

Plain strings pass through unchanged. Values in the str-like scalar allowlist keep their historical str() textual form. Enum members are projected through .value at the top level, matching their nested projection; this also covers IntEnum and StrEnum, whose int / str base would otherwise let the plain scalar branch return the bare member. Everything else -- including bytes or datetime -- is serialized with :class:ToolResultJSONEncoder, so dataclasses, Pydantic models, paths, and other common types produce valid JSON instead of Python repr text, and the top-level and nested projections agree.

Parameters:

Name Type Description Default
result Any

Raw value returned by a tool.

required
tool_name str

Tool name, used in the error message when result (or a value nested inside it) cannot be encoded.

''

Returns:

Type Description
str

The encoded result string.

Raises:

Type Description
TypeError

If result has no JSON projection. The message names the tool and the offending type, and suggests how to make the value encodable.

Source code in src/toolregistry/_serialisation.py
def encode_tool_result(result: Any, *, tool_name: str = "") -> str:
    """Encode a tool result to a string suitable for the wire.

    Plain strings pass through unchanged.  Values in the str-like scalar
    allowlist keep their historical ``str()`` textual form.  ``Enum``
    members are projected through ``.value`` at the top level, matching
    their nested projection; this also covers ``IntEnum`` and ``StrEnum``,
    whose ``int`` / ``str`` base would otherwise let the plain scalar
    branch return the bare member.  Everything else -- including ``bytes``
    or ``datetime`` -- is serialized with :class:`ToolResultJSONEncoder`,
    so dataclasses, Pydantic models, paths, and other common types produce
    valid JSON instead of Python ``repr`` text, and the top-level and
    nested projections agree.

    Args:
        result: Raw value returned by a tool.
        tool_name: Tool name, used in the error message when *result* (or
            a value nested inside it) cannot be encoded.

    Returns:
        The encoded result string.

    Raises:
        TypeError: If *result* has no JSON projection.  The message names
            the tool and the offending type, and suggests how to make the
            value encodable.
    """
    if isinstance(result, Enum):
        # Must precede the ``str`` check: ``StrEnum`` (and any
        # ``str``-mixin enum) is a ``str`` instance, and returning the
        # member would put ``S.A`` on the wire instead of ``"a"``.
        return json.dumps(result.value, cls=ToolResultJSONEncoder)
    if isinstance(result, str):
        return result
    if isinstance(result, Decimal) and not result.is_finite():
        # str(Decimal("NaN")) is the bare NaN, which is not valid JSON.
        return "null"
    if isinstance(result, _STR_LIKE_SCALARS) and not isinstance(result, datetime):
        return str(result)
    try:
        return json.dumps(result, cls=ToolResultJSONEncoder)
    except (TypeError, ValueError) as exc:
        raise TypeError(
            f"Tool {tool_name!r} returned a value that cannot be encoded to JSON "
            f"({exc}). Add a to_dict() or model_dump() method to the returned "
            f"type, expose tolist(), or return a str."
        ) from exc

generate_invocation_id

generate_invocation_id(prefix: Literal['bat', 'ptc', 'sig'] = 'sig') -> str

Generate a unique invocation ID for grouping related tool calls.

Prefixes
  • tr_bat_ — batch execution via execute_tool_calls()
  • tr_ptc_ — PTC code execution via PtcTool
  • tr_sig_ — single invocation via registry.invoke()

Parameters:

Name Type Description Default
prefix Literal['bat', 'ptc', 'sig']

One of "bat", "ptc", "sig".

'sig'

Returns:

Type Description
str

A unique ID like "tr_bat_a1b2c3d4".

Source code in src/toolregistry/utils.py
def generate_invocation_id(prefix: Literal["bat", "ptc", "sig"] = "sig") -> str:
    """Generate a unique invocation ID for grouping related tool calls.

    Prefixes:
        - ``tr_bat_`` — batch execution via ``execute_tool_calls()``
        - ``tr_ptc_`` — PTC code execution via ``PtcTool``
        - ``tr_sig_`` — single invocation via ``registry.invoke()``

    Args:
        prefix: One of ``"bat"``, ``"ptc"``, ``"sig"``.

    Returns:
        A unique ID like ``"tr_bat_a1b2c3d4"``.
    """
    return f"tr_{prefix}_{uuid.uuid4().hex[:8]}"

normalize_tool_name

normalize_tool_name(name: str) -> str

Normalize tool name to snake_case format and remove dots and spaces. Also handles OpenAPI-style duplicate names like 'add_add_get' by converting to 'add_get'.

Parameters:

Name Type Description Default
name str

Original tool name in various formats (including CamelCase, UpperCamelCase, or containing spaces)

required

Returns:

Name Type Description
str str

Normalized name in snake_case without dots or spaces

Source code in src/toolregistry/_names.py
def normalize_tool_name(name: str) -> str:
    """Normalize tool name to snake_case format and remove dots and spaces.
    Also handles OpenAPI-style duplicate names like 'add_add_get' by converting to 'add_get'.

    Args:
        name: Original tool name in various formats (including CamelCase, UpperCamelCase, or containing spaces)

    Returns:
        str: Normalized name in snake_case without dots or spaces
    """
    # First check for OpenAPI-style duplicate names (e.g. "add_add_get")
    openapi_pattern = r"^([a-zA-Z0-9]+)_\1_([a-zA-Z0-9]+)$"
    match = re.match(openapi_pattern, name)
    if match:
        return f"{match.group(1)}_{match.group(2)}"

    # Replace all special chars (., -, @, etc.) with single underscore
    name = re.sub(r"[.\-@]+", "_", name)

    # Remove spaces and collapse multiple spaces into a single space
    name = re.sub(r"\s+", " ", name).strip()

    # Replace spaces with underscores
    name = name.replace(" ", "_")

    # Convert CamelCase and UpperCamelCase to snake_case
    # Handles all cases including:
    # XMLParser -> xml_parser
    # getUserIDFromDB -> get_user_id_from_db
    # HTTPRequest -> http_request
    name = re.sub(r"(?<!^)(?=[A-Z][a-z])|(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()

    # Collapse multiple underscores into single underscore
    return re.sub(r"_+", "_", name)

redact_url_userinfo

redact_url_userinfo(text: str) -> str

Remove user:password@ userinfo from every URL in text.

Error messages may quote a URL that a caller supplied. A URL can carry credentials in its userinfo component, so strip them before the message reaches the caller or a log. Three forms are handled: with a scheme, protocol-relative (//user:password@host) and without a scheme (user:password@host). A bare email address is left alone.

This lives in the shared module because the OpenAPI, admin and MCP integrations all need it.

Parameters:

Name Type Description Default
text str

Arbitrary text, such as an exception message.

required

Returns:

Type Description
str

text with each URL's userinfo removed.

Source code in src/toolregistry/_http.py
def redact_url_userinfo(text: str) -> str:
    """Remove ``user:password@`` userinfo from every URL in *text*.

    Error messages may quote a URL that a caller supplied.  A URL can carry
    credentials in its userinfo component, so strip them before the message
    reaches the caller or a log.  Three forms are handled: with a scheme,
    protocol-relative (``//user:password@host``) and without a scheme
    (``user:password@host``).  A bare email address is left alone.

    This lives in the shared module because the OpenAPI, admin and MCP
    integrations all need it.

    Args:
        text: Arbitrary text, such as an exception message.

    Returns:
        *text* with each URL's userinfo removed.
    """
    text = _URL_USERINFO_SCHEME.sub(r"\1", text)
    text = _URL_USERINFO_NETLOC.sub(r"\1", text)
    return _URL_USERINFO_BARE.sub("", text)

utc_iso_now

utc_iso_now() -> str

Return the current UTC time as an ISO 8601 string.

Source code in src/toolregistry/utils.py
def utc_iso_now() -> str:
    """Return the current UTC time as an ISO 8601 string."""
    return datetime.now(timezone.utc).isoformat()