跳转至

MCP 集成

本节介绍 ToolRegistry 库的 Model Context Protocol (MCP) 集成功能。

架构概览

MCP 集成实现了与 Model Context Protocol 服务器的无缝通信,使 LLM 应用能够使用外部 MCP 服务器提供的工具。该架构采用客户端-服务器通信模型:

核心组件

  1. MCPToolWrapper:一个包装器类,提供与 MCP 服务器的同步和异步通信

  2. 通过 MCP 协议处理工具执行

  3. 支持多种内容类型(文本、图像、嵌入式资源)
  4. 管理客户端传输和通信生命周期

  5. MCPTool:一个工具类,包装 MCP 工具规范

  6. 保留原始工具元数据和描述

  7. 将 MCP 模式转换为 ToolRegistry 格式
  8. 支持命名空间组织

  9. MCPIntegration:主集成类,协调服务器通信

  10. 管理与 MCP 服务器的客户端连接
  11. 从服务器发现可用工具
  12. 为不同连接类型处理传输抽象

通信架构

  • 传输层:支持多种传输类型(HTTP、WebSocket、基于文件)
  • 协议层:实现 MCP 规范用于工具发现和执行
  • 内容处理:处理多种内容类型及后处理

主要特性

  • 支持多种传输类型(URL、文件路径、服务器实例)
  • 从 MCP 服务器自动发现工具
  • 多格式内容支持(文本、图像、嵌入式资源)
  • 命名空间管理,用于工具组织
  • 健壮的错误处理和详细日志记录
  • 同步和异步两种操作模式

传输支持

该集成支持多种传输机制:

  • HTTP/HTTPS 端点(可流式 HTTP、SSE)
  • WebSocket 连接
  • 本地文件路径(Python 脚本、JavaScript 文件)
  • 基于字典的 stdio 配置

API 参考

MCPToolWrapper

提供异步和同步版本的 MCP 工具调用的包装器类。

toolregistry.integrations.mcp.integration.MCPToolWrapper

MCPToolWrapper(connection: MCPConnectionManager, name: str, params: list[str] | None)

Bases: BaseToolWrapper

Wrapper class providing both async and sync versions of MCP tool calls.

Attributes:

Name Type Description
name str

Name of the tool/operation.

params Optional[List[str]]

List of parameter names.

Initialize MCP tool wrapper.

Parameters:

Name Type Description Default
connection MCPConnectionManager

Shared connection manager for the MCP server.

required
name str

Name of the tool/operation.

required
params Optional[List[str]]

List of parameter names.

required

transport property

transport: str | dict | Path

Transport source, for backward compatibility.

call_async async

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

Async implementation of MCP tool call.

Parameters:

Name Type Description Default
args Any

Positional arguments to pass to the tool.

()
kwargs Any

Keyword arguments to pass to the tool.

{}

Returns:

Name Type Description
Any Any

Result from tool execution.

Raises:

Type Description
ValueError

If name not set.

Exception

If tool execution fails.

call_sync

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

Synchronous implementation of MCP tool call.

Delegates to the connection manager's call_tool_sync which runs the coroutine on a persistent background event loop, keeping the MCP transport alive across calls.

Parameters:

Name Type Description Default
args Any

Positional arguments to pass to the tool.

()
kwargs Any

Keyword arguments to pass to the tool.

{}

Returns:

Name Type Description
Any Any

Result from tool execution.

Raises:

Type Description
ValueError

If name not set.

Exception

If tool execution fails.

MCPTool

保留原始函数元数据的 MCP 工具包装器类。

toolregistry.integrations.mcp.integration.MCPTool dataclass

