JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
perf(server): 汇总 MCP 批量注册成功日志
qq_52878433110beb269479
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 8089089304..d3a08eafe5 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -24,6 +24,7 @@ import threadingimport timeimport uuidfrom collections import Counter+from contextlib import AbstractContextManager, nullcontextfrom contextvars import ContextVar, Tokenfrom dataclasses import dataclass, field, replacefrom pathlib import Path@@ -5054,39 +5055,51 @@ class JiuWenSwarmDeepAdapter:def _install_staged_request_mcp_tools(self, buffers: _RequestMcpToolBuffers) -> None:"""Install a fully discovered generation without yielding to another request."""- for tool, strict in buffers.pending_tools:- card = tool.card- result = Runner.resource_mgr.add_tool(tool, tag="office-claw")- is_ok = getattr(result, "is_ok", None)- succeeded = bool(is_ok()) if callable(is_ok) else result is not False- if not succeeded:- if strict:- raise RuntimeError(f"failed to register OfficeClaw MCP tool: {card.name}")- logger.warning("[JiuWenSwarmDeepAdapter] MCP add_tool failed: tool_id=%s", card.id)- continue- # Track before installing the card so failures can roll back only our resources.- buffers.tool_ids.append(card.id)- buffers.tool_names.append(card.name)- buffers.registered_tools.append(tool)- try:- self._install_office_claw_ability_card(card)- except OfficeClawMcpBuiltinNameConflict:- if strict:- raise- # A user connector's built-in collision skips just that tool.+ # Older agent-core versions keep per-tool INFO logs without this optimization.+ logging_scope: AbstractContextManager[None]+ try:+ from openjiuwen.core.runner.resources_manager.registration_logging import batch_registration_logging+ except ModuleNotFoundError as exc:+ if exc.name != "openjiuwen.core.runner.resources_manager.registration_logging":+ raise+ logging_scope = nullcontext()+ else:+ logging_scope = batch_registration_logging()++ with logging_scope:+ for tool, strict in buffers.pending_tools:+ card = tool.card+ result = Runner.resource_mgr.add_tool(tool, tag="office-claw")+ is_ok = getattr(result, "is_ok", None)+ succeeded = bool(is_ok()) if callable(is_ok) else result is not False+ if not succeeded:+ if strict:+ raise RuntimeError(f"failed to register OfficeClaw MCP tool: {card.name}")+ logger.warning("[JiuWenSwarmDeepAdapter] MCP add_tool failed: tool_id=%s", card.id)+ continue+ # Track before installing the card so failures can roll back only our resources.+ buffers.tool_ids.append(card.id)+ buffers.tool_names.append(card.name)+ buffers.registered_tools.append(tool)try:- Runner.resource_mgr.remove_tool(card.id)- except Exception as exc:+ self._install_office_claw_ability_card(card)+ except OfficeClawMcpBuiltinNameConflict:+ if strict:+ raise+ # A user connector's built-in collision skips just that tool.+ try:+ Runner.resource_mgr.remove_tool(card.id)+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] MCP shadow-skip resource cleanup failed: "+ "tool_id=%s error=%s", card.id, exc,+ )+ buffers.tool_ids.pop()+ buffers.tool_names.pop()+ buffers.registered_tools.pop()logger.warning(- "[JiuWenSwarmDeepAdapter] MCP shadow-skip resource cleanup failed: "- "tool_id=%s error=%s", card.id, exc,+ "[JiuWenSwarmDeepAdapter] MCP tool shadows a built-in, skipped: tool_id=%s", card.id,)- buffers.tool_ids.pop()- buffers.tool_names.pop()- buffers.registered_tools.pop()- logger.warning(- "[JiuWenSwarmDeepAdapter] MCP tool shadows a built-in, skipped: tool_id=%s", card.id,- )def _activate_empty_request_scoped_mcp_registration(self, registration: OfficeClawMcpRegistration,@@ -5164,7 +5177,9 @@ class JiuWenSwarmDeepAdapter:return generation# There must be no await from this guard through publication: a slow# old discovery must never overwrite a newer request's tool bindings.+ install_started = time.perf_counter()self._install_staged_request_mcp_tools(buffers)+ install_ms = (time.perf_counter() - install_started) * 1000registration = _registration()if not replace_request_scoped_mcp_registration(generation, registration):raise RuntimeError("request-scoped MCP generation superseded during install")@@ -5180,8 +5195,9 @@ class JiuWenSwarmDeepAdapter:)logger.info("[JiuWenSwarmDeepAdapter] request-scoped MCP registered: "- "request_id=%s session_id=%s tools=%s", request.request_id,- request.session_id, buffers.tool_names,+ "request_id=%s session_id=%s tools=%s registered=%s skipped=%s install_ms=%.1f",+ request.request_id, request.session_id, buffers.tool_names,+ len(buffers.tool_ids), len(buffers.pending_tools) - len(buffers.tool_ids), install_ms,)logger.info("[latency] stage=2 name=mcp request_id=%s", request.request_id)return registrationdiff --git a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.pyindex 7ff826bed1..d2d15529a3 100644--- a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py+++ b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py@@ -1525,3 +1525,144 @@ def test_rail_set_office_claw_binding_stores_thread_and_invocation() -> None:rail.set_office_claw_active_tool_ids(None)assert rail._office_claw_delivery_thread_id is Noneassert rail._office_claw_invocation_id is None++[email protected](params=[True, False], ids=["installed-core", "forced-fallback"])+def batch_logging_available(request, monkeypatch):+ if not request.param:+ import builtins++ original_import = builtins.__import__++ def import_without_batch_logging(name, *args, **kwargs):+ if name == "openjiuwen.core.runner.resources_manager.registration_logging":+ raise ModuleNotFoundError(f"No module named {name!r}", name=name)+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", import_without_batch_logging)++ # The installed core may already be old; the parameter only controls fault injection.+ try:+ from openjiuwen.core.runner.resources_manager.registration_logging import batch_registration_logging+ except ModuleNotFoundError as exc:+ if exc.name != "openjiuwen.core.runner.resources_manager.registration_logging":+ raise+ return False+ assert callable(batch_registration_logging)+ return True+++async def test_batch_registration_uses_real_resources_and_one_summary(monkeypatch, batch_logging_available):+ from unittest.mock import Mock++ from openjiuwen.core.runner.resources_manager import resource_manager, tag_manager+ from openjiuwen.core.runner.resources_manager.resource_manager import ResourceMgr++ for key, value in _startup_env().items():+ monkeypatch.setenv(key, value)+ manager = ResourceMgr()+ resource_log, tag_log, adapter_log = Mock(), Mock(), Mock()+ monkeypatch.setattr(resource_manager, "logger", resource_log)+ monkeypatch.setattr(tag_manager, "logger", tag_log)+ monkeypatch.setattr(interface_deep, "logger", adapter_log)+ monkeypatch.setattr(interface_deep, "Runner", SimpleNamespace(resource_mgr=manager))+ monkeypatch.setattr(interface_deep, "list_office_claw_mcp_tools", AsyncMock(return_value=_tool_list()))+ adapter = _bare_session_adapter()+ registration = await adapter.register_request_scoped_office_claw_mcp(_request(_valid_config()))+ try:+ assert len(registration.tool_ids) == 2+ for tool in registration.tool_instances:+ assert manager.get_tool(tool.card.id) is tool+ assert manager.resource_has_tag(tool.card.id, "office-claw")+ assert adapter._instance.ability_manager.get(tool.card.name).id == tool.card.id+ if batch_logging_available:+ resource_log.info.assert_not_called()+ tag_log.info.assert_not_called()+ resource_details = resource_log.debug if batch_logging_available else resource_log.info+ tag_details = tag_log.debug if batch_logging_available else tag_log.info+ assert {+ call.kwargs.get("resource_id") for call in resource_details.call_args_list+ if call.args and call.args[0] == "add resource succeed"+ } == set(registration.tool_ids)+ # Old core formats eagerly; new core passes the template and arguments separately.+ tag_messages = [+ str(call.args[0]) % call.args[1:] if len(call.args) > 1 else str(call.args[0])+ for call in tag_details.call_args_list if call.args+ ]+ tag_prefix = "Added tags to resource. resource_id="+ assert {+ message.removeprefix(tag_prefix).split(",", 1)[0]+ for message in tag_messages if message.startswith(tag_prefix)+ } == set(registration.tool_ids)+ summaries = [c for c in adapter_log.info.call_args_list if "MCP registered:" in c.args[0]]+ assert len(summaries) == 1+ assert summaries[0].args[4:6] == (2, 0)+ assert summaries[0].args[6] >= 0+ finally:+ await adapter.cleanup_request_scoped_office_claw_mcp(registration)+ assert adapter._instance.ability_manager.cards == {}+ assert all(manager.get_tool(tool_id) is None for tool_id in registration.tool_ids)+++async def test_batch_registration_failure_rolls_back_and_restores_logging(monkeypatch, batch_logging_available):+ from unittest.mock import Mock++ from openjiuwen.core.runner.resources_manager import resource_manager, tag_manager+ from openjiuwen.core.runner.resources_manager.resource_manager import ResourceMgr++ for key, value in _startup_env().items():+ monkeypatch.setenv(key, value)+ manager = ResourceMgr()+ resource_log, tag_log, adapter_log = Mock(), Mock(), Mock()+ monkeypatch.setattr(resource_manager, "logger", resource_log)+ monkeypatch.setattr(tag_manager, "logger", tag_log)+ monkeypatch.setattr(interface_deep, "logger", adapter_log)+ monkeypatch.setattr(interface_deep, "Runner", SimpleNamespace(resource_mgr=manager))+ monkeypatch.setattr(interface_deep, "list_office_claw_mcp_tools", AsyncMock(return_value=_tool_list()))+ adapter = _bare_session_adapter()+ attempted = []+ original_add = manager.add_tool++ def fail_second(tool, **kwargs):+ attempted.append(tool)+ if len(attempted) == 2:+ raise RuntimeError("second registration failed")+ return original_add(tool, **kwargs)++ monkeypatch.setattr(manager, "add_tool", fail_second)+ registration = await adapter.register_request_scoped_office_claw_mcp(_request(_valid_config()))+ try:+ assert len(attempted) == 2+ assert registration.tool_ids == ()+ assert adapter._instance.ability_manager.cards == {}+ assert all(manager.get_tool(tool.card.id) is None for tool in attempted)+ assert any("registration failed" in c.args[0] for c in adapter_log.warning.call_args_list)+ assert not any("MCP registered:" in c.args[0] for c in adapter_log.info.call_args_list)+ resource_log.info.reset_mock()+ assert original_add(attempted[0], tag="office-claw").is_ok()+ resource_log.info.assert_called_once() # Scope did not leak after failure.+ finally:+ for tool in attempted:+ if manager.get_tool(tool.card.id) is tool:+ manager.remove_tool(tool.card.id)+ await adapter.cleanup_request_scoped_office_claw_mcp(registration)+++def test_batch_registration_does_not_hide_transitive_import_failure(monkeypatch):+ import builtins++ original_import = builtins.__import__+ failure = ModuleNotFoundError("missing logging dependency", name="missing_logging_dependency")++ def import_with_broken_dependency(name, *args, **kwargs):+ if name == "openjiuwen.core.runner.resources_manager.registration_logging":+ raise failure+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", import_with_broken_dependency)+ adapter = _bare_session_adapter()+ with pytest.raises(ModuleNotFoundError) as captured:+ adapter._install_staged_request_mcp_tools(interface_deep._RequestMcpToolBuffers())+ assert captured.value is failure