Skip to content

OpenAPI Integration

This section documents the OpenAPI/Swagger integration capabilities of the ToolRegistry library.

Architecture Overview

The OpenAPI integration is designed to automatically discover and register REST API endpoints as tools based on OpenAPI specifications. The architecture follows a three-layer design:

Core Components

  1. OpenAPIToolWrapper: A wrapper class that provides both synchronous and asynchronous HTTP client methods for API calls

  2. Handles GET, POST, PUT, DELETE requests

  3. Supports parameter processing and validation
  4. Integrates with a built-in HTTP client for HTTP communication

  5. OpenAPITool: A tool class that preserves function metadata extracted from OpenAPI specifications

  6. Automatically generates parameter schemas from OpenAPI specs

  7. Normalizes tool names and descriptions
  8. Maintains namespace support

  9. OpenAPIIntegration: The main integration class that orchestrates the registration process

  10. Parses OpenAPI specifications
  11. Creates tool instances for each endpoint
  12. Supports both synchronous and asynchronous registration

Design Patterns

  • Factory Pattern: OpenAPITool.from_openapi_spec() creates tool instances from specifications
  • Wrapper Pattern: OpenAPIToolWrapper provides a unified interface for HTTP operations
  • Template Method: Both sync and async versions follow similar patterns with async/await support

Key Features

  • Automatic parameter extraction from OpenAPI schemas
  • Support for query parameters, path parameters, and request bodies
  • Namespace support for organizing tools
  • Full async/await compatibility
  • Automatic HTTP status error handling

API Reference

OpenAPIToolWrapper

Wrapper class that provides both synchronous and asynchronous methods for OpenAPI tool calls.

toolregistry.integrations.openapi.integration.OpenAPIToolWrapper

OpenAPIToolWrapper(client_config: HttpClientConfig, name: str, method: str, path: str, params: list[str] | None, persistent: bool = True)

Bases: BaseToolWrapper

Wrapper class that provides both synchronous and asynchronous methods for OpenAPI tool calls.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for the HTTP client.

required
name str

The name of the tool.

required
method str

The HTTP method (e.g., "get", "post").

required
path str

The API endpoint path.

required
params Optional[List[str]]

List of parameter names for the API call.

required
persistent bool

If True, reuse a persistent HTTP client.

True

call_async async

call_async(*args: Any, **kwargs: Any) -> Any

Asynchronously call the API using the client configuration.

Parameters:

Name Type Description Default
*args Any

Positional arguments for the API call.

()
**kwargs Any

Keyword arguments for the API call.

{}

Returns:

Name Type Description
Any Any

The JSON response from the API.

Raises:

Type Description
ValueError

If the tool name is not set.

HTTPStatusError

If an HTTP error occurs.

call_sync

call_sync(*args: Any, **kwargs: Any) -> Any

Synchronously call the API using the client configuration.

Parameters:

Name Type Description Default
*args Any

Positional arguments for the API call.

()
**kwargs Any

Keyword arguments for the API call.

{}

Returns:

Name Type Description
Any Any

The JSON response from the API.

Raises:

Type Description
ValueError

If the tool name is not set.

HTTPStatusError

If an HTTP error occurs.

OpenAPITool

Wrapper class for OpenAPI tools preserving function metadata.

toolregistry.integrations.openapi.integration.OpenAPITool dataclass

OpenAPITool(*, name: str, description: str, parameters: dict[str, Any], callable: Callable[..., Any], metadata: ToolMetadata | None = None, parameters_model: Any | None = None, namespace: str | None = None, method_name: str | None = None, is_async: bool | None = None)

Bases: Tool

Wrapper class for OpenAPI tools preserving function metadata.

from_openapi_spec classmethod

from_openapi_spec(client_config: HttpClientConfig, path: str, method: str, spec: dict[str, Any], namespace: str | None = None, persistent: bool = True, sep: NameSeparator = '-') -> OpenAPITool

Create an OpenAPITool instance from an OpenAPI specification.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for HTTP client.

required
path str

API endpoint path.

required
method str

HTTP method.

required
spec Dict[str, Any]

The OpenAPI operation specification.

required
namespace Optional[str]

Optional namespace to prefix tool names with.

None
persistent bool

Whether to reuse a persistent HTTP client.

True
sep NameSeparator

Separator between namespace and tool name. Pass the registry's name_sep so the stored key matches.

'-'

Returns:

Name Type Description
OpenAPITool OpenAPITool