MCPTool(*, 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 MCP tools that preserves original function metadata.

Attributes:

Name Type Description
name str

Name of the tool.

description str

Description of the tool.

parameters Dict[str, Any]

Parameter schema definition.

callable Callable[..., Any]

The wrapped callable function.

is_async bool

Whether the tool is async, defaults to False.

from_tool_json classmethod

from_tool_json(tool_spec: Tool, connection: MCPConnectionManager, namespace: str | None = None, sep: NameSeparator = '-') -> MCPTool

Create an MCPTool instance from a JSON representation.

Parameters:

Name Type Description Default
tool_spec Tool

The JSON representation of the tool.

required
connection MCPConnectionManager

Shared connection manager for the MCP server.

required
namespace Optional[str]

An optional namespace to prefix the tool name. If provided, the tool name will be formatted as {namespace}{sep}{name}.

None
sep NameSeparator

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

'-'

Returns:

Name Type Description
MCPTool MCPTool

A new instance of MCPTool configured with the provided parameters.

MCPIntegration

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

toolregistry.integrations.mcp.integration.MCPIntegration

MCPIntegration(registry: ToolRegistry)

Handles integration with MCP server for tool registration.

Attributes:

Name Type Description
registry ToolRegistry

Tool registry instance.

close async

close() -> None

Close all persistent connections (async).

close_sync

close_sync() -> None

Close all persistent connections (sync).

Shuts down background loop threads without requiring an event loop in the calling thread.

refresh

refresh() -> RefreshResult

Synchronous version of :meth:refresh_async.

refresh_async async

refresh_async() -> RefreshResult

Re-list tools from the MCP server and synchronise the registry.

Opens a temporary client connection to call list_tools(), compares with the currently registered set, and applies additions, removals, and updates.

Returns:

Name Type Description
A RefreshResult

class:RefreshResult describing what changed.

Raises:

Type Description
ValueError

If transport was not stored (should not happen after a successful registration).

register_mcp_tools

register_mcp_tools(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True, headers: dict[str, str] | None = None, include: str | list[str] | None = None, exclude: str | list[str] | None = None, allow_replace: bool = False, allow_private_hosts: bool = False) -> None

Register all tools from an MCP server (synchronous entry point).

Parameters:

Name Type Description Default
transport str | dict[str, Any] | Path

MCP server transport — URL string, script path, or stdio dict with command, args, env keys.

required
namespace bool | str

Whether to prefix tool names with a namespace.

False
persistent bool

If True (default), keep the connection open across tool calls.

True
headers dict[str, str] | None

HTTP headers for SSE or streamable-http transports.

None
allow_private_hosts bool

Allow URL transports to reach loopback, link-local or private addresses.

False
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_mcp_tools_async async

register_mcp_tools_async(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True, headers: dict[str, str] | None = None, include: str | list[str] | None = None, exclude: str | list[str] | None = None, allow_replace: bool = False, allow_private_hosts: bool = False) -> None

Async implementation to register all tools from an MCP server.

Parameters:

Name Type Description Default
transport str | dict[str, Any] | Path

MCP server transport — URL string, script path, or stdio dict with command, args, env keys.

required
namespace bool | str

Whether to prefix tool names with a namespace. False (default) means no namespace, True derives it from the server info, or pass a string directly.

False
persistent bool

If True (default), keep the connection open across tool calls.

True
headers dict[str, str] | None

HTTP headers for SSE or streamable-http transports.

None
allow_private_hosts bool

Allow URL transports to reach loopback, link-local or private addresses.

False
include str | list[str] | None

A name, glob pattern, or list of them to keep. Matched against the raw MCP tool name, 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
RuntimeError

If connection to server fails.

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.

模块工具

MCPClient

基于官方 mcp SDK 的最小 MCP 客户端适配器。支持 stdio、SSE、可流式 HTTP 和 WebSocket 传输。

toolregistry.integrations.mcp.client.MCPClient

MCPClient(source: str | dict | Path, headers: dict[str, str] | None = None, allow_private_hosts: bool = False)

Thin async context manager around mcp.ClientSession.

Usage

async with MCPClient("http://localhost:8000/mcp") as client: tools = await client.list_tools() result = await client.call_tool("tool_name", {"arg": "value"})

Initialize MCPClient.

Parameters:

Name Type Description Default
source str | dict | Path

Connection target. Can be: - HTTP(S) URL string for SSE or streamable-http transport - WS(S) URL string for websocket transport - Dict with "command", "args", "env" keys for stdio transport - Path or string path to a .py/.js script for stdio transport

required
headers dict[str, str] | None

Optional HTTP headers to send with SSE or streamable-http requests (e.g. for authentication). Ignored for stdio and websocket transports.

None
allow_private_hosts bool

Allow a URL transport to reach loopback, link-local or private addresses. The default refuses them before any connection is opened.

False

initialize_result property

initialize_result

Access the full initialization result.

Returns:

Type Description

The InitializeResult from the session, or None.

is_connected property

is_connected: bool

Whether the client has an active session.

Returns:

Type Description
bool

True if connected with an active session, False otherwise.

server_info property

server_info

Access server information from the initialization result.

Returns:

Type Description

Server info from the session, or None if not available.

session property

session: ClientSession | None

Access the underlying ClientSession.

Returns:

Type Description
ClientSession | None

The active ClientSession, or None if not connected.

call_tool async

call_tool(name: str, arguments: dict[str, Any]) -> CallToolResult

Call a tool on the MCP server.

Parameters:

Name Type Description Default
name str

Name of the tool to call.

required
arguments dict[str, Any]

Dictionary of arguments to pass to the tool.

required

Returns:

Type Description
CallToolResult

CallToolResult from the MCP server.

list_tools async

list_tools() -> list[ToolSpec]

List available tools from the MCP server.

Returns:

Type Description
list[Tool]

List of ToolSpec objects describing available tools.

MCP 模块

MCP 集成主模块。

toolregistry.integrations.mcp

MCPConnectionManager

MCPConnectionManager(transport: str | dict | Path, headers: dict[str, str] | None = None, persistent: bool = True, allow_private_hosts: bool = False)

Persistent connection manager for an MCP server.

All tools registered from the same server share this connection. Supports lazy connect on first call and auto-reconnect on failure.

For sync callers, the shared :class:AsyncRuntime event loop is used so that the MCP transport stays alive across calls. Async callers use the caller's own loop and are unaffected.

Parameters:

Name Type Description Default
transport str | dict | Path

MCP server source (URL, dict, or Path).

required
headers dict[str, str] | None

Optional HTTP headers for SSE/streamable-http transports.

None
persistent bool

If True (default), keep the connection open across calls. If False, create a new connection per call (original behavior).

True
allow_private_hosts bool

Allow URL transports to reach loopback, link-local or private addresses.

False

is_connected property

is_connected: bool

Whether an active session exists.

transport property

transport: str | dict | Path

The transport source for the MCP server.

__getstate__

__getstate__() -> dict

Drop live connection state before pickling.

The config (transport, headers, persistent flag) is preserved. The live _client (holding OS sockets) and _lock (event-loop-bound) are dropped. The worker process will reconnect lazily on first call_tool().

__setstate__

__setstate__(state: dict) -> None

Restore config; connection will be re-established lazily.

call_tool async

call_tool(name: str, arguments: dict[str, Any]) -> CallToolResult

Call a tool on the MCP server.

Uses persistent or per-request connection based on config.

Parameters:

Name Type Description Default
name str

Name of the tool to call.

required
arguments dict[str, Any]

Arguments to pass to the tool.

required

Returns:

Type Description
CallToolResult

CallToolResult from the MCP server.

call_tool_sync

call_tool_sync(name: str, arguments: dict[str, Any]) -> CallToolResult

Call a tool synchronously via the shared async runtime.

Uses :class:AsyncRuntime so that the MCP transport stays alive across calls without per-instance loop management.

Parameters:

Name Type Description Default
name str

Name of the tool to call.

required
arguments dict[str, Any]

Arguments to pass to the tool.

required

Returns:

Type Description
CallToolResult

CallToolResult from the MCP server.

close async

close() -> None

Close the persistent connection.

close_sync

close_sync() -> None

Close from sync context via the shared async runtime.

list_tools async

list_tools()

List available tools using a temporary connection.

Returns:

Type Description

List of ToolSpec objects.

MCPIntegration

MCPIntegration(registry: ToolRegistry)

Handles integration with MCP server for tool registration.

Attributes:

Name Type Description
registry ToolRegistry

Tool registry instance.

close async

close() -> None

Close all persistent connections (async).

close_sync

close_sync() -> None

Close all persistent connections (sync).

Shuts down background loop threads without requiring an event loop in the calling thread.

refresh

refresh() -> RefreshResult

Synchronous version of :meth:refresh_async.

refresh_async async

refresh_async() -> RefreshResult

Re-list tools from the MCP server and synchronise the registry.

Opens a temporary client connection to call list_tools(), compares with the currently registered set, and applies additions, removals, and updates.

Returns:

Name Type Description
A RefreshResult

class:RefreshResult describing what changed.

Raises:

Type Description
ValueError

If transport was not stored (should not happen after a successful registration).

register_mcp_tools

register_mcp_tools(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True, headers: dict[str, str] | None = None, include: str | list[str] | None = None, exclude: str | list[str] | None = None, allow_replace: bool = False, allow_private_hosts: bool = False) -> None

Register all tools from an MCP server (synchronous entry point).

Parameters:

Name Type Description Default
transport str | dict[str, Any] | Path

MCP server transport — URL string, script path, or stdio dict with command, args, env keys.

required
namespace bool | str

Whether to prefix tool names with a namespace.

False
persistent bool

If True (default), keep the connection open across tool calls.

True
headers dict[str, str] | None

HTTP headers for SSE or streamable-http transports.

None
allow_private_hosts bool

Allow URL transports to reach loopback, link-local or private addresses.

False
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_mcp_tools_async async

register_mcp_tools_async(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True, headers: dict[str, str] | None = None, include: str | list[str] | None = None, exclude: str | list[str] | None = None, allow_replace: bool = False, allow_private_hosts: bool = False) -> None

Async implementation to register all tools from an MCP server.

Parameters:

Name Type Description Default
transport str | dict[str, Any] | Path

MCP server transport — URL string, script path, or stdio dict with command, args, env keys.

required
namespace bool | str

Whether to prefix tool names with a namespace. False (default) means no namespace, True derives it from the server info, or pass a string directly.

False
persistent bool

If True (default), keep the connection open across tool calls.

True
headers dict[str, str] | None

HTTP headers for SSE or streamable-http transports.

None
allow_private_hosts bool

Allow URL transports to reach loopback, link-local or private addresses.

False
include str | list[str] | None

A name, glob pattern, or list of them to keep. Matched against the raw MCP tool name, 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
RuntimeError

If connection to server fails.

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.

MCPTool dataclass

MCPTool(*, 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 MCP tools that preserves original function metadata.

Attributes:

Name Type Description
name str

Name of the tool.

description str

Description of the tool.

parameters Dict[str, Any]

Parameter schema definition.

callable Callable[..., Any]

The wrapped callable function.

is_async bool

Whether the tool is async, defaults to False.

from_tool_json classmethod

from_tool_json(tool_spec: Tool, connection: MCPConnectionManager, namespace: str | None = None, sep: NameSeparator = '-') -> MCPTool

Create an MCPTool instance from a JSON representation.

Parameters:

Name Type Description Default
tool_spec Tool

The JSON representation of the tool.

required
connection MCPConnectionManager

Shared connection manager for the MCP server.

required
namespace Optional[str]

An optional namespace to prefix the tool name. If provided, the tool name will be formatted as {namespace}{sep}{name}.

None
sep NameSeparator

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

'-'

Returns:

Name Type Description
MCPTool MCPTool

A new instance of MCPTool configured with the provided parameters.

MCPToolWrapper

MCPToolWrapper(connection: MCPConnectionManager, name: str, params: list[str] | None)

Bases: BaseToolWrapper

Wrapper class providing both async and sync versions of MCP tool calls.

Attributes:

Name Type Description
name str

Name of the tool/operation.

params Optional[List[str]]

List of parameter names.

Initialize MCP tool wrapper.

Parameters:

Name Type Description Default
connection MCPConnectionManager

Shared connection manager for the MCP server.

required
name str

Name of the tool/operation.

required
params Optional[List[str]]

List of parameter names.

required

transport property

transport: str | dict | Path

Transport source, for backward compatibility.

call_async async

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

Async implementation of MCP tool call.

Parameters:

Name Type Description Default
args Any

Positional arguments to pass to the tool.

()
kwargs Any

Keyword arguments to pass to the tool.

{}

Returns:

Name Type Description
Any Any

Result from tool execution.

Raises:

Type Description
ValueError

If name not set.

Exception

If tool execution fails.

call_sync

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

Synchronous implementation of MCP tool call.

Delegates to the connection manager's call_tool_sync which runs the coroutine on a persistent background event loop, keeping the MCP transport alive across calls.

Parameters:

Name Type Description Default
args Any

Positional arguments to pass to the tool.

()
kwargs Any

Keyword arguments to pass to the tool.

{}

Returns:

Name Type Description
Any Any

Result from tool execution.

Raises:

Type Description
ValueError

If name not set.

Exception

If tool execution fails.