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 |
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
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
|
None
|
allow_private_hosts
|
bool
|
Permit base_url to resolve to a loopback,
link-local or private address. Defaults to |
False
|
**extra_options
|
Any
|
Additional client parameters (e.g. verify, proxy,
pool_size, max_response_size). |
{}
|
Source code in src/toolregistry/_http.py
__getstate__ ¶
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
__setstate__ ¶
Restore config; clients will be created lazily on first use.
Source code in src/toolregistry/_http.py
close ¶
Close persistent clients (sync).
Only closes the sync client. Use close_async() to properly
close the async client.
close_async
async
¶
Close all persistent clients.
ensure_base_url_allowed ¶
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: |
Source code in src/toolregistry/_http.py
ensure_base_url_allowed_async
async
¶
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: |
Source code in src/toolregistry/_http.py
get_persistent_client ¶
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
to_client ¶
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
with_base_url ¶
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
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 ¶
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 |
Source code in src/toolregistry/_names.py
accepts ¶
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 ( |
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
warn_if_all_filtered_out ¶
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. |
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
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:
Enummembers -> their.valuepathlib.Path->strDecimal/UUID->strdatetime/date/time-> ISO 8601 stringbytes-> base64-encoded ASCII stringset/frozenset-> JSON array, ordered byreprso 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-argumentto_dict->dict, and array-like objects exposingtolist(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.
HttpxClientConfig ¶
Deprecated alias for HttpClientConfig.
.. deprecated::
Use HttpClientConfig instead. HttpxClientConfig will be
removed in a future release.
Source code in src/toolregistry/_http.py
compute_schema_hash ¶
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 |
required |
Returns:
| Type | Description |
|---|---|
str
|
A 64-character lowercase hex string. |
Source code in src/toolregistry/utils.py
encode_tool_result ¶
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
generate_invocation_id ¶
Generate a unique invocation ID for grouping related tool calls.
Prefixes
tr_bat_— batch execution viaexecute_tool_calls()tr_ptc_— PTC code execution viaPtcTooltr_sig_— single invocation viaregistry.invoke()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
Literal['bat', 'ptc', 'sig']
|
One of |
'sig'
|
Returns:
| Type | Description |
|---|---|
str
|
A unique ID like |
Source code in src/toolregistry/utils.py
normalize_tool_name ¶
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
redact_url_userinfo ¶
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. |