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(office_claw): 绑定 request-scoped MCP,防止并发会话串回调凭证

xiaowenzihwlf4aae6cf0c78
diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.py
index 09f3f22b78..ded18d227c 100644
--- a/jiuwenswarm/common/mcp_config.py
+++ b/jiuwenswarm/common/mcp_config.py
@@ -11,10 +11,11 @@ import json
import os
import re
import sys
-from contextlib import AsyncExitStack
+from contextlib import AsyncExitStack, contextmanager
+from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Mapping
+from typing import Any, Iterable, Iterator, Mapping
from urllib.parse import urlparse
from openjiuwen.core.common.exception.codes import StatusCode
@@ -674,6 +675,49 @@ class OfficeClawMcpRegistration:
tool_names: tuple[str, ...]
+OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX = "office-claw-request-"
+
+# 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.
+_active_office_claw_tool_ids: ContextVar[frozenset[str] | None] = ContextVar(
+ "active_office_claw_tool_ids",
+ default=None,
+)
+
+
+@contextmanager
+def bind_active_office_claw_mcp_tools(
+ tool_ids: Iterable[str] | None,
+) -> Iterator[None]:
+ """Bind the request-scoped OfficeClaw tool id allowlist for this task."""
+
+ allowed = frozenset(str(tool_id) for tool_id in (tool_ids or ()) if str(tool_id))
+ token = _active_office_claw_tool_ids.set(allowed)
+ 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."""
+
+ normalized = str(tool_id or "").strip()
+ if not normalized.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX):
+ return
+ allowed = _active_office_claw_tool_ids.get()
+ if allowed is None:
+ raise RuntimeError(
+ "OfficeClaw MCP tool invoked without an active request binding; "
+ "refusing unbound request-scoped invoke"
+ )
+ if normalized not in allowed:
+ raise RuntimeError(
+ "OfficeClaw MCP tool is bound to another request; refusing cross-request invoke"
+ )
+
+
def extract_office_claw_mcp(params: Any) -> dict[str, Any] | None:
"""Return only the legacy ``office_claw_mcp`` request field."""
@@ -815,6 +859,18 @@ class RequestScopedOfficeClawMcpTool(Tool):
from mcp import ClientSession
from mcp.client.stdio import stdio_client
+ tool_id = str(getattr(self._card, "id", "") or "")
+ try:
+ ensure_request_scoped_office_claw_tool_allowed(tool_id)
+ except RuntimeError as exc:
+ raise build_error(
+ StatusCode.TOOL_MCP_EXECUTION_ERROR,
+ cause=exc,
+ reason=str(exc),
+ method="invoke",
+ card=self._card,
+ ) from exc
+
arguments = inputs if isinstance(inputs, dict) else {}
stack = AsyncExitStack()
try:
@@ -843,11 +899,14 @@ class RequestScopedOfficeClawMcpTool(Tool):
__all__ = [
+ "OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX",
"OfficeClawMcpRegistration",
"RequestScopedOfficeClawMcpTool",
+ "bind_active_office_claw_mcp_tools",
"build_enabled_mcp_server_configs",
"build_mcp_server_config",
"create_mcp_tool",
+ "ensure_request_scoped_office_claw_tool_allowed",
"extract_enabled_mcp_server_entries",
"extract_office_claw_mcp",
"list_office_claw_mcp_tools",
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index fd6a30ddb9..522d0938b0 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -391,6 +391,7 @@ from jiuwenswarm.common.config import (
from jiuwenswarm.common.mcp_config import (
OfficeClawMcpRegistration,
RequestScopedOfficeClawMcpTool,
+ bind_active_office_claw_mcp_tools,
build_mcp_server_config,
extract_enabled_mcp_server_entries,
extract_office_claw_mcp,
@@ -2026,6 +2027,10 @@ class JiuWenSwarmDeepAdapter:
self._instance_overrides: dict[str, Any] = {}
self._is_session_scoped_adapter: bool = False
self._parent_session_id: str | None = None
+ # Active request-scoped OfficeClaw MCP registration for this session
+ # adapter. Used for safe short-name cleanup and diagnostics; invoke
+ # allowlisting is enforced via bind_active_office_claw_mcp_tools.
+ self._active_office_claw_mcp: OfficeClawMcpRegistration | None = None
# Tenant tip namespace for Track-B env reads (sync_agents_configs).
# Defaults match unbound single-tenant; AgentManager / copy_tenant_env_bindings_from
# overwrite for per-agent scopes.
@@ -3658,20 +3663,24 @@ class JiuWenSwarmDeepAdapter:
# are still fully removable by the common cleanup path.
tool_ids.append(tool_id)
tool_names.append(tool_name)
- ability_result = self._instance.ability_manager.add(card)
- if not bool(getattr(ability_result, "added", True)):
- raise RuntimeError(f"OfficeClaw MCP tool name conflicts with an existing tool: {tool_name}")
+ self._install_office_claw_ability_card(card)
registration = OfficeClawMcpRegistration(
request_id=request.request_id,
tool_ids=tuple(tool_ids),
tool_names=tuple(tool_names),
)
+ self._active_office_claw_mcp = registration
+ 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(
"[JiuWenSwarmDeepAdapter] request-scoped OfficeClaw MCP registered: "
- "request_id=%s tools=%s",
+ "request_id=%s session_id=%s invocation_id=%s tools=%s tool_ids=%s",
request.request_id,
+ request.session_id,
+ invocation_id or "-",
tool_names,
+ tool_ids,
)
return registration
except asyncio.CancelledError:
@@ -3697,6 +3706,77 @@ class JiuWenSwarmDeepAdapter:
)
return None
+ def _owned_office_claw_tool_ids(self) -> frozenset[str]:
+ active = self._active_office_claw_mcp
+ if active is None:
+ return frozenset()
+ return frozenset(active.tool_ids)
+
+ def _install_office_claw_ability_card(self, card: ToolCard) -> None:
+ """Register a request-scoped OfficeClaw tool card by short name.
+
+ Same-id rebinds are allowed. A different id is replaced only when the
+ existing card belongs to this adapter's active registration; otherwise
+ registration fails hard so a concurrent request cannot silently steal
+ the short-name mapping.
+ """
+
+ if self._instance is None:
+ raise RuntimeError("OfficeClaw MCP ability install requires an initialized agent")
+ ability_manager = self._instance.ability_manager
+ tool_name = str(card.name or "").strip()
+ tool_id = str(card.id or "").strip()
+ if not tool_name or not tool_id:
+ raise RuntimeError("OfficeClaw MCP tool card is missing name or id")
+
+ existing = None
+ getter = getattr(ability_manager, "get", None)
+ if callable(getter):
+ existing = getter(tool_name)
+ existing_id = str(getattr(existing, "id", "") or "") if existing is not None else ""
+
+ if existing is not None and existing_id and existing_id != tool_id:
+ if existing_id in self._owned_office_claw_tool_ids():
+ try:
+ ability_manager.remove(tool_name)
+ except Exception as exc:
+ raise RuntimeError(
+ f"failed to replace owned OfficeClaw MCP ability: {tool_name}"
+ ) from exc
+ try:
+ Runner.resource_mgr.remove_tool(existing_id)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] failed to remove replaced OfficeClaw MCP "
+ "resource: tool_id=%s error=%s",
+ existing_id,
+ exc,
+ )
+ else:
+ raise RuntimeError(
+ f"OfficeClaw MCP tool name conflicts with an existing tool: {tool_name} "
+ f"(existing_id={existing_id}, new_id={tool_id})"
+ )
+
+ ability_result = ability_manager.add(card)
+ if ability_result is None:
+ # Legacy AbilityManager.add returned None and may overwrite by name.
+ return
+ added = getattr(ability_result, "added", None)
+ if added is False:
+ # Conflict-aware AbilityManager kept the existing card. Retry once if
+ # we own it; otherwise fail closed.
+ existing = getter(tool_name) if callable(getter) else None
+ existing_id = str(getattr(existing, "id", "") or "") if existing is not None else ""
+ if existing_id and existing_id in self._owned_office_claw_tool_ids():
+ ability_manager.remove(tool_name)
+ ability_result = ability_manager.add(card)
+ added = getattr(ability_result, "added", None)
+ if added is False:
+ raise RuntimeError(
+ f"OfficeClaw MCP tool name conflicts with an existing tool: {tool_name}"
+ )
+
async def cleanup_request_scoped_office_claw_mcp(
self,
registration: OfficeClawMcpRegistration | None,
@@ -3717,9 +3797,29 @@ class JiuWenSwarmDeepAdapter:
exc,
)
if self._instance is not None:
+ ability_manager = self._instance.ability_manager
+ getter = getattr(ability_manager, "get", None)
+ owned_ids = frozenset(registration.tool_ids)
for tool_name in registration.tool_names:
try:
- self._instance.ability_manager.remove(tool_name)
+ existing = getter(tool_name) if callable(getter) else None
+ existing_id = (
+ str(getattr(existing, "id", "") or "") if existing is not None else ""
+ )
+ # Only drop the short-name mapping when it still points at
+ # this request's tool id — never delete another request's bind.
+ if existing is None:
+ continue
+ if existing_id and existing_id not in owned_ids:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] skip OfficeClaw MCP ability cleanup; "
+ "short name rebound: request_id=%s tool=%s existing_id=%s",
+ registration.request_id,
+ tool_name,
+ existing_id,
+ )
+ continue
+ ability_manager.remove(tool_name)
except Exception as exc:
logger.warning(
"[JiuWenSwarmDeepAdapter] request-scoped OfficeClaw MCP ability cleanup failed: "
@@ -3728,6 +3828,11 @@ class JiuWenSwarmDeepAdapter:
tool_name,
exc,
)
+ if (
+ self._active_office_claw_mcp is not None
+ and self._active_office_claw_mcp.request_id == registration.request_id
+ ):
+ self._active_office_claw_mcp = None
logger.info(
"[JiuWenSwarmDeepAdapter] request-scoped OfficeClaw MCP cleaned up: request_id=%s",
registration.request_id,
@@ -13109,7 +13214,10 @@ class JiuWenSwarmDeepAdapter:
session_adapter = await self._get_or_create_session_adapter(request.session_id)
request_mcp = await session_adapter.register_request_scoped_office_claw_mcp(request)
try:
- return await session_adapter.process_message_impl(request, inputs)
+ with bind_active_office_claw_mcp_tools(
+ request_mcp.tool_ids if request_mcp is not None else ()
+ ):
+ return await session_adapter.process_message_impl(request, inputs)
finally:
try:
await session_adapter.cleanup_request_scoped_office_claw_mcp(request_mcp)
@@ -13679,8 +13787,11 @@ class JiuWenSwarmDeepAdapter:
session_adapter = await self._get_or_create_session_adapter(request.session_id)
request_mcp = await session_adapter.register_request_scoped_office_claw_mcp(request)
try:
- async for chunk in session_adapter.process_message_stream_impl(request, inputs):
- yield chunk
+ with bind_active_office_claw_mcp_tools(
+ request_mcp.tool_ids if request_mcp is not None else ()
+ ):
+ async for chunk in session_adapter.process_message_stream_impl(request, inputs):
+ yield chunk
return
finally:
try:
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 ad7dfab2ab..89101bdb18 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
@@ -8,9 +8,13 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
+from openjiuwen.core.foundation.tool import ToolCard
from jiuwenswarm.common.mcp_config import (
OfficeClawMcpRegistration,
+ RequestScopedOfficeClawMcpTool,
+ bind_active_office_claw_mcp_tools,
+ ensure_request_scoped_office_claw_tool_allowed,
extract_office_claw_mcp,
validate_office_claw_mcp_config,
)
@@ -19,26 +23,31 @@ from jiuwenswarm.server.runtime.agent_adapter import interface_deep
from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
-def _request(config: object | None = None) -> AgentRequest:
+def _request(
+ config: object | None = None,
+ *,
+ request_id: str = "req-123",
+ session_id: str = "session-456",
+) -> AgentRequest:
params = {"query": "一分钟后提醒我喝水"}
if config is not None:
params["office_claw_mcp"] = config
return AgentRequest(
- request_id="req-123",
+ request_id=request_id,
channel_id="officeclaw",
- session_id="session-456",
+ session_id=session_id,
params=params,
)
-def _valid_config() -> dict[str, object]:
+def _valid_config(*, invocation_id: str = "invoke-1") -> dict[str, object]:
return {
"command": r"E:\node\node.exe",
"args": [r"E:\relay\packages\mcp-server\dist\index.js"],
"cwd": r"E:\relay",
"env": {
"OFFICE_CLAW_API_URL": "http://127.0.0.1:3000",
- "OFFICE_CLAW_INVOCATION_ID": "invoke-1",
+ "OFFICE_CLAW_INVOCATION_ID": invocation_id,
"OFFICE_CLAW_CALLBACK_TOKEN": "secret-token",
"OFFICE_CLAW_MCP_EXCLUDED_TOOLS": "office_claw_list_tasks",
},
@@ -58,10 +67,16 @@ class _AbilityManager:
self.cards: dict[str, object] = {}
self.removed: list[str] = []
+ def get(self, name: str) -> object | None:
+ return self.cards.get(name)
+
def add(self, card: object) -> SimpleNamespace:
name = str(getattr(card, "name"))
+ existing = self.cards.get(name)
+ if existing is not None and getattr(existing, "id", None) != getattr(card, "id", None):
+ return SimpleNamespace(added=False, reason="duplicate_tool")
self.cards[name] = card
- return SimpleNamespace(added=True)
+ return SimpleNamespace(added=True, reason="added_tool")
def remove(self, name: str) -> None:
self.removed.append(name)
@@ -86,9 +101,25 @@ class _ResourceManager:
def _bare_session_adapter() -> JiuWenSwarmDeepAdapter:
adapter = object.__new__(JiuWenSwarmDeepAdapter)
adapter._instance = SimpleNamespace(ability_manager=_AbilityManager())
+ adapter._active_office_claw_mcp = None
return adapter
+def _tool_list() -> list[dict[str, object]]:
+ return [
+ {
+ "name": "office_claw_preview_scheduled_task",
+ "description": "preview",
+ "input_params": {"type": "object"},
+ },
+ {
+ "name": "office_claw_multi_mention",
+ "description": "multi",
+ "input_params": {"type": "object"},
+ },
+ ]
+
+
def test_extract_supports_only_office_claw_mcp() -> None:
config = _valid_config()
@@ -117,6 +148,49 @@ def test_validation_pins_process_identity_to_relay_startup() -> None:
validate_office_claw_mcp_config(changed, environ=_startup_env())
+def test_request_scoped_tool_allowlist_rejects_cross_request_id() -> None:
+ with bind_active_office_claw_mcp_tools(["office-claw-request-aaa.office-claw.multi"]):
+ ensure_request_scoped_office_claw_tool_allowed(
+ "office-claw-request-aaa.office-claw.multi"
+ )
+ with pytest.raises(RuntimeError, match="bound to another request"):
+ ensure_request_scoped_office_claw_tool_allowed(
+ "office-claw-request-bbb.office-claw.multi"
+ )
+
+
+def test_request_scoped_tool_allowlist_rejects_unbound_invoke() -> None:
+ with pytest.raises(RuntimeError, match="without an active request binding"):
+ ensure_request_scoped_office_claw_tool_allowed(
+ "office-claw-request-aaa.office-claw.multi"
+ )
+
+
+async def test_request_scoped_tool_invoke_refuses_cross_request_binding() -> None:
+ card = ToolCard(
+ id="office-claw-request-bbb.office-claw.office_claw_multi_mention",
+ name="office_claw_multi_mention",
+ description="multi",
+ input_params={},
+ )
+ tool = RequestScopedOfficeClawMcpTool(
+ card,
+ {
+ "command": "node",
+ "args": ["index.js"],
+ "cwd": ".",
+ "env": {"OFFICE_CLAW_INVOCATION_ID": "other"},
+ },
+ )
+
+ with bind_active_office_claw_mcp_tools(
+ ["office-claw-request-aaa.office-claw.office_claw_multi_mention"]
+ ):
+ with pytest.raises(Exception, match="bound to another request"):
+ await tool.invoke({})
+
+
@pytest.mark.asyncio
async def test_registers_exact_tool_names_and_cleans_them_up(
monkeypatch: pytest.MonkeyPatch,
@@ -128,20 +202,7 @@ async def test_registers_exact_tool_names_and_cleans_them_up(
monkeypatch.setattr(
interface_deep,
"list_office_claw_mcp_tools",
- AsyncMock(
- return_value=[
- {
- "name": "office_claw_preview_scheduled_task",
- "description": "preview",
- "input_params": {"type": "object"},
- },
- {
- "name": "office_claw_register_scheduled_task",
- "description": "register",
- "input_params": {"type": "object"},
- },
- ]
- ),
+ AsyncMock(return_value=_tool_list()),
)
adapter = _bare_session_adapter()
@@ -152,16 +213,90 @@ async def test_registers_exact_tool_names_and_cleans_them_up(
assert registration is not None
assert registration.tool_names == (
"office_claw_preview_scheduled_task",
- "office_claw_register_scheduled_task",
+ "office_claw_multi_mention",
)
assert set(adapter._instance.ability_manager.cards) == set(registration.tool_names)
assert len(resource_manager.tools) == 2
+ assert adapter._active_office_claw_mcp == registration
await adapter.cleanup_request_scoped_office_claw_mcp(registration)
assert resource_manager.tools == {}
assert adapter._instance.ability_manager.cards == {}
assert resource_manager.removed == list(registration.tool_ids)
+ assert adapter._active_office_claw_mcp is None
+
+
+async def test_cleanup_does_not_remove_rebound_short_name(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ for key, value in _startup_env().items():
+ monkeypatch.setenv(key, value)
+ resource_manager = _ResourceManager()
+ monkeypatch.setattr(interface_deep.Runner, "resource_mgr", resource_manager)
+ monkeypatch.setattr(
+ interface_deep,
+ "list_office_claw_mcp_tools",
+ AsyncMock(return_value=_tool_list()),
+ )
+ shared_ability = _AbilityManager()
+ adapter_a = _bare_session_adapter()
+ adapter_b = _bare_session_adapter()
+ adapter_a._instance = SimpleNamespace(ability_manager=shared_ability)
+ adapter_b._instance = SimpleNamespace(ability_manager=shared_ability)
+
+ registration_a = await adapter_a.register_request_scoped_office_claw_mcp(
+ _request(_valid_config(invocation_id="inv-a"), request_id="req-a", session_id="sess-a")
+ )
+ assert registration_a is not None
+
+ # Simulate a polluted shared AbilityManager: B overwrites short names after
+ # owning the previous mapping (sequential replace on same AM).
+ adapter_b._active_office_claw_mcp = registration_a
+ registration_b = await adapter_b.register_request_scoped_office_claw_mcp(
+ _request(_valid_config(invocation_id="inv-b"), request_id="req-b", session_id="sess-b")
+ )
+ assert registration_b is not None
+ multi_card = shared_ability.get("office_claw_multi_mention")
+ assert multi_card is not None
+ assert str(multi_card.id) in registration_b.tool_ids
+
+ await adapter_a.cleanup_request_scoped_office_claw_mcp(registration_a)
+
+ # A's cleanup must not delete B's rebound short-name mapping.
+ assert "office_claw_multi_mention" in shared_ability.cards
+ assert str(shared_ability.get("office_claw_multi_mention").id) in registration_b.tool_ids
+
+
+async def test_foreign_short_name_conflict_fails_closed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ for key, value in _startup_env().items():
+ monkeypatch.setenv(key, value)
+ resource_manager = _ResourceManager()
+ monkeypatch.setattr(interface_deep.Runner, "resource_mgr", resource_manager)
+ monkeypatch.setattr(
+ interface_deep,
+ "list_office_claw_mcp_tools",
+ AsyncMock(return_value=_tool_list()),
+ )
+ adapter = _bare_session_adapter()
+ foreign = ToolCard(
+ id="office-claw-request-foreign.office-claw.office_claw_multi_mention",
+ name="office_claw_multi_mention",
+ description="foreign",
+ input_params={},
+ )
+ adapter._instance.ability_manager.cards["office_claw_multi_mention"] = foreign
+
+ registration = await adapter.register_request_scoped_office_claw_mcp(
+ _request(_valid_config())
+ )
+
+ assert registration is None
+ assert adapter._instance.ability_manager.get("office_claw_multi_mention") is foreign
@pytest.mark.asyncio
@@ -236,3 +371,46 @@ async def test_stream_request_cleans_up_when_consumer_finishes() -> None:
assert chunks == [chunk]
child.cleanup_request_scoped_office_claw_mcp.assert_awaited_once_with(registration)
+
+
+async def test_stream_request_binds_active_tool_allowlist() -> None:
+ parent = object.__new__(JiuWenSwarmDeepAdapter)
+ parent._is_session_scoped_adapter = False
+ registration = OfficeClawMcpRegistration(
+ "req-123",
+ ("office-claw-request-aaa.office-claw.office_claw_multi_mention",),
+ ("office_claw_multi_mention",),
+ )
+ seen: dict[str, bool] = {}
+
+ class _Child:
+ def __init__(self) -> None:
+ self.register_request_scoped_office_claw_mcp = AsyncMock(
+ return_value=registration
+ )
+ self.cleanup_request_scoped_office_claw_mcp = AsyncMock()
+
+ async def process_message_stream_impl(self, request, inputs):
+ ensure_request_scoped_office_claw_tool_allowed(registration.tool_ids[0])
+ seen["allowed"] = True
+ 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"
+ )
+ seen["rejected_foreign"] = True
+ yield AgentResponseChunk(request_id="req-123", channel_id="officeclaw")
+
+ child = _Child()
+ parent._get_or_create_session_adapter = AsyncMock(return_value=child)
+ parent._evict_idle_session_adapters = AsyncMock()
+
+ _ = [
+ item
+ async for item in parent.process_message_stream_impl(
+ _request(_valid_config()),
+ {},
+ )
+ ]
+
+ assert seen == {"allowed": True, "rejected_foreign": True}