MCP Integration¶
This section documents the Model Context Protocol (MCP) integration capabilities of the ToolRegistry library.
Architecture Overview¶
The MCP integration enables seamless communication with Model Context Protocol servers, allowing LLM applications to utilize tools provided by external MCP servers. The architecture follows a client-server communication model:
Core Components¶
-
MCPToolWrapper: A wrapper class that provides both synchronous and asynchronous communication with MCP servers
-
Handles tool execution via MCP protocol
- Supports various content types (text, image, embedded resources)
-
Manages client transport and communication lifecycle
-
MCPTool: A tool class that wraps MCP tool specifications
-
Preserves original tool metadata and descriptions
- Converts MCP schemas to ToolRegistry format
-
Supports namespace organization
-
MCPIntegration: The main integration class that orchestrates server communication
- Manages client connections to MCP servers
- Discovers available tools from servers
- Handles transport abstraction for different connection types
Communication Architecture¶
- Transport Layer: Supports multiple transport types (HTTP, WebSocket, file-based)
- Protocol Layer: Implements MCP specification for tool discovery and execution
- Content Processing: Handles multiple content types with post-processing
Key Features¶
- Support for various transport types (URL, file paths, server instances)
- Automatic tool discovery from MCP servers
- Multi-format content support (text, images, embedded resources)
- Namespace management for tool organization
- Robust error handling with detailed logging
- Both synchronous and asynchronous operation modes
Transport Support¶
The integration supports multiple transport mechanisms:
- HTTP/HTTPS endpoints (streamable HTTP, SSE)
- WebSocket connections
- Local file paths (Python scripts, JavaScript files)
- Dict-based stdio configurations
API Reference¶
MCPToolWrapper¶
Wrapper class providing both async and sync versions of MCP tool calls.
toolregistry.integrations.mcp.integration.MCPToolWrapper ¶
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 |
call_async
async
¶
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 ¶
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¶
Wrapper class for MCP tools that preserves original function metadata.
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
|
None
|
sep
|
NameSeparator
|
Separator between namespace and tool name. Pass the
registry's |
'-'
|
Returns:
| Name | Type | Description |
|---|---|---|
MCPTool |
MCPTool
|
A new instance of MCPTool configured with the provided parameters. |
MCPIntegration¶
Handles integration with MCP server for tool registration.
toolregistry.integrations.mcp.integration.MCPIntegration ¶
Handles integration with MCP server for tool registration.
Attributes:
| Name | Type | Description |
|---|---|---|
registry |
ToolRegistry
|
Tool registry instance. |
close_sync ¶
Close all persistent connections (sync).
Shuts down background loop threads without requiring an event loop in the calling thread.
refresh_async
async
¶
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: |
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 |
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 |
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.
Matched against the raw MCP tool name, the post-namespace
name, and the snake_case form of each; see
:class: |
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
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If connection to server fails. |
ValueError
|
If both include and exclude are given. |
start_polling ¶
Start periodic background refresh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Seconds between refresh attempts. |
required |
Module Utilities¶
MCPClient¶
Minimal MCP client adapter over the official mcp SDK. Supports stdio, SSE, streamable-http, and websocket transports.
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
¶
Access the full initialization result.
Returns:
| Type | Description |
|---|---|
|
The InitializeResult from the session, or None. |
is_connected
property
¶
Whether the client has an active session.
Returns:
| Type | Description |
|---|---|
bool
|
True if connected with an active session, False otherwise. |
server_info
property
¶
Access server information from the initialization result.
Returns:
| Type | Description |
|---|---|
|
Server info from the session, or None if not available. |
session
property
¶
Access the underlying ClientSession.
Returns:
| Type | Description |
|---|---|
ClientSession | None
|
The active ClientSession, or None if not connected. |
call_tool
async
¶
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 available tools from the MCP server.
Returns:
| Type | Description |
|---|---|
list[Tool]
|
List of ToolSpec objects describing available tools. |
MCP Module¶
The main MCP integration module.
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
|
__getstate__ ¶
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__ ¶
Restore config; connection will be re-established lazily.
call_tool
async
¶
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 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. |
list_tools
async
¶
List available tools using a temporary connection.
Returns:
| Type | Description |
|---|---|
|
List of ToolSpec objects. |
MCPIntegration ¶
Handles integration with MCP server for tool registration.
Attributes:
| Name | Type | Description |
|---|---|---|
registry |
ToolRegistry
|
Tool registry instance. |
close_sync ¶
Close all persistent connections (sync).
Shuts down background loop threads without requiring an event loop in the calling thread.
refresh_async
async
¶
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: |
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 |
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 |
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.
Matched against the raw MCP tool name, the post-namespace
name, and the snake_case form of each; see
:class: |
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
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If connection to server fails. |
ValueError
|
If both include and exclude are given. |
start_polling ¶
Start periodic background refresh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Seconds between refresh attempts. |
required |
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
|
None
|
sep
|
NameSeparator
|
Separator between namespace and tool name. Pass the
registry's |
'-'
|
Returns:
| Name | Type | Description |
|---|---|---|
MCPTool |
MCPTool
|
A new instance of MCPTool configured with the provided parameters. |
MCPToolWrapper ¶
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 |
call_async
async
¶
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 ¶
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. |