MCPStoreContext 类¶
MCPStoreContext 是 MCPStore 的核心操作上下文类,提供所有服务和工具管理功能。
类定义¶
class MCPStoreContext:
"""
MCPStore 操作上下文
提供服务管理、工具操作、LangChain集成等功能
"""
def __init__(self, store: MCPStore, context_type: ContextType = ContextType.STORE, agent_id: str = None):
"""
初始化上下文
Args:
store: MCPStore 实例
context_type: 上下文类型 (STORE 或 AGENT)
agent_id: Agent ID (仅在 AGENT 模式下使用)
"""
上下文类型¶
ContextType 枚举¶
from enum import Enum
class ContextType(Enum):
STORE = "store" # Store 级别上下文
AGENT = "agent" # Agent 级别上下文
上下文差异¶
特性 | Store 模式 | Agent 模式 |
---|---|---|
服务范围 | 全局所有服务 | 仅该 Agent 的服务 |
服务命名 | 完整名称(含后缀) | 本地名称(隐藏后缀) |
数据隔离 | 全局共享 | Agent 级别隔离 |
配置文件 | 影响 mcp.json | 同时影响多个配置文件 |
核心属性¶
属性 | 类型 | 描述 |
---|---|---|
context_type | ContextType | 上下文类型 |
agent_id | str | Agent ID(Agent 模式下) |
_store | MCPStore | 关联的 MCPStore 实例 |
_service_mapper | ServiceNameMapper | 服务名称映射器 |
_sync_helper | AsyncSyncHelper | 同步/异步转换助手 |
服务操作方法¶
add_service()¶
添加 MCP 服务,支持多种配置格式。
def add_service(self, config: Union[ServiceConfigUnion, List[str], None] = None,
json_file: str = None) -> 'MCPStoreContext'
参数: - config
: 服务配置(字典、列表或None) - json_file
: JSON配置文件路径
返回: 当前上下文实例(支持链式调用)
list_services()¶
获取服务列表。
返回: ServiceInfo 对象列表
get_service_info()¶
获取指定服务的详细信息。
参数: - name
: 服务名称
返回: 服务详细信息字典
restart_service()¶
重启指定服务。
参数: - name
: 服务名称
返回: 重启是否成功
check_services()¶
执行服务健康检查。
返回: 健康检查结果字典
delete_service()¶
删除指定服务。
参数: - name
: 服务名称
返回: 删除是否成功
update_service()¶
更新服务配置。
参数: - name
: 服务名称 - config
: 新的服务配置
返回: 更新是否成功
patch_service()¶
部分更新服务配置。
参数: - name
: 服务名称 - updates
: 要更新的配置项
返回: 更新是否成功
get_service_status()¶
获取单个服务的状态信息。
参数: - name
: 服务名称
返回: 服务状态信息字典
show_config()¶
显示配置信息。
参数: - scope
: 配置范围 ("all", "mcp", "agent", "client")
返回: 配置信息字典
reset_config()¶
重置配置。
参数: - scope
: 重置范围 ("all", "mcp", "agent", "client")
返回: 重置是否成功
show_mcpconfig()¶
显示 MCP 配置。
返回: MCP 配置字典
工具操作方法¶
list_tools()¶
获取工具列表。
返回: ToolInfo 对象列表
call_tool()¶
调用指定工具。
参数: - tool_name
: 工具名称 - args
: 工具参数 - **kwargs
: 额外参数
返回: 工具执行结果
use_tool()¶
调用工具的向后兼容别名。
说明: 与 call_tool()
功能完全相同,保持向后兼容性。
get_tools_with_stats()¶
获取工具列表及统计信息。
返回: 包含工具列表和统计信息的字典
batch_add_services()¶
批量添加服务。
参数: - services
: 服务配置列表
返回: 批量添加结果字典
get_system_stats()¶
获取系统统计信息。
返回: 系统统计信息字典,包含服务数量、工具数量、性能指标等
LangChain 集成¶
for_langchain()¶
获取 LangChain 适配器。
返回: LangChainAdapter 实例
使用示例:
# 获取 LangChain 工具
tools = store.for_store().for_langchain().list_tools()
# 链式调用
tools = (store.for_store()
.add_service(config)
.for_langchain()
.list_tools())
异步版本方法¶
所有同步方法都有对应的异步版本,方法名后缀为 _async
:
# 异步服务操作
async def add_service_async(config, json_file=None) -> 'MCPStoreContext'
async def list_services_async() -> List[ServiceInfo]
async def get_service_info_async(name: str) -> Any
async def restart_service_async(name: str) -> bool
async def check_services_async() -> Dict[str, Any]
# 异步工具操作
async def list_tools_async() -> List[ToolInfo]
async def call_tool_async(tool_name: str, args=None, **kwargs) -> Any
async def use_tool_async(tool_name: str, args=None, **kwargs) -> Any
async def get_tools_with_stats_async() -> Dict[str, Any]
async def batch_add_services_async(services) -> Dict[str, Any]
使用示例¶
Store 级别操作¶
from mcpstore import MCPStore
store = MCPStore.setup_store()
# 获取 Store 上下文
store_context = store.for_store()
# 添加服务
store_context.add_service({
"name": "weather-api",
"url": "https://weather.example.com/mcp"
})
# 列出服务和工具
services = store_context.list_services()
tools = store_context.list_tools()
# 调用工具
result = store_context.call_tool("get_weather", {"city": "北京"})
print(f"Store 级别: {len(services)} 服务, {len(tools)} 工具")
Agent 级别操作¶
from mcpstore import MCPStore
store = MCPStore.setup_store()
# 获取 Agent 上下文
agent_context = store.for_agent("my_agent")
# Agent 级别操作
agent_context.add_service({
"name": "agent-tool",
"url": "https://agent.example.com/mcp"
})
# Agent 只能看到自己的服务
agent_services = agent_context.list_services()
agent_tools = agent_context.list_tools()
print(f"Agent 级别: {len(agent_services)} 服务, {len(agent_tools)} 工具")
链式调用¶
from mcpstore import MCPStore
store = MCPStore.setup_store()
# Store 级别链式调用
result = (store.for_store()
.add_service({"name": "service1", "url": "https://api1.com/mcp"})
.add_service({"name": "service2", "url": "https://api2.com/mcp"})
.list_tools())
print(f"链式调用获得 {len(result)} 个工具")
# Agent 级别链式调用
agent_result = (store.for_agent("test_agent")
.add_service({"name": "agent_service", "url": "https://agent.com/mcp"})
.call_tool("some_tool", {"param": "value"}))
print(f"Agent 工具调用结果: {agent_result}")
异步操作¶
import asyncio
from mcpstore import MCPStore
async def async_operations():
store = MCPStore.setup_store()
# 异步添加服务
context = await store.for_store().add_service_async({
"name": "async-service",
"url": "https://async.example.com/mcp"
})
# 异步获取工具列表
tools = await context.list_tools_async()
# 异步调用工具
result = await context.call_tool_async("async_tool", {"data": "test"})
print(f"异步操作: {len(tools)} 工具, 结果: {result}")
# 运行异步示例
asyncio.run(async_operations())
注意事项¶
- 上下文隔离: Store 和 Agent 上下文完全隔离
- 链式调用: 大部分方法返回上下文实例,支持链式操作
- 异步支持: 所有方法都有异步版本
- 服务名称映射: Agent 模式下自动处理服务名称映射
- 向后兼容: 保留
use_tool()
等向后兼容方法
相关文档¶
- MCPStore 类 - 主入口类
- 数据模型 - 数据结构定义
- 服务注册 - 服务注册方法