Files
cowork-local/tests/unit/test_mcp_source_manager.py
T
vudt15andClaude Sonnet 5 ae4fe72b2e feat(R05): tool capability registry, unified policy gateway, MCP lifecycle manager
EPIC R05 (Team Hoa) - one security/approval path for every tool call.

R05-T01 domain/tools/{tool_descriptor,tool_registry}.py
  ToolCapability (READ/WRITE/EXECUTE/NETWORK, composable) + ToolDescriptor +
  ToolRegistry, replacing three independently-maintained gating lists
  (core/tools.py::WRITE_TOOLS, code_agent.py's WRITE_TOOLS|MS365_WRITE_TOOLS,
  chat_agent.py's literal ("run_command","install_package") tuple) with one
  capability lookup.

R05-T02 infrastructure/filesystem/{file_tools,command_tools,fetch_tools,tool_context}.py
  core/tools.py's execute_tool if/elif chain split into per-concern modules.
  core/tools.py is now a strangler-fig shim: re-exports ToolContext/ToolError,
  dispatches through a {name: handler} dict built from the split modules.
  core/tools.py: 566 -> 291 lines.

R05-T03 application/conversations/tool_policy_gateway.py
  ToolPolicyGateway.allow(name, gate, payload) - capability-driven ALLOW vs
  ask-the-gate decision. Wired into both chat_agent.py::run_cowork and
  code_agent.py::run_code, replacing their separate hand-rolled checks.
  Verified equivalent to the old hardcoded sets by test.

R05-T04 (behavior change, not just refactor)
  MCP/connector tools (core/mcp_client.py, core/ext_connectors.py) reached
  chat_agent.py via extra_executor(name, args) with NO permission check at
  all. They are now tagged with a conservative default capability
  (WRITE|EXECUTE|NETWORK - no MCP tool self-declares risk) and routed through
  the SAME ToolPolicyGateway as built-ins. When "confirm before running
  commands" is on, MCP/connector calls now prompt like run_command already
  did - a real gap closed, and a user-visible change worth calling out.

R05-T05 infrastructure/mcp/mcp_source_manager.py
  McpToolSourceManager extracts the connection cache/lock/start-or-skip
  lifecycle out of state.py::AppContext (_mcp_connections/_conn_lock) into a
  standalone, directly-testable class. AppContext.build_mcp_tools and
  _ms365_builtin_connection now call ensure()/stop(); _ext_connections
  (unified Connectors) is out of scope for this task and keeps its own lock.

New tests: tests/unit/test_tool_registry_and_policy.py,
test_code_agent_tool_policy.py, test_cowork_extra_tool_policy.py,
test_mcp_source_manager.py (26 new tests).

Suite: 254 passed, 4 pre-existing failures unrelated to R05 (2 EPIC R02
config-security, 2 environment-dependent routing tests - see checklist).
check_imports: PASS. All new files < 400 LOC.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 22:20:57 +09:00

107 lines
3.1 KiB
Python

"""EPIC R05-T05: the MCP connection lifecycle extracted out of
``state.py::AppContext`` into :class:`McpToolSourceManager`.
Uses a fake connection (no real subprocess/asyncio loop) so these tests run in
milliseconds and don't depend on any actual MCP server being installed.
"""
from __future__ import annotations
from typing import Dict, List, Optional
from cowork_local.infrastructure.mcp import McpToolSourceManager
class _FakeConnection:
"""Stands in for ``core.mcp_client.McpServerConnection`` — tracks
start/stop calls instead of spawning anything."""
instances: List["_FakeConnection"] = []
def __init__(self, name: str, command: str, args: Optional[List[str]] = None,
env: Optional[Dict[str, str]] = None):
self.name = name
self.command = command
self.args = args
self.env = env
self.started = False
self.stopped = False
self._alive = True
_FakeConnection.instances.append(self)
def start(self) -> None:
self.started = True
def stop(self) -> None:
self.stopped = True
self._alive = False
def is_alive(self) -> bool:
return self._alive
def _manager() -> McpToolSourceManager:
_FakeConnection.instances.clear()
return McpToolSourceManager(connection_factory=_FakeConnection)
def test_ensure_starts_once_and_caches_the_live_connection():
mgr = _manager()
first = mgr.ensure("github", "npx", ["-y", "github-mcp"])
second = mgr.ensure("github", "npx", ["-y", "github-mcp"])
assert first is second # same connection reused, not a second subprocess
assert len(_FakeConnection.instances) == 1
assert first.started is True
def test_two_concurrent_ensures_for_different_servers_dont_collide():
mgr = _manager()
a = mgr.ensure("server-a", "cmd-a")
b = mgr.ensure("server-b", "cmd-b")
assert a is not b
assert {c.name for c in mgr.active()} == {"server-a", "server-b"}
def test_ensure_restarts_when_the_cached_connection_died():
mgr = _manager()
first = mgr.ensure("flaky", "cmd")
first.stop() # simulate the subprocess crashing
assert mgr.is_alive("flaky") is False
second = mgr.ensure("flaky", "cmd")
assert second is not first
assert len(_FakeConnection.instances) == 2
def test_a_server_that_fails_to_start_returns_none_and_isnt_cached():
class _DyingConnection(_FakeConnection):
def start(self) -> None:
raise RuntimeError("boom")
mgr = McpToolSourceManager(connection_factory=_DyingConnection)
assert mgr.ensure("broken", "cmd") is None
assert mgr.get("broken") is None
def test_stop_removes_one_connection_without_touching_others():
mgr = _manager()
mgr.ensure("keep", "cmd")
doomed = mgr.ensure("drop", "cmd")
mgr.stop("drop")
assert doomed.stopped is True
assert mgr.get("drop") is None
assert mgr.get("keep") is not None
def test_stop_all_stops_every_connection_and_clears_the_cache():
mgr = _manager()
mgr.ensure("a", "cmd")
mgr.ensure("b", "cmd")
mgr.stop_all()
assert all(c.stopped for c in _FakeConnection.instances)
assert mgr.active() == []