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): schema 缓存改由 bundle 指纹自判新鲜度,不再随目录 revision 清空
huxiaokaic368b07caf60
diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex 60d3cbba2b..89ceccaf98 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -800,6 +800,10 @@ _office_claw_mcp_schema_inflight: dict[] = {}_office_claw_mcp_schema_cache_lock = threading.Lock()_office_claw_mcp_schema_generation = 0+# Orphaned entries (keys nobody computes anymore after a bundle upgrade) are+# bounded by this cap instead of an invalidation signal. Realistic cardinality+# is <20 (agent/toolset configs); clearing on overflow costs one re-discovery.+_OFFICE_CLAW_MCP_SCHEMA_CACHE_MAX_ENTRIES = 128def _office_claw_mcp_schema_cache_enabled() -> bool:@@ -809,10 +813,52 @@ def _office_claw_mcp_schema_cache_enabled() -> bool:)+_OFFICE_CLAW_MCP_BUNDLE_MAX_FILES = 256+++def _fingerprint_bundle_tree(root: Path) -> list[dict[str, Any]] | None:+ """Stat every file under ``root`` recursively, skipping node_modules and+ source maps. Returns ``None`` when the tree exceeds the file cap so the+ caller can refuse to cache rather than fingerprint an unbounded tree."""+ entries: list[dict[str, Any]] = []+ stack: list[Path] = [root]+ while stack:+ current = stack.pop()+ try:+ children = sorted(current.iterdir(), key=lambda item: item.name)+ except OSError:+ continue+ for child in children:+ if child.name == "node_modules":+ continue+ try:+ if child.is_dir():+ stack.append(child)+ continue+ except OSError:+ continue+ if child.name.endswith(".map"):+ continue+ if len(entries) >= _OFFICE_CLAW_MCP_BUNDLE_MAX_FILES:+ return None+ try:+ stat = child.stat()+ except OSError:+ continue+ entries.append(+ {+ "path": _normalized_path(str(child)),+ "size": stat.st_size,+ "mtime_ns": stat.st_mtime_ns,+ }+ )+ return sorted(entries, key=lambda entry: entry["path"])++def _office_claw_mcp_build_fingerprint(params: Mapping[str, Any],-) -> list[dict[str, Any]]:- """Fingerprint the MCP bundle file(s) so a rebuild rotates the cache key.+) -> list[dict[str, Any]] | None:+ """Fingerprint the MCP bundle so a rebuild rotates the cache key.Relative script paths in ``command``/``args`` are resolved against``params["cwd"]`` first — the stdio MCP process is spawned with that cwd,@@ -820,6 +866,16 @@ def _office_claw_mcp_build_fingerprint(to the sidecar process cwd. Resolving against the process cwd alone wouldeither miss the real bundle or stat the wrong file, so a bundle rebuildwould not change the fingerprint and the cache would serve a stale schema.++ The interpreter (``command``) is fingerprinted as a single file. Every+ script entry in ``args`` additionally fingerprints its owning directory+ tree: the entry file is typically a thin shell that imports the toolset+ modules next to it, so a rebuild that only touches those imports must+ still rotate the key. ``node_modules`` and ``*.map`` files are skipped.++ Returns ``None`` when a bundle tree exceeds ``_OFFICE_CLAW_MCP_BUNDLE_MAX_FILES``+ files — the caller then bypasses the cache instead of trusting a+ fingerprint it could not fully compute."""fingerprints: list[dict[str, Any]] = []base_dirs: list[Path] = []@@ -827,49 +883,76 @@ def _office_claw_mcp_build_fingerprint(if cwd_raw:base_dirs.append(Path(cwd_raw).expanduser())base_dirs.append(Path.cwd())- candidates = [params.get("command"), *(params.get("args") or [])]- seen: set[str] = set()- for candidate in candidates:- raw = str(candidate or "").strip()- if not raw:- continue+ seen_paths: set[str] = set()+ expanded_dirs: set[str] = set()++ def _resolve(raw: str) -> Path | None:probe = Path(raw).expanduser()- resolved: Path | None = Noneif probe.is_absolute():- resolved = probe- else:- for base in base_dirs:- candidate_path = base / probe- if candidate_path.is_file():- resolved = candidate_path- break- if resolved is None:- try:- resolved = probe.resolve(strict=False)- except OSError:- continue- resolved_str = str(resolved)- if not resolved.is_file() or resolved_str in seen:- continue- seen.add(resolved_str)+ return probe+ for base in base_dirs:+ candidate_path = base / probe+ if candidate_path.is_file():+ return candidate_path+ try:+ return probe.resolve(strict=False)+ except OSError:+ return None++ def _stat_once(resolved: Path) -> None:+ normalized = _normalized_path(str(resolved))+ if normalized in seen_paths:+ returntry:stat = resolved.stat()except OSError:- continue+ return+ seen_paths.add(normalized)fingerprints.append({- "path": _normalized_path(resolved_str),+ "path": normalized,"size": stat.st_size,"mtime_ns": stat.st_mtime_ns,})- return fingerprints+ command_raw = str(params.get("command") or "").strip()+ if command_raw:+ resolved = _resolve(command_raw)+ if resolved is not None and resolved.is_file():+ _stat_once(resolved)-def _office_claw_mcp_schema_cache_key(params: Mapping[str, Any]) -> str:+ for value in params.get("args") or []:+ raw = str(value or "").strip()+ if not raw:+ continue+ resolved = _resolve(raw)+ if resolved is None or not resolved.is_file():+ continue+ parent_key = _normalized_path(str(resolved.parent))+ if parent_key in expanded_dirs:+ continue+ expanded_dirs.add(parent_key)+ tree = _fingerprint_bundle_tree(resolved.parent)+ if tree is None:+ return None+ for entry in tree:+ if entry["path"] in seen_paths:+ continue+ seen_paths.add(entry["path"])+ fingerprints.append(entry)+ return sorted(fingerprints, key=lambda entry: entry["path"])+++def _office_claw_mcp_schema_cache_key(params: Mapping[str, Any]) -> str | None:raw_excluded = str((params.get("env") or {}).get("OFFICE_CLAW_MCP_EXCLUDED_TOOLS") or "")+ build_files = _office_claw_mcp_build_fingerprint(params)+ if not build_files:+ # No local bundle files (remote-style config) or an oversized bundle+ # tree: the key could never rotate on a change, so refuse to cache.+ return Nonepayload = {"command": _normalized_path(str(params.get("command") or "")),"args": [str(value) for value in params.get("args") or []],@@ -877,7 +960,7 @@ def _office_claw_mcp_schema_cache_key(params: Mapping[str, Any]) -> str:"excluded_tools": sorted({item.strip() for item in raw_excluded.split(",") if item.strip()}),- "build_files": _office_claw_mcp_build_fingerprint(params),+ "build_files": build_files,}return hashlib.sha256(json.dumps(@@ -889,11 +972,12 @@ def _office_claw_mcp_schema_cache_key(params: Mapping[str, Any]) -> str:def invalidate_office_claw_mcp_schema_cache() -> None:"""Drop the entire OfficeClaw MCP schema cache and abort coalesced discovery.- Called when the agent catalog revision changes (Relay resync) so that a- rebuilt MCP bundle or changed excluded-tool set is re-discovered instead- of serving a stale schema. Bumping ``_office_claw_mcp_schema_generation``- also prevents any in-flight discovery task from writing back into a newer- generation.+ Manual/test hook: production no longer calls this automatically. The+ cache key embeds the bundle tree fingerprint, so a rebuilt bundle or a+ changed excluded-tool set rotates the key on its own; orphaned entries+ are bounded by the entry-count cap. Bumping+ ``_office_claw_mcp_schema_generation`` also prevents any in-flight+ discovery task from writing back into a newer generation."""global _office_claw_mcp_schema_generationwith _office_claw_mcp_schema_cache_lock:@@ -2473,6 +2557,11 @@ async def _discover_and_cache_office_claw_mcp_schema(frozen = copy.deepcopy(tools)with _office_claw_mcp_schema_cache_lock:if generation == _office_claw_mcp_schema_generation:+ if (+ len(_office_claw_mcp_schema_cache)+ >= _OFFICE_CLAW_MCP_SCHEMA_CACHE_MAX_ENTRIES+ ):+ _office_claw_mcp_schema_cache.clear()_office_claw_mcp_schema_cache[cache_key] = frozenlogger.info("OfficeClaw MCP schema cache filled: key=%s tools=%s duration_ms=%.1f",@@ -2503,8 +2592,10 @@ async def list_office_claw_mcp_tools(same event loop + generation + key are coalesced into one in-flightproducer task; waiters are pure consumers wrapped in ``asyncio.shield``,so a cancelled waiter cannot abort the shared discovery or evict it from- the in-flight table. ``invalidate_office_claw_mcp_schema_cache`` drops- everything on catalog revision change. Setting the env var to+ the in-flight table. Freshness is decided by the key itself (it embeds+ the bundle tree fingerprint), not by any external invalidation signal;+ orphaned entries are bounded by an entry-count cap, and configs with no+ local bundle files (remote-style) are never cached. Setting the env var to``0/false/no/off`` falls back to the uncached path."""@@ -2512,6 +2603,10 @@ async def list_office_claw_mcp_tools(return await _list_office_claw_mcp_tools_uncached(params)cache_key = _office_claw_mcp_schema_cache_key(params)+ if cache_key is None:+ # No local bundle files (remote-style config) or an oversized bundle+ # tree: the key could never rotate on a change, so bypass the cache.+ return await _list_office_claw_mcp_tools_uncached(params)with _office_claw_mcp_schema_cache_lock:generation = _office_claw_mcp_schema_generationloop_key = (id(asyncio.get_running_loop()), generation, cache_key)diff --git a/jiuwenswarm/server/runtime/tenant_agent_pool.py b/jiuwenswarm/server/runtime/tenant_agent_pool.pyindex ca46d9c4f2..fe4a10e18e 100644--- a/jiuwenswarm/server/runtime/tenant_agent_pool.py+++ b/jiuwenswarm/server/runtime/tenant_agent_pool.py@@ -11,7 +11,6 @@ from jiuwenswarm.common.utils import (get_multi_tenant_user_workspace_dir,seed_tenant_agent_workspace,)-from jiuwenswarm.common.mcp_config import invalidate_office_claw_mcp_schema_cachefrom jiuwenswarm.server.runtime.reload_result import (ReloadAggregateResult,log_agent_config_hot_reload,@@ -701,15 +700,6 @@ class TenantAgentPool:],}- # A new catalog revision may reflect a rebuilt MCP bundle or a- # changed excluded-tool set; drop the process-local schema cache- # so the next discovery re-reads the (now possibly different)- # static schema. The cache key also embeds build-file size+mtime_ns,- # so this invalidate is belt-and-suspenders against stale entries- # left behind when the key itself changes.- if self._last_sync_revision.get(service_id) not in (None, revision):- invalidate_office_claw_mcp_schema_cache()-incoming_specs: dict[str, Any] = {}for entry in agents_payload:agent_id = entry["agent_id"]diff --git a/tests/unit_tests/agentserver/test_mcp_schema_cache.py b/tests/unit_tests/agentserver/test_mcp_schema_cache.pyindex 121655232e..805123df57 100644--- a/tests/unit_tests/agentserver/test_mcp_schema_cache.py+++ b/tests/unit_tests/agentserver/test_mcp_schema_cache.py@@ -3,26 +3,20 @@"""Correctness tests for the OfficeClaw MCP schema in-process cache.These do NOT spawn a real Node process; they monkeypatch the uncached-discovery so the cache logic (key, single-flight, deepcopy, generation-invalidation) is exercised deterministically.+discovery so the cache logic (key, single-flight, deepcopy, entry cap)+is exercised deterministically."""from __future__ import annotationsimport asyncio+from pathlib import Pathfrom unittest.mock import AsyncMockimport pytestfrom jiuwenswarm.common import mcp_config-_PARAMS = {- "command": "node",- "args": ["/repo/packages/mcp-server/dist/collab.js"],- "cwd": "/repo",- "env": {"OFFICE_CLAW_MCP_EXCLUDED_TOOLS": "office_claw_list_tasks"},-}-def _make_tool(name: str) -> dict:return {@@ -40,9 +34,29 @@ def _reset_cache(monkeypatch: pytest.MonkeyPatch) -> None:mcp_config._clear_office_claw_mcp_schema_cache_for_tests()+def bundle_params(tmp_path: Path) -> dict:+ """Params backed by a real temp bundle so the fingerprint is non-empty.++ Mirrors the deployed layout: a thin entry shell next to the toolset+ module that actually defines the tool schemas.+ """+ dist = tmp_path / "dist"+ dist.mkdir()+ (dist / "index.js").write_text("shell v1")+ (dist / "server-toolsets.js").write_text("toolset v1")+ return {+ "command": "node",+ "args": [str(dist / "index.js")],+ "cwd": str(tmp_path),+ "env": {"OFFICE_CLAW_MCP_EXCLUDED_TOOLS": "office_claw_list_tasks"},+ }++@pytest.mark.asyncioasync def test_second_call_hits_cache_and_returns_equal_schema(monkeypatch: pytest.MonkeyPatch,+ bundle_params: dict,) -> None:calls = 0@@ -53,8 +67,8 @@ async def test_second_call_hits_cache_and_returns_equal_schema(monkeypatch.setattr(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover)- first = await mcp_config.list_office_claw_mcp_tools(_PARAMS)- second = await mcp_config.list_office_claw_mcp_tools(_PARAMS)+ first = await mcp_config.list_office_claw_mcp_tools(bundle_params)+ second = await mcp_config.list_office_claw_mcp_tools(bundle_params)assert calls == 1, "second call must hit the cache, not re-discover"assert first == second == [_make_tool("office_claw_post_message")]@@ -63,6 +77,7 @@ async def test_second_call_hits_cache_and_returns_equal_schema(@pytest.mark.asyncioasync def test_returned_schema_is_deep_copied_so_callers_cannot_mutate_cache(monkeypatch: pytest.MonkeyPatch,+ bundle_params: dict,) -> None:monkeypatch.setattr(mcp_config,@@ -70,10 +85,10 @@ async def test_returned_schema_is_deep_copied_so_callers_cannot_mutate_cache(AsyncMock(return_value=[_make_tool("office_claw_post_message")]),)- first = await mcp_config.list_office_claw_mcp_tools(_PARAMS)+ first = await mcp_config.list_office_claw_mcp_tools(bundle_params)first[0]["name"] = "MUTATED"- second = await mcp_config.list_office_claw_mcp_tools(_PARAMS)+ second = await mcp_config.list_office_claw_mcp_tools(bundle_params)assert second[0]["name"] == "office_claw_post_message", ("cache must not be mutated by callers")@@ -82,6 +97,7 @@ async def test_returned_schema_is_deep_copied_so_callers_cannot_mutate_cache(@pytest.mark.asyncioasync def test_invalidate_forces_rediscovery(monkeypatch: pytest.MonkeyPatch,+ bundle_params: dict,) -> None:calls = 0@@ -92,18 +108,19 @@ async def test_invalidate_forces_rediscovery(monkeypatch.setattr(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover)- await mcp_config.list_office_claw_mcp_tools(_PARAMS)- await mcp_config.list_office_claw_mcp_tools(_PARAMS)+ await mcp_config.list_office_claw_mcp_tools(bundle_params)+ await mcp_config.list_office_claw_mcp_tools(bundle_params)assert calls == 1mcp_config.invalidate_office_claw_mcp_schema_cache()- await mcp_config.list_office_claw_mcp_tools(_PARAMS)+ await mcp_config.list_office_claw_mcp_tools(bundle_params)assert calls == 2, "invalidate must drop the cache and force a fresh discovery"@pytest.mark.asyncioasync def test_disabled_flag_falls_back_to_uncached(monkeypatch: pytest.MonkeyPatch,+ bundle_params: dict,) -> None:monkeypatch.setenv("JIUWENSWARM_MCP_SCHEMA_CACHE", "0")calls = 0@@ -115,14 +132,15 @@ async def test_disabled_flag_falls_back_to_uncached(monkeypatch.setattr(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover)- await mcp_config.list_office_claw_mcp_tools(_PARAMS)- await mcp_config.list_office_claw_mcp_tools(_PARAMS)+ await mcp_config.list_office_claw_mcp_tools(bundle_params)+ await mcp_config.list_office_claw_mcp_tools(bundle_params)assert calls == 2, "with cache disabled every call must discover"@pytest.mark.asyncioasync def test_concurrent_discovery_coalesces_into_one_inflight_task(monkeypatch: pytest.MonkeyPatch,+ bundle_params: dict,) -> None:started = asyncio.Event()releases = asyncio.Event()@@ -137,9 +155,9 @@ async def test_concurrent_discovery_coalesces_into_one_inflight_task(monkeypatch.setattr(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover)- t1 = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(_PARAMS))+ t1 = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(bundle_params))await started.wait()- t2 = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(_PARAMS))+ t2 = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(bundle_params))await asyncio.sleep(0) # let t2 observe in-flight taskreleases.set()@@ -152,6 +170,7 @@ async def test_concurrent_discovery_coalesces_into_one_inflight_task(@pytest.mark.asyncioasync def test_cancelled_waiter_does_not_evict_shared_inflight_task(monkeypatch: pytest.MonkeyPatch,+ bundle_params: dict,) -> None:"""A cancelled first waiter must not pop the in-flight task or skip the cache write.@@ -173,11 +192,11 @@ async def test_cancelled_waiter_does_not_evict_shared_inflight_task(monkeypatch.setattr(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover)- first = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(_PARAMS))+ first = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(bundle_params))await started.wait() # producer discovery is in-flight# a second waiter joins the same in-flight task- second = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(_PARAMS))+ second = asyncio.create_task(mcp_config.list_office_claw_mcp_tools(bundle_params))await asyncio.sleep(0)assert len(mcp_config._office_claw_mcp_schema_inflight) == 1@@ -227,6 +246,7 @@ def test_build_fingerprint_resolves_relative_args_against_params_cwd(}fp1 = mcp_config._office_claw_mcp_build_fingerprint(params)+ assert fp1 is not Noneassert len(fp1) == 1, "relative bundle must be found via params cwd"assert fp1[0]["path"].replace("\\", "/").endswith("dist/collab.js")@@ -236,3 +256,109 @@ def test_build_fingerprint_resolves_relative_args_against_params_cwd(assert fp2 != fp1, ("bundle rebuild must rotate the fingerprint (and thus the cache key)")+++def test_bundle_tree_change_rotates_key_without_entry_change(+ tmp_path,+) -> None:+ """A rebuild that only touches the entry's imported sibling must rotate the key.++ The entry file (index.js) is a thin shell; the toolset module next to it+ defines the schemas. The fingerprint covers the whole owning directory so+ a sibling-only rebuild cannot keep serving a stale cached schema — the+ exact blind spot the old revision-based invalidation used to cover by+ accident (by wiping on every catalog change).+ """+ dist = tmp_path / "dist"+ dist.mkdir()+ entry = dist / "index.js"+ entry.write_text("shell v1")+ (dist / "server-toolsets.js").write_text("toolset v1")++ params = {+ "command": "node",+ "args": [str(entry)],+ "cwd": str(tmp_path),+ "env": {},+ }+ key1 = mcp_config._office_claw_mcp_schema_cache_key(params)+ assert key1 is not None++ (dist / "server-toolsets.js").write_text("toolset v2-with-more-bytes")+ key2 = mcp_config._office_claw_mcp_schema_cache_key(params)+ assert key2 is not None+ assert key2 != key1, "sibling-only rebuild must rotate the cache key"++ # node_modules and source maps stay out of the fingerprint+ (dist / "node_modules").mkdir()+ (dist / "node_modules" / "dep.js").write_text("dep")+ (dist / "extras.js.map").write_text("{}")+ key3 = mcp_config._office_claw_mcp_schema_cache_key(params)+ assert key3 == key2, "node_modules / *.map must not affect the fingerprint"+++async def test_remote_config_without_local_files_is_never_cached(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """No local bundle files (remote-style config) -> always uncached.++ A remote MCP schema can change server-side at any time and a key without+ local files would never rotate, so the wrapper must bypass the cache+ entirely instead of serving a possibly stale entry forever.+ """+ calls = 0++ async def _discover(params):+ nonlocal calls+ calls += 1+ return [_make_tool("office_claw_post_message")]++ monkeypatch.setattr(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover)++ params = {+ "command": "node",+ "args": ["/nonexistent/bundle.js"],+ "cwd": str(tmp_path),+ "env": {},+ }+ await mcp_config.list_office_claw_mcp_tools(params)+ await mcp_config.list_office_claw_mcp_tools(params)+ assert calls == 2, "remote-style configs must not be cached"+ assert len(mcp_config._office_claw_mcp_schema_cache) == 0+++async def test_capacity_bound_clears_orphaned_entries(+ monkeypatch: pytest.MonkeyPatch,+ bundle_params: dict,+) -> None:+ """Entries beyond the cap are dropped instead of accumulating forever.++ Orphaned keys (nobody computes them anymore after a bundle upgrade) are+ bounded by the entry cap; clearing on overflow costs one re-discovery.+ """+ monkeypatch.setattr(mcp_config, "_OFFICE_CLAW_MCP_SCHEMA_CACHE_MAX_ENTRIES", 2)+ calls = 0++ async def _discover(params):+ nonlocal calls+ calls += 1+ return [_make_tool(f"tool_{calls}")]++ monkeypatch.setattr(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover)++ variants = []+ for index in range(3):+ params = dict(bundle_params)+ params["env"] = {"OFFICE_CLAW_MCP_EXCLUDED_TOOLS": f"office_claw_tool_{index}"}+ variants.append(params)+ await mcp_config.list_office_claw_mcp_tools(params)++ assert len(mcp_config._office_claw_mcp_schema_cache) == 1, (+ "third insert must clear the overflowed cache and keep only the new entry"+ )+ # the cleared entries are gone: a repeat of the first variant re-discovers+ await mcp_config.list_office_claw_mcp_tools(variants[0])+ assert calls == 4, "evicted entry must re-discover"diff --git a/tests/unit_tests/agentserver/test_sync_agents_configs.py b/tests/unit_tests/agentserver/test_sync_agents_configs.pyindex b63bc6de5c..8f53727847 100644--- a/tests/unit_tests/agentserver/test_sync_agents_configs.py+++ b/tests/unit_tests/agentserver/test_sync_agents_configs.py@@ -1012,3 +1012,52 @@ class TestOfficeclawGuard:)assert TenantAgentPool.require_officeclaw_agent(req) is None+async def test_sync_revision_change_keeps_schema_cache(mock_warmup, tmp_path):+ """Catalog revision churn must not wipe the OfficeClaw MCP schema cache.++ Regression for the belt-and-suspenders invalidation previously wired into+ sync_agents_configs: the relay revision hashes the whole catalog (agent+ models, credentials, teams) and churns on most syncs, so the cache was+ re-filled (a ~400ms Node spawn) every few minutes although the MCP bundle+ never changed. Freshness is now decided by the bundle-tree fingerprint+ embedded in the cache key.+ """+ from jiuwenswarm.common import mcp_config++ dist = tmp_path / "dist"+ dist.mkdir()+ (dist / "index.js").write_text("shell v1")+ params = {+ "command": "node",+ "args": [str(dist / "index.js")],+ "cwd": str(tmp_path),+ "env": {},+ }++ calls = 0++ async def _discover(p):+ nonlocal calls+ calls += 1+ return [{"name": "office_claw_post_message", "description": "d", "input_params": {}}]++ with patch.object(mcp_config, "_list_office_claw_mcp_tools_uncached", _discover):+ mcp_config._clear_office_claw_mcp_schema_cache_for_tests()+ try:+ await mcp_config.list_office_claw_mcp_tools(params)+ await mcp_config.list_office_claw_mcp_tools(params)+ assert calls == 1+ assert len(mcp_config._office_claw_mcp_schema_cache) == 1++ pool = TenantAgentPool.get_instance()+ await pool.sync_agents_configs(_sync_payload(revision="rev-a"))+ await pool.sync_agents_configs(_sync_payload(revision="rev-b"))++ assert len(mcp_config._office_claw_mcp_schema_cache) == 1, (+ "catalog revision change must not clear the MCP schema cache"+ )+ await mcp_config.list_office_claw_mcp_tools(params)+ assert calls == 1, "cache entry must survive catalog syncs"+ finally:+ mcp_config._clear_office_claw_mcp_schema_cache_for_tests()