"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): report partial registry construction
er-s-an48c5a0828e7c
diff --git a/agent/src/agent/tools.py b/agent/src/agent/tools.pyindex bf3f59a43..9edab91d1 100644--- a/agent/src/agent/tools.py+++ b/agent/src/agent/tools.py@@ -56,6 +56,8 @@ class ToolRegistry:def __init__(self) -> None:self._tools: Dict[str, BaseTool] = {}+ self._import_failures: Dict[str, str] = {}+ self._registration_failures: Dict[str, str] = {}def register(self, tool: BaseTool) -> None:"""Register a tool."""@@ -69,11 +71,60 @@ class ToolRegistry:"""Return all tools in OpenAI function calling format."""return [t.to_openai_schema() for t in self._tools.values()]+ def record_import_failure(self, module_name: str, reason: str) -> None:+ """Record a tool module that could not be imported during discovery."""+ self._import_failures[module_name] = reason++ def record_registration_failure(self, tool_name: str, reason: str) -> None:+ """Record a discovered tool that could not be instantiated."""+ self._registration_failures[tool_name] = reason++ def _unavailable_reason(self, name: str) -> tuple[str, str] | None:+ registration_reason = self._registration_failures.get(name)+ if registration_reason is not None:+ return name, registration_reason++ for module_name, reason in self._import_failures.items():+ expected_tool_name = module_name.removesuffix("_tool")+ if name in {module_name, expected_tool_name}:+ return module_name, reason+ return None+def execute(self, name: str, params: Dict[str, Any]) -> str:"""Execute a tool and guarantee a valid JSON return value."""tool = self._tools.get(name)if not tool:- return json.dumps({"status": "error", "error": f"Tool '{name}' not found"}, ensure_ascii=False)+ unavailable = self._unavailable_reason(name)+ if unavailable is not None:+ source, reason = unavailable+ return json.dumps(+ {+ "status": "error",+ "error": (+ f"Tool '{name}' is unavailable because '{source}' failed "+ f"during registry construction: {reason}"+ ),+ "registry_incomplete": True,+ "failed_source": source,+ },+ ensure_ascii=False,+ )++ payload: Dict[str, Any] = {+ "status": "error",+ "error": f"Tool '{name}' not found",+ }+ failure_count = len(self._import_failures) + len(+ self._registration_failures+ )+ if failure_count:+ payload["registry_incomplete"] = True+ payload["registry_failure_count"] = failure_count+ payload["error"] += (+ f"; the registry is incomplete because {failure_count} tool "+ "source(s) failed during startup"+ )+ return json.dumps(payload, ensure_ascii=False)try:return tool.execute(**params)except Exception as exc:@@ -87,6 +138,16 @@ class ToolRegistry:def tool_names(self) -> List[str]:return list(self._tools.keys())+ @property+ def import_failures(self) -> Dict[str, str]:+ """Return a copy of module import failures captured during discovery."""+ return dict(self._import_failures)++ @property+ def registration_failures(self) -> Dict[str, str]:+ """Return a copy of tool instantiation failures captured during build."""+ return dict(self._registration_failures)+def __len__(self) -> int:return len(self._tools)diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.pyindex 9c32d6a26..01a4e4a5c 100644--- a/agent/src/tools/__init__.py+++ b/agent/src/tools/__init__.py@@ -27,6 +27,7 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)_SUBCLASSES_CACHE: list[type[BaseTool]] | None = None+_DISCOVERY_FAILURES: dict[str, str] = {}_SHELL_TOOL_NAMES = {"bash", "background_run", "cancel_background"}@@ -38,18 +39,26 @@ def _discover_subclasses() -> list[type[BaseTool]]:Returns:List of concrete BaseTool subclasses with a non-empty name."""- global _SUBCLASSES_CACHE+ global _SUBCLASSES_CACHE, _DISCOVERY_FAILURESif _SUBCLASSES_CACHE is not None:return _SUBCLASSES_CACHEpkg_dir = str(Path(__file__).parent)+ discovery_failures: dict[str, str] = {}for _, module_name, _ in pkgutil.iter_modules([pkg_dir]):if module_name.startswith("_"):continuetry:importlib.import_module(f"src.tools.{module_name}")except Exception as exc:- logger.warning("Skipped src.tools.%s: %s", module_name, exc)+ reason = f"{type(exc).__name__}: {exc}"+ discovery_failures[module_name] = reason+ logger.debug(+ "Skipped src.tools.%s during discovery: %s",+ module_name,+ reason,+ exc_info=True,+ )classes: list[type[BaseTool]] = []queue = deque(BaseTool.__subclasses__())@@ -60,6 +69,7 @@ def _discover_subclasses() -> list[type[BaseTool]]:queue.extend(cls.__subclasses__())_SUBCLASSES_CACHE = classes+ _DISCOVERY_FAILURES = discovery_failuresreturn classes@@ -132,8 +142,12 @@ def build_registry(# Tools that need the host session id injected: they create or mutate the# session's research goal, and the LLM never knows the session id.session_injected_classes = goal_tool_classes | {RunResearchAutopilotTool}+ classes = _discover_subclasses()registry = ToolRegistry()- for cls in _discover_subclasses():+ for module_name, reason in _DISCOVERY_FAILURES.items():+ registry.record_import_failure(module_name, reason)++ for cls in classes:try:if cls.name in _SHELL_TOOL_NAMES and not include_shell_tools:logger.info("Tool %s disabled by shell tool policy", cls.name)@@ -150,7 +164,19 @@ def build_registry(else:registry.register(cls())except Exception as exc:- logger.warning("Failed to register tool %s: %s", cls.name, exc)+ reason = f"{type(exc).__name__}: {exc}"+ registry.record_registration_failure(cls.name, reason)+ logger.warning("Failed to register tool %s: %s", cls.name, reason)++ local_failure_count = len(registry.import_failures) + len(+ registry.registration_failures+ )+ if local_failure_count:+ summary = (+ f"Registered {len(registry)} local tools; {local_failure_count} tool "+ "source(s) failed during registry construction"+ )+ logger.warning(summary)if agent_config and agent_config.mcp_servers:from src.tools.mcp import build_mcp_tool_wrappers, resolve_mcp_server_tool_name_segmentsdiff --git a/agent/tests/test_tool_registry_diagnostics.py b/agent/tests/test_tool_registry_diagnostics.pynew file mode 100644index 000000000..046b172cf--- /dev/null+++ b/agent/tests/test_tool_registry_diagnostics.py@@ -0,0 +1,42 @@+from __future__ import annotations++import json+import logging++from src.agent.tools import ToolRegistry+++def test_missing_tool_reports_matching_import_failure() -> None:+ registry = ToolRegistry()+ registry.record_import_failure(+ "options_pricing_tool",+ "ImportError: No module named 'scipy'",+ )++ payload = json.loads(registry.execute("options_pricing", {}))++ assert payload["status"] == "error"+ assert payload["registry_incomplete"] is True+ assert payload["failed_source"] == "options_pricing_tool"+ assert "No module named 'scipy'" in payload["error"]+++def test_build_registry_surfaces_aggregate_failure_warning(monkeypatch, caplog) -> None:+ import src.tools as tools_module++ monkeypatch.setattr(tools_module, "_discover_subclasses", lambda: [])+ monkeypatch.setattr(+ tools_module,+ "_DISCOVERY_FAILURES",+ {"options_pricing_tool": "ImportError: missing optional dependency"},+ )+ with caplog.at_level(logging.WARNING, logger="src.tools"):+ registry = tools_module.build_registry()++ assert registry.import_failures == {+ "options_pricing_tool": "ImportError: missing optional dependency"+ }+ assert (+ "Registered 0 local tools; 1 tool source(s) failed during registry construction"+ in caplog.messages+ )