An instance of OpenAPITool configured for the specified operation.

OpenAPIIntegration

Handles integration with OpenAPI services for tool registration.

toolregistry.integrations.openapi.integration.OpenAPIIntegration

OpenAPIIntegration(registry: ToolRegistry)

Handles integration with OpenAPI services for tool registration.

Attributes:

Name Type Description
registry ToolRegistry

The tool registry where tools are registered.

close

close() -> None

Close all persistent HTTP clients (sync).

close_async async

close_async() -> None

Close all persistent HTTP clients (async).

forget_tracked_tools

forget_tracked_tools(names: Iterable[str]) -> None

Stop tracking names, so the next refresh registers them again.

Use this when a caller removes a tracked tool between refreshes — for example because a validation step rejected it. The refresh diff treats a tracked name that the document still lists as unchanged when the registry no longer holds it, so without this call the tool would never come back, even after the document that caused the drop is fixed.

Only the tracked-name set changes. The registry is untouched and no event is emitted, because the caller has already handled both.

Parameters:

Name Type Description Default
names Iterable[str]

Tool names to stop tracking. Unknown names are ignored.

required

refresh

refresh(openapi_spec: dict[str, Any] | None = None) -> RefreshResult

Synchronous version of :meth:refresh_async.

refresh_async async

refresh_async(openapi_spec: dict[str, Any] | None = None) -> RefreshResult

Re-fetch the OpenAPI spec and synchronise registered tools.

A servers[0] that moved is adopted as the new base URL, but only when the current base URL was itself derived from the document (it still equals the URL the registration spec produced). An explicit base URL passed by the caller is kept, and the document's servers are then irrelevant: they are not validated and cannot fail the refresh. Only a candidate that is about to be adopted is checked against the outbound address policy; a refusal raises and leaves both the tools and the base URL untouched. A templated servers[0] is never adopted or checked, because it cannot be resolved before substitution.

Parameters:

Name Type Description Default
openapi_spec dict[str, Any] | None

A pre-parsed spec dict. When None, the spec is re-fetched from :attr:_spec_url (with ETag support) or the last stored spec is reused.

None

Returns:

Name Type Description
A RefreshResult

class:RefreshResult describing what changed.

Raises:

Type Description
ValueError

If no spec can be obtained (no URL and no stored spec).

UnsafeAddressError

If the base URL the refresh would adopt is refused by the outbound address policy.

register_openapi_tools

register_openapi_tools(client_config: HttpClientConfig, openapi_spec: dict[str, Any], namespace: bool | str = False, persistent: bool = True, spec_url: str | None = None, include: str | list[str] | None = None, exclude: str | list[str] | None = None, allow_replace: bool = False) -> None

Synchronously register all tools defined in an OpenAPI specification.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for the HTTP client.

required
openapi_spec dict[str, Any]

The OpenAPI specification dictionary.

required
namespace bool | str

Whether to prefix tool names with a namespace. Defaults to False.

False
persistent bool

If True (default), reuse a persistent HTTP client for connection pooling.

True
spec_url str | None

Optional URL where the spec was fetched from.

None
include str | list[str] | None

A name, glob pattern, or list of them to keep.

None
exclude str | list[str] | None

A name, glob pattern, or list of them to drop.

None
allow_replace bool

Acknowledge replacing an already-registered tool under the same name without warning.

False

register_openapi_tools_async async

register_openapi_tools_async(client_config: HttpClientConfig, openapi_spec: dict[str, Any], namespace: bool | str = False, persistent: bool = True, spec_url: str | None = None, include: str | list[str] | None = None, exclude: str | list[str] | None = None, allow_replace: bool = False) -> None

Asynchronously register all tools defined in an OpenAPI specification.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for the HTTP client.

required
openapi_spec dict[str, Any]

The OpenAPI specification dictionary.

required
namespace bool | str

Whether to prefix tool names with a namespace. - If False, no namespace is used. - If True, the namespace is derived from the OpenAPI info.title. - If a string is provided, it is used as the namespace. Defaults to False.

False
persistent bool

If True (default), reuse a persistent HTTP client for connection pooling.

True
spec_url str | None

Optional URL where the spec was fetched from. Stored for later ETag-based refresh via :meth:refresh_async.

None
include str | list[str] | None

A name, glob pattern, or list of them to keep. Matched against the raw operationId, the post-namespace name, and the snake_case form of each; see :class:~toolregistry.utils.ToolNameFilter. A bare string is treated as a single pattern.

