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
fix(officeclaw): 修复 invoke_tool 调用 MCP 定时工具报请求绑定缺失
white2025ea7a8c12a007
diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.pyindex 778be40b6d..e1837fc17c 100644--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py@@ -31,7 +31,10 @@ from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (InvokeToolInput,InvokeToolTool,)-from jiuwenswarm.common.mcp_config import resolve_active_office_claw_tool_id+from jiuwenswarm.common.mcp_config import (+ bind_office_claw_from_agent,+ resolve_active_office_claw_tool_id,+)logger = logging.getLogger(__name__)@@ -907,108 +910,119 @@ class ProgressiveToolRail(DeepAgentRail):"tool_name": tool_name,}- target_tool_card = None- for tool in self._cached_deferred_tool_infos:- if str(getattr(tool, "name", "") or "") == tool_name:- target_tool_card = tool- break-- if target_tool_card is None:- agent = self._resolve_runtime_agent()- ability_manager = getattr(agent, "ability_manager", None)- lookup_timeout = getattr(AbilityManager, "_resolve_call_timeout")(None)- try:- with anyio.fail_after(lookup_timeout):- if ability_manager is not None:- try:- await ability_manager.list_tool_info()- except Exception as exc:- logger.warning(- "%s invoke fallback list_tool_info failed: %s",- _LOG_PREFIX,- exc,- )- await self._refresh_deferred_tool_cache()- for tool in self._cached_deferred_tool_infos:- if str(getattr(tool, "name", "") or "") == tool_name:- target_tool_card = tool- break- except TimeoutError:+ # Re-bind the OfficeClaw tool id allowlist from the shared ability_manager.+ # The supervisor / round task (where this code runs) was created at+ # session startup, before ``bind_active_office_claw_mcp_tools`` set+ # the ContextVar in the caller's task. ``bind_office_claw_from_agent``+ # reads the ids stored on the shared ability_manager by+ # ``register_request_scoped_office_claw_mcp`` and sets the ContextVar+ # for this task so that both tool resolution+ # (``resolve_active_office_claw_tool_id``) and tool invocation+ # (``ensure_request_scoped_office_claw_tool_allowed``) pass.+ runtime_agent = self._resolve_runtime_agent()+ with bind_office_claw_from_agent(runtime_agent):+ target_tool_card = None+ for tool in self._cached_deferred_tool_infos:+ if str(getattr(tool, "name", "") or "") == tool_name:+ target_tool_card = tool+ break++ if target_tool_card is None:+ agent = self._resolve_runtime_agent()+ ability_manager = getattr(agent, "ability_manager", None)+ lookup_timeout = getattr(AbilityManager, "_resolve_call_timeout")(None)+ try:+ with anyio.fail_after(lookup_timeout):+ if ability_manager is not None:+ try:+ await ability_manager.list_tool_info()+ except Exception as exc:+ logger.warning(+ "%s invoke fallback list_tool_info failed: %s",+ _LOG_PREFIX,+ exc,+ )+ await self._refresh_deferred_tool_cache()+ for tool in self._cached_deferred_tool_infos:+ if str(getattr(tool, "name", "") or "") == tool_name:+ target_tool_card = tool+ break+ except TimeoutError:+ return {+ "success": False,+ "error": (+ f"Tool lookup for '{tool_name}' timed out after "+ f"{lookup_timeout}s"+ ),+ "tool_name": tool_name,+ }++ if target_tool_card is None:return {"success": False,- "error": (- f"Tool lookup for '{tool_name}' timed out after "- f"{lookup_timeout}s"- ),+ "error": f"工具 '{tool_name}' 未注册或不在按需可见工具列表中。","tool_name": tool_name,}- if target_tool_card is None:- return {- "success": False,- "error": f"工具 '{tool_name}' 未注册或不在按需可见工具列表中。",- "tool_name": tool_name,- }-- preferred_id = str(getattr(target_tool_card, "id", "") or "")- target_tool, target_tool_id, refreshed_id = await self._resolve_tool_instance_with_recovery(- tool_name,- preferred_id,- )-- if target_tool is None:- logger.warning(- "%s invoke tool=%s failed: instance not found, "- "tool_id=%s, refresh_attempted=True, refreshed_id=%s, active_id=%s",- _LOG_PREFIX,+ preferred_id = str(getattr(target_tool_card, "id", "") or "")+ target_tool, target_tool_id, refreshed_id = await self._resolve_tool_instance_with_recovery(tool_name,- target_tool_id,- refreshed_id,- resolve_active_office_claw_tool_id(tool_name) or "",+ preferred_id,)- return {- "success": False,- "error": f"无法获取工具 '{tool_name}' 的实例。",- "tool_name": tool_name,- }- try:- kwargs_without_session = {k: v for k, v in kwargs.items() if k != "session"}- call_timeout = getattr(AbilityManager, "_resolve_call_timeout")(- target_tool_card- )- with self._bind_deepresearch_context(tool_name):- try:- with anyio.fail_after(call_timeout) as timeout_scope:- result = await target_tool.invoke(- arguments, session=session, **kwargs_without_session- )- except TimeoutError as exc:- if not timeout_scope.cancel_called:- raise- raise TimeoutError(- f"Tool '{tool_name}' timed out after {call_timeout}s"- ) from exc- logger.info(- "%s invoke tool=%s success=True result_type=%s",- _LOG_PREFIX,- tool_name,- type(result).__name__,- )- return {- "success": True,- "tool_name": tool_name,- "result": _json_safe_value(result),- }- except Exception as exc:- logger.warning(- "%s invoke tool=%s failed: %s",- _LOG_PREFIX,- tool_name,- exc,- )- return {- "success": False,- "error": str(exc),- "tool_name": tool_name,- }+ if target_tool is None:+ logger.warning(+ "%s invoke tool=%s failed: instance not found, "+ "tool_id=%s, refresh_attempted=True, refreshed_id=%s, active_id=%s",+ _LOG_PREFIX,+ tool_name,+ target_tool_id,+ refreshed_id,+ resolve_active_office_claw_tool_id(tool_name) or "",+ )+ return {+ "success": False,+ "error": f"无法获取工具 '{tool_name}' 的实例。",+ "tool_name": tool_name,+ }++ try:+ kwargs_without_session = {k: v for k, v in kwargs.items() if k != "session"}+ call_timeout = getattr(AbilityManager, "_resolve_call_timeout")(+ target_tool_card+ )+ with self._bind_deepresearch_context(tool_name):+ try:+ with anyio.fail_after(call_timeout) as timeout_scope:+ result = await target_tool.invoke(+ arguments, session=session, **kwargs_without_session+ )+ except TimeoutError as exc:+ if not timeout_scope.cancel_called:+ raise+ raise TimeoutError(+ f"Tool '{tool_name}' timed out after {call_timeout}s"+ ) from exc+ logger.info(+ "%s invoke tool=%s success=True result_type=%s",+ _LOG_PREFIX,+ tool_name,+ type(result).__name__,+ )+ return {+ "success": True,+ "tool_name": tool_name,+ "result": _json_safe_value(result),+ }+ except Exception as exc:+ logger.warning(+ "%s invoke tool=%s failed: %s",+ _LOG_PREFIX,+ tool_name,+ exc,+ )+ return {+ "success": False,+ "error": str(exc),+ "tool_name": tool_name,+ }diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex 8b1c30a6c6..e787fb1f5b 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -814,6 +814,15 @@ class OfficeClawMcpRegistration:OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX = "office-claw-request-"+# Attribute name used to store the request-scoped OfficeClaw tool id allowlist.+# The allowlist must cross the asyncio task boundary between the caller's task+# (where ``bind_active_office_claw_mcp_tools`` sets a ContextVar) and the+# DeepAgent's supervisor / round task (created at session startup, before the+# ContextVar is set). Storing the ids on the shared ability_manager gives the+# round task a reliable source to re-bind the ContextVar before invoking an+# OfficeClaw MCP tool.+_OFFICE_CLAW_TOOL_IDS_ATTR = "_active_office_claw_tool_ids"+# Task-local allowlist for request-scoped OfficeClaw tool ids. Set for the# duration of one Relay chat.send so a concurrent session cannot invoke this# request's MCP tools (or vice versa) via a polluted short-name AbilityManager.@@ -823,6 +832,24 @@ _active_office_claw_tool_ids: ContextVar[frozenset[str] | None] = ContextVar()+def _office_claw_tool_ids_carrier(agent: Any) -> Any:+ """Return the object that carries the request-scoped allowlist.++ The DeepAgent and its inner ReActAgent share the same ``ability_manager``+ (openjiuwen wires ``agent.ability_manager = deep_agent.ability_manager``),+ so storing the allowlist on the ability_manager makes it visible to+ whichever agent object runs the round (``ctx.agent`` may be either the+ DeepAgent or the ReActAgent).+ """++ if agent is None:+ return None+ ability_manager = getattr(agent, "ability_manager", None)+ if ability_manager is not None:+ return ability_manager+ return agent++@contextmanagerdef bind_active_office_claw_mcp_tools(tool_ids: Iterable[str] | None,@@ -837,6 +864,69 @@ def bind_active_office_claw_mcp_tools(_active_office_claw_tool_ids.reset(token)+def set_agent_office_claw_tool_ids(agent: Any, tool_ids: Iterable[str] | None) -> None:+ """Store the request-scoped OfficeClaw tool id allowlist on the shared ability_manager.++ The ContextVar ``_active_office_claw_tool_ids`` cannot propagate to the+ DeepAgent's supervisor task because that task is created (via+ ``asyncio.create_task``) at session startup — before the caller enters+ ``bind_active_office_claw_mcp_tools``. Storing the ids on the shared+ ability_manager gives the round task a way to re-bind the ContextVar+ before invoking an OfficeClaw MCP tool.+ """++ carrier = _office_claw_tool_ids_carrier(agent)+ if carrier is None:+ return+ ids = frozenset(str(tid) for tid in (tool_ids or ()) if str(tid))+ if ids:+ setattr(carrier, _OFFICE_CLAW_TOOL_IDS_ATTR, ids)+ else:+ try:+ delattr(carrier, _OFFICE_CLAW_TOOL_IDS_ATTR)+ except AttributeError:+ pass+++def clear_agent_office_claw_tool_ids(agent: Any) -> None:+ """Remove the request-scoped allowlist from the shared ability_manager."""++ carrier = _office_claw_tool_ids_carrier(agent)+ if carrier is None:+ return+ try:+ delattr(carrier, _OFFICE_CLAW_TOOL_IDS_ATTR)+ except AttributeError:+ pass+++@contextmanager+def bind_office_claw_from_agent(agent: Any) -> Iterator[None]:+ """Re-bind the ContextVar from the shared ability_manager for the current task.++ Call this inside the round task (e.g. in ``ProgressiveToolRail``) right+ before invoking an OfficeClaw MCP tool. If the shared ability_manager+ carries a stored allowlist, the ContextVar is set for the duration of the+ call so that ``ensure_request_scoped_office_claw_tool_allowed`` passes.+ """++ carrier = _office_claw_tool_ids_carrier(agent)+ ids = getattr(carrier, _OFFICE_CLAW_TOOL_IDS_ATTR, None) if carrier is not None else None+ if not ids:+ logger.debug(+ "OfficeClaw request-scoped allowlist not found on carrier; "+ "leaving ContextVar unbound for this invoke (agent_type=%s)",+ type(agent).__name__ if agent is not None else None,+ )+ yield+ return+ token = _active_office_claw_tool_ids.set(ids)+ try:+ yield+ finally:+ _active_office_claw_tool_ids.reset(token)++def ensure_request_scoped_office_claw_tool_allowed(tool_id: str) -> None:"""Refuse request-scoped OfficeClaw tools outside the active request allowlist."""@@ -1165,6 +1255,9 @@ __all__ = ["OfficeClawMcpRegistration","RequestScopedOfficeClawMcpTool","bind_active_office_claw_mcp_tools",+ "bind_office_claw_from_agent",+ "clear_agent_office_claw_tool_ids",+ "set_agent_office_claw_tool_ids","build_enabled_mcp_server_configs","build_mcp_server_config","create_mcp_tool",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 88a1b0a74e..afd1ff95c7 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -411,11 +411,13 @@ from jiuwenswarm.common.mcp_config import (RequestScopedOfficeClawMcpTool,bind_active_office_claw_mcp_tools,build_mcp_server_config,+ clear_agent_office_claw_tool_ids,extract_enabled_mcp_server_entries,extract_office_claw_mcp,is_asyncio_outer_cancellation,list_office_claw_mcp_tools,preflight_mcp_server_reachable,+ set_agent_office_claw_tool_ids,validate_office_claw_mcp_config,)from jiuwenswarm.common.mcp_call_timeout_patch import apply_mcp_call_timeout_patch@@ -3733,6 +3735,10 @@ class JiuWenSwarmDeepAdapter:tool_names=tuple(tool_names),)self._active_office_claw_mcp = registration+ # Store tool_ids on the agent's shared ability_manager so the+ # supervisor / round task (created before bind_active_office_claw_mcp_tools)+ # can re-bind the ContextVar before invoking OfficeClaw tools.+ set_agent_office_claw_tool_ids(self._instance, tool_ids)request_env = params.get("env") if isinstance(params.get("env"), dict) else {}invocation_id = str(request_env.get("OFFICE_CLAW_INVOCATION_ID") or "").strip()logger.info(@@ -3904,6 +3910,8 @@ class JiuWenSwarmDeepAdapter:and self._active_office_claw_mcp.request_id == registration.request_id):self._active_office_claw_mcp = None+ # Clear the shared ability_manager allowlist so stale ids are not reused.+ clear_agent_office_claw_tool_ids(self._instance)logger.info("[JiuWenSwarmDeepAdapter] request-scoped OfficeClaw MCP cleaned up: request_id=%s",registration.request_id,diff --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 3786781594..6eedd753af 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@@ -14,8 +14,11 @@ from jiuwenswarm.common.mcp_config import (OfficeClawMcpRegistration,RequestScopedOfficeClawMcpTool,bind_active_office_claw_mcp_tools,+ bind_office_claw_from_agent,+ clear_agent_office_claw_tool_ids,ensure_request_scoped_office_claw_tool_allowed,extract_office_claw_mcp,+ set_agent_office_claw_tool_ids,validate_office_claw_mcp_config,)from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk@@ -466,3 +469,46 @@ async def test_stream_request_binds_active_tool_allowlist() -> None:]assert seen == {"allowed": True, "rejected_foreign": True}+++def test_carrier_stores_on_ability_manager_and_rebinds() -> None:+ """The allowlist lives on the shared ability_manager, visible to either agent."""+ tool_id = "office-claw-request-aaa.office-claw.office_claw_multi_mention"+ ability = SimpleNamespace()+ deep_agent = SimpleNamespace(ability_manager=ability)+ # DeepAgent and its inner ReActAgent share the same ability_manager.+ react_agent = SimpleNamespace(ability_manager=ability)++ set_agent_office_claw_tool_ids(deep_agent, [tool_id])++ # Stored on the shared carrier, not on the agent object itself.+ assert not hasattr(deep_agent, "_active_office_claw_tool_ids")+ assert hasattr(ability, "_active_office_claw_tool_ids")++ # The rail may resolve to either agent object; both re-bind the allowlist.+ for agent in (deep_agent, react_agent):+ with bind_office_claw_from_agent(agent):+ ensure_request_scoped_office_claw_tool_allowed(tool_id)+ with pytest.raises(RuntimeError, match="bound to another request"):+ ensure_request_scoped_office_claw_tool_allowed(+ "office-claw-request-bbb.office-claw.office_claw_multi_mention"+ )+++def test_clear_agent_office_claw_tool_ids_unbinds() -> None:+ """Clearing the allowlist makes subsequent invokes fail closed as unbound."""+ tool_id = "office-claw-request-aaa.office-claw.office_claw_multi_mention"+ ability = SimpleNamespace()+ agent = SimpleNamespace(ability_manager=ability)++ set_agent_office_claw_tool_ids(agent, [tool_id])+ with bind_office_claw_from_agent(agent):+ ensure_request_scoped_office_claw_tool_allowed(tool_id)++ clear_agent_office_claw_tool_ids(agent)+ assert not hasattr(ability, "_active_office_claw_tool_ids")++ # After clear, bind is a no-op and the tool is refused as unbound.+ with bind_office_claw_from_agent(agent):+ with pytest.raises(RuntimeError, match="without an active request binding"):+ ensure_request_scoped_office_claw_tool_allowed(tool_id)