Files
Mofox-Core/src/plugin_system/apis/tool_api.py
明天好像没什么 f5e82685a0 feat(plugin): 集成 MCP 协议支持并优化代码风格
- 新增 fastmcp 依赖,支持通过 Streamable HTTP 连接外部工具服务器
- 在 component_registry 与 tool_api 中实现 MCP 工具加载、注册及调用链路
- 补充 README 中的 MCP 特性说明
- 统一修复多处 import 顺序、空行、引号及类型注解,提升代码整洁度
- 在 pyproject.toml 中忽略 PERF203 规则,允许循环内异常处理
- 优化语音缓存与本地 ASR 调用逻辑,减少冗余代码
2025-11-19 23:27:03 +08:00

59 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import Any
from src.common.logger import get_logger
from src.plugin_system.base.base_tool import BaseTool
from src.plugin_system.base.component_types import ComponentType
logger = get_logger("tool_api")
def get_tool_instance(tool_name: str) -> BaseTool | None:
"""获取公开工具实例"""
from src.plugin_system.core import component_registry
# 获取插件配置
tool_info = component_registry.get_component_info(tool_name, ComponentType.TOOL)
if tool_info:
plugin_config = component_registry.get_plugin_config(tool_info.plugin_name)
else:
plugin_config = None
tool_class: type[BaseTool] = component_registry.get_component_class(tool_name, ComponentType.TOOL) # type: ignore
return tool_class(plugin_config) if tool_class else None
def get_llm_available_tool_definitions() -> list[dict[str, Any]]:
"""获取LLM可用的工具定义列表包括 MCP 工具)
Returns:
list[dict[str, Any]]: 工具定义列表
"""
from src.plugin_system.core import component_registry
llm_available_tools = component_registry.get_llm_available_tools()
tool_definitions = []
# 获取常规工具定义
for tool_name, tool_class in llm_available_tools.items():
try:
# 调用类方法 get_tool_definition 获取定义
definition = tool_class.get_tool_definition()
tool_definitions.append(definition)
except Exception as e:
logger.error(f"获取工具 {tool_name} 的定义失败: {e}")
# 获取 MCP 工具定义
try:
mcp_tools = component_registry.get_mcp_tools()
for mcp_tool in mcp_tools:
try:
definition = mcp_tool.get_tool_definition()
tool_definitions.append(definition)
except Exception as e:
logger.error(f"获取 MCP 工具 {mcp_tool.name} 的定义失败: {e}")
except Exception as e:
logger.debug(f"获取 MCP 工具列表失败(可能未启用): {e}")
return tool_definitions