None
exclude str | list[str] | None

A name, glob pattern, or list of them to drop. Mutually exclusive with include.

None
allow_replace bool

Acknowledge replacing an already-registered tool under the same name without warning. Defaults to False.

False

Raises:

Type Description
ValueError

If both include and exclude are given.

start_polling

start_polling(interval: float) -> None

Start periodic background refresh.

Parameters:

Name Type Description Default
interval float

Seconds between refresh attempts.

required

stop_polling

stop_polling() -> None

Stop background polling if active.

Refreshing a document

OpenAPIIntegration.refresh() re-reads the document the source was registered from, using the stored ETag. A 304 returns skipped and changes nothing: no route rebuild, no last_refreshed_at bump. A changed document is diffed against the live tools, so a name the operator disabled by hand stays disabled, a path that disappeared is unregistered, and a tool whose definition did not change keeps its registry state.

The base URL follows the document, within a limit. The URL the registration document named at servers[0] is remembered, and a refresh adopts a moved servers[0] only while the client config still points at that remembered value — a base URL the caller supplied explicitly is never replaced. Only the entry a refresh would adopt is checked against the outbound address policy; entries that are never dialed are neither validated nor resolved, and an explicit override makes the document's servers irrelevant to the refresh. A templated entry such as https://{region}.example.com cannot be resolved before substitution, so it is never adopted or checked: the current base URL stays and the rest of the document still applies. Adoption rebuilds every tool's wrapper, including operations whose definition did not change; that replacement is not counted in updated, and RefreshResult.base_url_changed reports it instead. A candidate that is refused raises UnsafeAddressError and leaves the tools, the config and the stored document untouched.

forget_tracked_tools(names) is the hook for a caller that removes a tool between refreshes — for example a validation step that drops a tool whose schema it cannot accept. Without it the next refresh treats the name as tracked but absent and never registers it again; with it the name comes back when the document is fixed. It only changes the tracked set: the caller has already handled the registry and the events.

ToolRegistry.openapi_integrations returns those integrations in creation order, so a caller that needs the one it just registered can take the last element instead of reading a private list.

Module Utilities

OpenAPI Utils

Utility functions for OpenAPI processing.

toolregistry.integrations.openapi.utils

SpecTooDeepError

Bases: ValueError

An OpenAPI document nests deeper than the configured depth budget.

SpecTooLargeError

Bases: ValueError

A downloaded OpenAPI document exceeds the configured byte budget.

check_spec_servers

check_spec_servers(openapi_spec: dict[str, Any], *, allow_private_hosts: bool = False) -> None

Refuse a servers entry that the outbound policy does not allow.

