Skip to content

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(mcp): 修复 request-scoped OfficeClaw 工具在 interaction round 中 unbound 调用

openJiuwen-bot6d2bcec6c171
diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
index e1837fc17c..e5b39a0e92 100644
--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
@@ -12,8 +12,8 @@ Fixed schema maximizes LLM prefix caching while keeping rarely used tools reacha
from __future__ import annotations
import logging
-from contextlib import ExitStack, contextmanager
-from typing import Any, Callable, Iterator
+from contextlib import ExitStack, contextmanager, nullcontext
+from typing import Any, Callable, Iterable, Iterator
import anyio
from openjiuwen.core.runner import Runner
@@ -32,7 +32,11 @@ from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (
InvokeToolTool,
)
from jiuwenswarm.common.mcp_config import (
+ OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG,
+ OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX,
+ bind_active_office_claw_mcp_tools,
bind_office_claw_from_agent,
+ get_active_office_claw_mcp_tool_ids,
resolve_active_office_claw_tool_id,
)
@@ -114,6 +118,19 @@ class ProgressiveToolRail(DeepAgentRail):
self._owned_tool_ids: set[str] = set()
self._cached_all_tool_infos: list[Any] = []
self._cached_deferred_tool_infos: list[Any] = []
+ # Request-scoped OfficeClaw MCP allowlist for this session agent.
+ # Interaction rounds do not inherit the facade ContextVar, so
+ # invoke_tool re-binds from this attribute before tool execution.
+ self._office_claw_active_tool_ids: frozenset[str] | None = None
+
+ def set_office_claw_active_tool_ids(self, tool_ids: Iterable[str] | None) -> None:
+ """Publish or clear this rail's OfficeClaw request-scoped allowlist."""
+ if tool_ids is None:
+ self._office_claw_active_tool_ids = None
+ return
+ self._office_claw_active_tool_ids = frozenset(
+ str(tool_id).strip() for tool_id in tool_ids if str(tool_id).strip()
+ )
@contextmanager
def _bind_deepresearch_context(self, tool_name: str) -> Iterator[None]:
@@ -839,17 +856,47 @@ class ProgressiveToolRail(DeepAgentRail):
"""Resolve a live tool instance, recovering from stale card ids.
Order:
- 1. preferred_id from deferred cache / AbilityManager card
- 2. refresh AbilityManager cache and retry if the live card id changed
- 3. this request's ``bind_active_office_claw_mcp_tools`` allowlist
- (authoritative for OfficeClaw MCP even when short-name AM was
- overwritten or cleaned by a concurrent request)
+ 1. this request's ``bind_active_office_claw_mcp_tools`` allowlist
+ (authoritative for OfficeClaw MCP even when short-name AM / deferred
+ cache still points at a concurrent request's live card)
+ 2. preferred_id from deferred cache / AbilityManager card — skipped when
+ it is a foreign ``office-claw-request-*`` id under an active allowlist
+ 3. refresh AbilityManager cache and retry if the live card id changed
Returns ``(tool, resolved_id, refreshed_id_for_diagnostics)``.
"""
- target_tool = self._lookup_tool_instance(preferred_id)
- if target_tool is not None:
- return target_tool, preferred_id, ""
+ active_id = resolve_active_office_claw_tool_id(tool_name)
+ if active_id:
+ target_tool = self._lookup_tool_instance(active_id)
+ if target_tool is not None:
+ if active_id != preferred_id:
+ logger.info(
+ "%s active OfficeClaw tool_id preferred: tool_name=%s "
+ "preferred_id=%s active_id=%s",
+ _LOG_PREFIX,
+ tool_name,
+ preferred_id,
+ active_id,
+ )
+ return target_tool, active_id, ""
+
+ allowed = get_active_office_claw_mcp_tool_ids()
+ preferred_is_foreign_office_claw = (
+ preferred_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX)
+ and allowed is not None
+ and preferred_id not in allowed
+ )
+ if not preferred_is_foreign_office_claw:
+ target_tool = self._lookup_tool_instance(preferred_id)
+ if target_tool is not None:
+ return target_tool, preferred_id, ""
+ elif preferred_id:
+ logger.info(
+ "%s skip foreign OfficeClaw preferred_id: tool_name=%s preferred_id=%s",
+ _LOG_PREFIX,
+ tool_name,
+ preferred_id,
+ )
logger.info(
"%s stale tool_id retry: tool_name=%s old_id=%s",
@@ -867,21 +914,25 @@ class ProgressiveToolRail(DeepAgentRail):
str(getattr(refreshed_card, "id", "") or "") if refreshed_card is not None else ""
)
if refreshed_id and refreshed_id != preferred_id:
- target_tool = self._lookup_tool_instance(refreshed_id)
- if target_tool is not None:
- return target_tool, refreshed_id, refreshed_id
+ refreshed_is_foreign = (
+ refreshed_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX)
+ and allowed is not None
+ and refreshed_id not in allowed
+ )
+ if not refreshed_is_foreign:
+ target_tool = self._lookup_tool_instance(refreshed_id)
+ if target_tool is not None:
+ return target_tool, refreshed_id, refreshed_id
- active_id = resolve_active_office_claw_tool_id(tool_name)
if active_id:
- if active_id not in {preferred_id, refreshed_id}:
+ target_tool = self._lookup_tool_instance(active_id)
+ if target_tool is not None:
logger.info(
"%s active OfficeClaw tool_id fallback: tool_name=%s active_id=%s",
_LOG_PREFIX,
tool_name,
active_id,
)
- target_tool = self._lookup_tool_instance(active_id)
- if target_tool is not None:
return target_tool, active_id, refreshed_id or active_id
return None, preferred_id, refreshed_id
@@ -893,6 +944,24 @@ class ProgressiveToolRail(DeepAgentRail):
**kwargs,
) -> dict[str, Any]:
"""Invoke a deferred tool with validated arguments."""
+ owned = self._office_claw_active_tool_ids
+ bind_cm = (
+ bind_active_office_claw_mcp_tools(owned)
+ if owned is not None
+ else nullcontext()
+ )
+ with bind_cm:
+ return await self._invoke_target_tool_with_binding(
+ session, params, **kwargs
+ )
+
+ async def _invoke_target_tool_with_binding(
+ self,
+ session: Any,
+ params: InvokeToolInput,
+ **kwargs,
+ ) -> dict[str, Any]:
+ """Invoke a deferred tool after OfficeClaw allowlist ContextVar is bound."""
tool_name = str(params.tool_name or "").strip()
arguments = dict(params.arguments or {})
@@ -988,6 +1057,9 @@ class ProgressiveToolRail(DeepAgentRail):
try:
kwargs_without_session = {k: v for k, v in kwargs.items() if k != "session"}
+ owned = self._office_claw_active_tool_ids
+ if owned is not None:
+ kwargs_without_session[OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG] = owned
call_timeout = getattr(AbilityManager, "_resolve_call_timeout")(
target_tool_card
)
diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.py
index e787fb1f5b..e939e25789 100644
--- a/jiuwenswarm/common/mcp_config.py
+++ b/jiuwenswarm/common/mcp_config.py
@@ -14,6 +14,7 @@ import re
import sys
import threading
import time
+import weakref
from contextlib import AsyncExitStack, contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
@@ -810,9 +811,11 @@ class OfficeClawMcpRegistration:
request_id: str
tool_ids: tuple[str, ...]
tool_names: tuple[str, ...]
+ tool_instances: tuple[RequestScopedOfficeClawMcpTool, ...] = ()
OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX = "office-claw-request-"
+OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG = "_office_claw_expected_tool_ids"
# 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
@@ -831,6 +834,116 @@ _active_office_claw_tool_ids: ContextVar[frozenset[str] | None] = ContextVar(
default=None,
)
+# Process-local live registrations. DeepAgent runs tools on an interaction
+# round task created by the supervisor, which does not inherit the facade
+# task's ContextVar. ProgressiveToolRail / Tool.invoke re-bind from here.
+_live_office_claw_allowlists_by_tool_id: dict[str, frozenset[str]] = {}
+_live_office_claw_registration_count_by_tool_name: dict[str, int] = {}
+_live_office_claw_tool_instances: weakref.WeakKeyDictionary[Any, frozenset[str]] = (
+ weakref.WeakKeyDictionary()
+)
+_live_office_claw_allowlist_lock = threading.Lock()
+
+
+def _office_claw_tool_name_from_tool_id(tool_id: str) -> str:
+ normalized = str(tool_id or "").strip()
+ marker = ".office-claw."
+ if marker in normalized:
+ return normalized.split(marker, 1)[1]
+ return normalized.rsplit(".", 1)[-1]
+
+
+def publish_live_office_claw_allowlist(tool_ids: Iterable[str]) -> None:
+ """Publish a request's OfficeClaw tool ids for interaction-round re-bind."""
+
+ ids = frozenset(str(tool_id).strip() for tool_id in tool_ids if str(tool_id).strip())
+ seen_names: set[str] = set()
+ with _live_office_claw_allowlist_lock:
+ for tool_id in ids:
+ _live_office_claw_allowlists_by_tool_id[tool_id] = ids
+ tool_name = _office_claw_tool_name_from_tool_id(tool_id)
+ if tool_name in seen_names:
+ continue
+ seen_names.add(tool_name)
+ _live_office_claw_registration_count_by_tool_name[tool_name] = (
+ _live_office_claw_registration_count_by_tool_name.get(tool_name, 0) + 1
+ )
+
+
+def revoke_live_office_claw_allowlist(tool_ids: Iterable[str]) -> None:
+ """Drop live allowlist entries after request-scoped MCP cleanup."""
+
+ seen_names: set[str] = set()
+ with _live_office_claw_allowlist_lock:
+ for tool_id in tool_ids:
+ normalized = str(tool_id or "").strip()
+ if normalized:
+ _live_office_claw_allowlists_by_tool_id.pop(normalized, None)
+ tool_name = _office_claw_tool_name_from_tool_id(normalized)
+ if tool_name in seen_names:
+ continue
+ seen_names.add(tool_name)
+ count = _live_office_claw_registration_count_by_tool_name.get(tool_name, 0)
+ if count <= 1:
+ _live_office_claw_registration_count_by_tool_name.pop(tool_name, None)
+ else:
+ _live_office_claw_registration_count_by_tool_name[tool_name] = count - 1
+
+
+def get_live_office_claw_allowlist_for_tool_id(tool_id: str) -> frozenset[str] | None:
+ """Return the live allowlist that currently owns ``tool_id``, if any."""
+
+ normalized = str(tool_id or "").strip()
+ if not normalized:
+ return None
+ with _live_office_claw_allowlist_lock:
+ return _live_office_claw_allowlists_by_tool_id.get(normalized)
+
+
+def is_office_claw_tool_name_live_concurrent(tool_name: str) -> bool:
+ """True when more than one live request-scoped registration owns ``tool_name``."""
+
+ normalized = str(tool_name or "").strip()
+ if not normalized:
+ return False
+ with _live_office_claw_allowlist_lock:
+ return _live_office_claw_registration_count_by_tool_name.get(normalized, 0) > 1
+
+
+def register_live_office_claw_tool_instance(
+ tool: RequestScopedOfficeClawMcpTool,
+ tool_ids: Iterable[str],
+) -> None:
+ """Track one request-scoped tool object for safe unbound re-bind."""
+
+ ids = frozenset(str(tool_id).strip() for tool_id in tool_ids if str(tool_id).strip())
+ if ids:
+ with _live_office_claw_allowlist_lock:
+ _live_office_claw_tool_instances[tool] = ids
+
+
+def unregister_live_office_claw_tool_instance(tool: RequestScopedOfficeClawMcpTool) -> None:
+ """Drop a request-scoped tool object from the live instance registry."""
+
+ with _live_office_claw_allowlist_lock:
+ _live_office_claw_tool_instances.pop(tool, None)
+
+
+def get_live_office_claw_allowlist_for_tool_instance(
+ tool: RequestScopedOfficeClawMcpTool,
+) -> frozenset[str] | None:
+ """Return the allowlist registered for this tool object, if still live."""
+
+ with _live_office_claw_allowlist_lock:
+ return _live_office_claw_tool_instances.get(tool)
+
+
+def _clear_live_office_claw_allowlists_for_tests() -> None:
+ with _live_office_claw_allowlist_lock:
+ _live_office_claw_allowlists_by_tool_id.clear()
+ _live_office_claw_registration_count_by_tool_name.clear()
+ _live_office_claw_tool_instances.clear()
+
def _office_claw_tool_ids_carrier(agent: Any) -> Any:
"""Return the object that carries the request-scoped allowlist.
@@ -1208,6 +1321,46 @@ class RequestScopedOfficeClawMcpTool(Tool):
raise build_error(StatusCode.TOOL_STREAM_NOT_SUPPORTED, card=self._card)
async def invoke(self, inputs: Any, **kwargs: Any) -> dict[str, Any]:
+ tool_id = str(getattr(self._card, "id", "") or "")
+ if get_active_office_claw_mcp_tool_ids() is None and tool_id.startswith(
+ OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX
+ ):
+ live = self._resolve_unbound_office_claw_allowlist(tool_id, kwargs)
+ if live is not None:
+ with bind_active_office_claw_mcp_tools(live):
+ return await self._invoke_with_active_binding(inputs, **kwargs)
+ return await self._invoke_with_active_binding(inputs, **kwargs)
+
+ def _resolve_unbound_office_claw_allowlist(
+ self,
+ tool_id: str,
+ kwargs: Mapping[str, Any],
+ ) -> frozenset[str] | None:
+ """Re-bind only when the caller or live registry proves ownership."""
+
+ expected_raw = kwargs.get(OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG)
+ if expected_raw is not None:
+ expected = frozenset(
+ str(item).strip() for item in expected_raw if str(item).strip()
+ )
+ return expected if tool_id in expected else None
+
+ live = get_live_office_claw_allowlist_for_tool_instance(self)
+ if live is not None and tool_id in live:
+ return live
+
+ tool_name = str(getattr(self._card, "name", "") or "")
+ if is_office_claw_tool_name_live_concurrent(tool_name):
+ return None
+
+ live_by_id = get_live_office_claw_allowlist_for_tool_id(tool_id)
+ if live_by_id is not None and tool_id in live_by_id:
+ return live_by_id
+ return None
+
+ async def _invoke_with_active_binding(
+ self, inputs: Any, **kwargs: Any
+ ) -> dict[str, Any]:
from mcp import ClientSession
from mcp.client.stdio import stdio_client
@@ -1251,6 +1404,7 @@ class RequestScopedOfficeClawMcpTool(Tool):
__all__ = [
+ "OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG",
"OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX",
"OfficeClawMcpRegistration",
"RequestScopedOfficeClawMcpTool",
@@ -1265,10 +1419,17 @@ __all__ = [
"extract_enabled_mcp_server_entries",
"extract_office_claw_mcp",
"get_active_office_claw_mcp_tool_ids",
+ "get_live_office_claw_allowlist_for_tool_id",
+ "get_live_office_claw_allowlist_for_tool_instance",
"invalidate_office_claw_mcp_schema_cache",
+ "is_office_claw_tool_name_live_concurrent",
"list_office_claw_mcp_tools",
"preflight_mcp_server_reachable",
+ "publish_live_office_claw_allowlist",
+ "register_live_office_claw_tool_instance",
"resolve_active_office_claw_tool_id",
+ "revoke_live_office_claw_allowlist",
+ "unregister_live_office_claw_tool_instance",
"validate_office_claw_mcp_config",
"_check_dangerous_args",
"_is_blocked_host",
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index c448fb67bc..4fd1d50b4e 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -421,7 +421,11 @@ from jiuwenswarm.common.mcp_config import (
is_asyncio_outer_cancellation,
list_office_claw_mcp_tools,
preflight_mcp_server_reachable,
+ publish_live_office_claw_allowlist,
+ register_live_office_claw_tool_instance,
+ revoke_live_office_claw_allowlist,
set_agent_office_claw_tool_ids,
+ unregister_live_office_claw_tool_instance,
validate_office_claw_mcp_config,
)
from jiuwenswarm.common.mcp_call_timeout_patch import apply_mcp_call_timeout_patch
@@ -3677,6 +3681,7 @@ class JiuWenSwarmDeepAdapter:
tool_ids: list[str] = []
tool_names: list[str] = []
+ registered_tools: list[RequestScopedOfficeClawMcpTool] = []
try:
params = validate_office_claw_mcp_config(raw_config)
tool_defs = await list_office_claw_mcp_tools(params)
@@ -3697,6 +3702,7 @@ class JiuWenSwarmDeepAdapter:
input_params=tool_def.get("input_params") or {},
)
tool = RequestScopedOfficeClawMcpTool(card, params)
+ registered_tools.append(tool)
add_result = Runner.resource_mgr.add_tool(tool, tag="office-claw")
is_ok = getattr(add_result, "is_ok", None)
add_succeeded = True
@@ -3716,12 +3722,20 @@ class JiuWenSwarmDeepAdapter:
request_id=request.request_id,
tool_ids=tuple(tool_ids),
tool_names=tuple(tool_names),
+ tool_instances=tuple(registered_tools),
)
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)
+ publish_live_office_claw_allowlist(registration.tool_ids)
+ for registered_tool in registered_tools:
+ register_live_office_claw_tool_instance(
+ registered_tool,
+ registration.tool_ids,
+ )
+ self._sync_office_claw_allowlist_to_progressive_rail(registration.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(
@@ -3740,6 +3754,7 @@ class JiuWenSwarmDeepAdapter:
request_id=request.request_id,
tool_ids=tuple(tool_ids),
tool_names=tuple(tool_names),
+ tool_instances=tuple(registered_tools),
)
await self.cleanup_request_scoped_office_claw_mcp(registration)
raise
@@ -3748,6 +3763,7 @@ class JiuWenSwarmDeepAdapter:
request_id=request.request_id,
tool_ids=tuple(tool_ids),
tool_names=tuple(tool_names),
+ tool_instances=tuple(registered_tools),
)
await self.cleanup_request_scoped_office_claw_mcp(registration)
logger.warning(
@@ -3845,6 +3861,8 @@ class JiuWenSwarmDeepAdapter:
if registration is None:
return
+ for registered_tool in registration.tool_instances:
+ unregister_live_office_claw_tool_instance(registered_tool)
for tool_id in registration.tool_ids:
try:
Runner.resource_mgr.remove_tool(tool_id)
@@ -3893,13 +3911,34 @@ class JiuWenSwarmDeepAdapter:
and self._active_office_claw_mcp.request_id == registration.request_id
):
self._active_office_claw_mcp = None
+ self._sync_office_claw_allowlist_to_progressive_rail(None)
# Clear the shared ability_manager allowlist so stale ids are not reused.
clear_agent_office_claw_tool_ids(self._instance)
+ revoke_live_office_claw_allowlist(registration.tool_ids)
logger.info(
"[JiuWenSwarmDeepAdapter] request-scoped OfficeClaw MCP cleaned up: request_id=%s",
registration.request_id,
)
+ def _sync_office_claw_allowlist_to_progressive_rail(
+ self,
+ tool_ids: tuple[str, ...] | list[str] | frozenset[str] | None,
+ ) -> None:
+ """Keep ProgressiveToolRail's interaction-round allowlist in sync."""
+
+ rail = getattr(self, "_progressive_tool_rail", None)
+ setter = getattr(rail, "set_office_claw_active_tool_ids", None)
+ if not callable(setter):
+ return
+ try:
+ setter(tool_ids)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] failed to sync OfficeClaw allowlist to "
+ "ProgressiveToolRail: %s",
+ exc,
+ )
+
async def _register_mcp_servers_from_config(
self, config_base: dict[str, Any], *, tag: str = "agent.main"
) -> None:
diff --git a/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py b/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py
index aadc5f4842..5c25bf0b22 100644
--- a/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py
+++ b/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py
@@ -288,6 +288,100 @@ async def test_invoke_falls_back_to_active_office_claw_tool_id():
target.invoke.assert_awaited_once()
+async def test_invoke_prefers_owned_id_when_foreign_card_still_live():
+ """Concurrent request's card is still in resource_mgr; rail must use owned id."""
+
+ foreign_live = (
+ "office-claw-request-other.office-claw.office_claw_list_schedule_templates"
+ )
+ owned_live = (
+ "office-claw-request-mine.office-claw.office_claw_list_schedule_templates"
+ )
+ foreign_card = SimpleNamespace(
+ name="office_claw_list_schedule_templates",
+ id=foreign_live,
+ description="d",
+ input_params={},
+ properties={"resilience": {"timeout_s": None}},
+ )
+ foreign_tool = SimpleNamespace(invoke=AsyncMock(return_value={"foreign": True}))
+ owned_tool = SimpleNamespace(invoke=AsyncMock(return_value={"owned": True}))
+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])
+ rail.set_office_claw_active_tool_ids([owned_live])
+ rail._cached_deferred_tool_infos = [foreign_card]
+
+ async def _fake_refresh(_agent=None):
+ rail._cached_deferred_tool_infos = [foreign_card]
+
+ def _get_tool_side_effect(tool_id, session=None):
+ if tool_id == foreign_live:
+ return foreign_tool
+ if tool_id == owned_live:
+ return owned_tool
+ return None
+
+ with patch.object(
+ Runner.resource_mgr, "get_tool", side_effect=_get_tool_side_effect
+ ), patch.object(rail, "_refresh_deferred_tool_cache", new=_fake_refresh):
+ result = await rail._invoke_target_tool(
+ None,
+ InvokeToolInput(
+ tool_name="office_claw_list_schedule_templates",
+ arguments={},
+ ),
+ )
+
+ assert result == {
+ "success": True,
+ "tool_name": "office_claw_list_schedule_templates",
+ "result": {"owned": True},
+ }
+ owned_tool.invoke.assert_awaited_once()
+ foreign_tool.invoke.assert_not_awaited()
+
+
+async def test_invoke_rebinds_office_claw_allowlist_from_rail_attribute():
+ """Without facade ContextVar, rail-owned allowlist must still bind for invoke."""
+
+ from jiuwenswarm.common.mcp_config import get_active_office_claw_mcp_tool_ids
+
+ owned_live = (
+ "office-claw-request-mine.office-claw.office_claw_list_schedule_templates"
+ )
+ card = SimpleNamespace(
+ name="office_claw_list_schedule_templates",
+ id=owned_live,
+ description="d",
+ input_params={},
+ properties={"resilience": {"timeout_s": None}},
+ )
+ seen: dict[str, object] = {}
+
+ async def _invoke(arguments, session=None, **kwargs):
+ seen["allowed"] = get_active_office_claw_mcp_tool_ids()
+ return {"ok": True}
+
+ target = SimpleNamespace(invoke=AsyncMock(side_effect=_invoke))
+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool"])
+ rail.set_office_claw_active_tool_ids([owned_live])
+ rail._cached_deferred_tool_infos = [card]
+
+ with patch.object(Runner.resource_mgr, "get_tool", return_value=target):
+ result = await rail._invoke_target_tool(
+ None,
+ InvokeToolInput(
+ tool_name="office_claw_list_schedule_templates",
+ arguments={},
+ ),
+ )
+
+ assert result["success"] is True
+ assert seen["allowed"] == frozenset({owned_live})
+ assert get_active_office_claw_mcp_tool_ids() is None
+
+
@pytest.mark.asyncio
async def test_search_skips_dead_instance_without_active_fallback():
"""tools_search must not advertise a tool whose instance is gone and
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.py
index 6eedd753af..c3e8a1792a 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
@@ -5,7 +5,7 @@
from __future__ import annotations
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, patch
import pytest
from openjiuwen.core.foundation.tool import ToolCard
@@ -105,6 +105,7 @@ def _bare_session_adapter() -> JiuWenSwarmDeepAdapter:
adapter = object.__new__(JiuWenSwarmDeepAdapter)
adapter._instance = SimpleNamespace(ability_manager=_AbilityManager())
adapter._active_office_claw_mcp = None
+ adapter._active_office_claw_tool_instances = ()
return adapter
@@ -169,6 +170,138 @@ def test_request_scoped_tool_allowlist_rejects_unbound_invoke() -> None:
)
+async def test_request_scoped_tool_invoke_rebinds_from_live_allowlist() -> None:
+ from jiuwenswarm.common.mcp_config import (
+ _clear_live_office_claw_allowlists_for_tests,
+ get_active_office_claw_mcp_tool_ids,
+ publish_live_office_claw_allowlist,
+ register_live_office_claw_tool_instance,
+ revoke_live_office_claw_allowlist,
+ unregister_live_office_claw_tool_instance,
+ )
+
+ _clear_live_office_claw_allowlists_for_tests()
+ tool_id = "office-claw-request-aaa.office-claw.office_claw_multi_mention"
+ card = ToolCard(
+ id=tool_id,
+ name="office_claw_multi_mention",
+ description="multi",
+ input_params={},
+ )
+ tool = RequestScopedOfficeClawMcpTool(
+ card,
+ {
+ "command": "node",
+ "args": ["index.js"],
+ "cwd": ".",
+ "env": {"OFFICE_CLAW_INVOCATION_ID": "aaa"},
+ },
+ )
+ publish_live_office_claw_allowlist([tool_id])
+ register_live_office_claw_tool_instance(tool, [tool_id])
+ seen: dict[str, object] = {}
+
+ async def _capture(inputs, **kwargs):
+ seen["allowed"] = get_active_office_claw_mcp_tool_ids()
+ return {"result": "ok"}
+
+ try:
+ with patch.object(
+ RequestScopedOfficeClawMcpTool,
+ "_invoke_with_active_binding",
+ new=AsyncMock(side_effect=_capture),
+ ):
+ result = await tool.invoke({})
+ finally:
+ unregister_live_office_claw_tool_instance(tool)
+ revoke_live_office_claw_allowlist([tool_id])
+ _clear_live_office_claw_allowlists_for_tests()
+
+ assert result == {"result": "ok"}
+ assert seen["allowed"] == frozenset({tool_id})
+ assert get_active_office_claw_mcp_tool_ids() is None
+
+
+async def test_request_scoped_tool_invoke_rebinds_from_expected_allowlist_kwarg() -> None:
+ from jiuwenswarm.common.mcp_config import (
+ OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG,
+ get_active_office_claw_mcp_tool_ids,
+ )
+
+ tool_id = "office-claw-request-mine.office-claw.office_claw_multi_mention"
+ foreign_id = "office-claw-request-other.office-claw.office_claw_multi_mention"
+ card = ToolCard(
+ id=tool_id,
+ name="office_claw_multi_mention",
+ description="multi",
+ input_params={},
+ )
+ tool = RequestScopedOfficeClawMcpTool(
+ card,
+ {"command": "node", "args": ["index.js"], "cwd": ".", "env": {}},
+ )
+ seen: dict[str, object] = {}
+
+ async def _capture(inputs, **kwargs):
+ seen["allowed"] = get_active_office_claw_mcp_tool_ids()
+ return {"result": "ok"}
+
+ with patch.object(
+ RequestScopedOfficeClawMcpTool,
+ "_invoke_with_active_binding",
+ new=AsyncMock(side_effect=_capture),
+ ):
+ result = await tool.invoke(
+ {},
+ **{OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG: [tool_id]},
+ )
+
+ assert result == {"result": "ok"}
+ assert seen["allowed"] == frozenset({tool_id})
+ assert get_active_office_claw_mcp_tool_ids() is None
+
+ with pytest.raises(Exception, match="without an active request binding"):
+ await tool.invoke(
+ {},
+ **{OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG: [foreign_id]},
+ )
+
+
+async def test_request_scoped_tool_invoke_refuses_foreign_live_rebind_when_concurrent() -> None:
+ from jiuwenswarm.common.mcp_config import (
+ _clear_live_office_claw_allowlists_for_tests,
+ publish_live_office_claw_allowlist,
+ revoke_live_office_claw_allowlist,
+ )
+
+ _clear_live_office_claw_allowlists_for_tests()
+ owned_id = "office-claw-request-mine.office-claw.office_claw_multi_mention"
+ foreign_id = "office-claw-request-other.office-claw.office_claw_multi_mention"
+ foreign_card = ToolCard(
+ id=foreign_id,
+ name="office_claw_multi_mention",
+ description="foreign",
+ input_params={},
+ )
+ foreign_tool = RequestScopedOfficeClawMcpTool(
+ foreign_card,
+ {"command": "node", "args": ["foreign.js"], "cwd": ".", "env": {}},
+ )
+ publish_live_office_claw_allowlist([owned_id])
+ publish_live_office_claw_allowlist([foreign_id])
+
+ try:
+ with pytest.raises(Exception, match="without an active request binding"):
+ await foreign_tool.invoke({})
+ finally:
+ revoke_live_office_claw_allowlist([owned_id])
+ revoke_live_office_claw_allowlist([foreign_id])
+ _clear_live_office_claw_allowlists_for_tests()
+
+
@pytest.mark.asyncio
async def test_request_scoped_tool_invoke_refuses_cross_request_binding() -> None:
card = ToolCard(
@@ -221,6 +354,11 @@ async def test_registers_exact_tool_names_and_cleans_them_up(
assert set(adapter._instance.ability_manager.cards) == set(registration.tool_names)
assert len(resource_manager.tools) == 2
assert adapter._active_office_claw_mcp == registration
+ from jiuwenswarm.common.mcp_config import get_live_office_claw_allowlist_for_tool_id
+
+ assert get_live_office_claw_allowlist_for_tool_id(registration.tool_ids[0]) == frozenset(
+ registration.tool_ids
+ )
await adapter.cleanup_request_scoped_office_claw_mcp(registration)
@@ -228,6 +366,7 @@ async def test_registers_exact_tool_names_and_cleans_them_up(
assert adapter._instance.ability_manager.cards == {}
assert resource_manager.removed == list(registration.tool_ids)
assert adapter._active_office_claw_mcp is None
+ assert get_live_office_claw_allowlist_for_tool_id(registration.tool_ids[0]) is None
@pytest.mark.asyncio