Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(swarm): operator-configured external MCP tools in workers (#142)

shadowinlife7acaf74e10cf
diff --git a/README.md b/README.md
index 06bd6be81..214c2ec31 100644
--- a/README.md
+++ b/README.md
@@ -714,6 +714,10 @@ vibe-trading-mcp --transport sse # SSE for web clients
**MCP tools exposed (22):** `list_skills`, `load_skill`, `backtest`, `factor_analysis`, `analyze_options`, `pattern_recognition`, `get_market_data`, `web_search`, `read_url`, `read_document`, `read_file`, `write_file`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `list_swarm_presets`, `run_swarm`, `get_swarm_status`, `get_run_result`, `list_runs`.
+### SWARM external MCP tools
+
+`run_swarm` workers can call operator-approved tools from external MCP servers. Configure the server-side allowlist in `VIBE_TRADING_SWARM_AGENT_CONFIG`, `~/.vibe-trading/swarm-agent.json`, or the fallback `~/.vibe-trading/agent.json`; then list remote tools in a swarm preset using the local MCP wrapper name, such as `mcp_internal_kb_search`. Caller-provided `variables` stay template data only and cannot inject MCP URLs, commands, environment variables, or allowlist overrides.
+
<details>
<summary><b>Install from ClawHub (one command)</b></summary>
diff --git a/agent/api_server.py b/agent/api_server.py
index 8bbb06a78..50ba2bb97 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -1985,11 +1985,15 @@ def _get_swarm_runtime():
global _swarm_runtime
if _swarm_runtime is not None:
return _swarm_runtime
+ from src.config import load_swarm_agent_config
from src.swarm.store import SwarmStore
from src.swarm.runtime import SwarmRuntime
swarm_dir = Path(__file__).resolve().parent / ".swarm" / "runs"
store = SwarmStore(base_dir=swarm_dir)
- _swarm_runtime = SwarmRuntime(store=store)
+ # Boot-time / operator-trusted: REST API callers cannot influence the
+ # config path. See docs/2026-05-25_swarm_mcp_tools_roadmap.md.
+ agent_config = load_swarm_agent_config()
+ _swarm_runtime = SwarmRuntime(store=store, agent_config=agent_config)
return _swarm_runtime
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 47ce9625e..7b9915193 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -1944,6 +1944,7 @@ class _SwarmDashboard:
def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> None:
"""Run a swarm preset with Rich Live dashboard."""
from rich.live import Live
+ from src.config import load_swarm_agent_config
from src.swarm.runtime import SwarmRuntime
from src.swarm.store import SwarmStore
from src.swarm.models import RunStatus
@@ -1957,7 +1958,8 @@ def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> None:
return
store = SwarmStore(base_dir=SWARM_DIR)
- runtime = SwarmRuntime(store=store)
+ agent_config = load_swarm_agent_config()
+ runtime = SwarmRuntime(store=store, agent_config=agent_config)
_agent_color_map.clear()
console.print(f"\n[dim]Starting swarm:[/dim] [cyan]{preset}[/cyan]")
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 4718dde96..eb275008b 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -673,12 +673,17 @@ async def run_swarm(
"""
import asyncio
import time
+ from src.config import load_swarm_agent_config
from src.swarm.runtime import SwarmRuntime
from src.swarm.store import SwarmStore, swarm_runs_root
swarm_dir = swarm_runs_root()
store = SwarmStore(base_dir=swarm_dir)
- runtime = SwarmRuntime(store=store)
+ # Boot-time / operator-trusted: resolved from env var or on-disk config.
+ # The MCP caller (this tool's invoker) cannot influence the path — the
+ # ``variables`` arg below is template data, never config (R-06).
+ agent_config = load_swarm_agent_config()
+ runtime = SwarmRuntime(store=store, agent_config=agent_config)
try:
run = runtime.start_run(
diff --git a/agent/src/config/__init__.py b/agent/src/config/__init__.py
index fd8661e5f..3142fc790 100644
--- a/agent/src/config/__init__.py
+++ b/agent/src/config/__init__.py
@@ -1,6 +1,12 @@
"""Agent configuration helpers for MCP client integration."""
-from src.config.loader import load_agent_config, load_runtime_agent_config, merge_agent_config_overrides, sanitize_session_overrides
+from src.config.loader import (
+ load_agent_config,
+ load_runtime_agent_config,
+ load_swarm_agent_config,
+ merge_agent_config_overrides,
+ sanitize_session_overrides,
+)
from src.config.paths import get_config_path, get_data_dir, get_runtime_root
from src.config.schema import AgentConfig, MCPServerConfig
@@ -12,6 +18,7 @@ __all__ = [
"get_runtime_root",
"load_agent_config",
"load_runtime_agent_config",
+ "load_swarm_agent_config",
"merge_agent_config_overrides",
"sanitize_session_overrides",
]
diff --git a/agent/src/config/loader.py b/agent/src/config/loader.py
index 543da7ae7..0b9ff4704 100644
--- a/agent/src/config/loader.py
+++ b/agent/src/config/loader.py
@@ -10,11 +10,15 @@ from typing import Any, Mapping
from pydantic import ValidationError
-from src.config.paths import get_config_path
+from src.config.paths import get_config_path, get_runtime_root
from src.config.schema import AgentConfig, AgentConfigOverride, MCPServerConfig
logger = logging.getLogger(__name__)
+_SWARM_AGENT_CONFIG_ENV_VAR = "VIBE_TRADING_SWARM_AGENT_CONFIG"
+_SWARM_AGENT_CONFIG_FILENAME = "swarm-agent.json"
+_MAIN_AGENT_FALLBACK_FILENAMES = ("agent.json", "agent.yaml", "agent.yml")
+
try:
import yaml
except ImportError:
@@ -147,6 +151,84 @@ def load_runtime_agent_config(
return merge_agent_config_overrides(config, overrides)
+def _resolve_swarm_agent_config_path(
+ *,
+ runtime_root: Path | None = None,
+) -> Path | None:
+ """Pick the operator config the swarm runtime should boot against.
+
+ Resolution order (first hit wins):
+
+ 1. ``VIBE_TRADING_SWARM_AGENT_CONFIG`` env var — absolute override hatch
+ for CI / sandbox deployments where the runtime root is read-only.
+ Returned even if the file does not yet exist; the caller logs &
+ degrades gracefully so a misconfigured env var doesn't crash boot.
+ 2. ``<runtime_root>/swarm-agent.json`` — the swarm-specific operator
+ allowlist. Lets the swarm path use a *different* set of MCP servers
+ from the main agent without duplicating non-MCP fields.
+ 3. ``<runtime_root>/{agent.json,agent.yaml,agent.yml}`` — fallback to the
+ main agent config so single-config operators don't have to duplicate
+ their MCP allowlist.
+ 4. ``None`` when nothing matches — preserves byte-for-byte legacy
+ behaviour where the swarm runs strictly on local tools.
+
+ Trust model: callers of swarm entry points (e.g. an external MCP client
+ invoking ``run_swarm``) cannot influence this path — config resolution is
+ a boot-time / operator-trusted action.
+
+ Args:
+ runtime_root: Override the directory the on-disk lookup uses. Defaults
+ to ``~/.vibe-trading``. Tests pass a ``tmp_path`` here to keep
+ assertions hermetic.
+
+ Returns:
+ The chosen config path, or ``None`` when no candidate is available.
+ """
+ env_value = os.environ.get(_SWARM_AGENT_CONFIG_ENV_VAR, "").strip()
+ if env_value:
+ return Path(env_value).expanduser()
+
+ root = runtime_root if runtime_root is not None else get_runtime_root()
+ swarm_specific = root / _SWARM_AGENT_CONFIG_FILENAME
+ if swarm_specific.exists():
+ return swarm_specific
+
+ for fallback in _MAIN_AGENT_FALLBACK_FILENAMES:
+ candidate = root / fallback
+ if candidate.exists():
+ return candidate
+
+ return None
+
+
+def load_swarm_agent_config(
+ *,
+ runtime_root: Path | None = None,
+) -> AgentConfig:
+ """Load the swarm-side AgentConfig using the M3 boot resolution order.
+
+ This is the helper boot wiring (``mcp_server.py``, ``api_server.py``, CLI
+ swarm runners, in-process ``swarm_tool``) calls before constructing
+ ``SwarmRuntime``. It returns an :class:`AgentConfig` (never ``None``) so
+ every caller can pass the result through to ``SwarmRuntime(agent_config=...)``
+ without conditional unwrapping. An empty config (``mcp_servers={}``) is
+ treated identically to ``agent_config=None`` by ``build_swarm_registry``,
+ so the swarm stays strictly local-tool-only when nothing is configured.
+
+ Args:
+ runtime_root: Override the directory the on-disk lookup uses. Defaults
+ to ``~/.vibe-trading``.
+
+ Returns:
+ The validated swarm agent config, or an empty :class:`AgentConfig`
+ when no candidate is on disk / the chosen file fails to parse.
+ """
+ path = _resolve_swarm_agent_config_path(runtime_root=runtime_root)
+ if path is None:
+ return AgentConfig()
+ return load_agent_config(path)
+
+
def _read_config_file(path: Path) -> dict[str, Any]:
"""Read a supported config file format into a dictionary.
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.py
index dee51e9bb..c91910378 100644
--- a/agent/src/swarm/runtime.py
+++ b/agent/src/swarm/runtime.py
@@ -20,6 +20,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Callable
+from src.config.schema import AgentConfig
from src.swarm import grounding
from src.swarm.models import (
RunStatus,
@@ -56,15 +57,27 @@ class SwarmRuntime:
_max_workers: Maximum concurrent workers in ThreadPoolExecutor.
"""
- def __init__(self, store: SwarmStore, max_workers: int = 4) -> None:
+ def __init__(
+ self,
+ store: SwarmStore,
+ max_workers: int = 4,
+ agent_config: AgentConfig | None = None,
+ ) -> None:
"""Initialize SwarmRuntime.
Args:
store: SwarmStore instance for run persistence.
max_workers: Maximum concurrent worker threads.
+ agent_config: Optional resolved agent config carrying remote MCP
+ server definitions. Boot-time / operator-trusted; never derived
+ from a swarm caller. Forwarded to every worker on every run so
+ the worker can assemble a registry that includes remote MCP
+ tools. ``None`` (the default) preserves the current
+ local-tool-only behavior byte-for-byte.
"""
self._store = store
self._max_workers = max_workers
+ self._agent_config = agent_config
self._cancel_events: dict[str, threading.Event] = {}
self._live_callbacks: dict[str, Callable] = {}
self._lock = threading.Lock()
@@ -687,6 +700,7 @@ class SwarmRuntime:
event_callback=event_callback,
include_shell_tools=include_shell_tools,
grounding_block=grounding_block,
+ agent_config=self._agent_config,
)
cumulative_input_tokens += result.input_tokens
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 629c15e07..cf8777091 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -12,11 +12,13 @@ import os
import time
from datetime import datetime, timezone
from pathlib import Path
-from typing import Callable
+from typing import Any, Callable
from src.agent.context import ContextBuilder
from src.agent.progress import HeartbeatTimer
from src.agent.skills import SkillsLoader
+from src.agent.tools import ToolRegistry
+from src.config.schema import AgentConfig
from src.providers.chat import ChatLLM
from src.swarm.models import (
SwarmAgentSpec,
@@ -24,7 +26,8 @@ from src.swarm.models import (
SwarmTask,
WorkerResult,
)
-from src.tools import build_filtered_registry
+from src.tools import build_swarm_registry
+from src.tools.mcp import MCPRemoteTool
logger = logging.getLogger(__name__)
@@ -275,6 +278,7 @@ def run_worker(
event_callback: Callable[[SwarmEvent], None] | None = None,
include_shell_tools: bool = False,
grounding_block: str = "",
+ agent_config: AgentConfig | None = None,
) -> WorkerResult:
"""Execute a single worker task using a lightweight ReAct loop.
@@ -298,6 +302,11 @@ def run_worker(
grounding_block: Optional pre-rendered "Ground Truth" markdown that
anchors the worker on real recent prices for symbols mentioned in
``user_vars``. Forwarded verbatim to :func:`build_worker_prompt`.
+ agent_config: Optional resolved agent config carrying remote MCP
+ server definitions. Threaded from :class:`SwarmRuntime` and
+ consumed by :func:`build_swarm_registry` to merge remote MCP
+ tools with the local-tool pool before applying the agent's
+ whitelist. ``None`` preserves the prior local-only behavior.
Returns:
WorkerResult with status, summary, artifacts, and iteration count.
@@ -309,11 +318,13 @@ def run_worker(
_emit(event_callback, "worker_started", agent_id, task_id)
- # 1. Build filtered tool registry
- # TODO(v1): Swarm stays local-tool-only. Do not thread MCP config into this
- # path until swarm-specific config propagation and execution constraints are
- # designed explicitly.
- registry = build_filtered_registry(agent_spec.tools, include_shell_tools=include_shell_tools)
+ # 1. Build per-worker tool registry — local pool plus any operator-
+ # surfaced MCP tools, projected onto the agent's whitelist.
+ registry = build_swarm_registry(
+ agent_spec.tools,
+ agent_config=agent_config,
+ include_shell_tools=include_shell_tools,
+ )
# 2. Create LLM
llm = ChatLLM(model_name=agent_spec.model_name)
@@ -528,10 +539,12 @@ def run_worker(
# Execute each tool call — inject run_dir so tools write inside artifact_dir
for tc in response.tool_calls:
+ mcp_meta = _remote_tool_metadata(registry, tc.name)
_emit(
event_callback, "tool_call", agent_id, task_id,
{"tool": tc.name, "iteration": iteration,
- "arguments": _preview_tool_arguments(tc.arguments)},
+ "arguments": _preview_tool_arguments(tc.arguments),
+ **mcp_meta},
)
tc_start = time.monotonic()
args = {**tc.arguments, "run_dir": str(artifact_dir)}
@@ -562,7 +575,8 @@ def run_worker(
event_callback, "tool_result", agent_id, task_id,
{"tool": tc.name, "elapsed_ms": int(tc_elapsed * 1000),
"status": "ok", "iteration": iteration,
- "result_preview": str(result)[:200]},
+ "result_preview": _preview_tool_result(result),
+ **mcp_meta},
)
messages.append(
ContextBuilder.format_tool_result(tc.id, tc.name, result[:10_000])
@@ -614,6 +628,25 @@ def _best_summary(messages: list[dict], fallback: str) -> str:
return fallback
+def _remote_tool_metadata(registry: ToolRegistry, tool_name: str) -> dict[str, str]:
+ """Return MCP routing metadata for ``tool_name`` if it's a remote MCP tool.
+
+ Auditors of ``events.jsonl`` need to tell at a glance which remote MCP
+ server a swarm worker reached and what the *original* (non-prefixed)
+ tool name was. The local-side name is already in ``data["tool"]``; this
+ helper supplies the missing ``server`` + ``remote_tool`` pair when the
+ registered tool is an :class:`MCPRemoteTool`. Local-only tools yield
+ an empty dict so the event payload is unchanged for them.
+ """
+ tool = registry.get(tool_name)
+ if not isinstance(tool, MCPRemoteTool):
+ return {}
+ spec = getattr(tool, "_spec", None)
+ if spec is None:
+ return {}
+ return {"server": spec.server_name, "remote_tool": spec.remote_name}
+
+
def _preview_tool_arguments(arguments: dict) -> dict[str, str]:
"""Return a short, redacted argument preview for streamed events."""
preview: dict[str, str] = {}
@@ -623,11 +656,40 @@ def _preview_tool_arguments(arguments: dict) -> dict[str, str]:
if _is_sensitive_tool_argument(key):
preview[key] = "[redacted]"
continue
- text = str(value)
- preview[key] = text if len(text) <= 200 else text[:200] + "..."
+ preview[key] = _truncate_preview(_redact_preview_payload(value))
return preview
+def _preview_tool_result(result: str) -> str:
+ """Return a short, redacted result preview for streamed events."""
+ try:
+ parsed = json.loads(result)
+ except (TypeError, ValueError):
+ return _truncate_preview(result)
+ return _truncate_preview(_redact_preview_payload(parsed))
+
+
+def _redact_preview_payload(value: Any) -> Any:
+ """Recursively redact sensitive keys before event preview stringification."""
+ if isinstance(value, dict):
+ return {
+ key: "[redacted]" if _is_sensitive_tool_argument(str(key)) else _redact_preview_payload(item)
+ for key, item in value.items()
+ }
+ if isinstance(value, list):
+ return [_redact_preview_payload(item) for item in value]
+ return value
+
+
+def _truncate_preview(value: Any, *, limit: int = 200) -> str:
+ """Stringify and truncate an event preview payload."""
+ if isinstance(value, (dict, list)):
+ text = json.dumps(value, ensure_ascii=False, default=str)
+ else:
+ text = str(value)
+ return text if len(text) <= limit else text[:limit] + "..."
+
+
def _is_sensitive_tool_argument(key: str) -> bool:
"""Return whether a tool argument name should be redacted in events."""
normalized = key.strip().lower()
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index 0b3342723..5d5d8a8ff 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import importlib
import logging
import pkgutil
+from collections.abc import Mapping
from collections import deque
from pathlib import Path
from typing import TYPE_CHECKING, Callable
@@ -70,6 +71,7 @@ def build_registry(
session_id: str | None = None,
event_callback: Callable[[str, dict], None] | None = None,
warn_callback: Callable[[str], None] | None = None,
+ _mcp_server_tool_name_segments: Mapping[str, str] | None = None,
) -> ToolRegistry:
"""Build the tool registry via auto-discovery, optionally enriched with MCP tools.
@@ -142,10 +144,16 @@ def build_registry(
if agent_config and agent_config.mcp_servers:
from src.tools.mcp import build_mcp_tool_wrappers, resolve_mcp_server_tool_name_segments
- local_server_names = resolve_mcp_server_tool_name_segments(
- agent_config.mcp_servers.keys(),
- warn_callback=warn_callback,
- )
+ if _mcp_server_tool_name_segments is None:
+ local_server_names = resolve_mcp_server_tool_name_segments(
+ agent_config.mcp_servers.keys(),
+ warn_callback=warn_callback,
+ )
+ else:
+ local_server_names = {
+ server_name: _mcp_server_tool_name_segments[server_name]
+ for server_name in agent_config.mcp_servers
+ }
for server_name, server_config in agent_config.mcp_servers.items():
try:
@@ -173,10 +181,10 @@ def build_registry(
def build_filtered_registry(tool_names: list[str], *, include_shell_tools: bool = False) -> ToolRegistry:
"""Build a ToolRegistry with only specified tools.
- TODO(v1): Keep this path local-only for now. Swarm workers currently use
- filtered registries, and v1 MCP support does not propagate agent_config
- into swarm execution until a separate design pass defines how remote MCP
- tools should be configured and constrained there.
+ Local-tools-only filtered builder. Swarm workers should call
+ :func:`build_swarm_registry` instead so they can opt into remote MCP
+ tools when the operator has configured them. This function is preserved
+ for callers that explicitly want the local-only path.
Args:
tool_names: Tool names to include.
@@ -186,6 +194,91 @@ def build_filtered_registry(tool_names: list[str], *, include_shell_tools: bool
ToolRegistry containing only the requested tools.
"""
full = build_registry(include_shell_tools=include_shell_tools)
+ return _filter_registry(full, tool_names, include_shell_tools=include_shell_tools)
+
+
+def build_swarm_registry(
+ tool_names: list[str],
+ *,
+ agent_config: "AgentConfig | None" = None,
+ include_shell_tools: bool = False,
+) -> ToolRegistry:
+ """Build a per-worker registry that merges local + remote MCP tools.
+
+ Swarm workers receive a strict whitelist (``agent_spec.tools``). This
+ builder honors that whitelist while letting operator-configured MCP
+ servers contribute additional tools by name (``mcp_<server>_<tool>``).
+ Tools the whitelist requests but the operator has NOT surfaced — either
+ because ``agent_config`` is ``None``, the named MCP server is absent, or
+ the server's ``enabled_tools`` allowlist excluded it — are dropped with
+ an operator-facing warning instead of failing the worker.
+
+ Trust model: ``agent_config`` is resolved at server boot from a static
+ file or env var; callers of swarm entry points (e.g. an external MCP
+ client driving ``mcp_server.py::run_swarm``) cannot inject MCP server
+ URLs through this path.
+
+ Args:
+ tool_names: Per-agent tool whitelist from the preset.
+ agent_config: Optional resolved agent config. When provided, remote
+ MCP wrappers are appended to the candidate pool before filtering.
+ Pass ``None`` to keep the worker strictly local.
+ include_shell_tools: Whether shell-execution tools are eligible.
+
+ Returns:
+ ToolRegistry containing the whitelist intersection of local tools
+ and any operator-surfaced MCP tools.
+ """
+ swarm_agent_config, swarm_local_server_names = _prune_agent_config_for_swarm_tools(
+ agent_config,
+ tool_names,
+ )
+ full = build_registry(
+ agent_config=swarm_agent_config,
+ include_shell_tools=include_shell_tools,
+ _mcp_server_tool_name_segments=swarm_local_server_names,
+ )
+ return _filter_registry(full, tool_names, include_shell_tools=include_shell_tools)
+
+
+def _prune_agent_config_for_swarm_tools(
+ agent_config: "AgentConfig | None",
+ tool_names: list[str],
+) -> tuple["AgentConfig | None", dict[str, str] | None]:
+ """Keep only MCP servers whose local tool prefix appears in ``tool_names``."""
+ if not agent_config or not agent_config.mcp_servers:
+ return agent_config, None
+
+ requested_mcp_tool_names = [name for name in tool_names if name.startswith("mcp_")]
+ if not requested_mcp_tool_names:
+ return None, None
+
+ from src.config.schema import AgentConfig
+ from src.tools.mcp import resolve_mcp_server_tool_name_segments
+
+ local_server_names = resolve_mcp_server_tool_name_segments(agent_config.mcp_servers.keys())
+ selected_servers = {
+ server_name: server_config
+ for server_name, server_config in agent_config.mcp_servers.items()
+ if any(
+ tool_name.startswith(f"mcp_{local_server_names[server_name]}_")
+ for tool_name in requested_mcp_tool_names
+ )
+ }
+ selected_local_server_names = {
+ server_name: local_server_names[server_name]
+ for server_name in selected_servers
+ }
+ return AgentConfig(mcp_servers=selected_servers), selected_local_server_names
+
+
+def _filter_registry(
+ full: ToolRegistry,
+ tool_names: list[str],
+ *,
+ include_shell_tools: bool,
+) -> ToolRegistry:
+ """Project a full registry down to a whitelist with consistent drop logging."""
filtered = ToolRegistry()
for name in tool_names:
tool = full.get(name)
@@ -201,4 +294,4 @@ def build_filtered_registry(tool_names: list[str], *, include_shell_tools: bool
return filtered
-__all__ = ["build_registry", "build_filtered_registry"]
+__all__ = ["build_registry", "build_filtered_registry", "build_swarm_registry"]
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index 642138c05..df7ae69ac 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -621,13 +621,22 @@ class SwarmTool(BaseTool):
prompt[:100],
)
+ from src.config import load_swarm_agent_config
from src.swarm.runtime import SwarmRuntime
from src.swarm.store import SwarmStore
swarm_base_dir = Path(__file__).resolve().parents[2] / ".swarm" / "runs"
swarm_base_dir.mkdir(parents=True, exist_ok=True)
store = SwarmStore(base_dir=swarm_base_dir)
- runtime = SwarmRuntime(store=store, max_workers=int(os.getenv("SWARM_MAX_WORKERS", "4")))
+ # Boot-time / operator-trusted: even when reached via the in-process
+ # agent tool, the config path is resolved from disk / env, never from
+ # the calling LLM's prompt (R-06).
+ agent_config = load_swarm_agent_config()
+ runtime = SwarmRuntime(
+ store=store,
+ max_workers=int(os.getenv("SWARM_MAX_WORKERS", "4")),
+ agent_config=agent_config,
+ )
try:
run = runtime.start_run(
diff --git a/agent/tests/test_swarm_m1_config_plumbing.py b/agent/tests/test_swarm_m1_config_plumbing.py
new file mode 100644
index 000000000..8757cf9c2
--- /dev/null
+++ b/agent/tests/test_swarm_m1_config_plumbing.py
@@ -0,0 +1,187 @@
+"""M1 — SWARM external MCP tools: config plumbing regression tests.
+
+Covers requirements R-03, R-05, R-09 and tests T-01, T-02, T-03 in
+``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M1 lands the parameter wiring
+*only* — no remote tool registry assembly, no boot-time loading. Those land
+in M2 / M3 and bring their own tests. The contract this file defends:
+
+ * ``SwarmRuntime`` accepts an optional ``agent_config``.
+ * ``agent_config=None`` keeps the existing local-tool-only behavior
+ byte-for-byte (no construction surprises, no run-time surprises).
+ * When set, the same value reaches ``run_worker`` on every worker call.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import patch
+
+from src.config.schema import AgentConfig, MCPServerConfig
+from src.swarm.models import SwarmAgentSpec, SwarmTask, WorkerResult, WorkerStatus
+from src.swarm.runtime import SwarmRuntime
+from src.swarm.store import SwarmStore
+
+
+def _make_runtime(tmp_path: Path, **kwargs) -> SwarmRuntime:
+ """Build a SwarmRuntime backed by a tmp-path SwarmStore."""
+ store = SwarmStore(base_dir=tmp_path / "swarm_runs")
+ return SwarmRuntime(store=store, **kwargs)
+
+
+def _make_agent_spec() -> SwarmAgentSpec:
+ """Build a minimal SwarmAgentSpec for direct worker invocation."""
+ return SwarmAgentSpec(
+ id="test_agent",
+ role="Test analyst",
+ system_prompt="You are a test agent.",
+ tools=["read_file"],
+ skills=[],
+ max_iterations=1,
+ timeout_seconds=5,
+ max_retries=0,
+ )
+
+
+def _make_task() -> SwarmTask:
+ """Build a minimal SwarmTask bound to ``test_agent``."""
+ return SwarmTask(
+ id="task-1",
+ agent_id="test_agent",
+ prompt_template="trivial prompt",
+ )
+
+
+# --------------------------------------------------------------------------- #
+# T-01 — backwards-compatible default (R-03, R-05)
+# --------------------------------------------------------------------------- #
+
+
+def test_runtime_default_construction_keeps_agent_config_none(tmp_path: Path) -> None:
+ """Default construction (no kwarg) leaves ``_agent_config`` at None.
+
+ Existing callers (``api_server.py``, ``cli/_legacy.py``,
+ ``mcp_server.py``, ``swarm_tool.py``) construct ``SwarmRuntime`` without
+ the new kwarg. None of them should change behavior in M1.
+ """
+ runtime = _make_runtime(tmp_path)
+ assert runtime._agent_config is None
+
+
+def test_runtime_explicit_none_construction_is_identical(tmp_path: Path) -> None:
+ """Passing ``agent_config=None`` explicitly is equivalent to omitting it."""
+ runtime = _make_runtime(tmp_path, agent_config=None)
+ assert runtime._agent_config is None
+
+
+# --------------------------------------------------------------------------- #
+# T-02 — forwarding into run_worker (R-05)
+# --------------------------------------------------------------------------- #
+
+
+def test_run_worker_receives_agent_config_from_runtime(tmp_path: Path) -> None:
+ """``_run_worker_with_retries`` forwards ``self._agent_config`` to ``run_worker``.
+
+ This is the load-bearing M1 contract: any future M2 registry assembly that
+ reads ``agent_config`` from inside ``run_worker`` can rely on the value
+ actually reaching it.
+ """
+ sentinel_config = AgentConfig(
+ mcp_servers={
+ "internal_kb": MCPServerConfig(
+ type="stdio",
+ command="/usr/bin/true",
+ enabled_tools=["search"],
+ )
+ }
+ )
+
+ runtime = _make_runtime(tmp_path, agent_config=sentinel_config)
+ agent_spec = _make_agent_spec()
+ task = _make_task()
+ run_dir = tmp_path / "run-x"
+ run_dir.mkdir()
+
+ fake_result = WorkerResult(status=WorkerStatus.completed, summary="ok")
+
+ with patch("src.swarm.runtime.run_worker", return_value=fake_result) as spy:
+ result = runtime._run_worker_with_retries(
+ agent_spec=agent_spec,
+ task=task,
+ upstream_summaries={},
+ user_vars={},
+ run_dir=run_dir,
+ event_callback=None,
+ run_id="run-x",
+ include_shell_tools=False,
+ grounding_block="",
+ )
+
+ assert result.status == WorkerStatus.completed
+ spy.assert_called_once()
+ assert spy.call_args.kwargs["agent_config"] is sentinel_config
+
+
+def test_run_worker_receives_none_when_runtime_has_no_agent_config(
+ tmp_path: Path,
+) -> None:
+ """Default construction forwards ``agent_config=None`` to ``run_worker``.
+
+ Guarantees that today's behavior (local tools only, no MCP plumbing) is
+ preserved when the operator hasn't opted in. Pairs with M5 trust-model
+ regressions: a caller cannot silently flip this on.
+ """
+ runtime = _make_runtime(tmp_path) # no agent_config kwarg
+ agent_spec = _make_agent_spec()
+ task = _make_task()
+ run_dir = tmp_path / "run-y"
+ run_dir.mkdir()
+
+ fake_result = WorkerResult(status=WorkerStatus.completed, summary="ok")
+
+ with patch("src.swarm.runtime.run_worker", return_value=fake_result) as spy:
+ runtime._run_worker_with_retries(
+ agent_spec=agent_spec,
+ task=task,
+ upstream_summaries={},
+ user_vars={},
+ run_dir=run_dir,
+ event_callback=None,
+ run_id="run-y",
+ include_shell_tools=False,
+ grounding_block="",
+ )
+
+ assert spy.call_args.kwargs["agent_config"] is None
+
+
+# --------------------------------------------------------------------------- #
+# T-03 — lazy discovery: construction with non-None config never crashes
+# even when the configured MCP server would fail to spawn (R-05, R-09)
+# --------------------------------------------------------------------------- #
+
+
+def test_runtime_construction_with_unreachable_mcp_server_does_not_raise(
+ tmp_path: Path,
+) -> None:
+ """A misconfigured MCP server must not break ``SwarmRuntime`` construction.
+
+ Discovery of remote tools is M2's job and must stay lazy: a typo in an
+ MCP server command should surface only when that server's tools are
+ actually invoked, not at runtime construction time. M1 simply stores the
+ config; it must not touch it. This test pins that invariant before M2
+ introduces real discovery.
+ """
+ cfg = AgentConfig(
+ mcp_servers={
+ "definitely_does_not_exist": MCPServerConfig(
+ type="stdio",
+ command="/path/that/does/not/exist/mcp_server",
+ args=["--no-such-flag"],
+ enabled_tools=["*"],
+ )
+ }
+ )
+
+ runtime = _make_runtime(tmp_path, agent_config=cfg)
+ assert runtime._agent_config is cfg
+ assert "definitely_does_not_exist" in runtime._agent_config.mcp_servers
diff --git a/agent/tests/test_swarm_m2_registry_assembly.py b/agent/tests/test_swarm_m2_registry_assembly.py
new file mode 100644
index 000000000..4754a333f
--- /dev/null
+++ b/agent/tests/test_swarm_m2_registry_assembly.py
@@ -0,0 +1,286 @@
+"""M2 — SWARM external MCP tools: registry assembly regression tests.
+
+Covers requirements R-01, R-02, R-03 and tests T-04, T-05, T-06, T-07 in
+``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M2 introduces
+``build_swarm_registry`` — the per-worker registry-builder that merges local
+tools with remote MCP wrappers from ``agent_config.mcp_servers`` and then
+filters the result through the agent's ``tools:`` whitelist.
+
+The contract this file defends:
+
+ * Local tools listed in the agent whitelist are still resolved as before.
+ * Remote MCP tools listed in the whitelist AND surfaced by the boot allowlist
+ are wrapped and returned.
+ * Remote MCP tools listed in the whitelist but NOT surfaced (server missing,
+ ``enabled_tools`` doesn't permit them, or no ``agent_config``) are dropped
+ with an operator-facing warning instead of crashing the worker.
+ * Remote tools surfaced by the server but NOT in the whitelist are filtered
+ out — defense-in-depth on top of the per-server ``enabled_tools``.
+
+Tests follow the existing fake-wrappers pattern from
+``tests/test_registry_mcp_integration.py`` (patch ``src.tools.mcp.build_mcp_tool_wrappers``)
+so we exercise the real ``build_registry`` merge logic without reaching for a
+network. The MCP wire protocol stays untouched — we only mock the wrapper
+builder, not the adapter or transport.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+from src.config.schema import AgentConfig
+from src.tools import build_swarm_registry
+from src.tools.mcp import MCPRemoteTool, resolve_mcp_server_tool_name_segments
+
+
+def _make_agent_config(servers: dict[str, dict[str, Any]]) -> AgentConfig:
+ """Build an AgentConfig from a server-name → config-dict map."""
+ return AgentConfig.model_validate(
+ {"mcpServers": {name: cfg for name, cfg in servers.items()}}
+ )
+
+
+def _make_fake_wrappers(server_name: str, tool_names: list[str]) -> list[MCPRemoteTool]:
+ """Build lightweight ``MCPRemoteTool`` stubs without a live adapter.
+
+ Mirrors the helper in ``tests/test_registry_mcp_integration.py`` so M2
+ tests behave exactly like the existing main-path MCP regressions.
+ """
+ wrappers: list[MCPRemoteTool] = []
+ for tname in tool_names:
+ stub = MagicMock(spec=MCPRemoteTool)
+ stub.name = f"mcp_{server_name}_{tname}"
+ stub.description = f"Remote {tname}"
+ stub.parameters = {"type": "object", "properties": {}, "required": []}
+ stub.is_readonly = False
+ wrappers.append(stub)
+ return wrappers # type: ignore[return-value]
+
+
+# --------------------------------------------------------------------------- #
+# T-04 — happy path: local + remote MCP tool both reachable (R-01)
+# --------------------------------------------------------------------------- #
+
+
+def test_build_swarm_registry_includes_local_and_remote_tools_when_both_whitelisted() -> None:
+ """An agent whitelist containing one local and one remote tool yields both.
+
+ The swarm whitelist should be the *only* gate on tool exposure. When the
+ boot ``agent_config`` surfaces ``mcp_kb_search`` and the agent's
+ ``tools:`` list also names it, both ``read_file`` (local) and
+ ``mcp_kb_search`` (remote) must be on the resulting registry. This is the
+ primary R-01 contract.
+ """
+ fake_wrappers = _make_fake_wrappers("kb", ["search"])
+ cfg = _make_agent_config({"kb": {"command": "uvx", "args": ["kb-server"]}})
+
+ with patch("src.tools.mcp.build_mcp_tool_wrappers", return_value=fake_wrappers):
+ registry = build_swarm_registry(
+ ["read_file", "mcp_kb_search"],
+ agent_config=cfg,
+ )
+
+ names = registry.tool_names
+ assert "read_file" in names
+ assert "mcp_kb_search" in names
+ assert len(names) == 2
+
+
+# --------------------------------------------------------------------------- #
+# T-05 — server-side enabled_tools narrows what the whitelist can reach (R-02)
+# --------------------------------------------------------------------------- #
+
+
+def test_build_swarm_registry_drops_whitelisted_tool_when_server_excludes_it(
+ caplog,
+) -> None:
+ """An ``enabled_tools`` allowlist still wins over a permissive whitelist.
+
+ Operators express trust at boot time (``enabled_tools`` on the server
+ config). Even if a preset author writes ``mcp_kb_search`` into an agent's
+ whitelist, the boot allowlist may only have surfaced ``mcp_kb_fetch`` —
+ in which case the worker must run without ``search`` and surface a clear
+ operator-facing log line. Crashing or silently exposing a tool the
+ operator did not bless are both unacceptable outcomes.
+ """
+ fake_wrappers = _make_fake_wrappers("kb", ["fetch"])
+ cfg = _make_agent_config(
+ {
+ "kb": {
+ "command": "uvx",
+ "args": ["kb-server"],
+ "enabledTools": ["fetch"],
+ }
+ }
+ )
+
+ with patch("src.tools.mcp.build_mcp_tool_wrappers", return_value=fake_wrappers):
+ with caplog.at_level(logging.WARNING):
+ registry = build_swarm_registry(
+ ["mcp_kb_search"],
+ agent_config=cfg,
+ )
+
+ assert "mcp_kb_search" not in registry.tool_names
+ assert registry.tool_names == []
+ assert any(
+ "mcp_kb_search" in record.message and "unavailable" in record.message
+ for record in caplog.records
+ ), "Expected operator-facing 'unavailable' warning for dropped MCP tool"
+
+
+# --------------------------------------------------------------------------- #
+# T-06 — no agent_config → MCP-named whitelist entries drop cleanly (R-02, R-03)
+# --------------------------------------------------------------------------- #
+
+
+def test_build_swarm_registry_without_agent_config_drops_mcp_tools(caplog) -> None:
+ """``agent_config=None`` keeps swarm strictly local-tool-only.
+
+ Today's behavior must continue to hold when no operator config is wired
+ in. A preset that *requests* an ``mcp_*`` tool stays loadable, but the
+ actual tool is absent from the registry and a warning is logged so the
+ operator can see why.
+ """
+ with caplog.at_level(logging.WARNING):
+ registry = build_swarm_registry(
+ ["mcp_kb_search"],
+ agent_config=None,
+ )
+
+ assert "mcp_kb_search" not in registry.tool_names
+ assert registry.tool_names == []
+ assert any(
+ "mcp_kb_search" in record.message and "unavailable" in record.message
+ for record in caplog.records
+ )
+
+
+# --------------------------------------------------------------------------- #
+# T-07 — per-agent whitelist filters server tools beyond enabled_tools (S-06)
+# --------------------------------------------------------------------------- #
+
+
+def test_build_swarm_registry_filters_remote_tools_outside_agent_whitelist() -> None:
+ """A remote tool surfaced by the server but absent from the whitelist stays out.
+
+ The server may surface ``mcp_kb_search`` and ``mcp_kb_fetch`` via
+ ``enabled_tools=["*"]``. If a particular agent only whitelists
+ ``mcp_kb_search``, the worker must NOT see ``mcp_kb_fetch``. This is the
+ per-worker whitelist invariant — the same protection we already give
+ local tools, extended to remote ones.
+ """
+ fake_wrappers = _make_fake_wrappers("kb", ["search", "fetch"])
+ cfg = _make_agent_config(
+ {
+ "kb": {
+ "command": "uvx",
+ "args": ["kb-server"],
+ "enabledTools": ["*"],
+ }
+ }
+ )
+
+ with patch("src.tools.mcp.build_mcp_tool_wrappers", return_value=fake_wrappers):
+ registry = build_swarm_registry(
+ ["mcp_kb_search"],
+ agent_config=cfg,
+ )
+
+ assert "mcp_kb_search" in registry.tool_names
+ assert "mcp_kb_fetch" not in registry.tool_names
+
+
+def test_build_swarm_registry_discovers_only_servers_named_by_whitelist() -> None:
+ """Remote discovery is limited to MCP servers implied by the whitelist."""
+ cfg = _make_agent_config(
+ {
+ "kb": {"command": "uvx", "args": ["kb-server"]},
+ "expensive": {"command": "uvx", "args": ["expensive-server"]},
+ }
+ )
+
+ def fake_build_mcp_tool_wrappers(server_name, *_args, **_kwargs):
+ return _make_fake_wrappers(server_name, ["search"])
+
+ with patch(
+ "src.tools.mcp.build_mcp_tool_wrappers",
+ side_effect=fake_build_mcp_tool_wrappers,
+ ) as build_wrappers:
+ registry = build_swarm_registry(
+ ["mcp_kb_search"],
+ agent_config=cfg,
+ )
+
+ assert "mcp_kb_search" in registry.tool_names
+ assert [call.args[0] for call in build_wrappers.call_args_list] == ["kb"]
+
+
+def test_build_swarm_registry_preserves_collision_hash_prefix_after_pruning() -> None:
+ """Pruning keeps full-config MCP collision disambiguation stable."""
+ cfg = _make_agent_config(
+ {
+ "foo-bar": {"command": "uvx", "args": ["foo-bar-server"]},
+ "foo_bar": {"command": "uvx", "args": ["foo-bar-alt-server"]},
+ "expensive": {"command": "uvx", "args": ["expensive-server"]},
+ }
+ )
+ resolved_names = resolve_mcp_server_tool_name_segments(cfg.mcp_servers.keys())
+ requested_tool = f"mcp_{resolved_names['foo-bar']}_ping"
+
+ def fake_build_mcp_tool_wrappers(_server_name, *_args, **kwargs):
+ return _make_fake_wrappers(kwargs["local_server_name"], ["ping"])
+
+ with patch(
+ "src.tools.mcp.build_mcp_tool_wrappers",
+ side_effect=fake_build_mcp_tool_wrappers,
+ ) as build_wrappers:
+ registry = build_swarm_registry(
+ [requested_tool],
+ agent_config=cfg,
+ )
+
+ assert registry.tool_names == [requested_tool]
+ assert [call.args[0] for call in build_wrappers.call_args_list] == ["foo-bar"]
+ assert build_wrappers.call_args.kwargs["local_server_name"] == resolved_names["foo-bar"]
+
+
+def test_build_swarm_registry_skips_mcp_discovery_for_local_only_whitelist() -> None:
+ """A local-only agent whitelist must not discover any configured MCP server."""
+ cfg = _make_agent_config({"kb": {"command": "uvx", "args": ["kb-server"]}})
+
+ with patch("src.tools.mcp.build_mcp_tool_wrappers") as build_wrappers:
+ registry = build_swarm_registry(
+ ["read_file"],
+ agent_config=cfg,
+ )
+
+ assert "read_file" in registry.tool_names
+ build_wrappers.assert_not_called()
+
+
+# --------------------------------------------------------------------------- #
+# Backward compatibility: empty MCP config behaves like None (R-03)
+# --------------------------------------------------------------------------- #
+
+
+def test_build_swarm_registry_with_empty_mcp_servers_is_local_only() -> None:
+ """An ``AgentConfig`` with no servers configured is equivalent to None.
+
+ Operators who keep a swarm-agent.json file but haven't enrolled any MCP
+ servers must see today's behavior: local tools resolve as before; any
+ ``mcp_*`` whitelist entry drops with a warning. No partial discovery, no
+ crash.
+ """
+ cfg = AgentConfig.model_validate({"mcpServers": {}})
+
+ registry = build_swarm_registry(
+ ["read_file"],
+ agent_config=cfg,
+ )
+
+ assert "read_file" in registry.tool_names
+ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_")]
+ assert mcp_names == []
diff --git a/agent/tests/test_swarm_m3_boot_wiring.py b/agent/tests/test_swarm_m3_boot_wiring.py
new file mode 100644
index 000000000..88dd686bb
--- /dev/null
+++ b/agent/tests/test_swarm_m3_boot_wiring.py
@@ -0,0 +1,208 @@
+"""M3 — SWARM external MCP tools: boot wiring & config resolution.
+
+Covers requirements R-09 (lazy boot discovery) and tests T-08, T-09, T-10, T-11
+in ``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M3 introduces the boot-time
+config resolver that lets operators point a swarm-only MCP allowlist at a
+distinct file from the main agent config.
+
+The contract this file defends:
+
+ * ``VIBE_TRADING_SWARM_AGENT_CONFIG`` env var, when set, wins absolutely —
+ even if neighbouring ``swarm-agent.json`` / ``agent.json`` exist on disk.
+ * Without the env var, ``~/.vibe-trading/swarm-agent.json`` (the swarm-
+ specific operator file) is preferred over ``agent.json``.
+ * Without either swarm-specific file, ``~/.vibe-trading/agent.json``
+ (the main-agent config) is reused as a sane default — operators with a
+ single-config setup don't have to duplicate it.
+ * With nothing on disk and no env var, the resolver returns ``None`` so the
+ runtime keeps today's local-only behaviour byte-for-byte (R-03).
+
+Tests use ``tmp_path`` to redirect the runtime root so they never touch the
+real ``~/.vibe-trading`` directory of whoever is running the suite.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from src.config import AgentConfig
+from src.config.loader import (
+ _resolve_swarm_agent_config_path,
+ load_swarm_agent_config,
+)
+
+
+def _write_agent_json(path: Path, server_name: str) -> None:
+ """Write a minimal AgentConfig JSON file pinning a single MCP server.
+
+ The server name is used in assertions to verify *which* file the resolver
+ picked up — that's how we tell ``swarm-agent.json`` apart from
+ ``agent.json`` even when both exist on disk.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ server_name: {"command": "uvx", "args": [f"{server_name}-server"]}
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+# --------------------------------------------------------------------------- #
+# T-08 — env var wins absolutely (S-10)
+# --------------------------------------------------------------------------- #
+
+
+def test_resolve_swarm_agent_config_path_uses_env_var_when_set(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``VIBE_TRADING_SWARM_AGENT_CONFIG`` is the absolute first-priority source.
+
+ An operator who explicitly points the env var at a custom file MUST get
+ that file even if the well-known ``swarm-agent.json`` and ``agent.json``
+ happen to exist alongside. The env var is the override hatch for CI /
+ sandbox deployments where the runtime root is read-only.
+ """
+ runtime_root = tmp_path / "runtime"
+ env_pointed = tmp_path / "external" / "operator-swarm.json"
+ _write_agent_json(env_pointed, "env_pointed")
+ _write_agent_json(runtime_root / "swarm-agent.json", "swarm_specific")
+ _write_agent_json(runtime_root / "agent.json", "main_agent")
+ monkeypatch.setenv("VIBE_TRADING_SWARM_AGENT_CONFIG", str(env_pointed))
+
+ resolved = _resolve_swarm_agent_config_path(runtime_root=runtime_root)
+
+ assert resolved == env_pointed
+
+
+# --------------------------------------------------------------------------- #
+# T-09 — swarm-agent.json beats agent.json when env unset (S-11)
+# --------------------------------------------------------------------------- #
+
+
+def test_resolve_swarm_agent_config_path_prefers_swarm_specific_file(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``swarm-agent.json`` shadows ``agent.json`` when both are present.
+
+ Operators express "I want the swarm path to use a different MCP allowlist
+ from the main agent" by dropping a ``swarm-agent.json`` next to the main
+ config. When that file exists, the main ``agent.json`` is *ignored* for
+ swarm — preventing accidental cross-pollination of allowlists.
+ """
+ monkeypatch.delenv("VIBE_TRADING_SWARM_AGENT_CONFIG", raising=False)
+ runtime_root = tmp_path / "runtime"
+ _write_agent_json(runtime_root / "swarm-agent.json", "swarm_specific")
+ _write_agent_json(runtime_root / "agent.json", "main_agent")
+
+ resolved = _resolve_swarm_agent_config_path(runtime_root=runtime_root)
+
+ assert resolved == runtime_root / "swarm-agent.json"
+
+
+# --------------------------------------------------------------------------- #
+# T-10 — agent.json fallback (S-12)
+# --------------------------------------------------------------------------- #
+
+
+def test_resolve_swarm_agent_config_path_falls_back_to_main_agent_config(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``agent.json`` is reused when no swarm-specific file is provided.
+
+ Single-config operators (the common case during early adoption) shouldn't
+ have to duplicate their MCP allowlist. The resolver gracefully falls back
+ to the main ``agent.json`` so the operator's existing configuration stays
+ the source of truth for both code paths.
+ """
+ monkeypatch.delenv("VIBE_TRADING_SWARM_AGENT_CONFIG", raising=False)
+ runtime_root = tmp_path / "runtime"
+ _write_agent_json(runtime_root / "agent.json", "main_agent")
+
+ resolved = _resolve_swarm_agent_config_path(runtime_root=runtime_root)
+
+ assert resolved == runtime_root / "agent.json"
+
+
+# --------------------------------------------------------------------------- #
+# T-11 — nothing configured → None (S-13, R-03)
+# --------------------------------------------------------------------------- #
+
+
+def test_resolve_swarm_agent_config_path_returns_none_when_nothing_configured(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No env var, no on-disk files → resolver returns ``None``.
+
+ This preserves the byte-for-byte legacy behaviour from R-03: a fresh
+ install with no operator config keeps the swarm strictly local-tool-only.
+ A ``None`` resolution flows through to ``SwarmRuntime(agent_config=None)``
+ which the M1/M2 plumbing already handles.
+ """
+ monkeypatch.delenv("VIBE_TRADING_SWARM_AGENT_CONFIG", raising=False)
+ runtime_root = tmp_path / "runtime"
+ runtime_root.mkdir()
+
+ resolved = _resolve_swarm_agent_config_path(runtime_root=runtime_root)
+
+ assert resolved is None
+
+
+# --------------------------------------------------------------------------- #
+# Integration: load_swarm_agent_config returns AgentConfig at every level
+# --------------------------------------------------------------------------- #
+
+
+def test_load_swarm_agent_config_returns_default_when_unconfigured(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Boot wiring stays safe even with no operator config on disk.
+
+ The boot helpers in ``mcp_server.py`` / ``api_server.py`` / CLI runners
+ call ``load_swarm_agent_config()`` at startup, then forward the result
+ into ``SwarmRuntime(agent_config=...)``. When nothing is configured, the
+ result is an empty ``AgentConfig()`` whose ``mcp_servers`` dict is empty —
+ ``build_swarm_registry`` already treats that case identically to ``None``
+ (verified by the M2 ``test_build_swarm_registry_with_empty_mcp_servers_is_local_only``).
+ """
+ monkeypatch.delenv("VIBE_TRADING_SWARM_AGENT_CONFIG", raising=False)
+ runtime_root = tmp_path / "runtime"
+ runtime_root.mkdir()
+
+ config = load_swarm_agent_config(runtime_root=runtime_root)
+
+ assert isinstance(config, AgentConfig)
+ assert config.mcp_servers == {}
+
+
+def test_load_swarm_agent_config_loads_swarm_specific_file(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """When ``swarm-agent.json`` exists, its servers are validated and loaded.
+
+ End-to-end check that the resolver + loader integrates cleanly: the
+ ``swarm_specific`` server name we pinned in the file is the one that
+ surfaces on the returned ``AgentConfig.mcp_servers`` mapping.
+ """
+ monkeypatch.delenv("VIBE_TRADING_SWARM_AGENT_CONFIG", raising=False)
+ runtime_root = tmp_path / "runtime"
+ _write_agent_json(runtime_root / "swarm-agent.json", "swarm_specific")
+ _write_agent_json(runtime_root / "agent.json", "main_agent")
+
+ config = load_swarm_agent_config(runtime_root=runtime_root)
+
+ assert "swarm_specific" in config.mcp_servers
+ assert "main_agent" not in config.mcp_servers
diff --git a/agent/tests/test_swarm_m4_e2e.py b/agent/tests/test_swarm_m4_e2e.py
new file mode 100644
index 000000000..c98454544
--- /dev/null
+++ b/agent/tests/test_swarm_m4_e2e.py
@@ -0,0 +1,609 @@
+"""M4 — SWARM external MCP tools: end-to-end worker integration tests.
+
+Covers requirements R-04, R-07, R-10 and tests T-12, T-13, T-14, T-15 in
+``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M4 is the milestone that makes
+the contract from M1+M2+M3 *visible to the operator at run time*: a worker
+that calls a remote MCP tool emits ``tool_call`` / ``tool_result`` events
+carrying ``server`` and ``remote_tool`` fields, sensitive arguments stay
+redacted, and a transport failure on one tool call does not crash the
+worker — it surfaces an error envelope to the LLM and execution continues.
+
+Per the TDD's "Test Plan" preface, we **do not** mock the MCP wire
+protocol. Instead we drive a real :class:`MCPServerAdapter` with the
+existing ``_FakeClient``-style factory used in
+``tests/test_mcp_client_adapter.py`` and ``tests/test_registry_mcp_integration.py``.
+That keeps the ``MCPRemoteTool`` wrapper, schema normalization, and
+adapter error path on the hot path. ``ChatLLM`` is the only thing
+stubbed — :func:`run_worker` doesn't need a real LLM to exercise the
+event-emit / tool-execution / report-write contract.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+from unittest.mock import patch
+
+from fastmcp.client.client import CallToolResult
+from mcp import types as mcp_types
+
+from src.config.schema import MCPServerConfig
+from src.providers.chat import LLMResponse, ToolCallRequest
+from src.swarm.models import SwarmAgentSpec, SwarmEvent, SwarmTask
+from src.swarm.worker import run_worker
+from src.tools.mcp import build_mcp_tool_wrappers
+
+
+# --------------------------------------------------------------------------- #
+# Fakes — fake MCP transport + scripted ChatLLM
+# --------------------------------------------------------------------------- #
+
+
+class _FakeMCPClient:
+ """In-process MCP client that satisfies the ``AsyncMCPClient`` protocol.
+
+ Mirrors ``tests/test_mcp_client_adapter.py::_FakeClient`` so we can drop
+ it into a real :class:`MCPServerAdapter` via ``client_factory=`` and
+ exercise the real wrapper without reaching for stdio.
+ """
+
+ def __init__(self, state: dict[str, Any]) -> None:
+ self._state = state
+
+ async def __aenter__(self) -> "_FakeMCPClient":
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb) -> bool | None:
+ return None
+
+ async def list_tools(self) -> list[mcp_types.Tool]:
+ outcome = self._state["list_outcomes"].pop(0)
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any] | None = None,
+ *,
+ timeout: float | int | None = None,
+ raise_on_error: bool = False,
+ ) -> CallToolResult:
+ self._state["call_records"].append(
+ {"name": name, "arguments": arguments or {}, "timeout": timeout}
+ )
+ outcome = self._state["call_outcomes"].pop(0)
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
+
+def _make_state(
+ *,
+ list_outcomes: list,
+ call_outcomes: list,
+) -> dict[str, Any]:
+ return {
+ "list_outcomes": list_outcomes,
+ "call_outcomes": call_outcomes,
+ "call_records": [],
+ }
+
+
+def _make_factory(state: dict[str, Any]):
+ def _factory() -> _FakeMCPClient:
+ return _FakeMCPClient(state)
+
+ return _factory
+
+
+def _make_server_config(*, enabled_tools=None) -> MCPServerConfig:
+ return MCPServerConfig.model_validate(
+ {
+ "command": "uvx",
+ "args": ["fake-server"],
+ "enabledTools": enabled_tools or ["*"],
+ "toolTimeout": 7,
+ }
+ )
+
+
+def _ok_call_result(payload: dict[str, Any]) -> CallToolResult:
+ """Build a CallToolResult that mimics a successful remote call.
+
+ The adapter's normalizer copies ``data`` / ``structured_content`` /
+ text content into the JSON envelope returned to the agent loop. We
+ populate ``data`` so the caller can read it back as ``payload["data"]``.
+ """
+ return CallToolResult(content=[], structured_content=payload, meta=None, data=payload)
+
+
+class _StubChatLLM:
+ """Scripted replacement for :class:`ChatLLM`.
+
+ Each ``stream_chat`` call returns the next item from ``responses`` so
+ a test can drive the worker through a precise tool-call sequence.
+ """
+
+ def __init__(self, responses: list[LLMResponse]) -> None:
+ self._responses = list(responses)
+ self.tool_defs_seen: list[list[dict] | None] = []
+
+ def __call__(self, *args, **kwargs): # pragma: no cover — supports ChatLLM(model_name=...)
+ return self
+
+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):
+ self.tool_defs_seen.append(tools)
+ if not self._responses:
+ return LLMResponse(content="(stub exhausted)", finish_reason="stop")
+ return self._responses.pop(0)
+
+ def chat(self, messages, tools=None, timeout=None): # pragma: no cover — fallback path
+ return self.stream_chat(messages, tools=tools)
+
+
+def _stub_llm_factory(responses: list[LLMResponse]):
+ """Build a callable that reads as ``ChatLLM(model_name=...)`` would.
+
+ The worker does ``llm = ChatLLM(model_name=...)`` once per run; we
+ swap that constructor with a callable returning a single shared
+ stub so the test can introspect the recorded ``tool_defs_seen``.
+ """
+ stub = _StubChatLLM(responses)
+
+ def _factory(model_name=None):
+ return stub
+
+ _factory.stub = stub # type: ignore[attr-defined]
+ return _factory
+
+
+# --------------------------------------------------------------------------- #
+# Builders — agent specs, tasks, single-call response sequences
+# --------------------------------------------------------------------------- #
+
+
+def _agent_spec(
+ *,
+ agent_id: str,
+ tools: list[str],
+ max_iterations: int = 4,
+) -> SwarmAgentSpec:
+ return SwarmAgentSpec(
+ id=agent_id,
+ role="Test analyst",
+ system_prompt="You analyse markets.",
+ tools=tools,
+ skills=[],
+ max_iterations=max_iterations,
+ timeout_seconds=60,
+ )
+
+
+def _task(*, task_id: str, agent_id: str, prompt: str = "Run the tool.") -> SwarmTask:
+ return SwarmTask(id=task_id, agent_id=agent_id, prompt_template=prompt)
+
+
+def _tool_call_response(
+ *,
+ call_id: str,
+ tool: str,
+ arguments: dict[str, Any],
+) -> LLMResponse:
+ return LLMResponse(
+ content=None,
+ tool_calls=[ToolCallRequest(id=call_id, name=tool, arguments=arguments)],
+ finish_reason="tool_calls",
+ )
+
+
+def _final_response(content: str = "Done.") -> LLMResponse:
+ return LLMResponse(content=content, tool_calls=[], finish_reason="stop")
+
+
+# --------------------------------------------------------------------------- #
+# T-12 — happy path: 1 agent / 1 task / 1 fake server.
+# The worker invokes a remote MCP tool, then writes
+# report.md whose body cites the canned remote payload.
+# --------------------------------------------------------------------------- #
+
+
+def test_run_worker_uses_remote_mcp_tool_and_report_cites_canned_data(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A run_worker call against a fake MCP server returns a report.md whose
+ text comes from the remote tool's payload. This is the smallest possible
+ proof that the wiring (M1 plumbing → M2 registry → M4 events) actually
+ routes data from a remote MCP server through the worker into the agent's
+ deliverable. Maps to T-12 and the R-04 audit-trail requirement.
+ """
+ # write_file's path sandbox limits run_dir to a known set of roots.
+ # ``tmp_path`` is a pytest scratch dir outside those defaults; whitelist
+ # it for the duration of this test so the real write_file tool can run.
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))
+
+ canned_payload = {"answer": "Bullish per fake KB", "source": "fake_kb"}
+ state = _make_state(
+ list_outcomes=[[
+ mcp_types.Tool(
+ name="search",
+ description="Knowledge-base search",
+ inputSchema={
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ },
+ )
+ ]],
+ call_outcomes=[_ok_call_result(canned_payload)],
+ )
+ remote_tools = build_mcp_tool_wrappers(
+ "kb",
+ _make_server_config(),
+ client_factory=_make_factory(state),
+ )
+
+ # Simulate two LLM turns: first one calls the remote tool, second writes
+ # report.md using the (real) write_file tool, third returns final text.
+ report_body = (
+ f"# Findings\n\nRemote KB says: {canned_payload['answer']}.\n"
+ )
+ responses = [
+ _tool_call_response(
+ call_id="tc-1",
+ tool="mcp_kb_search",
+ arguments={"query": "AAPL outlook"},
+ ),
+ _tool_call_response(
+ call_id="tc-2",
+ tool="write_file",
+ arguments={"path": "report.md", "content": report_body},
+ ),
+ _final_response("Wrote report.md with KB-cited findings."),
+ ]
+ llm_factory = _stub_llm_factory(responses)
+
+ events: list[SwarmEvent] = []
+
+ with (
+ patch(
+ "src.swarm.worker.build_swarm_registry",
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False: _registry_with_remote(
+ tool_names,
+ remote_tools,
+ include_shell_tools=include_shell_tools,
+ ),
+ ),
+ patch("src.swarm.worker.ChatLLM", llm_factory),
+ ):
+ result = run_worker(
+ agent_spec=_agent_spec(
+ agent_id="kb_analyst",
+ tools=["mcp_kb_search", "write_file"],
+ max_iterations=5,
+ ),
+ task=_task(task_id="t1", agent_id="kb_analyst"),
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=events.append,
+ )
+
+ assert result.status == "completed"
+ report_path = tmp_path / "artifacts" / "kb_analyst" / "report.md"
+ assert report_path.is_file()
+ contents = report_path.read_text(encoding="utf-8")
+ assert canned_payload["answer"] in contents
+ # report.md was the source of truth for the worker's summary.
+ assert canned_payload["answer"] in result.summary
+
+ # The remote MCP server actually got the call — i.e. the registry
+ # wired up a real adapter, not a stub that swallows the args.
+ assert state["call_records"] == [
+ {"name": "search", "arguments": {"query": "AAPL outlook"}, "timeout": 7}
+ ]
+
+
+# --------------------------------------------------------------------------- #
+# T-13 — isolation: two agents each whitelist their own server's tool, and
+# the LLM-visible tool list per agent never leaks the other.
+# --------------------------------------------------------------------------- #
+
+
+def test_two_agents_with_distinct_servers_only_see_their_own_remote_tools(
+ tmp_path: Path,
+) -> None:
+ """Per-agent whitelist isolation persists at the LLM-tools layer.
+
+ When agent A's preset declares ``mcp_alpha_search`` and agent B's
+ declares ``mcp_beta_query``, the worker for A must hand the LLM only
+ A's tools — never B's. We assert this by introspecting the
+ ``tools=`` list captured by the stub LLM on the first iteration.
+ Maps to T-13 / S-02.
+ """
+ alpha_state = _make_state(
+ list_outcomes=[[
+ mcp_types.Tool(name="search", description="Alpha", inputSchema={"type": "object"}),
+ ]],
+ call_outcomes=[_ok_call_result({"alpha": True})],
+ )
+ beta_state = _make_state(
+ list_outcomes=[[
+ mcp_types.Tool(name="query", description="Beta", inputSchema={"type": "object"}),
+ ]],
+ call_outcomes=[_ok_call_result({"beta": True})],
+ )
+
+ alpha_tools = build_mcp_tool_wrappers(
+ "alpha", _make_server_config(), client_factory=_make_factory(alpha_state)
+ )
+ beta_tools = build_mcp_tool_wrappers(
+ "beta", _make_server_config(), client_factory=_make_factory(beta_state)
+ )
+
+ def _run_agent(agent_id: str, whitelist: list[str], remote_tools, tool_call: str):
+ llm_factory = _stub_llm_factory([
+ _tool_call_response(
+ call_id="tc-1", tool=tool_call, arguments={"q": "x"},
+ ),
+ _final_response(),
+ ])
+
+ with (
+ patch(
+ "src.swarm.worker.build_swarm_registry",
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False: _registry_with_remote(
+ tool_names, remote_tools, include_shell_tools=include_shell_tools,
+ ),
+ ),
+ patch("src.swarm.worker.ChatLLM", llm_factory),
+ ):
+ run_worker(
+ agent_spec=_agent_spec(agent_id=agent_id, tools=whitelist),
+ task=_task(task_id=f"task_{agent_id}", agent_id=agent_id),
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=lambda evt: None,
+ )
+ return llm_factory.stub # type: ignore[attr-defined]
+
+ alpha_stub = _run_agent("alpha_agent", ["mcp_alpha_search"], alpha_tools, "mcp_alpha_search")
+ beta_stub = _run_agent("beta_agent", ["mcp_beta_query"], beta_tools, "mcp_beta_query")
+
+ alpha_first_call_tools = _tool_names(alpha_stub.tool_defs_seen[0])
+ beta_first_call_tools = _tool_names(beta_stub.tool_defs_seen[0])
+
+ assert "mcp_alpha_search" in alpha_first_call_tools
+ assert "mcp_beta_query" not in alpha_first_call_tools
+ assert "mcp_beta_query" in beta_first_call_tools
+ assert "mcp_alpha_search" not in beta_first_call_tools
+
+
+# --------------------------------------------------------------------------- #
+# T-14 — events.jsonl carries server/remote_tool fields and redacts secrets.
+# --------------------------------------------------------------------------- #
+
+
+def test_tool_call_events_carry_mcp_metadata_and_redact_sensitive_arguments(
+ tmp_path: Path,
+) -> None:
+ """Auditing :file:`events.jsonl` after a run must show *which remote
+ server* a tool call hit (``server``), the original remote tool name
+ (``remote_tool``), AND it must not leak ``api_key`` / ``token`` /
+ ``password`` argument values into the recorded preview. Maps to
+ R-04 + R-10.
+ """
+ state = _make_state(
+ list_outcomes=[[
+ mcp_types.Tool(
+ name="search",
+ description="Knowledge base",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "query": {"type": "string"},
+ "api_key": {"type": "string"},
+ "token": {"type": "string"},
+ },
+ "required": ["query"],
+ },
+ )
+ ]],
+ call_outcomes=[
+ _ok_call_result(
+ {
+ "hit": "ok",
+ "token": "result-token-should-not-appear",
+ "nested": {"authorization": "Bearer result-secret"},
+ }
+ )
+ ],
+ )
+ remote_tools = build_mcp_tool_wrappers(
+ "kb", _make_server_config(), client_factory=_make_factory(state)
+ )
+
+ responses = [
+ _tool_call_response(
+ call_id="tc-1",
+ tool="mcp_kb_search",
+ arguments={
+ "query": "AAPL",
+ "api_key": "should-not-appear-in-events",
+ "token": "also-secret",
+ "request": {
+ "headers": {"Authorization": "Bearer nested-secret"},
+ "payload": {"password": "nested-password"},
+ },
+ },
+ ),
+ _final_response("done"),
+ ]
+ llm_factory = _stub_llm_factory(responses)
+
+ events: list[SwarmEvent] = []
+
+ with (
+ patch(
+ "src.swarm.worker.build_swarm_registry",
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False: _registry_with_remote(
+ tool_names, remote_tools, include_shell_tools=include_shell_tools,
+ ),
+ ),
+ patch("src.swarm.worker.ChatLLM", llm_factory),
+ ):
+ run_worker(
+ agent_spec=_agent_spec(
+ agent_id="kb_analyst", tools=["mcp_kb_search"], max_iterations=3,
+ ),
+ task=_task(task_id="t1", agent_id="kb_analyst"),
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=events.append,
+ )
+
+ tool_calls = [e for e in events if e.type == "tool_call" and e.data.get("tool") == "mcp_kb_search"]
+ tool_results = [e for e in events if e.type == "tool_result" and e.data.get("tool") == "mcp_kb_search"]
+ assert tool_calls, f"expected an mcp_kb_search tool_call event; got {[e.type for e in events]}"
+ assert tool_results, "expected an mcp_kb_search tool_result event"
+
+ call_data = tool_calls[0].data
+ result_data = tool_results[0].data
+
+ # R-04: server + remote_tool must appear on both events.
+ assert call_data["server"] == "kb"
+ assert call_data["remote_tool"] == "search"
+ assert result_data["server"] == "kb"
+ assert result_data["remote_tool"] == "search"
+
+ # R-10: redaction is applied to known sensitive keys.
+ assert call_data["arguments"]["api_key"] == "[redacted]"
+ assert call_data["arguments"]["token"] == "[redacted]"
+ assert call_data["arguments"]["query"] == "AAPL"
+ assert "nested-secret" not in call_data["arguments"]["request"]
+ assert "nested-password" not in call_data["arguments"]["request"]
+ assert "result-token-should-not-appear" not in result_data["result_preview"]
+ assert "result-secret" not in result_data["result_preview"]
+ # Defense-in-depth: the secret values must never appear anywhere in
+ # the event payload (including via str-coerced views).
+ serialized = json.dumps([e.data for e in events], ensure_ascii=False)
+ assert "should-not-appear-in-events" not in serialized
+ assert "also-secret" not in serialized
+ assert "nested-secret" not in serialized
+ assert "nested-password" not in serialized
+ assert "result-token-should-not-appear" not in serialized
+ assert "result-secret" not in serialized
+
+
+# --------------------------------------------------------------------------- #
+# T-15 — failure mode: a remote tool transport failure must not crash the
+# worker; the LLM sees an error envelope and the worker
+# continues to a clean completion.
+# --------------------------------------------------------------------------- #
+
+
+def test_remote_tool_transport_failure_does_not_crash_worker(tmp_path: Path) -> None:
+ """Per S-07 / R-07, a transport-level failure on a remote MCP call must
+ surface as an error envelope to the LLM (so the LLM can decide whether
+ to retry or fall back) — it must NOT bubble up as an exception that
+ fails the whole worker. The worker continues with the next iteration
+ and ends in a normal completion state.
+ """
+ state = _make_state(
+ list_outcomes=[[
+ mcp_types.Tool(name="search", description="KB", inputSchema={"type": "object"}),
+ ]],
+ call_outcomes=[TimeoutError("simulated remote stall")],
+ )
+ remote_tools = build_mcp_tool_wrappers(
+ "kb", _make_server_config(), client_factory=_make_factory(state)
+ )
+
+ responses = [
+ _tool_call_response(
+ call_id="tc-1", tool="mcp_kb_search", arguments={"query": "x"},
+ ),
+ _final_response("Tool call failed; falling back to qualitative analysis."),
+ ]
+ llm_factory = _stub_llm_factory(responses)
+
+ events: list[SwarmEvent] = []
+
+ with (
+ patch(
+ "src.swarm.worker.build_swarm_registry",
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False: _registry_with_remote(
+ tool_names, remote_tools, include_shell_tools=include_shell_tools,
+ ),
+ ),
+ patch("src.swarm.worker.ChatLLM", llm_factory),
+ ):
+ result = run_worker(
+ agent_spec=_agent_spec(
+ agent_id="kb_analyst", tools=["mcp_kb_search"], max_iterations=3,
+ ),
+ task=_task(task_id="t1", agent_id="kb_analyst"),
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=events.append,
+ )
+
+ # The worker did NOT crash; it returned a status that lets the
+ # runtime decide whether to mark the task complete or retry.
+ assert result.status in {"completed", "incomplete"}
+ # The fake adapter actually saw the call (we routed through the real
+ # MCPRemoteTool wrapper, not a stubbed-out path that swallows it).
+ assert state["call_records"] and state["call_records"][0]["name"] == "search"
+
+ # The LLM observed the error envelope on its second turn so it could
+ # decide what to do next. ``stream_chat`` was called twice: once to
+ # produce the tool call and once to produce the final text.
+ assert len(llm_factory.stub.tool_defs_seen) >= 2 # type: ignore[attr-defined]
+
+
+# --------------------------------------------------------------------------- #
+# Helpers
+# --------------------------------------------------------------------------- #
+
+
+def _registry_with_remote(
+ tool_names: list[str],
+ remote_tools,
+ *,
+ include_shell_tools: bool = False,
+):
+ """Build a swarm registry that exposes the given remote tools verbatim.
+
+ Reuses the real :func:`build_swarm_registry` for the local-tool side
+ (so e.g. ``write_file`` continues to work end-to-end) and then
+ grafts the supplied :class:`MCPRemoteTool` instances on top — but
+ only the ones the agent's whitelist actually names. This mirrors
+ what the M2 path does in production, just without spinning up a real
+ MCP server discovery cycle inside the test.
+ """
+ from src.tools import build_swarm_registry as _real
+
+ registry = _real(tool_names, agent_config=None, include_shell_tools=include_shell_tools)
+ whitelist = set(tool_names)
+ for tool in remote_tools:
+ if tool.name in whitelist:
+ registry.register(tool)
+ return registry
+
+
+def _tool_names(tool_defs: list[dict] | None) -> set[str]:
+ """Extract tool names from an OpenAI-format tool-definitions list."""
+ if not tool_defs:
+ return set()
+ names: set[str] = set()
+ for entry in tool_defs:
+ fn = entry.get("function") if isinstance(entry, dict) else None
+ if isinstance(fn, dict) and isinstance(fn.get("name"), str):
+ names.add(fn["name"])
+ return names
diff --git a/agent/tests/test_swarm_m5_trust_model.py b/agent/tests/test_swarm_m5_trust_model.py
new file mode 100644
index 000000000..634489dbc
--- /dev/null
+++ b/agent/tests/test_swarm_m5_trust_model.py
@@ -0,0 +1,443 @@
+"""M5 — SWARM external MCP tools: trust-model regression tests.
+
+Covers requirements R-06 and tests T-16, T-17, T-18 in
+``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M5 pins the contract that an
+external MCP caller of ``run_swarm`` cannot influence which remote MCP
+servers a worker reaches, no matter what they put in ``variables`` or
+the preset YAML:
+
+ * T-16 — the ``run_swarm`` FastMCP tool's input schema MUST NOT expose
+ any field that would let a caller inject MCP server URLs, commands,
+ env vars, or allowlist overrides (``mcp_servers``, ``mcp_url``,
+ ``mcp_command``, ``mcp_env``, ``agent_config``, ``extra_tools``).
+
+ * T-17 — keys in the ``variables`` dict that *look like* config keys
+ (``mcp_url``, ``mcp_command``, ``agent_config`` …) are forwarded
+ verbatim as template values. The worker uses them only as text
+ substitutions; they are never re-read as configuration. The single
+ source of MCP config is the boot-time loader
+ (:func:`load_swarm_agent_config`).
+
+ * T-18 — a preset that whitelists an ``mcp_*`` tool whose server is
+ not in the boot allowlist logs an operator-facing drop warning and
+ the worker still reaches a terminal state. The unknown tool is NEVER
+ fetched via a caller-supplied lookup path.
+
+The trust boundary being defended is the one called out in the roadmap
+SSRF section: the operator owns ``agent_config`` (via env var or static
+file on disk); the MCP caller only owns ``preset_name`` + ``variables``
+which carry no config authority.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+from typing import Any
+from unittest.mock import patch
+
+import mcp_server
+from src.config.schema import AgentConfig
+from src.providers.chat import LLMResponse
+from src.swarm.models import RunStatus, SwarmAgentSpec, SwarmRun, SwarmTask
+from src.swarm.worker import run_worker
+
+
+# --------------------------------------------------------------------------- #
+# T-16 — FastMCP schema introspection (R-06)
+# --------------------------------------------------------------------------- #
+
+
+# Field names whose presence in ``run_swarm``'s input schema would let an
+# external MCP caller inject MCP server connection details directly. They
+# must never appear on the wire schema. Mirrors the SSRF guard called out
+# in ``docs/2026-05-25_swarm_mcp_tools_roadmap.md``.
+_FORBIDDEN_RUN_SWARM_PARAMETERS = frozenset(
+ {
+ "mcp_servers",
+ "mcp_url",
+ "mcp_command",
+ "mcp_env",
+ "agent_config",
+ "extra_tools",
+ }
+)
+
+# The exact set of parameters ``run_swarm`` is allowed to expose. ``ctx``
+# is the FastMCP-supplied progress channel — it is bound by the runtime,
+# never by the caller, but it does appear in the JSON-Schema signature on
+# some FastMCP versions, so we allow it as a known-safe inclusion.
+_ALLOWED_RUN_SWARM_PARAMETERS = frozenset(
+ {"preset_name", "variables", "wait_seconds", "start_only", "ctx"}
+)
+
+
+def _get_run_swarm_tool_schema() -> dict[str, Any]:
+ """Return the JSON-Schema for ``run_swarm`` via FastMCP introspection.
+
+ Uses the public ``FastMCP.get_tool`` API so the test exercises the
+ schema *as an external client would observe it* — same code path
+ that produces the ``tools/list`` payload over the wire.
+ """
+ tool = asyncio.run(mcp_server.mcp.get_tool("run_swarm"))
+ return tool.parameters
+
+
+def test_run_swarm_schema_excludes_mcp_config_injection_fields() -> None:
+ """The wire schema for ``run_swarm`` must not name any config fields.
+
+ A future refactor that adds e.g. ``mcp_url`` as a parameter would
+ silently turn the swarm entry point into an SSRF primitive — every
+ MCP caller could redirect a worker to a server of their choosing.
+ The boot-time loader is the only authority for that config, by
+ design, and this test pins that design at the schema level.
+ """
+ schema = _get_run_swarm_tool_schema()
+ properties = schema.get("properties", {})
+
+ leaks = sorted(_FORBIDDEN_RUN_SWARM_PARAMETERS & set(properties.keys()))
+ assert not leaks, (
+ f"run_swarm exposes forbidden config-injection field(s): {leaks}. "
+ "These let a caller override MCP server config — boot-time loader "
+ "must remain the only authority. See docs/2026-05-25_swarm_mcp_tools_roadmap.md."
+ )
+
+
+def test_run_swarm_schema_only_exposes_known_safe_parameters() -> None:
+ """Defense-in-depth: flag any *new* parameter for explicit review.
+
+ The forbidden-list test above catches the names we know to fear.
+ This test catches the names we *haven't* thought to fear yet — any
+ new parameter that doesn't appear on the allowlist forces a code
+ review of whether it expands the trust surface.
+ """
+ schema = _get_run_swarm_tool_schema()
+ properties = set(schema.get("properties", {}).keys())
+
+ unexpected = sorted(properties - _ALLOWED_RUN_SWARM_PARAMETERS)
+ assert not unexpected, (
+ f"run_swarm gained unexpected parameter(s): {unexpected}. "
+ "Review whether they expand the trust surface before adding them "
+ "to _ALLOWED_RUN_SWARM_PARAMETERS in this test."
+ )
+
+
+# --------------------------------------------------------------------------- #
+# T-17 — variables are template data; never re-read as config (S-04 / R-06)
+# --------------------------------------------------------------------------- #
+
+
+def test_run_swarm_variables_are_template_data_only_never_config(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """A caller that stuffs ``variables`` with config-shaped keys cannot
+ influence which MCP server the worker reaches.
+
+ The check is two-sided:
+
+ 1. ``SwarmRuntime`` is constructed with the ``agent_config`` returned
+ by the boot-time loader — not anything derived from the caller's
+ ``variables``. We pin this by patching the loader to return a
+ distinct sentinel object and asserting the runtime saw exactly
+ that object.
+
+ 2. ``runtime.start_run`` receives the caller's ``variables`` dict
+ verbatim, with all the attack-shaped keys preserved. They flow
+ into ``SwarmRun.user_vars`` and from there into the prompt
+ template — they are *data*, not config. The worker has no path
+ by which ``variables["mcp_url"]`` becomes a server URL.
+ """
+ # Step 1 — pin the boot-time config source as a sentinel.
+ boot_cfg = AgentConfig.model_validate({"mcpServers": {}})
+
+ def _loader_returns_sentinel() -> AgentConfig:
+ return boot_cfg
+
+ monkeypatch.setattr(
+ "src.config.load_swarm_agent_config", _loader_returns_sentinel
+ )
+
+ # Step 2 — pin the SwarmStore base dir to a tmp path so the test
+ # never touches the repo-level ``.swarm/runs`` directory.
+ monkeypatch.setattr(
+ "src.swarm.store.swarm_runs_root", lambda: tmp_path / "swarm_runs"
+ )
+
+ captured: dict[str, Any] = {}
+
+ class _SpyRuntime:
+ """Record construction + start_run args; return a stub SwarmRun."""
+
+ def __init__(
+ self,
+ *,
+ store: Any,
+ agent_config: AgentConfig | None = None,
+ max_workers: int = 4,
+ ) -> None:
+ captured["construct_agent_config"] = agent_config
+ captured["construct_store"] = store
+
+ def start_run(
+ self,
+ preset_name: str,
+ user_vars: dict[str, str],
+ include_shell_tools: bool = False,
+ ) -> SwarmRun:
+ captured["start_preset"] = preset_name
+ captured["start_user_vars"] = dict(user_vars)
+ captured["start_include_shell_tools"] = include_shell_tools
+ return SwarmRun(
+ id="swarm-test-trustcheck",
+ preset_name=preset_name,
+ status=RunStatus.pending,
+ user_vars=user_vars,
+ agents=[],
+ tasks=[],
+ created_at="2026-05-25T00:00:00+00:00",
+ )
+
+ monkeypatch.setattr("src.swarm.runtime.SwarmRuntime", _SpyRuntime)
+
+ # ``_build_run_payload`` calls store.load_run(run_id) which won't know
+ # about our stub run — short-circuit it so the test focuses on the
+ # trust-side captures (construction + start_run forwarding).
+ monkeypatch.setattr(
+ mcp_server,
+ "_build_run_payload",
+ lambda store, run_id, preset_name, *, timed_out: {
+ "status": "pending",
+ "run_id": run_id,
+ "preset": preset_name,
+ },
+ )
+
+ # An ``variables`` payload crafted to look like a config-injection
+ # attempt. The attacker hopes the runtime treats ``mcp_url`` /
+ # ``mcp_command`` as MCP server config; the worker must instead
+ # treat every key as a plain template variable.
+ attack_vars = {
+ "mcp_url": "http://attacker.example/evil",
+ "mcp_command": "rm -rf /",
+ "mcp_servers": '{"evil": {"command": "bash"}}',
+ "mcp_env": "EVIL_API_KEY=stolen",
+ "agent_config": '{"mcpServers": {"evil": "..."}}',
+ "extra_tools": "mcp_evil_anything",
+ # A legitimate template variable so the preset *could* render.
+ "target": "AAPL.US",
+ }
+
+ asyncio.run(
+ mcp_server.run_swarm(
+ preset_name="any_preset_name",
+ variables=attack_vars,
+ start_only=True,
+ )
+ )
+
+ # Trust check #1: the boot-time loader was the source of agent_config.
+ # The runtime saw the exact sentinel object — no copy, no derivation
+ # from the caller's variables.
+ assert "construct_agent_config" in captured, (
+ "run_swarm did not construct SwarmRuntime; trust path likely broken."
+ )
+ assert captured["construct_agent_config"] is boot_cfg, (
+ "SwarmRuntime was constructed with a different AgentConfig than the "
+ "boot-time loader returned. The caller's variables must NEVER reach "
+ "this argument."
+ )
+
+ # Trust check #2: variables were forwarded verbatim as template data.
+ # Every attack-shaped key is preserved as a plain string — they will
+ # end up in ``SwarmRun.user_vars`` and be rendered into the prompt as
+ # text, never consulted as configuration.
+ assert captured["start_user_vars"] == attack_vars, (
+ "variables were mutated, filtered, or otherwise touched on the "
+ "way to start_run. They must arrive verbatim — the trust model "
+ "depends on the worker treating them as opaque text."
+ )
+
+ # Trust check #3: the preset name was the literal user-supplied
+ # string. The caller picks the preset; that's expected and bounded
+ # by the on-disk preset catalogue.
+ assert captured["start_preset"] == "any_preset_name"
+
+
+# --------------------------------------------------------------------------- #
+# T-18 — preset-referenced ``mcp_*`` tool whose server is not in the boot
+# allowlist drops with a warning; worker still reaches a terminal
+# state; caller-supplied attack-shaped variables are NOT consulted
+# as a fallback config source.
+# --------------------------------------------------------------------------- #
+
+
+class _StubChatLLM:
+ """Minimal scripted replacement for :class:`ChatLLM`.
+
+ The worker only needs the LLM to produce a final response for this
+ test — we never want the LLM to *use* the dropped tool. Captures
+ the ``tools=`` argument so we can verify the dropped MCP tool was
+ not handed to the LLM either.
+ """
+
+ def __init__(self, responses: list[LLMResponse]) -> None:
+ self._responses = list(responses)
+ self.tool_defs_seen: list[list[dict] | None] = []
+
+ def __call__(self, *args, **kwargs): # ChatLLM(model_name=...) constructor shim
+ return self
+
+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):
+ self.tool_defs_seen.append(tools)
+ if not self._responses:
+ return LLMResponse(content="(stub exhausted)", finish_reason="stop")
+ return self._responses.pop(0)
+
+ def chat(self, messages, tools=None, timeout=None): # pragma: no cover
+ return self.stream_chat(messages, tools=tools)
+
+
+def _stub_llm_factory(responses: list[LLMResponse]):
+ stub = _StubChatLLM(responses)
+
+ def _factory(model_name=None):
+ return stub
+
+ _factory.stub = stub # type: ignore[attr-defined]
+ return _factory
+
+
+def _llm_tool_names(tool_defs: list[dict] | None) -> set[str]:
+ """Extract tool names from an OpenAI-format tool-definitions list."""
+ if not tool_defs:
+ return set()
+ names: set[str] = set()
+ for entry in tool_defs:
+ fn = entry.get("function") if isinstance(entry, dict) else None
+ if isinstance(fn, dict) and isinstance(fn.get("name"), str):
+ names.add(fn["name"])
+ return names
+
+
+def test_unknown_mcp_server_tool_drops_cleanly_with_attack_shaped_variables(
+ tmp_path: Path,
+ caplog,
+) -> None:
+ """A preset that names an ``mcp_*`` tool whose server is absent from
+ the boot allowlist must drop the tool with an operator-facing warning,
+ NOT silently look it up from the caller's ``variables`` dict.
+
+ Setup mirrors what an attacker would attempt:
+
+ * Boot ``agent_config`` lists *no* MCP servers — the operator has
+ not approved anything.
+ * The agent's whitelist names ``mcp_attacker_evil_tool`` (perhaps
+ injected via a preset PR the operator did not review carefully).
+ * ``user_vars`` contains attacker-shaped keys
+ (``mcp_attacker_url``, ``mcp_attacker_command``, …) that a
+ broken implementation might treat as a fallback lookup source.
+
+ The worker must:
+
+ * Drop ``mcp_attacker_evil_tool`` with a warning (M2 contract,
+ re-pinned here at the worker integration layer).
+ * NOT hand ``mcp_attacker_evil_tool`` to the LLM (no leaked
+ capability surface).
+ * Reach a terminal state without crashing — variables are opaque
+ text, not config.
+ * NEVER trigger MCP wrapper construction for an attacker-named
+ server — the only authority for which servers exist is the
+ boot ``agent_config``.
+ """
+ # Boot allowlist is empty: operator has approved zero MCP servers.
+ boot_cfg = AgentConfig.model_validate({"mcpServers": {}})
+
+ # The LLM stub returns a final response immediately — we don't want
+ # it to call the dropped tool (it shouldn't be able to: dropped tools
+ # are absent from ``tools=``).
+ llm_factory = _stub_llm_factory(
+ [LLMResponse(content="No remote tool available; analysis skipped.", finish_reason="stop")]
+ )
+
+ # Spy on the MCP wrapper builder. With an empty boot allowlist the
+ # worker must NEVER call this — no server to wrap. If the test sees
+ # any call, the trust boundary has been crossed.
+ wrapper_calls: list[tuple] = []
+
+ def _spy_build_mcp_tool_wrappers(*args, **kwargs): # pragma: no cover — should not run
+ wrapper_calls.append((args, kwargs))
+ return []
+
+ attack_vars = {
+ "mcp_attacker_url": "http://attacker.example",
+ "mcp_attacker_command": "rm -rf /",
+ "agent_config": '{"mcpServers": {"attacker": ...}}',
+ "target": "AAPL.US",
+ }
+
+ with (
+ patch("src.tools.mcp.build_mcp_tool_wrappers", side_effect=_spy_build_mcp_tool_wrappers),
+ patch("src.swarm.worker.ChatLLM", llm_factory),
+ caplog.at_level(logging.WARNING),
+ ):
+ result = run_worker(
+ agent_spec=SwarmAgentSpec(
+ id="kb_analyst",
+ role="Analyst",
+ system_prompt="Analyse markets.",
+ tools=["mcp_attacker_evil_tool", "write_file"],
+ skills=[],
+ max_iterations=3,
+ timeout_seconds=30,
+ ),
+ task=SwarmTask(
+ id="t1",
+ agent_id="kb_analyst",
+ prompt_template="Analyse {target}.",
+ ),
+ upstream_summaries={},
+ user_vars=attack_vars,
+ run_dir=tmp_path,
+ agent_config=boot_cfg,
+ )
+
+ # The worker reached a terminal state — variables didn't crash the
+ # pipeline by being misinterpreted as config.
+ assert result.status in {"completed", "incomplete"}, (
+ f"Worker did not reach a clean terminal state: status={result.status}, "
+ f"error={getattr(result, 'error', None)!r}"
+ )
+
+ # Operator-facing drop warning fired for the unknown MCP tool —
+ # standard M2 contract, re-checked here from the worker entry point.
+ drop_warnings = [
+ rec for rec in caplog.records
+ if "mcp_attacker_evil_tool" in rec.message and "unavailable" in rec.message
+ ]
+ assert drop_warnings, (
+ "Expected an 'unavailable' drop warning for mcp_attacker_evil_tool. "
+ f"Got log records: {[(r.levelname, r.message) for r in caplog.records]}"
+ )
+
+ # The LLM was never handed the dropped tool — capability isolation
+ # holds at the layer that actually matters (what the model can see).
+ first_seen = llm_factory.stub.tool_defs_seen[0] # type: ignore[attr-defined]
+ seen_names = _llm_tool_names(first_seen)
+ assert "mcp_attacker_evil_tool" not in seen_names, (
+ f"Dropped MCP tool leaked into LLM tools= argument: {sorted(seen_names)}"
+ )
+ # Local tool that the preset legitimately requested *was* exposed.
+ assert "write_file" in seen_names, (
+ f"Local write_file should remain available; LLM saw: {sorted(seen_names)}"
+ )
+
+ # Trust check: even though the caller stuffed attacker-shaped keys
+ # into variables, no MCP wrapper was ever built for an attacker
+ # server. The only authority for "which servers exist" is the boot
+ # ``agent_config`` — which is empty in this test.
+ assert wrapper_calls == [], (
+ f"build_mcp_tool_wrappers was called {len(wrapper_calls)} time(s) "
+ "despite boot allowlist being empty; trust boundary breached: "
+ f"{wrapper_calls!r}"
+ )