Every HTTP(S) entry is checked, not only the one a caller returns: a document must not carry a private address that a later step could pick up. Entries that use OpenAPI server variables (https://{region}.example.com) are skipped, because they cannot be resolved before substitution.

Parameters:

Name Type Description Default
openapi_spec dict[str, Any]

The parsed OpenAPI specification.

required
allow_private_hosts bool

Accept an entry that resolves to a loopback, link-local or private address. Defaults to False.

False

Raises:

Type Description
UnsafeAddressError

If any HTTP(S) entry names a host the policy refuses.

determine_urls

determine_urls(url: str, *, max_bytes: int = DEFAULT_MAX_SPEC_BYTES, allow_private_hosts: bool = False, follow_redirects: bool = False) -> dict[str, Any]

Determine whether the given URL or its common endpoints contain an OpenAPI schema.

The probe requests are opened as streams and closed after the headers are inspected, so the probe phase never buffers a body. A candidate whose declared Content-Length exceeds max_bytes is skipped.

Parameters:

Name Type Description Default
url str

Base URL or schema URL.

required
max_bytes int

Maximum declared body size a candidate may have.

DEFAULT_MAX_SPEC_BYTES
allow_private_hosts bool

Probe a host that resolves to a loopback, link-local or private address. Defaults to False.

False
follow_redirects bool

Follow a redirect while probing. Defaults to False: the next hop cannot be validated, so a redirect is refused rather than followed.

False

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: Contains "found" (bool), "schema_url" (str) if valid or None, and "base_api_url" (str).

Raises:

Type Description
UnsafeAddressError

If url is not allowed by the outbound policy.

extract_base_url_from_specs

extract_base_url_from_specs(openapi_spec: dict[str, Any], *, allow_private_hosts: bool = False) -> str | None

Extract and validate the base URL from the 'servers' field.

Every HTTP(S) entry in servers is checked against the outbound address policy, not only the entry that is returned: a document must not carry a private address that a later step could pick up. Entries that use OpenAPI server variables (https://{region}.example.com) are skipped, because they cannot be resolved before substitution.

Parameters:

Name Type Description Default
openapi_spec dict[str, Any]

The parsed OpenAPI specification.

required
allow_private_hosts bool

Accept a server URL that resolves to a loopback, link-local or private address. Defaults to False.

False

Returns:

Type Description
str | None

The validated base API URL from servers[0], or None when the

str | None

first entry is not an HTTP(S) URL or any entry is refused.

first_server_url

first_server_url(openapi_spec: dict[str, Any]) -> str | None

Return servers[0].url when it is an HTTP(S) URL, unchecked.

This only reads the entry that a caller may dial. Whoever adopts the value must validate it against the outbound address policy first; the helper exists so a stored base URL can be derived without resolving entries that will never be requested.

Parameters:

Name Type Description Default
openapi_spec dict[str, Any]

The parsed OpenAPI specification.

required

Returns:

Type Description
str | None

The first server URL without a trailing slash, or None when the

str | None

document names no server or the entry is not an HTTP(S) URL.

load_openapi_spec

load_openapi_spec(uri: str, *, allow_local_files: bool = False, allow_private_hosts: bool = False, follow_redirects: bool = False, max_bytes: int = DEFAULT_MAX_SPEC_BYTES, max_depth: int = DEFAULT_MAX_SPEC_DEPTH) -> dict[str, Any]

Sync version that calls the async implementation.

Parameters:

Name Type Description Default
uri str

URL or file path pointing to an OpenAPI specification.

required
allow_local_files bool

Read uri from the local file system when it names a path or a file:// URI. Defaults to False.

False
allow_private_hosts bool

Fetch from a host that resolves to a loopback, link-local or private address. Defaults to False.

False
follow_redirects bool

Follow an HTTP redirect. Defaults to False: the next hop cannot be validated, so a redirect is refused before the target is contacted. Pass True only for a source you trust to redirect within its own origin.

False
max_bytes int

Maximum number of bytes to read from the document.

DEFAULT_MAX_SPEC_BYTES
max_depth int

Maximum number of nested containers.

DEFAULT_MAX_SPEC_DEPTH

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: A dictionary containing the parsed OpenAPI specification.

Raises:

Type Description
UnsafeAddressError

If uri is not allowed by the outbound policy.

SpecTooLargeError

If the document exceeds max_bytes.

SpecTooDeepError

If the document nests deeper than max_depth or exceeds the interpreter's recursion limit.

ValueError

If URI retrieval, parsing, or decoding fails, or if uri names a local file while allow_local_files is false.

load_openapi_spec_async async

load_openapi_spec_async(uri: str, *, allow_local_files: bool = False, allow_private_hosts: bool = False, follow_redirects: bool = False, max_bytes: int = DEFAULT_MAX_SPEC_BYTES, max_depth: int = DEFAULT_MAX_SPEC_DEPTH) -> dict[str, Any]

Async version of load_openapi_spec using AsyncClient.

A URI with no scheme, or with the file scheme, names a local file. Such a URI is refused by default so that a spec location supplied by someone else cannot be turned into a read of the local file system. A caller that really means to read a local file passes allow_local_files=True.

An HTTP(S) URI is checked against the outbound address policy before any request is made: a host that resolves to a loopback, link-local or private address is refused unless allow_private_hosts is true.

The document is streamed and charged against max_bytes as it arrives. A declared Content-Length above the budget is refused before any body byte is read. Nesting is bounded by max_depth before references are resolved.

Parameters:

Name Type Description Default
uri str

URL or file path pointing to an OpenAPI specification.

required
allow_local_files bool

Read uri from the local file system when it names a path or a file:// URI. Defaults to False.

False
allow_private_hosts bool

Fetch from a host that resolves to a loopback, link-local or private address. Defaults to False.

False
follow_redirects bool

Follow an HTTP redirect. Defaults to False: the next hop cannot be validated, so a redirect is refused before the target is contacted. Pass True only for a source you trust to redirect within its own origin.

False
max_bytes int

Maximum number of bytes to read from the document.

DEFAULT_MAX_SPEC_BYTES
max_depth int

Maximum number of nested containers.

DEFAULT_MAX_SPEC_DEPTH

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: A dictionary containing the parsed OpenAPI specification.

Raises:

Type Description
UnsafeAddressError

If uri is not allowed by the outbound policy.

SpecTooLargeError

If the document exceeds max_bytes.

SpecTooDeepError

If the document nests deeper than max_depth or exceeds the interpreter's recursion limit.

ValueError

If URI retrieval, parsing, or decoding fails, or if uri names a local file while allow_local_files is false.

load_openapi_spec_conditional

load_openapi_spec_conditional(uri: str, etag: str | None = None, headers: dict[str, str] | None = None, *, allow_private_hosts: bool = False, follow_redirects: bool = False, max_bytes: int = DEFAULT_MAX_SPEC_BYTES, max_depth: int = DEFAULT_MAX_SPEC_DEPTH) -> tuple[dict[str, Any] | None, str | None]

Sync version of :func:load_openapi_spec_conditional_async.

load_openapi_spec_conditional_async async

load_openapi_spec_conditional_async(uri: str, etag: str | None = None, headers: dict[str, str] | None = None, *, allow_private_hosts: bool = False, follow_redirects: bool = False, max_bytes: int = DEFAULT_MAX_SPEC_BYTES, max_depth: int = DEFAULT_MAX_SPEC_DEPTH) -> tuple[dict[str, Any] | None, str | None]

Fetch an OpenAPI spec with ETag-based conditional request support.

When etag is provided, an If-None-Match header is sent. If the server responds with 304 Not Modified the spec is unchanged and (None, etag) is returned, avoiding re-parsing. The body is streamed and charged against max_bytes; nesting is bounded by max_depth.

Parameters:

Name Type Description Default
uri str

URL pointing to an OpenAPI specification.

required
etag str | None

ETag value from a previous fetch. None for the first request.

None
headers dict[str, str] | None

Extra HTTP headers to include in the request.

None
allow_private_hosts bool

Fetch from a host that resolves to a loopback, link-local or private address. Defaults to False.

False
follow_redirects bool

Follow an HTTP redirect. Defaults to False: the next hop cannot be validated, so a redirect is refused before the target is contacted. Pass True only for a source you trust to redirect within its own origin.

False
max_bytes int

Maximum number of bytes to read from the document.

DEFAULT_MAX_SPEC_BYTES
max_depth int

Maximum number of nested containers.

DEFAULT_MAX_SPEC_DEPTH

Returns:

Type Description
dict[str, Any] | None

A (spec_dict, new_etag) tuple. spec_dict is None when the

str | None

server returned 304.

Raises:

Type Description
UnsafeAddressError

If uri is not allowed by the outbound policy.

SpecTooLargeError

If the document exceeds max_bytes.

SpecTooDeepError

If the document nests deeper than max_depth or exceeds the interpreter's recursion limit.

validate_spec_url

validate_spec_url(uri: str, *, allow_private_hosts: bool = False) -> str

Return uri unchanged when it is an allowed HTTP(S) URL.

load_openapi_spec reads a URI with no scheme, or with file, as a local path only when the caller opts in with allow_local_files=True, while load_openapi_spec_conditional_async can only fetch over HTTP(S). Callers that accept a URL from an untrusted source use this to refuse anything else before any I/O starts.

The host is resolved on the calling thread. Async callers use :func:validate_spec_url_async.

Parameters:

Name Type Description Default
uri str

A candidate specification URL.

required
allow_private_hosts bool

Accept a host that resolves to a loopback, link-local or private address. Defaults to False.

False

Returns:

Type Description
str

uri, unchanged.

Raises:

Type Description
ValueError

If the URL cannot be parsed, its scheme is not http/https, or it names no host.

UnsafeAddressError

If the host does not resolve, or (unless allow_private_hosts) it resolves to a non-public address.

validate_spec_url_async async

validate_spec_url_async(uri: str, *, allow_private_hosts: bool = False) -> str

Async twin of :func:validate_spec_url.

The resolver runs through the event loop, so a slow name server does not block other tasks.

Parameters:

Name Type Description Default
uri str

A candidate specification URL.

required
allow_private_hosts bool

Accept a host that resolves to a loopback, link-local or private address. Defaults to False.

False

Returns:

Type Description
str

uri, unchanged.

Raises:

Type Description
ValueError

If the URL cannot be parsed, its scheme is not http/https, or it names no host.

UnsafeAddressError

If the host does not resolve, or (unless allow_private_hosts) it resolves to a non-public address.