跳转至

OpenAPI 集成

本节介绍 ToolRegistry 库的 OpenAPI/Swagger 集成功能。

架构概览

OpenAPI 集成旨在基于 OpenAPI 规范自动发现和注册 REST API 端点为工具。该架构采用三层设计:

核心组件

  1. OpenAPIToolWrapper:一个包装器类,提供同步和异步 HTTP 客户端方法用于 API 调用

  2. 处理 GET、POST、PUT、DELETE 请求

  3. 支持参数处理和验证
  4. 使用内置 HTTP 客户端实现 HTTP 通信

  5. OpenAPITool:一个工具类,保留从 OpenAPI 规范中提取的函数元数据

  6. 从 OpenAPI 规范自动生成参数模式

  7. 规范化工具名称和描述
  8. 支持命名空间

  9. OpenAPIIntegration:主集成类,协调注册流程

  10. 解析 OpenAPI 规范
  11. 为每个端点创建工具实例
  12. 支持同步和异步注册

设计模式

  • 工厂模式:OpenAPITool.from_openapi_spec() 从规范创建工具实例
  • 包装器模式:OpenAPIToolWrapper 为 HTTP 操作提供统一接口
  • 模板方法:同步和异步版本遵循相似的模式,支持 async/await

主要特性

  • 从 OpenAPI 模式自动提取参数
  • 支持查询参数、路径参数和请求体
  • 命名空间支持,用于工具组织
  • 完整的 async/await 兼容性
  • 自动 HTTP 状态错误处理

API 参考

OpenAPIToolWrapper

提供同步和异步方法用于 OpenAPI 工具调用的包装器类。

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

保留函数元数据的 OpenAPI 工具包装器类。

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

处理与 OpenAPI 服务集成以进行工具注册的类。

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.

刷新文档

OpenAPIIntegration.refresh() 使用已保存的 ETag 重新读取注册时的文档。 304 返回 skipped 且不做任何改动:不重建路由,也不更新 last_refreshed_at。文档发生变化时会与现有工具做 diff:运维手动禁用的名称 仍保持禁用,已消失的路径会被注销,定义未变的工具保留其注册表状态。

base URL 会跟随文档,但有边界。注册时文档在 servers[0] 中写明的 URL 会被 记住;只有当前客户端配置仍等于该记忆值时,刷新才会采纳移动后的 servers[0]——调用方显式提供的 base URL 永远不会被替换。只有刷新真正要采纳的 那一个条目会接受出站地址策略检查;不会被拨打的条目既不校验也不解析,而显式 override 会让文档的 servers 与本次刷新无关。模板化条目(如 https://{region}.example.com)在替换前无法解析,因此既不会被采纳也不会被 检查:当前 base URL 保持不变,文档的其余变更照常生效。采纳会重建每个工具的 包装器,包括定义未变的操作;这种替换不计入 updated,而由 RefreshResult.base_url_changed 表示。被拒绝的候选条目会抛出 UnsafeAddressError,工具、配置与已保存的文档都保持不变。

forget_tracked_tools(names) 供「在两次刷新之间移除了工具」的调用方使用——例如 校验步骤丢掉了 schema 无法接受的工具。没有它,下一次刷新会认为该名称仍被跟踪但 不在注册表中,从而永远不会重新注册;调用后,文档修好时名称会回来。它只修改跟踪 集合:注册表与事件由调用方自己处理。

ToolRegistry.openapi_integrations 按创建顺序返回这些集成,因此刚完成注册的 调用方可以直接取最后一个元素,而不必读取私有列表。

模块工具

OpenAPI 工具函数

用于 OpenAPI 处理的实用函数。

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.