MCP 集成¶
本节介绍 ToolRegistry 库的 Model Context Protocol (MCP) 集成功能。
架构概览¶
MCP 集成实现了与 Model Context Protocol 服务器的无缝通信,使 LLM 应用能够使用外部 MCP 服务器提供的工具。该架构采用客户端-服务器通信模型:
核心组件¶
-
MCPToolWrapper:一个包装器类,提供与 MCP 服务器的同步和异步通信
-
通过 MCP 协议处理工具执行
- 支持多种内容类型(文本、图像、嵌入式资源)
-
管理客户端传输和通信生命周期
-
MCPTool:一个工具类,包装 MCP 工具规范
-
保留原始工具元数据和描述
- 将 MCP 模式转换为 ToolRegistry 格式
-
支持命名空间组织
-
MCPIntegration:主集成类,协调服务器通信
- 管理与 MCP 服务器的客户端连接
- 从服务器发现可用工具
- 为不同连接类型处理传输抽象
通信架构¶
- 传输层:支持多种传输类型(HTTP、WebSocket、基于文件)
- 协议层:实现 MCP 规范用于工具发现和执行
- 内容处理:处理多种内容类型及后处理
主要特性¶
- 支持多种传输类型(URL、文件路径、服务器实例)
- 从 MCP 服务器自动发现工具
- 多格式内容支持(文本、图像、嵌入式资源)
- 命名空间管理,用于工具组织
- 健壮的错误处理和详细日志记录
- 同步和异步两种操作模式
传输支持¶
该集成支持多种传输机制:
- HTTP/HTTPS 端点(可流式 HTTP、SSE)
- WebSocket 连接
- 本地文件路径(Python 脚本、JavaScript 文件)
- 基于字典的 stdio 配置
API 参考¶
MCPToolWrapper¶
提供异步和同步版本的 MCP 工具调用的包装器类。
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.
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 URL or name not set. |
Exception
|
If tool execution fails. |
MCPTool¶
保留原始函数元数据的 MCP 工具包装器类。
toolregistry.integrations.mcp.integration.MCPTool ¶
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) -> 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}.{name}". |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
MCPTool |
MCPTool
|
A new instance of MCPTool configured with the provided parameters. |
MCPIntegration¶
处理与 MCP 服务器集成以进行工具注册的类。
toolregistry.integrations.mcp.integration.MCPIntegration ¶
Handles integration with MCP server for tool registration.
Attributes:
| Name | Type | Description |
|---|---|---|
registry |
ToolRegistry
|
Tool registry instance. |
register_mcp_tools ¶
register_mcp_tools(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True) -> None
Register all tools from an MCP server (synchronous entry point).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport
|
Union[str, Dict[str, Any], Path]
|
Can be: - URL string (http(s)://, ws(s)://) - Path to script file (.py, .js) - Dict with "command", "args", "env" keys for stdio transport |
required |
namespace
|
Union[bool, str]
|
Whether to prefix tool names with a namespace.
- If |
False
|
persistent
|
bool
|
If True (default), keep the connection open across tool calls. If False, create a new connection per call. |
True
|
register_mcp_tools_async
async
¶
register_mcp_tools_async(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True) -> None
Async implementation to register all tools from an MCP server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport
|
Union[str, Dict[str, Any], Path]
|
Can be: - URL string (http(s)://, ws(s)://) - Path to script file (.py, .js) - Dict with "command", "args", "env" keys for stdio transport |
required |
namespace
|
Union[bool, str]
|
Whether to prefix tool names with a namespace.
- If |
False
|
persistent
|
bool
|
If True (default), keep the connection open across tool calls. If False, create a new connection per call. |
True
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If connection to server fails. |
模块工具¶
MCPClient¶
基于官方 mcp SDK 的最小 MCP 客户端适配器。支持 stdio、SSE、可流式 HTTP 和 WebSocket 传输。
toolregistry.integrations.mcp.client.MCPClient ¶
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
|
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 模块¶
MCP 集成主模块。
toolregistry.integrations.mcp ¶
MCPConnectionManager ¶
MCPConnectionManager(transport: str | dict | Path, headers: dict[str, str] | None = None, persistent: bool = True)
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.
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
|
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. |
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. |
register_mcp_tools ¶
register_mcp_tools(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True) -> None
Register all tools from an MCP server (synchronous entry point).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport
|
Union[str, Dict[str, Any], Path]
|
Can be: - URL string (http(s)://, ws(s)://) - Path to script file (.py, .js) - Dict with "command", "args", "env" keys for stdio transport |
required |
namespace
|
Union[bool, str]
|
Whether to prefix tool names with a namespace.
- If |
False
|
persistent
|
bool
|
If True (default), keep the connection open across tool calls. If False, create a new connection per call. |
True
|
register_mcp_tools_async
async
¶
register_mcp_tools_async(transport: str | dict[str, Any] | Path, namespace: bool | str = False, persistent: bool = True) -> None
Async implementation to register all tools from an MCP server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport
|
Union[str, Dict[str, Any], Path]
|
Can be: - URL string (http(s)://, ws(s)://) - Path to script file (.py, .js) - Dict with "command", "args", "env" keys for stdio transport |
required |
namespace
|
Union[bool, str]
|
Whether to prefix tool names with a namespace.
- If |
False
|
persistent
|
bool
|
If True (default), keep the connection open across tool calls. If False, create a new connection per call. |
True
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If connection to server fails. |
MCPTool ¶
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) -> 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}.{name}". |
None
|
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.
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 URL or name not set. |
Exception
|
If tool execution fails. |