The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: isolate execution-owned MCP registry overlays
Teknium96e4d2962bfe
diff --git a/tests/tools/test_mcp_session_scope.py b/tests/tools/test_mcp_session_scope.pynew file mode 100644index 00000000000..d45d96165cc--- /dev/null+++ b/tests/tools/test_mcp_session_scope.py@@ -0,0 +1,44 @@+"""Real stdio registrations must not become sibling-session capabilities."""+import concurrent.futures+import sys+++def test_session_mcp_registry_isolation_and_scoped_release(tmp_path):+ from tools.registry import registry, session_tool_scope+ from tools.mcp_tool_discovery import register_mcp_servers+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers++ script = tmp_path / 'peer.py'+ script.write_text('''import json, os, sys+for line in sys.stdin:+ r=json.loads(line); method=r.get('method'); ident=r.get('id')+ if ident is None: continue+ if method=='initialize': result={'protocolVersion':r['params']['protocolVersion'],'capabilities':{'tools':{}},'serverInfo':{'name':'owned-peer','version':'1'}}+ elif method=='tools/list': result={'tools':[{'name':'echo','description':'owned echo','inputSchema':{'type':'object','properties':{}}}]}+ elif method=='tools/call': result={'content':[{'type':'text','text':os.environ['OWNED_MARKER']}]}+ else: result={}+ print(json.dumps({'jsonrpc':'2.0','id':ident,'result':result}),flush=True)+''')+ def connect(scope, name, marker):+ with session_tool_scope(scope):+ register_mcp_servers({name: {'command': sys.executable, 'args': [str(script)],+ 'env': {'OWNED_MARKER': marker}, 'connect_timeout': 5}})+ names = [n for n in registry.get_all_tool_names() if n.startswith('mcp__')]+ assert len(names) == 1, names+ return names[0], registry.dispatch(names[0], {})+ try:+ with concurrent.futures.ThreadPoolExecutor(2) as pool:+ a = pool.submit(connect, 'editor-session:a', 'owned_a', 'ONLY_A')+ b = pool.submit(connect, 'editor-session:b', 'owned_b', 'ONLY_B')+ an, av = a.result(timeout=30)+ bn, bv = b.result(timeout=30)+ assert 'ONLY_A' in av and 'ONLY_B' not in av+ assert 'ONLY_B' in bv and 'ONLY_A' not in bv+ assert registry.get_entry(an) is None and registry.get_entry(bn) is None+ shutdown_mcp_servers(scope='editor-session:a')+ with session_tool_scope('editor-session:b'):+ assert registry.get_entry(an) is None+ assert 'ONLY_B' in registry.dispatch(bn, {})+ finally:+ shutdown_mcp_servers(scope='editor-session:a')+ shutdown_mcp_servers(scope='editor-session:b')diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex 25c324ac4cb..6583fc661e3 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -612,6 +612,10 @@ def _update_death_supervisor(verb: str, pgids) -> None:def _mcp_registry_scope() -> Optional[str]:"""Registry scope for MCP registrations: a profile overlay under a multiplexer, else None."""+ from tools.registry import current_session_tool_scope+ session_scope = current_session_tool_scope()+ if session_scope is not None:+ return session_scopefrom agent.secret_scope import is_multiplex_activeif not is_multiplex_active():return Nonediff --git a/tools/registry.py b/tools/registry.pyindex b82ae4aeeae..a16c8c91e79 100644--- a/tools/registry.py+++ b/tools/registry.py@@ -14,6 +14,8 @@ import sysimport threadingimport timefrom dataclasses import dataclass+from contextlib import contextmanager+from contextvars import ContextVarfrom pathlib import Pathfrom typing import Callable, Dict, List, Optional, Set@@ -21,6 +23,23 @@ from hermes_constants import hermes_home_keylogger = logging.getLogger(__name__)+_session_tool_scope = ContextVar("session_tool_scope", default=None)+++@contextmanager+def session_tool_scope(scope):+ """Execution-owned overlay, additive to the existing profile registry."""+ token = _session_tool_scope.set(scope)+ try:+ yield+ finally:+ _session_tool_scope.reset(token)+++def current_session_tool_scope():+ return _session_tool_scope.get()++# Cap on a tool error body; only trims runaway interpolated exceptions (static msgs are ~115 chars)._MAX_TOOL_ERROR_CHARS = 2048_TOOL_ERROR_TRUNCATION_MARKER = "… [truncated]"@@ -410,7 +429,10 @@ class ToolRegistry:def _merged_tools(self, scope: Optional[str] = None) -> Dict[str, ToolEntry]:"""Return global tools overlaid with one profile's plugin tools."""- return {**self._tools, **self._scoped_tools.get(scope or self.current_scope_key(), {})}+ entries = {**self._tools, **self._scoped_tools.get(scope or self.current_scope_key(), {})}+ if scope is None:+ entries.update(self._scoped_tools.get(current_session_tool_scope(), {}))+ return entriesdef _toolset_entries(self, toolset: str, scope: Optional[str]) -> List[ToolEntry]:return self._grouped(self._merged_tools(scope).values()).get(toolset, [])