Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(workspace): share workspace across different agents (#1951)
DiegoCluv7732010138ab8
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.pyindex 922d41bb8..e004a16e1 100644--- a/src/agentscope/app/_lifespan.py+++ b/src/agentscope/app/_lifespan.py@@ -156,6 +156,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:app.state.session_service = SessionService(storage=storage,message_bus=message_bus,+ workspace_manager=workspace_manager,)app.state.workspace_service = WorkspaceService(diff --git a/src/agentscope/app/_router/_workspace.py b/src/agentscope/app/_router/_workspace.pyindex 918535cef..1426aa972 100644--- a/src/agentscope/app/_router/_workspace.py+++ b/src/agentscope/app/_router/_workspace.py@@ -63,7 +63,10 @@ async def list_mcps(agent_id,session_id,)- clients = await workspace.list_mcps()+ clients = await workspace.list_mcps(+ agent_id=agent_id,+ session_id=session_id,+ )results = []for client in clients:@@ -115,7 +118,13 @@ async def add_mcp(agent_id,session_id,)- await workspace.add_mcp(mcp)+ try:+ await workspace.add_mcp(mcp, agent_id=agent_id, session_id=session_id)+ except ValueError as e:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=str(e),+ ) from eif await storage.get_mcp_by_name(user_id, mcp.name) is None:# No hub_id or card_id — this one has no card behind it, which@@ -151,7 +160,13 @@ async def add_mcps_from_library(agent_id,session_id,)- present = {client.name for client in await workspace.list_mcps()}+ present = {+ client.name+ for client in await workspace.list_mcps(+ agent_id=agent_id,+ session_id=session_id,+ )+ }added: list[str] = []failed: dict[str, str] = {}@@ -164,7 +179,11 @@ async def add_mcps_from_library(# Already there: not an error, just nothing to do.continuetry:- await workspace.add_mcp(record.client)+ await workspace.add_mcp(+ record.client,+ agent_id=agent_id,+ session_id=session_id,+ )except Exception as e:failed[record.client.name] = _describe_exception(e)continue@@ -190,7 +209,11 @@ async def remove_mcp(agent_id,session_id,)- await workspace.remove_mcp(mcp_name)+ await workspace.remove_mcp(+ mcp_name,+ agent_id=agent_id,+ session_id=session_id,+ )# ---------------------------------------------------------------------------diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.pyindex bea352608..f0bd06688 100644--- a/src/agentscope/app/_service/_session.py+++ b/src/agentscope/app/_service/_session.py@@ -50,6 +50,7 @@ from enum import StrEnumfrom ..message_bus import MessageBus, MessageBusKeysfrom ..storage import StorageBase+from ..workspace_manager import WorkspaceManagerBasefrom ..storage._utils import _ensure_team_membersfrom ._session_projection import SessionProjectionfrom ._projectors import SubagentHitlProjector@@ -121,15 +122,21 @@ class SessionService:self,storage: StorageBase,message_bus: MessageBus,+ workspace_manager: WorkspaceManagerBase | None = None,) -> None:"""Bind dependencies.Args:storage (`StorageBase`): Persistent storage backend.message_bus (`MessageBus`): Live message bus.+ workspace_manager (`WorkspaceManagerBase | None`, optional):+ Used by :meth:`delete_session` to drop the deleted+ session's workspace state. ``None`` skips that step —+ callers without a manager keep the previous behaviour."""self._storage = storageself._bus = message_bus+ self._workspace_manager = workspace_managerself._projection = SessionProjection(message_bus)# ------------------------------------------------------------------@@ -336,6 +343,10 @@ class SessionService:this session leads one — recursive into worker agents).3. Purge transient bus state for ``session_id`` (events log,inbox).+ 4. Drop the session's workspace state (MCP clients, offload+ files). Workspaces outlive sessions and are usually shared+ by every session of an agent, so this would otherwise+ accumulate for the life of the workspace.Worker sessions that storage cascades through are picked uphere too: when this session is a team leader,@@ -364,17 +375,47 @@ class SessionService:)all_sids = [session_id, *worker_sids]+ # Resolve the workspace binding while the record still exists.+ record = await self._storage.get_session(user_id, agent_id, session_id)+ workspace_id = record.config.workspace_id if record else None+# Clean leader-side subagent HITL projections before storage# cascades remove the records we need to resolve roles from.await self._purge_subagent_hitl(user_id, agent_id, session_id)- await self._cancel_runs(all_sids)+ await asyncio.gather(+ *(self.cancel_session_run(sid) for sid in all_sids),+ )deleted = await self._storage.delete_session(user_id,agent_id,session_id,)- await self._purge_bus(all_sids)+ await asyncio.gather(+ *(self._purge_session_bus(sid) for sid in all_sids),+ )++ # Best-effort: a workspace that cannot be resolved (backend+ # down, sandbox gone) must not fail a committed deletion.+ if deleted and self._workspace_manager and workspace_id:+ try:+ workspace = await self._workspace_manager.get_workspace(+ user_id,+ agent_id,+ session_id,+ workspace_id,+ )+ await workspace.purge_session(+ agent_id=agent_id,+ session_id=session_id,+ )+ except Exception as e:+ logger.warning(+ "Failed to purge workspace %r for session %r: %s",+ workspace_id,+ session_id,+ e,+ )return deletedasync def delete_team(self, user_id: str, team_id: str) -> bool:@@ -582,32 +623,6 @@ class SessionService:members = await _ensure_team_members(self._storage, user_id, team)return [m.session_id for m in members]- async def _cancel_runs(self, session_ids: list[str]) -> None:- """Cancel every in-flight run in ``session_ids`` concurrently.-- Args:- session_ids (`list[str]`):- Sessions whose runs should be cancelled.- """- if not session_ids:- return- await asyncio.gather(- *(self.cancel_session_run(sid) for sid in session_ids),- )-- async def _purge_bus(self, session_ids: list[str]) -> None:- """Drop bus state (events log + inbox) for each id concurrently.-- Args:- session_ids (`list[str]`):- Sessions whose bus state should be purged.- """- if not session_ids:- return- await asyncio.gather(- *(self._purge_session_bus(sid) for sid in session_ids),- )-async def _purge_session_bus(self, session_id: str) -> None:"""Drop all per-session bus state for one session."""await self._bus.log_trim(diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.pyindex ac381cdbe..9db971ff6 100644--- a/src/agentscope/app/_service/_toolkit.py+++ b/src/agentscope/app/_service/_toolkit.py@@ -268,6 +268,9 @@ time or interval"return Toolkit(tools=tools,skills_or_loaders=await workspace.list_skills(),- mcps=await workspace.list_mcps(),+ mcps=await workspace.list_mcps(+ agent_id=agent_record.id,+ session_id=session_record.id,+ ),tool_groups=tool_groups,)diff --git a/src/agentscope/app/_tool/_team_delete.py b/src/agentscope/app/_tool/_team_delete.pyindex ea34bfe3c..8e957df93 100644--- a/src/agentscope/app/_tool/_team_delete.py+++ b/src/agentscope/app/_tool/_team_delete.py@@ -110,6 +110,7 @@ This is irreversible.session_service = SessionService(storage=self._storage,message_bus=self._message_bus,+ workspace_manager=self._workspace_manager,)await session_service.delete_team(self._user_id, team.id)return ToolChunk(diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.pyindex e87e58656..3f00ed73a 100644--- a/src/agentscope/workspace/_base.py+++ b/src/agentscope/workspace/_base.py@@ -1,4 +1,5 @@# -*- coding: utf-8 -*-+# pylint: disable=too-many-lines"""WorkspaceBase — abstract interface and shared backend-driven impl.A workspace provides:@@ -35,11 +36,17 @@ the workspace's :class:`BackendBase` plus a fixed layout derived from.. code-block:: text{workdir}/- ├── .mcp # persisted MCP client configs (JSON array)+ ├── .mcp # declared MCP configs, per agent and session├── data/ # offloaded multimodal payloads├── skills/ # skill subdirectories└── sessions/ # per-session context and tool-result files+MCPs are declared per agent and session, and instantiated lazily:+nothing connects until that session first calls ``list_mcps``, and+each session gets its own instances so stateful MCP state never leaks+across agents or sessions. ``.mcp`` holds only the declarations, and+only for sessions that diverged from ``default_mcps``.+Subclasses only set ``self.workdir`` (the agent-visible root); allother directory paths are derived via :meth:`BackendBase.join_path`,keeping path semantics consistent with whichever backend is bound.@@ -53,6 +60,7 @@ import jsonimport mimetypesimport osimport tarfile+import timefrom abc import abstractmethodfrom copy import deepcopyfrom pathlib import Path@@ -80,6 +88,12 @@ from ._utils import (DEFAULT_SKILLS_DIR,)+#: Current ``.mcp`` schema version. Version 1 was a bare JSON list of+#: specs with no ids; it is read back under the legacy empty ids.+MCP_FILE_VERSION = 2++_DEFAULT_MAX_LIVE_STATEFUL_MCPS = 40+_EXTRACT_TAR_SHIM = ("import tarfile, sys, os\n""src, dst = sys.argv[1], sys.argv[2]\n"@@ -176,17 +190,25 @@ class WorkspaceBase:skill_paths: list[str]"""Local skill directories to seed on first :meth:`initialize`."""- _mcps: list[MCPClient]- """Currently registered MCP clients (in-memory authoritative copy).+ max_live_stateful_mcps: int+ """Cap on live stateful MCP instances retained for *other*+ agents and sessions. See :meth:`_enforce_mcp_capacity`."""- :class:`LocalWorkspace` stores the local live handles directly;- :class:`SandboxedWorkspaceBase` stores gateway-side- :class:`GatewayMCPClient` wrappers (also ``MCPClient`` instances)- so ``list_mcps`` / persistence work uniformly across both.- """+ _mcp_specs: dict[tuple[str, str], list[MCPClient]]+ """Declared MCP configs keyed by agent id and session id — the+ persisted layer. A missing session inherits :attr:`default_mcps`;+ an empty list means none."""++ _mcp_instances: dict[tuple[str, str], dict[str, MCPClient]]+ """Live handles keyed by agent id and session id, then by MCP+ name — built lazily, never persisted."""++ _mcp_last_used: dict[tuple[str, str], float]+ """Last :meth:`list_mcps` per agent/session, driving LRU eviction.+ Turn-level granularity — tool calls do not reach the workspace."""_mcp_lock: asyncio.Lock- """Guards mutation of :attr:`_mcps` and the ``.mcp`` file."""+ """Guards mutation of the MCP dicts and the ``.mcp`` file."""_skill_lock: asyncio.Lock"""Guards mutation of the ``skills/`` directory."""@@ -208,6 +230,7 @@ class WorkspaceBase:workspace_id: str | None = None,default_mcps: list[MCPClient] | None = None,skill_paths: list[str] | None = None,+ max_live_stateful_mcps: int | None = None,) -> None:"""Initialise the shared workspace state.@@ -222,11 +245,15 @@ class WorkspaceBase:Existing identifier to adopt; ``None`` mints a freshUUID.default_mcps (`list[MCPClient] | None`, optional):- MCP clients to register when the workspace boots- without a persisted ``.mcp`` file.+ MCP clients seeded into any agent/session that has+ never added or removed an MCP of its own.skill_paths (`list[str] | None`, optional):Local skill directories to copy into ``skills/`` onfirst start.+ max_live_stateful_mcps (`int | None`, optional):+ Cap on concurrently live *stateful* MCP instances.+ ``None`` derives ``max(40, 2 * <stateful defaults>)``+ so one session can always start its own seeded set."""self.workspace_id = workspace_id or _generate_id()self.is_alive = False@@ -236,8 +263,14 @@ class WorkspaceBase:self.skill_paths = [_normalize_local_path(path) for path in skill_paths or []]+ self.max_live_stateful_mcps = max_live_stateful_mcps or max(+ _DEFAULT_MAX_LIVE_STATEFUL_MCPS,+ 2 * len([m for m in self.default_mcps if m.is_stateful]),+ )- self._mcps = []+ self._mcp_specs = {}+ self._mcp_instances = {}+ self._mcp_last_used = {}self._mcp_lock = asyncio.Lock()self._skill_lock = asyncio.Lock()@@ -389,45 +422,292 @@ class WorkspaceBase:Write(backend=backend),]- async def list_mcps(self) -> list[MCPClient]:- """Return the currently registered MCP clients."""- return list(self._mcps)+ def _declared_specs(+ self,+ agent_id: str,+ session_id: str,+ ) -> list[MCPClient]:+ """Configs declared for one agent/session, seeded from defaults.++ A session missing from :attr:`_mcp_specs` has never been+ modified and inherits fresh copies of :attr:`default_mcps`; an+ empty list means it explicitly has none.+ """+ declared = self._mcp_specs.get((agent_id, session_id))+ if declared is not None:+ return declared+ return [+ MCPClient.model_validate(m.model_dump(mode="json"))+ for m in self.default_mcps+ ]++ async def list_mcps(+ self,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> list[MCPClient]:+ """Return the MCP clients for one agent/session.++ Instances are built on first use and are private to that+ agent/session, so stateful sessions (browser cookies, login+ state) never leak across agents or sessions. Instances dropped+ by :meth:`_enforce_mcp_capacity` are rebuilt here.++ Subclasses that route through a gateway+ (:class:`SandboxedWorkspaceBase`) override this to hand back+ gateway-wired proxies instead of local clients.++ Args:+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ Keyword-only: both ids are plain strings, so passing+ them positionally could silently hit another session.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``.+ """+ agent_id, session_id = agent_id or "", session_id or ""+ async with self._mcp_lock:+ self._mcp_last_used[(agent_id, session_id)] = time.monotonic()+ live = self._mcp_instances.setdefault((agent_id, session_id), {})+ specs = self._declared_specs(agent_id, session_id)+ for spec in specs:+ if spec.name in live:+ continue+ await self._enforce_mcp_capacity(agent_id, session_id, spec)+ try:+ # Copy rather than share, so two sessions running+ # the same MCP hold independent state.+ client = MCPClient.model_validate(+ spec.model_dump(mode="json"),+ )+ if client.is_stateful:+ await client.connect()+ live[spec.name] = client+ except Exception as e:+ logger.warning(+ "Failed to start MCP %r for agent=%r session=%r: "+ "%s, skipping.",+ spec.name,+ agent_id,+ session_id,+ e,+ )+ # Declaration order: an MCP rebuilt after eviction must+ # not jump to the end.+ return [live[s.name] for s in specs if s.name in live]# ── for User: dynamic MCP management ───────────────────────────@abstractmethod- async def add_mcp(self, mcp_client: MCPClient) -> None:- """Register a new MCP server.+ async def add_mcp(+ self,+ mcp_client: MCPClient,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> None:+ """Register a new MCP server for one agent/session and persist.++ Implementations record the config in :attr:`_mcp_specs`, start+ one live instance under :meth:`_enforce_mcp_capacity`, and call+ :meth:`_save_mcp_file`.Args:mcp_client (`MCPClient`):The MCP to register.+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ Keyword-only: both ids are plain strings, so passing+ them positionally could silently hit another session.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``.Raises:`ValueError`:- If an MCP with the same name already exists.+ If the name already exists for this agent/session."""@abstractmethod- async def remove_mcp(self, name: str) -> None:- """Deregister an MCP server by name.+ async def remove_mcp(+ self,+ name: str,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> None:+ """Deregister an MCP by name within one agent/session.++ Other agents and sessions keep their own declarations and+ instances, so there is nothing to reconcile across them.Args:name (`str`):MCP name to remove. Unknown names log a warning andreturn silently.+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ Keyword-only: both ids are plain strings, so passing+ them positionally could silently hit another session.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``."""+ # ── session teardown ───────────────────────────────────────────++ async def purge_session(+ self,+ *,+ agent_id: str,+ session_id: str,+ ) -> None:+ """Drop everything this workspace holds for one session.++ Closes the session's MCP instances, forgets its ``.mcp``+ declaration and deletes its offload directory. Removing every+ MCP one by one is not equivalent: an emptied session persists+ as ``[]``, which is a meaningful state, and would keep dead+ sessions in ``.mcp`` forever.++ Best-effort — failures are logged, never raised, so a purge+ cannot block session deletion.++ Args:+ agent_id (`str`):+ The agent that owned the session.+ session_id (`str`):+ The session being deleted.+ """+ async with self._mcp_lock:+ dropped = self._mcp_instances.pop((agent_id, session_id), {})+ for instance in list(dropped.values()):+ await self._close_mcp_instance(instance)+ self._mcp_last_used.pop((agent_id, session_id), None)+ forgotten = self._mcp_specs.pop((agent_id, session_id), None)+ if forgotten is not None:+ await self._save_mcp_file()++ if self._backend is None or not session_id:+ return+ try:+ await self._backend.delete_path(+ self._backend.join_path(self._sessions_dir, session_id),+ )+ except Exception as e:+ logger.warning(+ "Failed to delete offload directory for session %r: %s",+ session_id,+ e,+ )++ # ── instance lifecycle ─────────────────────────────────────────++ @staticmethod+ async def _close_mcp_instance(instance: MCPClient) -> None:+ """Close one live handle, downgrading failures to warnings.++ Stateless clients hold no connection, so they are skipped.+ """+ if not (instance.is_stateful and instance.is_connected):+ return+ try:+ await instance.close()+ except Exception as e:+ logger.warning("MCP %r close failed: %s", instance.name, e)++ async def _enforce_mcp_capacity(+ self,+ agent_id: str,+ session_id: str,+ incoming: MCPClient,+ ) -> None:+ """Make room for ``incoming`` under+ :attr:`max_live_stateful_mcps`.++ Only stateful instances count — a stateless client holds no+ connection or subprocess, so capping them reclaims nothing.+ Eviction never targets the requesting agent/session, which+ therefore always gets its full set no matter how the cap is+ configured; when every live instance belongs to it the cap is+ exceeded instead.++ Callers must hold :attr:`_mcp_lock`.+ """+ if not incoming.is_stateful:+ return+ while True:+ live_count = sum(+ 1+ for by_name in self._mcp_instances.values()+ for c in by_name.values()+ if c.is_stateful+ )+ if live_count < self.max_live_stateful_mcps:+ return++ victim_agent, victim_session, oldest = None, None, 0.0+ for (+ other_agent,+ other_session,+ ), by_name in self._mcp_instances.items():+ if other_agent == agent_id and other_session == session_id:+ continue+ if not any(c.is_stateful for c in by_name.values()):+ continue+ used = self._mcp_last_used.get(+ (other_agent, other_session),+ 0.0,+ )+ if victim_agent is None or used < oldest:+ victim_agent = other_agent+ victim_session = other_session+ oldest = used++ if victim_agent is None or victim_session is None:+ logger.warning(+ "All %d live stateful MCPs belong to agent=%r "+ "session=%r; exceeding max_live_stateful_mcps to "+ "start %r.",+ live_count,+ agent_id,+ session_id,+ incoming.name,+ )+ return++ by_name = self._mcp_instances[(victim_agent, victim_session)]+ name = next(n for n, c in by_name.items() if c.is_stateful)+ logger.info(+ "Evicting idle MCP %r (agent=%r session=%r) to stay "+ "under max_live_stateful_mcps=%d.",+ name,+ victim_agent,+ victim_session,+ self.max_live_stateful_mcps,+ )+ await self._close_mcp_instance(by_name.pop(name))++ async def _close_all_mcp_instances(self) -> None:+ """Close every live handle and drop the instance layer.++ Declarations survive — a later :meth:`list_mcps` rebuilds.+ """+ for by_name in self._mcp_instances.values():+ for instance in list(by_name.values()):+ await self._close_mcp_instance(instance)+ self._mcp_instances.clear()+ self._mcp_last_used.clear()+# ── MCP persistence (shared) ───────────────────────────────────async def _save_mcp_file(self) -> None:- """Persist ``self._mcps`` to ``${workdir}/.mcp`` via backend.+ """Persist :attr:`_mcp_specs` to ``${workdir}/.mcp``.- No-op when :attr:`is_persistent` is ``False`` (e.g. ephemeral- Docker container without a host bind-mount). Failures are- logged but not raised — the in-memory MCP list remains the- authoritative copy regardless of whether disk persistence- succeeded.+ Only declarations are written, and only for sessions that+ diverged from :attr:`default_mcps`, so the file does not grow+ with session count on its own. No-op when+ :attr:`is_persistent` is ``False``; failures are logged, not+ raised — the in-memory copy stays authoritative.Callers are expected to hold :attr:`_mcp_lock` already."""@@ -436,8 +716,15 @@ class WorkspaceBase:backend = self._backendif backend is None:return+ # Nested {agent_id: {session_id: [...]}} on disk rather than a+ # joined key, so no separator can collide with an id.+ mcps: dict[str, dict[str, list[dict]]] = {}+ for (agent_id, session_id), specs in self._mcp_specs.items():+ mcps.setdefault(agent_id, {})[session_id] = [+ m.model_dump(mode="json") for m in specs+ ]payload = json.dumps(- [m.model_dump(mode="json") for m in self._mcps],+ {"version": MCP_FILE_VERSION, "mcps": mcps},indent=2,ensure_ascii=False,).encode("utf-8")@@ -450,6 +737,82 @@ class WorkspaceBase:e,)+ async def _restore_mcp_specs(+ self,+ ) -> dict[tuple[str, str], list[MCPClient]]:+ """Read the declarations persisted in ``${workdir}/.mcp``.++ Returns an empty mapping when the file is absent or unusable —+ every agent/session then falls back to :attr:`default_mcps`, so+ a corrupt file cannot block startup. Version 1 files (a bare+ list) are read under the legacy empty ids; the next write emits+ v2.+ """+ if not self.is_persistent:+ return {}+ backend = self._backend+ if backend is None:+ return {}+ try:+ if not await backend.file_exists(self._mcp_file):+ return {}+ raw = await backend.read_file(self._mcp_file)+ data = json.loads(raw.decode("utf-8"))+ except Exception as e:+ logger.warning(+ "Failed to read MCP file at %s, falling back to "+ "default_mcps: %s",+ self._mcp_file,+ e,+ )+ return {}++ def _parse(+ cfgs: list,+ agent_id: str,+ session_id: str,+ ) -> list[MCPClient]:+ """Parse serialised configs, skipping invalid entries."""+ parsed: list[MCPClient] = []+ for m in cfgs:+ try:+ parsed.append(MCPClient.model_validate(m))+ except Exception as e:+ name = m.get("name", "?") if isinstance(m, dict) else "?"+ logger.warning(+ "Skipping invalid MCP entry %r for agent=%r "+ "session=%r: %s",+ name,+ agent_id,+ session_id,+ e,+ )+ return parsed++ if isinstance(data, list):+ logger.info("Migrating .mcp v1 (flat list) to the legacy ids.")+ return {("", ""): _parse(data, "", "")}++ if not isinstance(data, dict):+ logger.warning(+ "%s is neither a list nor an object; ignoring it.",+ self._mcp_file,+ )+ return {}++ specs: dict[tuple[str, str], list[MCPClient]] = {}+ for agent_id, by_session in (data.get("mcps") or {}).items():+ if not isinstance(by_session, dict):+ continue+ for session_id, cfgs in by_session.items():+ if isinstance(cfgs, list):+ specs[(agent_id, session_id)] = _parse(+ cfgs,+ agent_id,+ session_id,+ )+ return specs+# ── for Agent: offload (shared) ────────────────────────────────async def offload_context(diff --git a/src/agentscope/workspace/_bubblewrap/_bubblewrap_workspace.py b/src/agentscope/workspace/_bubblewrap/_bubblewrap_workspace.pyindex 1838f65ce..77c1177d6 100644--- a/src/agentscope/workspace/_bubblewrap/_bubblewrap_workspace.py+++ b/src/agentscope/workspace/_bubblewrap/_bubblewrap_workspace.py@@ -384,7 +384,6 @@ class BubblewrapWorkspace(SandboxedWorkspaceBase):launch_cmd = (f"exec {shlex.quote(self._gateway_python)} -I -u "f"{shlex.quote(self._gateway_script)} "- f"--config {shlex.quote(self._mcp_file)} "f"--port {gateway_port} "f"--auth-token {shlex.quote(self._gateway_token)} "f"--instance-nonce {shlex.quote(self._gateway_nonce)} "@@ -411,8 +410,6 @@ class BubblewrapWorkspace(SandboxedWorkspaceBase):else: # pragma: no cover - loop always breaks or raisesawait self._raise_gateway_timeout(health_timeout)- self._mcps = list(await self._gateway.list_mcps())-async def _bootstrap_is_ready(self) -> bool:"""Check whether persisted user-space bootstrap artifacts work."""result = await self.get_backend().exec_shell(diff --git a/src/agentscope/workspace/_gateway_client.py b/src/agentscope/workspace/_gateway_client.pyindex 95b3d7da8..e2c164cf6 100644--- a/src/agentscope/workspace/_gateway_client.py+++ b/src/agentscope/workspace/_gateway_client.py@@ -28,6 +28,7 @@ import jsonimport secretsimport uuidfrom typing import TYPE_CHECKING, Any+from urllib.parse import urlencodeimport mcp.typesfrom pydantic import PrivateAttr@@ -70,6 +71,8 @@ class GatewayMCPTool(ToolBase):mcp_name: str,tool: mcp.types.Tool,gateway: "GatewayClient",+ agent_id: str = "",+ session_id: str = "",) -> None:"""Build a gateway-backed MCP tool.@@ -88,8 +91,14 @@ class GatewayMCPTool(ToolBase):gateway (`GatewayClient`):Facade dispatching every call through:meth:`GatewayClient.exec_request`.+ agent_id (`str`, defaults to ``""``):+ The agent whose gateway-side session to run against.+ session_id (`str`, defaults to ``""``):+ The session whose gateway-side session to run against."""self.mcp_name = mcp_name+ self._agent_id = agent_id+ self._session_id = session_idself.name = f"mcp__{mcp_name}__{tool.name}"self.description = tool.description or ""@@ -138,6 +147,10 @@ class GatewayMCPTool(ToolBase):status, body = await self._gateway.exec_request("POST",f"/mcps/{self.mcp_name}/tools/{self._tool.name}",+ params={+ "agent_id": self._agent_id,+ "session_id": self._session_id,+ },body={"arguments": kwargs},)if status >= 400:@@ -173,6 +186,8 @@ class GatewayMCPClient(MCPClient):"""_gateway: "GatewayClient | None" = PrivateAttr(default=None)+ _agent_id: str = PrivateAttr(default="")+ _session_id: str = PrivateAttr(default="")def model_post_init(self, __context: Any) -> None:"""No-op — the parent builds local stdio/HTTP transport, which@@ -186,6 +201,8 @@ class GatewayMCPClient(MCPClient):self,gateway: "GatewayClient",*,+ agent_id: str = "",+ session_id: str = "",connected: bool = False,) -> None:"""Wire this client to a gateway facade.@@ -199,12 +216,21 @@ class GatewayMCPClient(MCPClient):gateway (`GatewayClient`):Facade dispatching calls through:meth:`GatewayClient.exec_request`.+ agent_id (`str`, defaults to ``""``):+ The agent this MCP client belongs to.+ session_id (`str`, defaults to ``""``):+ The session this MCP client belongs to. Together with+ ``agent_id`` it is sent on every ``connect`` /+ ``close`` / tool-call request so the gateway keeps one+ upstream session per agent and session.connected (`bool`, defaults to `False`):When ``True``, mark this client as already connected(used by :meth:`GatewayClient.list_mcps` for entriesthe gateway is already serving)."""self._gateway = gateway+ self._agent_id = agent_id+ self._session_id = session_idif connected:self._is_connected = True@@ -229,6 +255,10 @@ class GatewayMCPClient(MCPClient):status, resp_body = await self._gateway.exec_request("POST","/mcps",+ params={+ "agent_id": self._agent_id,+ "session_id": self._session_id,+ },body=body,)if status >= 400:@@ -257,6 +287,10 @@ class GatewayMCPClient(MCPClient):status, resp_body = await self._gateway.exec_request("DELETE",f"/mcps/{self.name}",+ params={+ "agent_id": self._agent_id,+ "session_id": self._session_id,+ },)if status >= 400 and not ignore_errors:raise RuntimeError(@@ -287,6 +321,10 @@ class GatewayMCPClient(MCPClient):status, body = await self._gateway.exec_request("GET",f"/mcps/{self.name}/tools",+ params={+ "agent_id": self._agent_id,+ "session_id": self._session_id,+ },)if status >= 400:raise RuntimeError(@@ -343,6 +381,8 @@ class GatewayMCPClient(MCPClient):mcp_name=self.name,tool=tool,gateway=self._gateway,+ agent_id=self._agent_id,+ session_id=self._session_id,)@@ -459,29 +499,53 @@ class GatewayClient:and secrets.compare_digest(nonce, self.instance_nonce))- async def list_mcps(self) -> list[GatewayMCPClient]:- """Fetch every MCP the gateway is currently serving.+ async def list_mcps(+ self,+ agent_id: str = "",+ session_id: str = "",+ ) -> list[GatewayMCPClient]:+ """Fetch MCPs the gateway is serving for one agent/session.Returned clients are marked already-connected (via:meth:`GatewayMCPClient.attach`) — the gateway is alreadymaintaining their upstream sessions.+ Args:+ agent_id (`str`, defaults to ``""``):+ The agent whose MCP clients to fetch.+ session_id (`str`, defaults to ``""``):+ The session whose MCP clients to fetch.+Raises:`RuntimeError`:Gateway returned non-2xx."""- status, body = await self.exec_request("GET", "/mcps")+ status, body = await self.exec_request(+ "GET",+ "/mcps",+ params={"agent_id": agent_id, "session_id": session_id},+ )if status >= 400:raise RuntimeError(f"gateway failed to list MCPs: {_safe_detail(status, body)}",)specs = json.loads(body)- return [self.make_client(spec, connected=True) for spec in specs]+ return [+ self.make_client(+ spec,+ agent_id=agent_id,+ session_id=session_id,+ connected=True,+ )+ for spec in specs+ ]def make_client(self,spec: dict[str, Any],*,+ agent_id: str = "",+ session_id: str = "",connected: bool = False,) -> GatewayMCPClient:"""Build a :class:`GatewayMCPClient` wired to this gateway.@@ -490,13 +554,22 @@ class GatewayClient:spec (`dict[str, Any]`):``MCPClient.model_dump(mode="json")`` payload — eitherfrom ``GET /mcps`` or from user input via ``add_mcp``.+ agent_id (`str`, defaults to ``""``):+ The agent this MCP client belongs to.+ session_id (`str`, defaults to ``""``):+ The session this MCP client belongs to.connected (`bool`, defaults to `False`):Mark the client as already-connected. Set by:meth:`list_mcps`; leave ``False`` when the caller will``await client.connect()`` itself."""client = GatewayMCPClient.model_validate(spec)- client.attach(self, connected=connected)+ client.attach(+ self,+ agent_id=agent_id,+ session_id=session_id,+ connected=connected,+ )return clientasync def aclose(self) -> None:@@ -512,6 +585,7 @@ class GatewayClient:method: str,path: str,*,+ params: dict[str, str] | None = None,body: Any = None,include_auth: bool = True,) -> tuple[int, bytes]:@@ -538,6 +612,10 @@ class GatewayClient:HTTP verb (``GET`` / ``POST`` / ``DELETE``).path (`str`):Path-only URL, e.g. ``/mcps/<name>/tools/<tool>``.+ params (`dict[str, str] | None`, optional):+ Query parameters, URL-encoded onto ``path``. Ids can+ contain arbitrary characters, so callers must pass+ them here rather than formatting them into ``path``.body (`Any`, optional):JSON-serializable request body; ``None`` for no body.include_auth (`bool`, defaults to `True`):@@ -554,6 +632,7 @@ class GatewayClient:Shim crash (non-zero exit / non-JSON stdout) ortransport failure (``status == -1``)."""+ path = f"{path}?{urlencode(params)}" if params else pathbody_file = ""wrote_body_file: str | None = Noneif body is not None:diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.pyindex f98d7e9f5..82c10ee27 100644--- a/src/agentscope/workspace/_local_workspace.py+++ b/src/agentscope/workspace/_local_workspace.py@@ -67,7 +67,7 @@ class LocalWorkspace(WorkspaceBase):Layout::{workdir}/- ├── .mcp # persisted MCP client configs (JSON array)+ ├── .mcp # declared MCP configs per agent/session├── data/ # offloaded multimodal files├── skills/ # skill subdirectories└── sessions/ # per-session context and tool-result files@@ -81,6 +81,7 @@ class LocalWorkspace(WorkspaceBase):default_mcps: list[MCPClient] | None = None,skill_paths: list[str] | None = None,instructions: str = DEFAULT_WORKSPACE_INSTRUCTIONS,+ max_live_stateful_mcps: int | None = None,) -> None:"""Construct a :class:`LocalWorkspace`.@@ -92,19 +93,26 @@ class LocalWorkspace(WorkspaceBase):Existing workspace identifier to adopt. ``None``generates a fresh UUID.default_mcps (`list[MCPClient] | None`, optional):- MCP clients seeded into a brand-new workspace.- Ignored on subsequent restarts that already have a- persisted ``<workdir>/.mcp`` file.+ MCP clients seeded into every agent/session that has+ not added or removed one of its own.skill_paths (`list[str] | None`, optional):Local skill directories seeded into``<workdir>/skills`` on first :meth:`initialize`.instructions (`str`, defaults to \- `_DEFAULT_WORKSPACE_INSTRUCTIONS`):+ `DEFAULT_WORKSPACE_INSTRUCTIONS`):System-prompt fragment template returned by:meth:`get_instructions`. Supports the ``{workdir}``placeholder.+ max_live_stateful_mcps (`int | None`, optional):+ Cap on concurrently live stateful MCP instances+ across all agents and sessions."""- super().__init__(workspace_id=workspace_id)+ super().__init__(+ workspace_id=workspace_id,+ default_mcps=default_mcps,+ skill_paths=skill_paths,+ max_live_stateful_mcps=max_live_stateful_mcps,+ )# ── serializable config ─────────────────────────────────self.workdir = os.path.abspath(workdir)@@ -113,15 +121,8 @@ class LocalWorkspace(WorkspaceBase):workdir=self.workdir,)- # ── seed-only ───────────────────────────────────────────- self.default_mcps: list[MCPClient] = list(default_mcps or [])- self.skill_paths: list[str] = [- _normalize_local_path(path) for path in skill_paths or []- ]-# ── runtime state ───────────────────────────────────────self._backend = LocalBackend()- self._mcps: list[MCPClient] = []self._skill_lock = asyncio.Lock()self._mcp_lock = asyncio.Lock()@@ -152,9 +153,10 @@ class LocalWorkspace(WorkspaceBase):async def initialize(self) -> None:"""Initialise the workspace.- MCP state is restored from ``.mcp`` if it exists; otherwise- ``default_mcps`` are used and persisted so the next start picks- them up from disk. ``skill_paths`` are seeded on first use.+ MCP *declarations* are restored from ``.mcp``; sessions absent+ from it fall back to ``default_mcps``. Nothing is connected+ here — clients are built on the first ``list_mcps`` for a given+ agent/session. ``skill_paths`` are seeded on first use.Idempotent: a no-op when the workspace is already alive."""@@ -163,38 +165,7 @@ class LocalWorkspace(WorkspaceBase):os.makedirs(self.workdir, exist_ok=True)- # Restore or seed MCPs- mcp_file = os.path.join(self.workdir, ".mcp")- if await self._backend.file_exists(mcp_file):- raw = await self._backend.read_file(mcp_file)- raw_list = json.loads(raw.decode("utf-8"))- for m in raw_list:- try:- self._mcps.append(MCPClient.model_validate(m))- except Exception as e:- logger.warning(- "Skipping invalid MCP entry '%s': %s",- m.get("name", "?"),- e,- )- else:- self._mcps = list(self.default_mcps)- await self._save_mcp_file()-- failed: list[MCPClient] = []- for mcp in self._mcps:- if mcp.is_stateful and not mcp.is_connected:- try:- await mcp.connect()- except Exception as e:- logger.warning(- "Failed to connect stateful MCP '%s': %s, removing.",- mcp.name,- e,- )- failed.append(mcp)- for mcp in failed:- self._mcps.remove(mcp)+ self._mcp_specs = await self._restore_mcp_specs()# Seed skillsskills_dir = os.path.join(self.workdir, "skills")@@ -434,41 +405,21 @@ class LocalWorkspace(WorkspaceBase):spin up an ad-hoc session per call and have nothing to close."""async with self._mcp_lock:- for mcp in self._mcps:- if mcp.is_stateful and mcp.is_connected:- try:- await mcp.close()- except Exception as e:- logger.warning(- (- "Failed to close MCP %r "- "when closing local workspace: %s"- ),- mcp.name,- e,- )+ await self._close_all_mcp_instances()self.is_alive = Falseasync def reset(self) -> None:- """Return the workspace to an empty state.+ """Return the workspace to a factory state.Closes and drops all MCPs (including the persisted ``.mcp``)and deletes ``skills/``, ``sessions/``, and ``data/``.- ``default_mcps`` and ``skill_paths`` are not re-seeded.+ ``skill_paths`` are not re-seeded, but ``default_mcps`` are:+ with ``.mcp`` gone, every agent/session is "never configured"+ again and inherits the defaults on its next ``list_mcps``."""async with self._mcp_lock:- for mcp in self._mcps:- if mcp.is_stateful and mcp.is_connected:- try:- await mcp.close()- except Exception as e:- logger.warning(- "MCP %r close failed during reset: %s",- mcp.name,- e,- )- self._mcps = []-+ await self._close_all_mcp_instances()+ self._mcp_specs.clear()mcp_file = os.path.join(self.workdir, ".mcp")await self._backend.delete_path(mcp_file)@@ -684,45 +635,88 @@ class LocalWorkspace(WorkspaceBase):)return None- async def add_mcp(self, mcp_client: MCPClient) -> None:- """Add an MCP client, connect it if stateful, and persist.+ async def add_mcp(+ self,+ mcp_client: MCPClient,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> None:+ """Add an MCP client for one agent/session and persist it.Args:mcp_client (`MCPClient`):The MCP client to add.+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``.Raises:- ValueError:- If an MCP with the same name already exists. Names are- unique because they compose the model-facing tool name- ``mcp__{name}__{tool}``.+ `ValueError`:+ If the name already exists for this agent/session.+ Names are unique because they compose the model-facing+ tool name ``mcp__{name}__{tool}``."""+ agent_id, session_id = agent_id or "", session_id or ""async with self._mcp_lock:- if any(m.name == mcp_client.name for m in self._mcps):+ specs = self._declared_specs(agent_id, session_id)+ if any(m.name == mcp_client.name for m in specs):raise ValueError(- f"MCP {mcp_client.name!r} already exists in workspace.",+ f"MCP {mcp_client.name!r} already exists for "+ f"agent={agent_id!r} session={session_id!r}.",)+ live = self._mcp_instances.setdefault(+ (agent_id, session_id),+ {},+ )+ await self._enforce_mcp_capacity(agent_id, session_id, mcp_client)if mcp_client.is_stateful and not mcp_client.is_connected:await mcp_client.connect()- self._mcps.append(mcp_client)+ live[mcp_client.name] = mcp_client+ # Materialise the full list on first divergence so the+ # persisted copy is self-contained.+ self._mcp_specs[(agent_id, session_id)] = [*specs, mcp_client]await self._save_mcp_file()- async def remove_mcp(self, name: str) -> None:+ async def remove_mcp(+ self,+ name: str,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> None:"""Remove an MCP client by name, disconnecting it if stateful.Args:name (`str`):The ``name`` field of the client to remove.+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``."""+ agent_id, session_id = agent_id or "", session_id or ""async with self._mcp_lock:- for i, mcp in enumerate(self._mcps):- if mcp.name == name:- if mcp.is_stateful and mcp.is_connected:- await mcp.close()- self._mcps.pop(i)- await self._save_mcp_file()- return- logger.warning("MCP client %r not found in workspace", name)+ specs = self._declared_specs(agent_id, session_id)+ if not any(m.name == name for m in specs):+ logger.warning(+ "MCP client %r not found for agent=%r session=%r",+ name,+ agent_id,+ session_id,+ )+ return+ instance = self._mcp_instances.get(+ (agent_id, session_id),+ {},+ ).pop(name, None)+ if instance is not None:+ await self._close_mcp_instance(instance)+ self._mcp_specs[(agent_id, session_id)] = [+ m for m in specs if m.name != name+ ]+ await self._save_mcp_file()async def add_skill(self, skill_path: str) -> None:"""Add a skill to the workspace by copying from the given path.diff --git a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.pyindex 47d503fcf..d4b4da7b1 100644--- a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py+++ b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py@@ -1,21 +1,27 @@# -*- coding: utf-8 -*-"""In-workspace MCP gateway — FastAPI router over agentscope MCPClients.-Runs inside the workspace environment as a standalone script. Reads-``--config`` — a JSON list of ``MCPClient.model_dump()`` dicts (same-format as the workspace's ``.mcp`` file) — instantiates one client per-entry, and exposes per-server HTTP endpoints. Authentication is optional.-Sandboxes sharing a host network namespace can enable a bearer token to+Runs inside the workspace environment as a standalone script. It starts+with an empty registry and never reads the workspace's ``.mcp`` file:+the workspace is the authority on which MCPs exist, and registers them+here on demand. Boot cost is therefore independent of how many agents+or sessions the workspace has accumulated. Authentication is optional —+sandboxes sharing a host network namespace can enable a bearer token toprevent cross-workspace gateway access.Endpoints::GET /health- GET /mcps # [MCPClient.model_dump(), ...]- POST /mcps # body: MCPClient.model_dump()+ GET /mcps # [MCPClient.model_dump(), ...]+ POST /mcps # body: MCPClient.model_dump()DELETE /mcps/{name}GET /mcps/{name}/tools- POST /mcps/{name}/tools/{tool} # body: {arguments: {...}}+ POST /mcps/{name}/tools/{tool} # body: {arguments: {...}}++Every endpoint except ``/health`` takes ``?agent_id=&session_id=``.+Upstream sessions are kept per agent, session and MCP name, so two+sessions running the same MCP get independent state (browser cookies,+login state) and one closing its client never disturbs the other.The absolute import for ``agentscope.mcp`` avoids loading``agentscope.workspace.__init__`` (which pulls in skill/tool trees the@@ -24,7 +30,6 @@ gateway does not need).import argparseimport asyncio-import jsonimport secretsfrom typing import Any@@ -38,7 +43,7 @@ class _State:"""Mutable runtime state shared by FastAPI routes."""def __init__(self) -> None:- self.clients: dict[str, MCPClient] = {}+ self.clients: dict[tuple[str, str], dict[str, MCPClient]] = {}self.lock = asyncio.Lock()@@ -61,6 +66,17 @@ def _build_app("""Build the FastAPI app with all routes wired against ``state``."""app = FastAPI(title="agentscope-workspace-mcp-gateway")+ def _lookup(agent_id: str, session_id: str, name: str) -> MCPClient:+ """Resolve one registered client or raise 404."""+ client = state.clients.get((agent_id, session_id), {}).get(name)+ if client is None:+ raise HTTPException(+ 404,+ f"{name!r} not found for agent={agent_id!r} "+ f"session={session_id!r}",+ )+ return client+if auth_token:@app.middleware("http")@@ -88,42 +104,63 @@ def _build_app(return PlainTextResponse("ok")@app.get("/mcps")- async def _list_mcps() -> list[dict[str, Any]]:- return [c.model_dump(mode="json") for c in state.clients.values()]+ async def _list_mcps(+ agent_id: str = "",+ session_id: str = "",+ ) -> list[dict[str, Any]]:+ return [+ c.model_dump(mode="json")+ for c in state.clients.get((agent_id, session_id), {}).values()+ ]@app.post("/mcps")- async def _add_mcp(request: Request) -> dict[str, Any]:+ async def _add_mcp(+ request: Request,+ agent_id: str = "",+ session_id: str = "",+ ) -> dict[str, Any]:body = await request.json()name = body.get("name", "")if not name:raise HTTPException(400, "name required")async with state.lock:- if name in state.clients:- raise HTTPException(409, f"{name!r} already exists")+ by_name = state.clients.setdefault((agent_id, session_id), {})+ if name in by_name:+ raise HTTPException(+ 409,+ f"{name!r} already exists for agent={agent_id!r} "+ f"session={session_id!r}",+ )try:- client = await _build_client(body)+ by_name[name] = await _build_client(body)except HTTPException:raiseexcept Exception as e: # noqa: BLE001raise HTTPException(500, f"connect failed: {e}") from e- state.clients[name] = clientreturn {"ok": True}@app.delete("/mcps/{name}")- async def _remove_mcp(name: str) -> dict[str, Any]:+ async def _remove_mcp(+ name: str,+ agent_id: str = "",+ session_id: str = "",+ ) -> dict[str, Any]:async with state.lock:- client = state.clients.pop(name, None)- if client is None:- raise HTTPException(404, f"{name!r} not found")+ client = _lookup(agent_id, session_id, name)+ del state.clients[(agent_id, session_id)][name]+ if not state.clients[(agent_id, session_id)]:+ del state.clients[(agent_id, session_id)]if client.is_stateful and client.is_connected:await client.close()return {"ok": True}@app.get("/mcps/{name}/tools")- async def _list_tools(name: str) -> list[dict[str, Any]]:- client = state.clients.get(name)- if client is None:- raise HTTPException(404, f"{name!r} not found")+ async def _list_tools(+ name: str,+ agent_id: str = "",+ session_id: str = "",+ ) -> list[dict[str, Any]]:+ client = _lookup(agent_id, session_id, name)raw = await client.list_raw_tools()return [t.model_dump(mode="json") for t in raw]@@ -132,10 +169,10 @@ def _build_app(name: str,tool: str,request: Request,+ agent_id: str = "",+ session_id: str = "",) -> dict[str, Any]:- client = state.clients.get(name)- if client is None:- raise HTTPException(404, f"{name!r} not found")+ client = _lookup(agent_id, session_id, name)body = await request.json()arguments = body.get("arguments") or {}try:@@ -150,50 +187,19 @@ def _build_app(return app-async def _connect_initial(- state: _State,- server_cfgs: list[dict[str, Any]],-) -> None:- """Connect every server listed in the config file."""- for cfg in server_cfgs:- client = await _build_client(cfg)- if client.name in state.clients:- if client.is_stateful and client.is_connected:- await client.close()- raise ValueError(- f"Duplicated server name in config: {client.name!r}",- )- state.clients[client.name] = client- print(f"[gateway] connected {client.name!r}", flush=True)--async def _run(- config_path: str,port: int,auth_token: str | None = None,instance_nonce: str | None = None,) -> None:- """Read config, connect upstreams, start uvicorn, clean up on exit."""- with open(config_path, encoding="utf-8") as f:- servers = json.load(f)- if not isinstance(servers, list):- raise ValueError(- f"config file must be a JSON list of MCPClient specs, "- f"got {type(servers).__name__}",- )-+ """Start uvicorn on an empty registry, clean up upstreams on exit."""state = _State()- await _connect_initial(state, servers)-app = _build_app(state,auth_token=auth_token,instance_nonce=instance_nonce,)- print(- f"[gateway] serving {len(state.clients)} MCPs on :{port}",- flush=True,- )+ print(f"[gateway] serving on :{port}", flush=True)import uvicorn@@ -207,9 +213,10 @@ async def _run(try:await server.serve()finally:- for client in list(state.clients.values()):- if client.is_stateful and client.is_connected:- await client.close()+ for by_name in state.clients.values():+ for client in by_name.values():+ if client.is_stateful and client.is_connected:+ await client.close()def main() -> None:@@ -217,14 +224,15 @@ def main() -> None:parser = argparse.ArgumentParser(description="In-workspace MCP gateway (FastAPI)",)- parser.add_argument("--config", required=True)+ # Accepted and ignored — kept so an image shipping an older+ # launch command still starts.+ parser.add_argument("--config", default=None)parser.add_argument("--port", type=int, default=5600)parser.add_argument("--auth-token")parser.add_argument("--instance-nonce")args = parser.parse_args()asyncio.run(_run(- args.config,args.port,auth_token=args.auth_token,instance_nonce=args.instance_nonce,diff --git a/src/agentscope/workspace/_sandboxed_base.py b/src/agentscope/workspace/_sandboxed_base.pyindex d89a47a01..230b0241d 100644--- a/src/agentscope/workspace/_sandboxed_base.py+++ b/src/agentscope/workspace/_sandboxed_base.py@@ -17,8 +17,8 @@ add/remove routing, ``.mcp`` persistence, reset — lives here."""import asyncio-import jsonimport shlex+import timefrom abc import abstractmethodfrom .._logging import logger@@ -64,9 +64,6 @@ class SandboxedWorkspaceBase(WorkspaceBase):is_alive: bool"""Inherited lifecycle flag, repeated for file-scoped type checks."""- _mcps: list[MCPClient]- """Inherited MCP handle list, repeated for file-scoped type checks."""-_bootstrap_cmd_timeout: float = 1800.0"""Per-command timeout applied to every :meth:`_setup_mcp_gateway`bootstrap step. Subclasses lower this for lighter base images@@ -120,6 +117,7 @@ class SandboxedWorkspaceBase(WorkspaceBase):workspace_id: str | None = None,default_mcps: list[MCPClient] | None = None,skill_paths: list[str] | None = None,+ max_live_stateful_mcps: int | None = None,) -> None:"""Initialise sandbox-workspace state.@@ -127,14 +125,19 @@ class SandboxedWorkspaceBase(WorkspaceBase):workspace_id (`str | None`, optional):Existing identifier; ``None`` mints a fresh UUID.default_mcps (`list[MCPClient] | None`, optional):- MCPs registered when no persisted ``.mcp`` exists.+ MCPs seeded into every agent/session that has not+ declared its own.skill_paths (`list[str] | None`, optional):Local skill dirs seeded on first start.+ max_live_stateful_mcps (`int | None`, optional):+ Cap on concurrently live stateful MCP instances+ across all agents and sessions."""super().__init__(workspace_id=workspace_id,default_mcps=default_mcps,skill_paths=skill_paths,+ max_live_stateful_mcps=max_live_stateful_mcps,)self._gateway = None@@ -188,10 +191,14 @@ class SandboxedWorkspaceBase(WorkspaceBase):self._backend is not None), "_provision_backend must set self._backend before returning"+ # Restore MCP declarations from .mcp+ self._mcp_specs = await self._restore_mcp_specs()+# Set up the workspace layoutawait self._ensure_workspace_layout()- # Set up the MCP gateway server+ # The gateway starts empty; each session registers its own+ # MCPs on its first list_mcps.await self._setup_mcp_gateway()# Set up the skills if not exists@@ -217,6 +224,10 @@ class SandboxedWorkspaceBase(WorkspaceBase):except Exception:passself._gateway = None+ # The gateway process dies with the sandbox, so the proxies+ # need no individual close — just drop them.+ self._mcp_instances.clear()+ self._mcp_last_used.clear()try:await self._teardown_backend()@@ -229,71 +240,144 @@ class SandboxedWorkspaceBase(WorkspaceBase):Deregisters every MCP from the gateway, clears local handles,and wipes ``.mcp``, ``skills/``, ``sessions/``, and ``data/``.- ``default_mcps`` / ``skill_paths`` are not re-seeded.+ ``skill_paths`` are not re-seeded, but ``default_mcps`` are:+ with ``.mcp`` gone, every agent/session is "never configured"+ again and inherits the defaults on its next ``list_mcps``."""backend = self.get_backend()async with self._mcp_lock, self._skill_lock:- for mcp in list(self._mcps):- try:- await mcp.close()- except Exception as e:- logger.warning(- "MCP %r close failed during reset: %s",- mcp.name,- e,- )- self._mcps = []+ await self._close_all_mcp_instances()+ self._mcp_specs.clear()for path in (self._sessions_dir,self._data_dir,self._skills_dir,+ self._mcp_file,):await backend.delete_path(path)- # Empty out .mcp so a restart won't fall back to default_mcps.- await self._save_mcp_file()-# ── MCP management (gateway-routed) ───────────────────────────- async def list_mcps(self) -> list[MCPClient]:- """Gateway-wrapped MCP handles, one per registered MCP."""- return list(self._mcps)+ async def list_mcps(+ self,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> list[MCPClient]:+ """Gateway-wrapped MCP handles for one agent/session.++ Same contract as :meth:`WorkspaceBase.list_mcps`, but every+ handle is a :class:`GatewayMCPClient` proxy tagged with the two+ ids, so the gateway keeps one upstream session per agent,+ session and MCP name.- async def add_mcp(self, mcp_client: MCPClient) -> None:+ Args:+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``.+ """+ if self._gateway is None:+ return []+ agent_id, session_id = agent_id or "", session_id or ""+ async with self._mcp_lock:+ self._mcp_last_used[(agent_id, session_id)] = time.monotonic()+ live = self._mcp_instances.setdefault((agent_id, session_id), {})+ specs = self._declared_specs(agent_id, session_id)+ for spec in specs:+ if spec.name in live:+ continue+ await self._enforce_mcp_capacity(agent_id, session_id, spec)+ try:+ client = self._gateway.make_client(+ spec.model_dump(mode="json"),+ agent_id=agent_id,+ session_id=session_id,+ )+ await client.connect()+ live[spec.name] = client+ except Exception as e:+ logger.warning(+ "Failed to start MCP %r for agent=%r session=%r: "+ "%s, skipping.",+ spec.name,+ agent_id,+ session_id,+ e,+ )+ # Declaration order: an MCP rebuilt after eviction must+ # not jump to the end.+ return [live[s.name] for s in specs if s.name in live]++ async def add_mcp(+ self,+ mcp_client: MCPClient,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> None:"""Register a new MCP server through the in-sandbox gateway.Args:mcp_client (`MCPClient`):The MCP to register.+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``.Raises:`ValueError`:- If an MCP with the same name already exists.+ If the name already exists for this agent/session.`RuntimeError`:If the gateway is not attached or rejects theregistration."""if self._gateway is None:raise RuntimeError("Workspace has no MCP gateway attached.")+ agent_id, session_id = agent_id or "", session_id or ""async with self._mcp_lock:- if any(m.name == mcp_client.name for m in self._mcps):+ specs = self._declared_specs(agent_id, session_id)+ if any(m.name == mcp_client.name for m in specs):raise ValueError(- f"MCP {mcp_client.name!r} already exists in workspace.",+ f"MCP {mcp_client.name!r} already exists for "+ f"agent={agent_id!r} session={session_id!r}.",)- spec = mcp_client.model_dump(mode="json")- gw_client = self._gateway.make_client(spec)- await gw_client.connect()- self._mcps.append(gw_client)+ live = self._mcp_instances.setdefault(+ (agent_id, session_id),+ {},+ )+ await self._enforce_mcp_capacity(agent_id, session_id, mcp_client)+ client = self._gateway.make_client(+ mcp_client.model_dump(mode="json"),+ agent_id=agent_id,+ session_id=session_id,+ )+ await client.connect()+ live[client.name] = client+ # Materialise the full list on first divergence so the+ # persisted copy is self-contained.+ self._mcp_specs[(agent_id, session_id)] = [*specs, mcp_client]await self._save_mcp_file()- async def remove_mcp(self, name: str) -> None:- """Deregister an MCP server by name.+ async def remove_mcp(+ self,+ name: str,+ *,+ agent_id: str | None = None,+ session_id: str | None = None,+ ) -> None:+ """Deregister an MCP by name, closing it on the gateway.Args:name (`str`):MCP name to remove. Unknown names log a warning andreturn silently.+ agent_id (`str | None`, optional):+ The owning agent. ``None`` means the legacy ``""``.+ session_id (`str | None`, optional):+ The owning session. ``None`` means the legacy ``""``.Raises:`RuntimeError`:@@ -301,17 +385,27 @@ class SandboxedWorkspaceBase(WorkspaceBase):"""if self._gateway is None:raise RuntimeError("Workspace has no MCP gateway attached.")+ agent_id, session_id = agent_id or "", session_id or ""async with self._mcp_lock:- for i, mcp in enumerate(self._mcps):- if mcp.name == name:- self._mcps.pop(i)- try:- await mcp.close()- except Exception as e:- logger.warning("MCP %r close failed: %s", name, e)- await self._save_mcp_file()- return- logger.warning("MCP %r not found in workspace", name)+ specs = self._declared_specs(agent_id, session_id)+ if not any(m.name == name for m in specs):+ logger.warning(+ "MCP %r not found for agent=%r session=%r",+ name,+ agent_id,+ session_id,+ )+ return+ instance = self._mcp_instances.get(+ (agent_id, session_id),+ {},+ ).pop(name, None)+ if instance is not None:+ await self._close_mcp_instance(instance)+ self._mcp_specs[(agent_id, session_id)] = [+ m for m in specs if m.name != name+ ]+ await self._save_mcp_file()# ── workspace layout helpers ──────────────────────────────────@@ -331,40 +425,8 @@ class SandboxedWorkspaceBase(WorkspaceBase):cwd="/",)- # Seed ``.mcp`` on first use. If a persisted file already- # exists we validate it: a partial/corrupted write (crash mid- # ``_save_mcp_file``) would otherwise brick the gateway on the- # next startup because it expects a JSON list. When the- # payload is unusable we log and reseed the defaults instead- # of failing initialization.- payload = json.dumps(- [m.model_dump(mode="json") for m in self.default_mcps],- indent=2,- ensure_ascii=False,- ).encode("utf-8")-- if await backend.file_exists(self._mcp_file):- try:- existing = await backend.read_file(self._mcp_file)- parsed = json.loads(existing.decode("utf-8"))- except (UnicodeDecodeError, json.JSONDecodeError) as e:- logger.warning(- "%s: %s is corrupted (%s); reseeding defaults",- type(self).__name__,- self._mcp_file,- e,- )- else:- if isinstance(parsed, list):- return- logger.warning(- "%s: %s does not contain a JSON list "- "(got %s); reseeding defaults",- type(self).__name__,- self._mcp_file,- type(parsed).__name__,- )- await backend.write_file(self._mcp_file, payload)+ # ``.mcp`` is not seeded: an absent file means no session+ # has diverged from default_mcps yet.# ── gateway lifecycle helpers ─────────────────────────────────@@ -425,12 +487,11 @@ class SandboxedWorkspaceBase(WorkspaceBase):["sh", "-c", "pkill -f '[_]mcp_gateway_app.py' || true"],)- # Launch. The gateway reads ``.mcp`` directly — no separate- # config file.+ # Launch. The gateway starts with an empty registry — it never+ # reads ``.mcp``; every MCP is registered through it on demand.launch_cmd = (f"nohup {shlex.quote(self._gateway_python)} -u "f"{shlex.quote(self._gateway_script)} "- f"--config {shlex.quote(self._mcp_file)} "f"--port {self.gateway_port} "f"> {shlex.quote(self._gateway_log)} 2>&1 &")@@ -462,7 +523,4 @@ class SandboxedWorkspaceBase(WorkspaceBase):f"Tail of {self._gateway_log}:\n{tail}",)- # Replace the seed specs with the gateway-side wrappers — same- # set, name-for-name — so subsequent list_mcps / add / remove- # operate on the live proxies.- self._mcps = list(await self._gateway.list_mcps())+ # Nothing is registered here — sessions register on demand.diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.pyindex 87e07c5fb..1c38381a9 100644--- a/tests/service_toolkit_test.py+++ b/tests/service_toolkit_test.py@@ -61,7 +61,11 @@ class _FakeWorkspace:"""Return the configured workspace skills."""return list(self._skills)- async def list_mcps(self) -> list:+ async def list_mcps(+ self,+ agent_id: str, # pylint: disable=unused-argument+ session_id: str, # pylint: disable=unused-argument+ ) -> list:"""Return the configured workspace MCP descriptors."""return list(self._mcps)diff --git a/tests/test_e2e_api.py b/tests/test_e2e_api.pynew file mode 100644index 000000000..85f42bf9b--- /dev/null+++ b/tests/test_e2e_api.py@@ -0,0 +1,320 @@+# -*- coding: utf-8 -*-+"""E2E test: per-scope MCP isolation via HTTP API (pytest).++Requires: Redis running on localhost:6379+"""+# pylint: disable=redefined-outer-name+import asyncio+import tempfile+import os+import threading++import httpx+import pytest+import redis.asyncio as aioredis+import uvicorn++from agentscope.app import create_app+from agentscope.app.message_bus import RedisMessageBus+from agentscope.app.storage import RedisStorage+from agentscope.app.workspace_manager import LocalWorkspaceManager+from agentscope.mcp import MCPClient, HttpMCPConfig++WORKDIR = os.path.join(tempfile.mkdtemp(), "workspaces")+HEADERS = {"X-User-ID": "test-user"}+PORT = 8765++_app = create_app(+ storage=RedisStorage(host="localhost", port=6379),+ message_bus=RedisMessageBus(host="localhost", port=6379),+ workspace_manager=LocalWorkspaceManager(+ basedir=WORKDIR,+ default_mcps=[+ MCPClient(+ name="default-search",+ is_stateful=False,+ mcp_config=HttpMCPConfig(url="http://127.0.0.1:1/mcp"),+ ),+ ],+ ),+)+_server = None+_thread = None+++async def _check_redis() -> bool:+ """Check if Redis is reachable at localhost:6379."""+ redis_client = aioredis.Redis(host="localhost", port=6379)+ try:+ await redis_client.ping()+ return True+ except Exception:+ return False+ finally:+ await redis_client.aclose()+++def _setup_module() -> None:+ """Start uvicorn in background thread."""+ if not asyncio.run(_check_redis()):+ pytest.skip(+ "Redis not available on localhost:6379",+ allow_module_level=True,+ )++ global _server, _thread+ config = uvicorn.Config(+ _app,+ host="127.0.0.1",+ port=PORT,+ log_level="warning",+ )+ _server = uvicorn.Server(config)++ def _run() -> None:+ asyncio.run(_server.serve())++ _thread = threading.Thread(target=_run, daemon=True)+ _thread.start()++ # Wait for readiness+ async def _wait() -> None:+ async with httpx.AsyncClient(timeout=5.0) as c:+ for _ in range(50):+ try:+ r = await c.get(+ f"http://127.0.0.1:{PORT}/openapi.json",+ )+ if r.status_code == 200:+ return+ except Exception:+ pass+ await asyncio.sleep(0.1)+ raise RuntimeError("Server did not start")++ asyncio.run(_wait())+++def _teardown_module() -> None:+ """Stop uvicorn."""+ if _server is not None:+ _server.should_exit = True+++_setup_module()+++def client() -> httpx.AsyncClient:+ """httpx client for each test."""++ async def _get() -> httpx.AsyncClient:+ return httpx.AsyncClient(+ base_url=f"http://127.0.0.1:{PORT}",+ headers=HEADERS,+ timeout=30.0,+ )++ return asyncio.run(_get())+++class TestPerAgentMCPAPI:+ """Per-agent MCP isolation via full HTTP API stack."""++ async def _create_agent(+ self,+ client: httpx.AsyncClient,+ name: str,+ ) -> str:+ resp = await client.post(+ "/agent/",+ json={"name": name, "system_prompt": "You are helpful."},+ )+ assert resp.status_code == 201, resp.text+ return resp.json()["agent_id"]++ async def _create_session(+ self,+ client: httpx.AsyncClient,+ agent_id: str,+ ) -> str:+ resp = await client.post(+ "/sessions/",+ json={"agent_id": agent_id},+ )+ assert resp.status_code == 201, resp.text+ return resp.json()["session_id"]++ async def _list_mcps(+ self,+ client: httpx.AsyncClient,+ agent_id: str,+ session_id: str,+ ) -> list[str]:+ resp = await client.get(+ "/workspace/mcp",+ params={"agent_id": agent_id, "session_id": session_id},+ )+ assert resp.status_code == 200, resp.text+ return [m["name"] for m in resp.json()]++ @pytest.mark.asyncio+ async def test_both_agents_get_default_search(+ self,+ client: httpx.AsyncClient,+ ) -> None:+ """Each scope is seeded from ``default_mcps`` on first list."""+ leader = await self._create_agent(client, "Leader")+ worker = await self._create_agent(client, "Worker")+ lsid = await self._create_session(client, leader)+ wsid = await self._create_session(client, worker)++ l_names = await self._list_mcps(client, leader, lsid)+ assert "default-search" in l_names+ w_names = await self._list_mcps(client, worker, wsid)+ assert "default-search" in w_names++ # cleanup+ await client.delete(f"/sessions/{lsid}")+ await client.delete(f"/sessions/{wsid}")+ await client.delete(f"/agent/{leader}")+ await client.delete(f"/agent/{worker}")++ @pytest.mark.asyncio+ async def test_add_mcp_per_agent_isolation(+ self,+ client: httpx.AsyncClient,+ ) -> None:+ """Leader adds an MCP; the worker does NOT see it."""+ leader = await self._create_agent(client, "LeaderAdd")+ worker = await self._create_agent(client, "WorkerAdd")+ lsid = await self._create_session(client, leader)+ wsid = await self._create_session(client, worker)++ resp = await client.post(+ "/workspace/mcp",+ json=MCPClient(+ name="leader-extra",+ is_stateful=False,+ mcp_config=HttpMCPConfig(url="http://127.0.0.1:1/mcp"),+ ).model_dump(),+ params={"agent_id": leader, "session_id": lsid},+ )+ assert resp.status_code == 201++ l_names = await self._list_mcps(client, leader, lsid)+ assert "leader-extra" in l_names+ w_names = await self._list_mcps(client, worker, wsid)+ assert "leader-extra" not in w_names++ await client.delete(f"/sessions/{lsid}")+ await client.delete(f"/sessions/{wsid}")+ await client.delete(f"/agent/{leader}")+ await client.delete(f"/agent/{worker}")++ @pytest.mark.asyncio+ async def test_duplicate_mcp_returns_409(+ self,+ client: httpx.AsyncClient,+ ) -> None:+ """The same name within one scope returns 409."""+ leader = await self._create_agent(client, "LeaderDup")+ lsid = await self._create_session(client, leader)++ mcp = MCPClient(+ name="dup-me",+ is_stateful=False,+ mcp_config=HttpMCPConfig(url="http://127.0.0.1:1/mcp"),+ )+ resp = await client.post(+ "/workspace/mcp",+ json=mcp.model_dump(),+ params={"agent_id": leader, "session_id": lsid},+ )+ assert resp.status_code == 201++ resp = await client.post(+ "/workspace/mcp",+ json=mcp.model_dump(),+ params={"agent_id": leader, "session_id": lsid},+ )+ assert resp.status_code == 409+ assert "already exists" in resp.json()["detail"].lower()++ await client.delete(f"/sessions/{lsid}")+ await client.delete(f"/agent/{leader}")++ @pytest.mark.asyncio+ async def test_remove_mcp_per_agent_isolation(+ self,+ client: httpx.AsyncClient,+ ) -> None:+ """Remove from the leader; the worker is unaffected."""+ leader = await self._create_agent(client, "LeaderRm")+ worker = await self._create_agent(client, "WorkerRm")+ lsid = await self._create_session(client, leader)+ wsid = await self._create_session(client, worker)++ mcp = MCPClient(+ name="to-remove",+ is_stateful=False,+ mcp_config=HttpMCPConfig(url="http://127.0.0.1:1/mcp"),+ )+ await client.post(+ "/workspace/mcp",+ json=mcp.model_dump(),+ params={"agent_id": leader, "session_id": lsid},+ )++ resp = await client.delete(+ "/workspace/mcp/to-remove",+ params={"agent_id": leader, "session_id": lsid},+ )+ assert resp.status_code == 204++ l_names = await self._list_mcps(client, leader, lsid)+ assert "to-remove" not in l_names++ await client.delete(f"/sessions/{lsid}")+ await client.delete(f"/sessions/{wsid}")+ await client.delete(f"/agent/{leader}")+ await client.delete(f"/agent/{worker}")++ @pytest.mark.asyncio+ async def test_mcp_isolated_between_sessions_of_one_agent(+ self,+ client: httpx.AsyncClient,+ ) -> None:+ """Two sessions of one agent hold independent MCP sets."""+ agent = await self._create_agent(client, "TwoSessions")+ sid_a = await self._create_session(client, agent)+ sid_b = await self._create_session(client, agent)++ resp = await client.post(+ "/workspace/mcp",+ json=MCPClient(+ name="session-a-only",+ is_stateful=False,+ mcp_config=HttpMCPConfig(url="http://127.0.0.1:1/mcp"),+ ).model_dump(),+ params={"agent_id": agent, "session_id": sid_a},+ )+ assert resp.status_code == 201++ a_names = await self._list_mcps(client, agent, sid_a)+ assert "session-a-only" in a_names+ b_names = await self._list_mcps(client, agent, sid_b)+ assert "session-a-only" not in b_names+ assert "default-search" in b_names++ # Deleting session A drops its declaration: a session recreated+ # later starts from default_mcps again.+ await client.delete(f"/sessions/{sid_a}")+ sid_c = await self._create_session(client, agent)+ c_names = await self._list_mcps(client, agent, sid_c)+ assert "session-a-only" not in c_names+ assert "default-search" in c_names++ await client.delete(f"/sessions/{sid_b}")+ await client.delete(f"/sessions/{sid_c}")+ await client.delete(f"/agent/{agent}")diff --git a/tests/test_e2e_docker_mcp.py b/tests/test_e2e_docker_mcp.pynew file mode 100644index 000000000..8b4f05b14--- /dev/null+++ b/tests/test_e2e_docker_mcp.py@@ -0,0 +1,251 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""E2E test: per-scope MCP isolation via DockerWorkspace.++Requires: Docker running locally.+"""+import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest++from agentscope.workspace import DockerWorkspace+from agentscope.mcp import MCPClient, StdioMCPConfig+++# ── minimal MCP stdio server (runs inside the container) ───────────++_MINIMAL_MCP_SERVER = """\+import json, sys++def _send(data):+ sys.stdout.write(json.dumps(data) + "\\n")+ sys.stdout.flush()++for line in sys.stdin:+ req = json.loads(line)+ mid = req.get("id")+ method = req.get("method", "")+ if method == "initialize":+ _send({"jsonrpc": "2.0", "id": mid, "result": {+ "protocolVersion": "2024-11-05",+ "capabilities": {},+ "serverInfo": {"name": "test-mcp", "version": "0.1.0"},+ }})+ elif method == "notifications/initialized":+ pass+ elif method == "tools/list":+ _send({"jsonrpc": "2.0", "id": mid, "result": {"tools": []}})+"""+++def _docker_available() -> bool:+ """Return ``True`` iff the Docker daemon is reachable."""+ if shutil.which("docker") is None:+ return False+ try:+ result = subprocess.run(+ ["docker", "info"],+ capture_output=True,+ timeout=5,+ check=False,+ )+ return result.returncode == 0+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):+ return False+++_DOCKER_OK = _docker_available()+_SKIP_REASON = "Docker daemon not available"++[email protected](_DOCKER_OK, _SKIP_REASON)+ sys.platform == "win32",+ "Docker on Windows CI uses Windows container mode, "+ "Linux images unavailable",+)+class TestDockerPerScopeMCP(unittest.IsolatedAsyncioTestCase):+ """Per-``(agent_id, session_id)`` MCP isolation for DockerWorkspace."""++ def setUp(self) -> None:+ self.tmpdir = tempfile.mkdtemp()++ def tearDown(self) -> None:+ shutil.rmtree(self.tmpdir, ignore_errors=True)++ @staticmethod+ def _make_mcp(name: str) -> MCPClient:+ """Build a real MCP client backed by a minimal stdio MCP server+ that runs inside the container via ``python3 -c``.+ """+ return MCPClient(+ name=name,+ is_stateful=True,+ mcp_config=StdioMCPConfig(+ command="python3",+ args=["-c", _MINIMAL_MCP_SERVER],+ ),+ )++ async def test_lazy_instantiation_from_default_mcps(self) -> None:+ """Each scope instantiates its own copy of ``default_mcps``."""+ ws = DockerWorkspace(+ workspace_id="test-docker-clone",+ host_workdir=self.tmpdir,+ default_mcps=[self._make_mcp("default-fs")],+ )+ try:+ await ws.initialize()++ # Nothing is connected until a scope asks.+ self.assertEqual(ws._mcp_instances, {})++ mcps_a = await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertEqual([m.name for m in mcps_a], ["default-fs"])++ # Second access reuses the same instances.+ mcps_a2 = await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertEqual([id(m) for m in mcps_a2], [id(m) for m in mcps_a])++ # A different session of the same agent gets its own.+ mcps_a_s2 = await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-2",+ )+ self.assertEqual([m.name for m in mcps_a_s2], ["default-fs"])+ self.assertIsNot(mcps_a_s2[0], mcps_a[0])++ # And so does a different agent.+ mcps_b = await ws.list_mcps(+ agent_id="agent-B",+ session_id="sess-1",+ )+ self.assertEqual([m.name for m in mcps_b], ["default-fs"])+ self.assertIsNot(mcps_b[0], mcps_a[0])+ finally:+ await ws.close()++ async def test_add_remove_per_scope_isolation(self) -> None:+ """``add_mcp`` / ``remove_mcp`` only touch the given scope."""+ ws = DockerWorkspace(+ workspace_id="test-docker-addrm",+ host_workdir=self.tmpdir,+ )+ try:+ await ws.initialize()++ await ws.add_mcp(+ self._make_mcp("extra"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ mcps = await ws.list_mcps(agent_id="agent-A", session_id="sess-1")+ self.assertIn("extra", [m.name for m in mcps])++ # Neither another session of the same agent...+ other_session = await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-2",+ )+ self.assertNotIn("extra", [m.name for m in other_session])++ # ...nor another agent is affected.+ other_agent = await ws.list_mcps(+ agent_id="agent-B",+ session_id="sess-1",+ )+ self.assertNotIn("extra", [m.name for m in other_agent])++ await ws.remove_mcp(+ "extra",+ agent_id="agent-A",+ session_id="sess-1",+ )+ mcps = await ws.list_mcps(agent_id="agent-A", session_id="sess-1")+ self.assertNotIn("extra", [m.name for m in mcps])+ finally:+ await ws.close()++ async def test_duplicate_in_same_scope_raises(self) -> None:+ """A duplicate MCP name within one scope raises ``ValueError``."""+ ws = DockerWorkspace(+ workspace_id="test-docker-dup",+ host_workdir=self.tmpdir,+ )+ try:+ await ws.initialize()+ await ws.add_mcp(+ self._make_mcp("dup-me"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ with self.assertRaises(ValueError):+ await ws.add_mcp(+ self._make_mcp("dup-me"),+ agent_id="agent-A",+ session_id="sess-1",+ )++ # The same name in a different session is fine.+ await ws.add_mcp(+ self._make_mcp("dup-me"),+ agent_id="agent-A",+ session_id="sess-2",+ )+ finally:+ await ws.close()++ async def test_persistence_scoped_format(self) -> None:+ """``.mcp`` is written in the v2 nested agent/session format."""+ ws = DockerWorkspace(+ workspace_id="test-docker-persist",+ host_workdir=self.tmpdir,+ )+ try:+ await ws.initialize()+ mcp_file = os.path.join(self.tmpdir, ".mcp")++ # Untouched scopes leave no trace on disk.+ await ws.list_mcps(agent_id="agent-A", session_id="sess-1")+ self.assertFalse(os.path.exists(mcp_file))++ await ws.add_mcp(+ self._make_mcp("a-tool"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ await ws.add_mcp(+ self._make_mcp("b-tool"),+ agent_id="agent-B",+ session_id="sess-2",+ )++ with open(mcp_file, encoding="utf-8") as f:+ saved = json.load(f)+ self.assertEqual(saved["version"], 2)+ self.assertEqual(+ [m["name"] for m in saved["mcps"]["agent-A"]["sess-1"]],+ ["a-tool"],+ )+ self.assertEqual(+ [m["name"] for m in saved["mcps"]["agent-B"]["sess-2"]],+ ["b-tool"],+ )++ # purge_session forgets the scope entirely.+ await ws.purge_session(agent_id="agent-A", session_id="sess-1")+ with open(mcp_file, encoding="utf-8") as f:+ saved = json.load(f)+ self.assertNotIn("agent-A", saved["mcps"])+ finally:+ await ws.close()diff --git a/tests/test_e2e_e2b_mcp.py b/tests/test_e2e_e2b_mcp.pynew file mode 100644index 000000000..f2816d3e0--- /dev/null+++ b/tests/test_e2e_e2b_mcp.py@@ -0,0 +1,176 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""E2E test: per-scope MCP isolation via E2BWorkspace.++Requires: ``E2B_API_KEY`` environment variable.+"""+import os+import unittest++from agentscope.workspace import E2BWorkspace+from agentscope.mcp import MCPClient, StdioMCPConfig+++# ── minimal MCP stdio server (runs inside the sandbox) ─────────────++_MINIMAL_MCP_SERVER = """\+import json, sys++def _send(data):+ sys.stdout.write(json.dumps(data) + "\\n")+ sys.stdout.flush()++for line in sys.stdin:+ req = json.loads(line)+ mid = req.get("id")+ method = req.get("method", "")+ if method == "initialize":+ _send({"jsonrpc": "2.0", "id": mid, "result": {+ "protocolVersion": "2024-11-05",+ "capabilities": {},+ "serverInfo": {"name": "test-mcp", "version": "0.1.0"},+ }})+ elif method == "notifications/initialized":+ pass+ elif method == "tools/list":+ _send({"jsonrpc": "2.0", "id": mid, "result": {"tools": []}})+"""++_E2B_API_KEY = os.getenv("E2B_API_KEY", "")+_SKIP_REASON = "E2B_API_KEY environment variable is not set"++[email protected](_E2B_API_KEY, _SKIP_REASON)+class TestE2BPerScopeMCP(unittest.IsolatedAsyncioTestCase):+ """Per-``(agent_id, session_id)`` MCP isolation for E2BWorkspace."""++ @staticmethod+ def _make_mcp(name: str) -> MCPClient:+ """Build a real MCP client backed by a minimal stdio MCP server+ that runs inside the sandbox via ``python3 -c``.+ """+ return MCPClient(+ name=name,+ is_stateful=True,+ mcp_config=StdioMCPConfig(+ command="python3",+ args=["-c", _MINIMAL_MCP_SERVER],+ ),+ )++ async def asyncSetUp(self) -> None:+ self._ws = E2BWorkspace(+ api_key=_E2B_API_KEY,+ default_mcps=[self._make_mcp("default-fs")],+ )+ await self._ws.initialize()++ async def asyncTearDown(self) -> None:+ await self._ws.close()++ async def test_lazy_instantiation_from_default_mcps(self) -> None:+ """Each scope instantiates its own copy of ``default_mcps``."""+ self.assertEqual(self._ws._mcp_instances, {})++ mcps_a = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertEqual([m.name for m in mcps_a], ["default-fs"])++ mcps_a2 = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertEqual([id(m) for m in mcps_a2], [id(m) for m in mcps_a])++ mcps_a_s2 = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-2",+ )+ self.assertEqual([m.name for m in mcps_a_s2], ["default-fs"])+ self.assertIsNot(mcps_a_s2[0], mcps_a[0])++ mcps_b = await self._ws.list_mcps(+ agent_id="agent-B",+ session_id="sess-1",+ )+ self.assertEqual([m.name for m in mcps_b], ["default-fs"])+ self.assertIsNot(mcps_b[0], mcps_a[0])++ async def test_add_remove_per_scope_isolation(self) -> None:+ """``add_mcp`` / ``remove_mcp`` only touch the given scope."""+ await self._ws.add_mcp(+ self._make_mcp("extra"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ mcps = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertIn("extra", [m.name for m in mcps])++ other_session = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-2",+ )+ self.assertNotIn("extra", [m.name for m in other_session])++ other_agent = await self._ws.list_mcps(+ agent_id="agent-B",+ session_id="sess-1",+ )+ self.assertNotIn("extra", [m.name for m in other_agent])++ await self._ws.remove_mcp(+ "extra",+ agent_id="agent-A",+ session_id="sess-1",+ )+ mcps = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertNotIn("extra", [m.name for m in mcps])++ async def test_duplicate_in_same_scope_raises(self) -> None:+ """A duplicate MCP name within one scope raises ``ValueError``."""+ await self._ws.add_mcp(+ self._make_mcp("dup-me"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ with self.assertRaises(ValueError):+ await self._ws.add_mcp(+ self._make_mcp("dup-me"),+ agent_id="agent-A",+ session_id="sess-1",+ )++ # The same name in a different session is fine.+ await self._ws.add_mcp(+ self._make_mcp("dup-me"),+ agent_id="agent-A",+ session_id="sess-2",+ )++ async def test_purge_session_drops_the_scope(self) -> None:+ """``purge_session`` forgets a scope; defaults come back."""+ await self._ws.add_mcp(+ self._make_mcp("a-tool"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ mcps = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertIn("a-tool", [m.name for m in mcps])++ await self._ws.purge_session(agent_id="agent-A", session_id="sess-1")+ mcps = await self._ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ self.assertEqual([m.name for m in mcps], ["default-fs"])diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.pyindex e4a2679f4..a7b75b30d 100644--- a/tests/workspace_daytona_test.py+++ b/tests/workspace_daytona_test.py@@ -442,22 +442,35 @@ class _FakeGateway:"""Always healthy."""return True- async def list_mcps(self) -> list[MCPClient]:- """Read persisted MCP specs from the fake sandbox."""+ async def list_mcps(+ self,+ agent_id: str = "",+ session_id: str = "",+ ) -> list[MCPClient]:+ """Read the persisted specs for one agent/session."""path = self.backend.join_path(self.backend._workdir, ".mcp")try:raw = await self.backend.read_file(path)except FileNotFoundError:return []- specs = json.loads(raw.decode("utf-8"))+ data = json.loads(raw.decode("utf-8"))+ specs = data["mcps"].get(agent_id, {}).get(session_id, [])return [MCPClient.model_validate(spec) for spec in specs]async def aclose(self) -> None:"""Mark closed."""self.closed = True- def make_client(self, spec: dict[str, object]) -> MCPClient:+ def make_client(+ self,+ spec: dict[str, object],+ *,+ agent_id: str = "",+ session_id: str = "",+ connected: bool = False,+ ) -> MCPClient:"""Build a regular MCP client from spec for add_mcp tests."""+ del agent_id, session_id, connectedreturn _FakeGatewayMCPClient(spec)@@ -467,9 +480,15 @@ class _FakeGatewayMCPClient:def __init__(self, spec: dict[str, object]) -> None:self._spec = specself.name = str(spec["name"])+ self.is_stateful = bool(spec.get("is_stateful"))self.connected = Falseself.closed = False+ @property+ def is_connected(self) -> bool:+ """Whether :meth:`connect` has run and :meth:`close` has not."""+ return self.connected and not self.closed+def model_dump(self, mode: str = "python") -> dict[str, object]:"""Return the original MCP spec for persistence."""del mode@@ -479,8 +498,9 @@ class _FakeGatewayMCPClient:"""Mark connected."""self.connected = True- async def close(self) -> None:+ async def close(self, ignore_errors: bool = True) -> None:"""Mark closed."""+ del ignore_errorsself.closed = True@@ -848,7 +868,7 @@ class TestDaytonaWorkspaceMock(_DaytonaWorkspaceMockBase):"""The persisted ``.mcp`` file is rooted at the SDK workdir."""workspace = DaytonaWorkspace(workspace_id="wid-9")await workspace.initialize()- workspace._mcps = [+ workspace._mcp_specs[("agent-a", "sess-1")] = [MCPClient(name="demo",mcp_config=StdioMCPConfig(command="node", args=["server.js"]),@@ -860,7 +880,10 @@ class TestDaytonaWorkspaceMock(_DaytonaWorkspaceMockBase):raw = await workspace._backend.read_file("/home/daytona/.mcp")data = json.loads(raw.decode("utf-8"))- self.assertEqual(data[0]["name"], "demo")+ self.assertEqual(+ data["mcps"]["agent-a"]["sess-1"][0]["name"],+ "demo",+ )async def test_missing_mcp_file_seeds_default_mcps(self) -> None:"""Missing persisted MCP config falls back to configured defaults."""@@ -876,9 +899,10 @@ class TestDaytonaWorkspaceMock(_DaytonaWorkspaceMockBase):await workspace.initialize()- self.assertEqual([m.name for m in workspace._mcps], ["default"])- raw = await workspace._backend.read_file("/home/daytona/.mcp")- self.assertEqual(json.loads(raw.decode("utf-8"))[0]["name"], "default")+ self.assertEqual(+ [m.name for m in workspace._declared_specs("a", "s")],+ ["default"],+ )async def test_invalid_mcp_file_falls_back_to_default_mcps(self) -> None:"""Invalid persisted MCP JSON falls back to configured defaults."""@@ -898,11 +922,9 @@ class TestDaytonaWorkspaceMock(_DaytonaWorkspaceMockBase):await workspace.initialize()- self.assertEqual([m.name for m in workspace._mcps], ["fallback"])- raw = await workspace._backend.read_file("/home/daytona/.mcp")self.assertEqual(- json.loads(raw.decode("utf-8"))[0]["name"],- "fallback",+ [m.name for m in workspace._declared_specs("a", "s")],+ ["fallback"],)async def test_initialize_bootstrap_error_includes_command_and_output(@@ -1097,26 +1119,29 @@ class TestDaytonaWorkspaceBuiltinToolsMock(IsolatedAsyncioTestCase):is_stateful=True,)- await self.workspace.add_mcp(mcp)+ await self.workspace.add_mcp(mcp, agent_id="a", session_id="s")- self.assertIn("demo", [m.name for m in self.workspace._mcps])+ live = self.workspace._mcp_instances[("a", "s")]+ self.assertIn("demo", live)raw = await self.workspace._backend.read_file("/home/daytona/.mcp")- self.assertEqual(json.loads(raw.decode("utf-8"))[0]["name"], "demo")+ data = json.loads(raw.decode("utf-8"))+ self.assertEqual(data["mcps"]["a"]["s"][0]["name"], "demo")- gw_client = next(m for m in self.workspace._mcps if m.name == "demo")- await self.workspace.remove_mcp("demo")+ gw_client = live["demo"]+ await self.workspace.remove_mcp("demo", agent_id="a", session_id="s")self.assertTrue(gw_client.closed)- self.assertNotIn("demo", [m.name for m in self.workspace._mcps])+ self.assertNotIn("demo", self.workspace._mcp_instances[("a", "s")])raw = await self.workspace._backend.read_file("/home/daytona/.mcp")- self.assertEqual(json.loads(raw.decode("utf-8")), [])+ data = json.loads(raw.decode("utf-8"))+ self.assertEqual(data["mcps"]["a"]["s"], [])async def test_remove_missing_mcp_is_noop(self) -> None:"""Removing an unknown MCP leaves persisted config unchanged."""- await self.workspace.remove_mcp("missing")+ await self.workspace.remove_mcp("missing", agent_id="a")- raw = await self.workspace._backend.read_file("/home/daytona/.mcp")- self.assertEqual(json.loads(raw.decode("utf-8")), [])+ # Unknown name: nothing is declared, so nothing is persisted.+ self.assertEqual(self.workspace._mcp_specs, {})@unittest.skipIf(os.name == "nt",@@ -1245,8 +1270,10 @@ class TestDaytonaWorkspaceBuiltinToolsMock(IsolatedAsyncioTestCase):self.assertFalse(await self.workspace._backend.file_exists("/home/daytona/data"),)- raw = await self.workspace._backend.read_file("/home/daytona/.mcp")- self.assertEqual(json.loads(raw.decode("utf-8")), [])+ # ``reset`` drops ``.mcp`` so default_mcps are seeded again.+ self.assertFalse(+ await self.workspace._backend.file_exists("/home/daytona/.mcp"),+ )def _mcp_server_script() -> bytes:diff --git a/tests/workspace_docker_test.py b/tests/workspace_docker_test.pyindex 3c6fe5248..0efb80715 100644--- a/tests/workspace_docker_test.py+++ b/tests/workspace_docker_test.py@@ -28,6 +28,7 @@ The whole module is skipped when no Docker daemon is reachable.import base64import hashlibimport os+import sysimport reimport shutilimport subprocess@@ -68,6 +69,11 @@ def _docker_available() -> bool:Probes via the ``docker`` CLI rather than the aiodocker async clientso the check is cheap and synchronous (runs at module import time)."""+ if sys.platform == "win32":+ # Docker workspace tests require Linux containers; the Windows+ # CI runner ships Docker in Windows mode which cannot build or+ # run the Linux-based workspace images.+ return Falseif shutil.which("docker") is None:return Falsetry:@@ -704,7 +710,13 @@ class TestDockerWorkspaceLifecycle(IsolatedAsyncioTestCase):)try:await ws.initialize()- self.assertListEqual(await ws.list_mcps(), [])+ self.assertListEqual(+ await ws.list_mcps(+ agent_id="test-agent",+ session_id="test-session",+ ),+ [],+ )finally:await ws.close()diff --git a/tests/workspace_e2b_test.py b/tests/workspace_e2b_test.pyindex 2a5a8a7e3..a3d146126 100644--- a/tests/workspace_e2b_test.py+++ b/tests/workspace_e2b_test.py@@ -62,7 +62,10 @@ class TestE2BWorkspaceLifecycle(IsolatedAsyncioTestCase):await workspace.initialize()- mcps = await workspace.list_mcps()+ mcps = await workspace.list_mcps(+ agent_id="test-agent",+ session_id="test-session",+ )self.assertGreater(len(mcps), 0)for mcp in mcps:diff --git a/tests/workspace_k8s_test.py b/tests/workspace_k8s_test.pyindex eb9299f5b..a4d21a661 100644--- a/tests/workspace_k8s_test.py+++ b/tests/workspace_k8s_test.py@@ -157,7 +157,6 @@ class TestK8sWorkspaceHappyPath(IsolatedAsyncioTestCase):f"{POD_WORKDIR}/data",f"{POD_WORKDIR}/skills",f"{POD_WORKDIR}/sessions",- f"{POD_WORKDIR}/.mcp",f"{GATEWAY_HOME}/_mcp_gateway_app.py",f"{GATEWAY_HOME}/_glob_helper.py",f"{GATEWAY_HOME}/.venv/bin/python",@@ -201,18 +200,41 @@ class TestK8sWorkspaceHappyPath(IsolatedAsyncioTestCase):args=["--with", "mcp<2.0.0", "mcp-server-time"],),)- self.assertListEqual(await ws.list_mcps(), [])+ self.assertListEqual(+ await ws.list_mcps(+ agent_id="test-agent",+ session_id="test-session",+ ),+ [],+ )- await ws.add_mcp(mcp_client)- mcps = await ws.list_mcps()+ await ws.add_mcp(+ mcp_client,+ agent_id="test-agent",+ session_id="test-session",+ )+ mcps = await ws.list_mcps(+ agent_id="test-agent",+ session_id="test-session",+ )self.assertEqual(len(mcps), 1)self.assertEqual(mcps[0].name, "time")tools = await mcps[0].list_raw_tools()self.assertGreater(len(tools), 0)- await ws.remove_mcp("time")- self.assertListEqual(await ws.list_mcps(), [])+ await ws.remove_mcp(+ "time",+ agent_id="test-agent",+ session_id="test-session",+ )+ self.assertListEqual(+ await ws.list_mcps(+ agent_id="test-agent",+ session_id="test-session",+ ),+ [],+ )# ── 4. Backend public API ───────────────────────────────# 4a. exec_shell success@@ -329,7 +351,10 @@ class TestK8sWorkspaceReset(IsolatedAsyncioTestCase):state_after = {"skills": await ws.list_skills(),- "mcps": await ws.list_mcps(),+ "mcps": await ws.list_mcps(+ agent_id="test-agent",+ session_id="test-session",+ ),"sessions_exists": await backend.file_exists(f"{POD_WORKDIR}/sessions",),diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.pyindex 9f3069fe9..a2d3b2dbe 100644--- a/tests/workspace_local_test.py+++ b/tests/workspace_local_test.py@@ -1507,6 +1507,7 @@ class TestLocalWorkspaceMCPInit(IsolatedAsyncioTestCase):ws = LocalWorkspace(workdir=self.temp_dir.name)await ws.initialize()+ # A v1 flat-list .mcp is migrated into the legacy scopemcps = await ws.list_mcps()names = [m.name for m in mcps]self.assertIn("good_one", names)@@ -1533,5 +1534,304 @@ class TestLocalWorkspaceMCPInit(IsolatedAsyncioTestCase):)await ws.initialize()self.assertTrue(ws.is_alive)- names = [m.name for m in await ws.list_mcps()]+ # Instantiated lazily on first list_mcps for this scope+ names = [+ m.name+ for m in await ws.list_mcps(+ agent_id="test-agent",+ session_id="test-session",+ )+ ]self.assertNotIn("will_fail_connect", names)+++class TestLocalWorkspaceMCPScoping(IsolatedAsyncioTestCase):+ """Per-``(agent_id, session_id)`` MCP scoping in LocalWorkspace.++ Covers:+ - each scope is seeded from ``default_mcps`` and gets its own+ instances, built lazily on first ``list_mcps``+ - ``add_mcp`` / ``remove_mcp`` only touch the calling scope+ - a scope absent from ``.mcp`` is not the same as one persisted+ with an empty list+ - ``purge_session`` drops declarations, instances and offload files+ - the live-stateful cap never evicts the requesting scope+ """++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ # pylint: disable=consider-using-with+ self.temp_dir = tempfile.TemporaryDirectory()+ self.mcp_file = os.path.join(self.temp_dir.name, ".mcp")++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ self.temp_dir.cleanup()++ @staticmethod+ def _make_mcp(name: str) -> MCPClient:+ """Return a stateless HTTP MCP that needs no live server."""+ return MCPClient(+ name=name,+ is_stateful=False,+ mcp_config={+ "type": "http_mcp",+ "url": f"http://127.0.0.1:1/{name}",+ },+ )++ def _read_mcp_file(self) -> dict:+ """Return the parsed ``.mcp`` payload."""+ with open(self.mcp_file, encoding="utf-8") as f:+ return json.load(f)++ async def _workspace(self, **kwargs: Any) -> LocalWorkspace:+ """Build and initialise a workspace over the temp workdir."""+ ws = LocalWorkspace(workdir=self.temp_dir.name, **kwargs)+ await ws.initialize()+ self.addAsyncCleanup(ws.close)+ return ws++ async def test_scopes_get_independent_instances(self) -> None:+ """Each scope is seeded from defaults with its own instances."""+ ws = await self._workspace(default_mcps=[self._make_mcp("seed")])++ # Nothing is instantiated before the first list_mcps.+ self.assertEqual(ws._mcp_instances, {})++ a1 = await ws.list_mcps(agent_id="agent-A", session_id="sess-1")+ a2 = await ws.list_mcps(agent_id="agent-A", session_id="sess-2")+ b1 = await ws.list_mcps(agent_id="agent-B", session_id="sess-1")++ self.assertEqual([m.name for m in a1], ["seed"])+ self.assertEqual([m.name for m in a2], ["seed"])+ self.assertIsNot(a1[0], a2[0])+ self.assertIsNot(a1[0], b1[0])++ # Repeat access reuses the same instances.+ self.assertIs(+ (await ws.list_mcps(agent_id="agent-A", session_id="sess-1"))[0],+ a1[0],+ )++ # A scope that only read defaults leaves no trace on disk.+ self.assertFalse(os.path.exists(self.mcp_file))++ async def test_add_and_remove_are_scoped(self) -> None:+ """``add_mcp`` / ``remove_mcp`` touch only the calling scope."""+ ws = await self._workspace(default_mcps=[self._make_mcp("seed")])++ await ws.add_mcp(+ self._make_mcp("extra"),+ agent_id="agent-A",+ session_id="sess-1",+ )++ self.assertEqual(+ [+ m.name+ for m in await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ ],+ ["seed", "extra"],+ )+ self.assertEqual(+ [+ m.name+ for m in await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-2",+ )+ ],+ ["seed"],+ )+ self.assertEqual(+ [+ m.name+ for m in await ws.list_mcps(+ agent_id="agent-B",+ session_id="sess-1",+ )+ ],+ ["seed"],+ )++ saved = self._read_mcp_file()+ self.assertEqual(saved["version"], 2)+ self.assertEqual(list(saved["mcps"]), ["agent-A"])++ await ws.remove_mcp("extra", agent_id="agent-A", session_id="sess-1")+ self.assertEqual(+ [+ m.name+ for m in await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ ],+ ["seed"],+ )++ async def test_duplicate_name_in_one_scope_raises(self) -> None:+ """A duplicate name is rejected per scope, not globally."""+ ws = await self._workspace()++ await ws.add_mcp(+ self._make_mcp("dup"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ with self.assertRaises(ValueError):+ await ws.add_mcp(+ self._make_mcp("dup"),+ agent_id="agent-A",+ session_id="sess-1",+ )++ # The same name in another scope is fine.+ await ws.add_mcp(+ self._make_mcp("dup"),+ agent_id="agent-A",+ session_id="sess-2",+ )++ async def test_emptied_scope_is_not_reseeded(self) -> None:+ """An empty declaration differs from an absent one."""+ ws = await self._workspace(default_mcps=[self._make_mcp("seed")])++ await ws.remove_mcp("seed", agent_id="agent-A", session_id="sess-1")+ self.assertEqual(+ await ws.list_mcps(agent_id="agent-A", session_id="sess-1"),+ [],+ )+ self.assertEqual(+ self._read_mcp_file()["mcps"]["agent-A"]["sess-1"],+ [],+ )++ # It survives a restart rather than falling back to defaults.+ await ws.close()+ ws2 = await self._workspace(default_mcps=[self._make_mcp("seed")])+ self.assertEqual(+ await ws2.list_mcps(agent_id="agent-A", session_id="sess-1"),+ [],+ )+ # An untouched scope still gets the defaults.+ self.assertEqual(+ [+ m.name+ for m in await ws2.list_mcps(+ agent_id="agent-A",+ session_id="sess-9",+ )+ ],+ ["seed"],+ )++ async def test_reset_returns_to_factory_defaults(self) -> None:+ """``reset`` drops ``.mcp``, so defaults are seeded again."""+ ws = await self._workspace(default_mcps=[self._make_mcp("seed")])++ await ws.add_mcp(+ self._make_mcp("extra"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ await ws.remove_mcp("seed", agent_id="agent-A", session_id="sess-1")+ self.assertTrue(os.path.exists(self.mcp_file))++ await ws.reset()++ self.assertFalse(os.path.exists(self.mcp_file))+ self.assertEqual(+ [+ m.name+ for m in await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ ],+ ["seed"],+ )++ async def test_purge_session_drops_scope_and_offload(self) -> None:+ """``purge_session`` forgets declarations and offload files."""+ ws = await self._workspace(default_mcps=[self._make_mcp("seed")])++ await ws.add_mcp(+ self._make_mcp("extra"),+ agent_id="agent-A",+ session_id="sess-1",+ )+ await ws.offload_context(+ "sess-1",+ [UserMsg(name="user", content="hi")],+ )+ session_dir = os.path.join(self.temp_dir.name, "sessions", "sess-1")+ self.assertTrue(os.path.isdir(session_dir))++ await ws.purge_session(agent_id="agent-A", session_id="sess-1")++ self.assertFalse(os.path.exists(session_dir))+ self.assertNotIn("agent-A", self._read_mcp_file()["mcps"])+ # The scope is back to "never seen" — defaults apply again.+ self.assertEqual(+ [+ m.name+ for m in await ws.list_mcps(+ agent_id="agent-A",+ session_id="sess-1",+ )+ ],+ ["seed"],+ )++ async def test_capacity_never_evicts_the_caller(self) -> None:+ """The live-stateful cap only evicts other agents/sessions."""+ connected: list[str] = []++ async def _fake_connect(client: MCPClient) -> None:+ """Mark connected without opening a transport."""+ connected.append(client.name)+ client._is_connected = True++ async def _fake_close(client: MCPClient, *_a: Any, **_kw: Any) -> None:+ """Mark disconnected without touching a transport."""+ client._is_connected = False++ def _stateful(name: str) -> MCPClient:+ """A stateful spec whose transport is never opened."""+ return MCPClient(+ name=name,+ is_stateful=True,+ mcp_config={+ "type": "http_mcp",+ "url": f"http://127.0.0.1:1/{name}",+ },+ )++ with patch.object(MCPClient, "connect", _fake_connect), patch.object(+ MCPClient,+ "close",+ _fake_close,+ ):+ ws = await self._workspace(+ default_mcps=[_stateful("a"), _stateful("b")],+ max_live_stateful_mcps=2,+ )++ first = await ws.list_mcps(agent_id="agent-A", session_id="s1")+ self.assertEqual(len(first), 2)++ # The cap is 2, so serving another session evicts the+ # first — but the newcomer still gets its full set.+ second = await ws.list_mcps(agent_id="agent-B", session_id="s1")+ self.assertEqual(len(second), 2)+ self.assertEqual(ws._mcp_instances[("agent-A", "s1")], {})++ # Coming back rebuilds the evicted session's declaration.+ again = await ws.list_mcps(agent_id="agent-A", session_id="s1")+ self.assertEqual([m.name for m in again], ["a", "b"])+ self.assertEqual(len(connected), 6)diff --git a/tests/workspace_skill_archive_test.py b/tests/workspace_skill_archive_test.pyindex c26df571d..ac5dd0419 100644--- a/tests/workspace_skill_archive_test.py+++ b/tests/workspace_skill_archive_test.py@@ -121,10 +121,9 @@ class AddSkillArchiveLocalTest(IsolatedAsyncioTestCase):"zip","pack",)- self.assertEqual(- sorted(os.listdir(self.tmp)),- [".mcp", "skills"],- )+ # No ``.mcp``: it is only written once an agent/session+ # diverges from ``default_mcps``.+ self.assertEqual(sorted(os.listdir(self.tmp)), ["skills"])class AddSkillArchiveSandboxedTest(IsolatedAsyncioTestCase):