"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(agent): add MCP client integration (stdio, v1) (#83)
shadowinlifee346fa1adf95
diff --git a/.gitignore b/.gitignoreindex 0573517ba..e63bdd996 100644--- a/.gitignore+++ b/.gitignore@@ -71,3 +71,5 @@ NOTES.md# Agent tool aliases (auto-generated mirror of CLAUDE.md)AGENTS.md++.DS_Storediff --git a/README.md b/README.mdindex 5bab31dce..5510b7128 100644--- a/README.md+++ b/README.md@@ -691,6 +691,87 @@ OpenSpace will auto-discover all 74 skills, enabling auto-fix, auto-improve, and---+## π Loading Tools from External MCP Servers (MCP Client Mode)++> **This is the opposite direction from the MCP Plugin above.**+> The MCP Plugin lets *other* agents call Vibe-Trading tools.+> This section lets the *built-in* Vibe-Trading agent call tools from *your* external MCP servers.++### Quick start++Create `~/.vibe-trading/agent.json`:++```json+{+ "mcpServers": {+ "my-server": {+ "command": "uvx",+ "args": ["my-mcp-server"]+ }+ }+}+```++Run any CLI command β tools from `my-server` are automatically injected into the agent's registry after local tools:++```bash+vibe-trading run "use my-server to do X"+```++### Config reference++| Field | Type | Default | Description |+|-------|------|---------|-------------|+| `command` | string | required | Executable to spawn |+| `args` | array | `[]` | Command-line arguments |+| `env` | object | `{}` | Extra environment variables merged into the subprocess env |+| `toolTimeout` | number | `30` | Per-tool call timeout in seconds |+| `enabledTools` | array | `["*"]` | Tool allowlist. Use `["*"]` to expose all tools from the server |++Config file location: `~/.vibe-trading/agent.json` (JSON or YAML).++### Per-session overrides (API)++When creating a session via the API you can pass `mcpServers` inside `session.config` to extend or override the global config for that session only:++```json+{+ "config": {+ "mcpServers": {+ "research-server": {+ "command": "uvx",+ "args": ["research-mcp"],+ "enabledTools": ["search", "fetch"]+ }+ }+ }+}+```++### Tool naming++Remote tools are exposed with stable names: `mcp_<server>_<tool>`.++If two server names produce the same ASCII-safe local prefix (e.g. `foo-bar` and `foo_bar` both become `foo_bar`), a deterministic hash suffix is appended at the server-segment level so names remain unique. The operator receives a warning:++```+WARNING: Configured MCP server 'foo-bar' collides with another server after local name+normalization. Using local tool prefix 'mcp_foo_bar_<hash>_<tool>' to keep generated+tool names unique. Rename the server in agent config if you want a different prefix.+```++### v1 limits++| Limit | Detail |+|-------|--------|+| Transport | stdio only (SSE / streamable HTTP excluded in v1) |+| Execution | serial only β MCP tools never enter the parallel readonly path |+| Surfaces | tools only (resources and prompts excluded in v1) |+| Hot reload | not supported β restart the process to pick up config changes |+| Swarm path | MCP tools are not available inside Swarm worker registries in v1 |++---+## π Project Structure<details>diff --git a/agent/SKILL.md b/agent/SKILL.mdindex d2e71132e..192adef53 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -149,6 +149,89 @@ pip install vibe-trading-aiThat's it β no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, and all 74 skills immediately.+## Loading Tools from External MCP Servers++The built-in agent can load tools from your own external MCP servers in addition to its local toolset.++> **Note:** This is the *MCP client* path β the opposite of the MCP plugin listed above. The plugin above makes Vibe-Trading's tools available to your agents. This section lets Vibe-Trading's own agent call tools from *your* servers.++### Setup++Create `~/.vibe-trading/agent.json`:++```json+{+ "mcpServers": {+ "my-server": {+ "command": "uvx",+ "args": ["my-mcp-server"],+ "toolTimeout": 30,+ "enabledTools": ["*"]+ }+ }+}+```++Remote tools appear automatically in every `vibe-trading run` / `vibe-trading chat` call. They are injected after local tools under stable names: `mcp_<server>_<tool>`.++### Config fields++| Field | Required | Default | Description |+|-------|----------|---------|-------------|+| `command` | yes | β | Executable to launch |+| `args` | no | `[]` | Command arguments |+| `env` | no | `{}` | Extra env vars for the subprocess |+| `toolTimeout` | no | `30` | Seconds before a tool call is cancelled |+| `enabledTools` | no | `["*"]` | Allowlist of remote tool names. `["*"]` enables all |++### Per-session override (API)++> **Security β disabled by default.** `mcpServers` defines subprocess `command`/`args`/`env` and is therefore restricted to operator-level trust. API callers **cannot** inject MCP server definitions through `POST /sessions` unless the server operator explicitly opts in.++To enable session-level MCP injection, set the environment variable on the server before starting the agent:++```bash+export ALLOW_SESSION_MCP_SERVERS=1+```++With the opt-in active, pass `mcpServers` inside `session.config` to extend or replace the global config for that session only:++```json+{+ "config": {+ "mcpServers": {+ "research": {+ "command": "uvx",+ "args": ["research-mcp"],+ "enabledTools": ["search"]+ }+ }+ }+}+```++Without `ALLOW_SESSION_MCP_SERVERS=1`, any `mcpServers` key in `session.config` is silently stripped before config loading. The global operator config on disk (`~/.vibe-trading/agent.json`) is always respected regardless of this flag.++### v1 limits++- **Transport:** stdio only. SSE and HTTP transports are rejected.+- **Execution:** serial only. MCP tools never enter the parallel readonly path.+- **Surfaces:** tools only. Resources and prompts are not exposed.+- **Swarm:** MCP tools are excluded from Swarm worker registries in v1.+- **Hot reload:** not supported. Restart the process to pick up config changes.++### Failure handling++| Case | Behavior |+|------|----------|+| Missing config file | falls back to empty config β no MCP servers loaded |+| Invalid config file | logs a warning and falls back to empty config |+| Server fails to start | that server is skipped; local tools and other servers still load |+| Tool call times out | returns a normalized error payload instead of raising |+| Two server names collide after sanitization | deterministic hash suffix appended; operator warning emitted |+++## Examples**Backtest a MACD strategy on Apple:**diff --git a/agent/cli.py b/agent/cli.pyindex a2c066d4b..b4d5cd5aa 100644--- a/agent/cli.py+++ b/agent/cli.py@@ -718,8 +718,23 @@ def _run_agent(from src.memory.persistent import PersistentMemorypm = PersistentMemory()+ from src.config.loader import load_agent_config++ agent_config = load_agent_config()++ def _mcp_warn(msg: str) -> None:+ if no_rich:+ print(f"WARNING: {msg}", flush=True)+ else:+ console.print(f"[yellow]WARNING:[/yellow] {msg}")+agent = AgentLoop(- registry=build_registry(persistent_memory=pm, include_shell_tools=True),+ registry=build_registry(+ persistent_memory=pm,+ include_shell_tools=True,+ agent_config=agent_config,+ warn_callback=_mcp_warn,+ ),llm=ChatLLM(),event_callback=on_event,max_iterations=max_iter,@@ -1405,7 +1420,6 @@ def cmd_interactive(max_iter: int) -> None:except KeyboardInterrupt:console.print("\n[yellow]Interrupted[/yellow]")continue-stats.last_elapsed = time.perf_counter() - startstats.tool_count += dashboard.iterations_print_result(result, stats.last_elapsed)diff --git a/agent/src/config/__init__.py b/agent/src/config/__init__.pynew file mode 100644index 000000000..fd8661e5f--- /dev/null+++ b/agent/src/config/__init__.py@@ -0,0 +1,17 @@+"""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.paths import get_config_path, get_data_dir, get_runtime_root+from src.config.schema import AgentConfig, MCPServerConfig++__all__ = [+ "AgentConfig",+ "MCPServerConfig",+ "get_config_path",+ "get_data_dir",+ "get_runtime_root",+ "load_agent_config",+ "load_runtime_agent_config",+ "merge_agent_config_overrides",+ "sanitize_session_overrides",+]diff --git a/agent/src/config/loader.py b/agent/src/config/loader.pynew file mode 100644index 000000000..3f4422c72--- /dev/null+++ b/agent/src/config/loader.py@@ -0,0 +1,190 @@+"""Structured agent config loading utilities."""++from __future__ import annotations++import json+import logging+import os+from pathlib import Path+from typing import Any, Mapping++from pydantic import ValidationError++from src.config.paths import get_config_path+from src.config.schema import AgentConfig, AgentConfigOverride++logger = logging.getLogger(__name__)++try:+ import yaml+except ImportError:+ yaml = None # type: ignore+++def load_agent_config(config_path: Path | None = None) -> AgentConfig:+ """Load structured agent config from disk with safe fallback.++ Args:+ config_path: Optional explicit config path. When omitted, the default+ config discovery path is used.++ Returns:+ The validated agent config. Invalid or unreadable config files fall+ back to ``AgentConfig()``.+ """+ path = get_config_path(config_path)++ if not path.exists():+ return AgentConfig()++ try:+ raw = _read_config_file(path)+ return AgentConfig.model_validate(raw)+ except (OSError, ValueError, ValidationError) as exc:+ logger.warning(+ "Failed to load agent config from %s: %s",+ path,+ type(exc).__name__,+ )+ logger.debug("Agent config load error details: %s", exc)+ return AgentConfig()+++def merge_agent_config_overrides(+ config: AgentConfig,+ overrides: Mapping[str, Any] | None,+) -> AgentConfig:+ """Merge runtime overrides on top of a base config.++ Overrides are validated against a partial schema first so both snake_case+ and camelCase keys are accepted while only explicitly provided fields+ override the base config.++ Args:+ config: Base agent config loaded from disk or defaults.+ overrides: Runtime overrides, typically from session-level config.++ Returns:+ A new validated config containing the merged result.+ """+ if not overrides:+ return config++ try:+ override_model = AgentConfigOverride.model_validate(dict(overrides))+ except ValidationError as exc:+ logger.warning(+ "Ignoring invalid agent config overrides (%s): %s β using base config",+ type(exc).__name__,+ [str(e["loc"]) for e in exc.errors()],+ )+ return config++ merged = _merge_dicts(+ config.model_dump(mode="json"),+ override_model.model_dump(mode="json", exclude_unset=True),+ )+ return AgentConfig.model_validate(merged)+++# Keys in session overrides that carry subprocess definitions and therefore+# require operator-level trust rather than API-caller trust.+_SESSION_RESTRICTED_KEYS: frozenset[str] = frozenset({"mcpServers", "mcp_servers"})+++def sanitize_session_overrides(overrides: Mapping[str, Any]) -> dict[str, Any]:+ """Strip operator-only keys from API-caller-supplied session overrides.++ ``mcpServers`` / ``mcp_servers`` define subprocess ``command``/``args``/``env``+ and therefore grant execution-level capabilities. They must originate from+ the operator-controlled config file on disk, not from unauthenticated or+ semi-trusted API callers. Operators who deliberately want to allow session-+ level MCP injection can set ``ALLOW_SESSION_MCP_SERVERS=1``.++ Args:+ overrides: Raw session config dict received from the API caller.++ Returns:+ A new dict with restricted keys removed (or the original mapping+ converted to dict if the env opt-in is active).+ """+ if os.environ.get("ALLOW_SESSION_MCP_SERVERS", "").strip().lower() in {"1", "true", "yes"}:+ return dict(overrides)++ restricted_present = _SESSION_RESTRICTED_KEYS & overrides.keys()+ if restricted_present:+ logger.warning(+ "Stripped %s from session config overrides: MCP server definitions "+ "require operator-level trust (disk config). "+ "Set ALLOW_SESSION_MCP_SERVERS=1 to allow session-level injection.",+ sorted(restricted_present),+ )+ return {k: v for k, v in overrides.items() if k not in _SESSION_RESTRICTED_KEYS}+++def load_runtime_agent_config(+ config_path: Path | None = None,+ overrides: Mapping[str, Any] | None = None,+) -> AgentConfig:+ """Load disk config and apply runtime overrides.++ Args:+ config_path: Optional explicit config file path.+ overrides: Runtime override mapping applied on top of file-based config.++ Returns:+ The merged runtime config.+ """+ config = load_agent_config(config_path)+ return merge_agent_config_overrides(config, overrides)+++def _read_config_file(path: Path) -> dict[str, Any]:+ """Read a supported config file format into a dictionary.++ Args:+ path: Config file path to decode.++ Returns:+ The decoded config object as a dictionary.++ Raises:+ ValueError: If the file format is unsupported, YAML support is+ unavailable, or the decoded payload is not an object.+ """+ suffix = path.suffix.lower()+ text = path.read_text(encoding="utf-8")++ if suffix == ".json":+ data = json.loads(text)+ elif suffix in {".yaml", ".yml"}:+ if yaml is None:+ raise ValueError("YAML config is not available because PyYAML is missing")+ data = yaml.safe_load(text) or {}+ else:+ raise ValueError(f"Unsupported config file format: {suffix or '<none>'}")++ if not isinstance(data, dict):+ raise ValueError("Agent config must decode to a JSON/YAML object")+ return data+++def _merge_dicts(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:+ """Recursively merge two plain dictionaries.++ Args:+ base: Base dictionary.+ override: Override dictionary applied on top of ``base``.++ Returns:+ A merged dictionary where nested mappings are merged recursively and+ scalar values from ``override`` replace those in ``base``.+ """+ merged = dict(base)+ for key, value in override.items():+ current = merged.get(key)+ if isinstance(current, dict) and isinstance(value, dict):+ merged[key] = _merge_dicts(current, value)+ else:+ merged[key] = value+ return merged\ No newline at end of filediff --git a/agent/src/config/paths.py b/agent/src/config/paths.pynew file mode 100644index 000000000..3656e1324--- /dev/null+++ b/agent/src/config/paths.py@@ -0,0 +1,71 @@+"""Path helpers for agent-level structured config."""++from __future__ import annotations++from pathlib import Path++_DEFAULT_FILENAMES = ("agent.json", "agent.yaml", "agent.yml")+++def get_runtime_root(config_path: Path | None = None) -> Path:+ """Return the runtime root directory for user-level agent state.++ Args:+ config_path: Optional explicit config file path. When provided, the+ runtime root is derived from that file's parent directory.++ Returns:+ The directory containing the explicit structured config file when one+ is provided, otherwise the default ``~/.vibe-trading`` runtime root.+ """+ if config_path is not None:+ return config_path.expanduser().parent+ return Path.home() / ".vibe-trading"+++def get_config_candidates(config_path: Path | None = None) -> list[Path]:+ """Return supported config path candidates in lookup order.++ Returns:+ Candidate config paths ordered by lookup priority. When an explicit+ config path is provided, only that path is returned.+ """+ if config_path is not None:+ return [config_path.expanduser()]+ root = get_runtime_root()+ return [root / filename for filename in _DEFAULT_FILENAMES]+++def get_config_path(config_path: Path | None = None) -> Path:+ """Return the active config file path.++ Prefers the first existing candidate. If an explicit path is provided,+ returns that path directly. If no candidate exists yet, returns the+ recommended default JSON path.++ Args:+ config_path: Optional explicit config file path.++ Returns:+ The selected config file path for the current runtime context.+ """+ candidates = get_config_candidates(config_path)+ for candidate in candidates:+ if candidate.exists():+ return candidate+ return candidates[0]+++def get_data_dir(config_path: Path | None = None) -> Path:+ """Return and create the runtime data directory derived from config path.++ Args:+ config_path: Optional explicit config file path.++ Returns:+ The directory containing the active config file. The directory is+ created when it does not already exist.+ """+ data_dir = get_config_path(config_path).parent+ data_dir.mkdir(parents=True, exist_ok=True)+ return data_dir\ No newline at end of filediff --git a/agent/src/config/schema.py b/agent/src/config/schema.pynew file mode 100644index 000000000..9124e1269--- /dev/null+++ b/agent/src/config/schema.py@@ -0,0 +1,103 @@+"""Structured agent config schema for MCP client integration."""++from __future__ import annotations++from typing import Literal++from pydantic import BaseModel, ConfigDict, Field, model_validator+++def _to_camel(name: str) -> str:+ """Convert snake_case names to camelCase aliases.++ Args:+ name: Field name in snake_case form.++ Returns:+ The camelCase alias used for external config compatibility.+ """+ parts = name.split("_")+ return parts[0] + "".join(part.capitalize() for part in parts[1:])+++class ConfigBase(BaseModel):+ """Base config model accepting both snake_case and camelCase keys."""++ model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True, extra="forbid")+++class MCPServerConfig(ConfigBase):+ """Single external MCP server definition."""++ type: Literal["stdio", "sse", "streamableHttp"] | None = None+ command: str = ""+ args: list[str] = Field(default_factory=list)+ env: dict[str, str] = Field(default_factory=dict)+ url: str = ""+ headers: dict[str, str] = Field(default_factory=dict)+ tool_timeout: float = Field(default=30.0, ge=0.1)+ enabled_tools: list[str] = Field(default_factory=lambda: ["*"])++ @model_validator(mode="after")+ def validate_v1_stdio_only(self) -> "MCPServerConfig":+ """Reject non-stdio transports for the first release.++ Returns:+ The validated MCP server config instance.++ Raises:+ ValueError: If the config implies a non-stdio transport, uses+ HTTP-only fields, or omits the command required for stdio.+ """+ transport = self.type+ if transport is None:+ if self.command:+ transport = "stdio"+ elif self.url:+ transport = "sse" if self.url.rstrip("/").endswith("/sse") else "streamableHttp"++ if transport and transport != "stdio":+ raise ValueError("Only stdio MCP servers are supported in v1")+ if self.url or self.headers:+ raise ValueError("HTTP MCP transports are not supported in v1")+ if not self.command.strip():+ raise ValueError("stdio MCP servers require a command")+ return self+++class MCPServerConfigOverride(ConfigBase):+ """Partial MCP server override used for runtime config layering."""++ type: Literal["stdio", "sse", "streamableHttp"] | None = None+ command: str | None = None+ args: list[str] | None = None+ env: dict[str, str] | None = None+ url: str | None = None+ headers: dict[str, str] | None = None+ tool_timeout: float | None = Field(default=None, ge=0.1)+ enabled_tools: list[str] | None = None+++class AgentConfig(ConfigBase):+ """Top-level structured agent config."""++ mcp_servers: dict[str, MCPServerConfig] = Field(default_factory=dict)+++class AgentConfigOverride(ConfigBase):+ """Partial top-level config override used for runtime layering."""++ model_config = ConfigDict(+ alias_generator=_to_camel,+ populate_by_name=True,+ # Load-bearing: SessionService passes the entire session.config dict+ # (which carries unrelated keys like include_shell_tools) through+ # merge_agent_config_overrides. Flipping this back to "forbid" makes+ # any such payload raise ValidationError and silently drops the whole+ # override, including any valid mcpServers. Regression test:+ # tests/test_agent_config.py::+ # test_runtime_load_preserves_mcp_servers_when_opted_in_with_unknown_keys+ extra="ignore",+ )++ mcp_servers: dict[str, MCPServerConfigOverride] = Field(default_factory=dict)\ No newline at end of filediff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex d71af4341..f8f1c6bd3 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -192,7 +192,12 @@ class SessionService:try:messages = self.store.get_messages(session.session_id)- result = await self._run_with_agent(attempt, messages=messages, include_shell_tools=include_shell_tools)+ result = await self._run_with_agent(+ attempt,+ messages=messages,+ include_shell_tools=include_shell_tools,+ session_config=dict(session.config),+ )if result.get("status") == "success":attempt.mark_completed(summary=result.get("content", ""))else:@@ -233,6 +238,7 @@ class SessionService:messages: list = None,*,include_shell_tools: bool = False,+ session_config: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Execute an attempt with the V5 AgentLoop.@@ -240,6 +246,10 @@ class SessionService:attempt: Current execution attempt.messages: Session message history.include_shell_tools: Whether the registry may include shell tools.+ session_config: Optional session-level config overrides. MCP server+ definitions under the ``mcpServers`` key are merged on top of+ the user config file via ``load_runtime_agent_config`` so each+ session can extend or override the global MCP server list.Returns:Result dictionary containing status, run_dir, run_id, metrics, and related fields.@@ -248,6 +258,7 @@ class SessionService:from src.providers.chat import ChatLLMfrom src.agent.loop import AgentLoopfrom src.memory.persistent import PersistentMemory+ from src.config.loader import load_runtime_agent_config, sanitize_session_overridesllm = ChatLLM()pm = PersistentMemory()@@ -255,13 +266,25 @@ class SessionService:session_id = attempt.session_idattempt_id = attempt.attempt_id+ safe_overrides = sanitize_session_overrides(session_config) if session_config else session_config+ agent_config = load_runtime_agent_config(overrides=safe_overrides)+def event_callback(event_type: str, data: Dict[str, Any]) -> None:"""Forward AgentLoop events to the SSE event bus."""data["attempt_id"] = attempt_idself.event_bus.emit(session_id, event_type, data)+ def _mcp_collision_warn(msg: str) -> None:+ """Forward MCP server-name collision warnings to the operator event channel."""+ self.event_bus.emit(session_id, "mcp.warning", {"attempt_id": attempt_id, "message": msg})+agent = AgentLoop(- registry=build_registry(persistent_memory=pm, include_shell_tools=include_shell_tools),+ registry=build_registry(+ persistent_memory=pm,+ include_shell_tools=include_shell_tools,+ agent_config=agent_config,+ warn_callback=_mcp_collision_warn,+ ),llm=llm,event_callback=event_callback,max_iterations=50,diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex 587f7cea8..8b38f8fd0 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -263,6 +263,9 @@ 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)# 2. Create LLMdiff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.pyindex c0681817f..9b2d73f23 100644--- a/agent/src/tools/__init__.py+++ b/agent/src/tools/__init__.py@@ -8,14 +8,21 @@ Tools with missing dependencies can override check_available() β Falseto be silently excluded from the registry."""+from __future__ import annotations+import importlibimport loggingimport pkgutilfrom collections import dequefrom pathlib import Path+from typing import TYPE_CHECKING, Callablefrom src.agent.tools import BaseTool, ToolRegistry+if TYPE_CHECKING:+ from src.config.schema import AgentConfig+ from src.memory.persistent import PersistentMemory+logger = logging.getLogger(__name__)_SUBCLASSES_CACHE: list[type[BaseTool]] | None = None@@ -59,8 +66,16 @@ def build_registry(*,persistent_memory: "PersistentMemory | None" = None,include_shell_tools: bool = False,+ agent_config: "AgentConfig | None" = None,+ warn_callback: Callable[[str], None] | None = None,) -> ToolRegistry:- """Build the tool registry via auto-discovery.+ """Build the tool registry via auto-discovery, optionally enriched with MCP tools.++ Local tools are discovered and registered first. When ``agent_config``+ provides one or more MCP server definitions, remote tools are appended+ after the local tools. Each MCP server is isolated: a failure to connect+ or discover tools for one server emits a warning and skips that server+ without affecting local tools or other MCP servers.Args:persistent_memory: Shared PersistentMemory instance. Injected into@@ -70,9 +85,18 @@ def build_registry(commands. Local CLI/stdin entry points can enable this; networkedserver entry points should keep it disabled unless explicitlyopted in.+ agent_config: Optional structured agent config. When provided and+ non-empty, MCP tools are appended to the registry after local+ tool discovery. Pass ``None`` (default) to preserve existing+ behavior with no MCP integration.+ warn_callback: Optional callable invoked with operator-facing warning+ messages. When provided, server-name collision warnings are passed+ to this callback in addition to the standard logger so CLI and+ SessionService can surface them to operators.Returns:- ToolRegistry containing all available tools.+ ToolRegistry containing all available local tools followed by any+ successfully discovered MCP tools."""from src.tools.remember_tool import RememberToolfrom src.tools.swarm_tool import SwarmTool@@ -94,12 +118,46 @@ def build_registry(registry.register(cls())except Exception as exc:logger.warning("Failed to register tool %s: %s", cls.name, exc)++ 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,+ )++ for server_name, server_config in agent_config.mcp_servers.items():+ try:+ wrappers = build_mcp_tool_wrappers(+ server_name,+ server_config,+ local_server_name=local_server_names[server_name],+ )+ for tool in wrappers:+ registry.register(tool)+ logger.info(+ "Registered %d MCP tool(s) from server '%s'",+ len(wrappers),+ server_name,+ )+ except Exception as exc:+ skip_msg = f"MCP server '{server_name}' skipped: {exc}"+ logger.warning("Skipped MCP server '%s': %s", server_name, exc)+ if warn_callback is not None:+ warn_callback(skip_msg)+return registrydef 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.+Args:tool_names: Tool names to include.include_shell_tools: Whether to include filtered shell execution tools.diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pynew file mode 100644index 000000000..2bdfac869--- /dev/null+++ b/agent/src/tools/mcp.py@@ -0,0 +1,948 @@+"""MCP client adapter and remote tool wrappers."""++from __future__ import annotations++import asyncio+import hashlib+import json+import logging+import os+import re+import threading+from copy import deepcopy+from dataclasses import dataclass+from typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, TypeVar++from fastmcp.client import Client+from fastmcp.client.client import CallToolResult+from fastmcp.client.transports.stdio import StdioTransport+from fastmcp.exceptions import McpError, ToolError+from mcp import types as mcp_types++from src.agent.tools import BaseTool+from src.config.schema import MCPServerConfig++logger = logging.getLogger(__name__)++_NAME_SEGMENT_RE = re.compile(r"[^a-z0-9]+")+_SCHEMA_COMPOSITION_KEYS = ("anyOf", "oneOf", "allOf")+_LOCAL_ONLY_ARGUMENTS = {"run_dir"}+_TRANSIENT_ERROR_TOKENS = (+ "broken pipe",+ "connection closed",+ "connection reset",+ "eof",+ "temporar",+ "timed out",+ "timeout",+ "try again",+ "unavailable",+)++ResultT = TypeVar("ResultT")+++class AsyncMCPClient(Protocol):+ """Protocol for async MCP clients used by the adapter."""++ async def __aenter__(self) -> "AsyncMCPClient":+ """Enter the async client context."""+ ...++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_val: BaseException | None,+ exc_tb: Any,+ /,+ ) -> None:+ """Exit the async client context."""+ ...++ async def list_tools(self) -> list[mcp_types.Tool]:+ """List tools exposed by the remote MCP server."""+ ...++ async def call_tool(+ self,+ name: str,+ arguments: dict[str, Any] | None = None,+ *,+ timeout: float | int | None = None,+ raise_on_error: bool = False,+ ) -> CallToolResult:+ """Call a remote MCP tool."""+ ...+++ClientFactory = Callable[[], AsyncMCPClient]+++@dataclass(frozen=True)+class MCPRemoteToolSpec:+ """Resolved metadata for one remote MCP tool."""++ server_name: str+ remote_name: str+ local_name: str+ description: str+ parameters: dict[str, Any]+++def build_mcp_tool_wrappers(+ server_name: str,+ server_config: MCPServerConfig,+ *,+ local_server_name: str | None = None,+ client_factory: ClientFactory | None = None,+) -> list["MCPRemoteTool"]:+ """Build local tool wrappers for a configured MCP server.++ Args:+ server_name: Logical server name from config.+ server_config: Validated stdio MCP server config.+ local_server_name: Optional local naming override for the server+ portion of generated tool names. This lets registry assembly keep+ tool names stable when multiple raw server names sanitize to the+ same local prefix.+ client_factory: Optional async client factory for tests.++ Returns:+ Local BaseTool wrappers for all enabled remote tools.++ Raises:+ Exception: Propagates discovery failures so callers can decide whether+ to warn, skip, or abort.+ """+ adapter = MCPServerAdapter(+ server_name,+ server_config,+ local_server_name=local_server_name,+ client_factory=client_factory,+ )+ return [MCPRemoteTool(adapter=adapter, spec=spec) for spec in adapter.discover_tools()]+++def make_mcp_tool_name(server_name: str, tool_name: str) -> str:+ """Create the stable local tool name for a remote MCP tool.++ Args:+ server_name: Logical MCP server name.+ tool_name: Remote tool name reported by the MCP server.++ Returns:+ Stable local tool name in ``mcp_<server>_<tool>`` format.+ """+ return f"mcp_{_sanitize_name_segment(server_name)}_{_sanitize_name_segment(tool_name)}"+++def format_mcp_server_name_collision_warning(server_name: str, local_server_name: str) -> str:+ """Build operator-facing warning text for sanitized server-name collisions.++ Args:+ server_name: Raw MCP server name from config.+ local_server_name: Unique local server-name segment assigned after+ collision disambiguation.++ Returns:+ Warning copy suitable for CLI, SessionService, and logs.+ """+ return (+ f"Configured MCP server '{server_name}' collides with another server after local name normalization. "+ f"Using local tool prefix 'mcp_{local_server_name}_<tool>' to keep generated tool names unique. "+ "Rename the server in agent config if you want a different prefix."+ )+++def resolve_mcp_server_tool_name_segments(+ server_names: Iterable[str],+ warn_callback: Callable[[str], None] | None = None,+) -> dict[str, str]:+ """Resolve unique local server-name segments for MCP tool names.++ The first release keeps MCP tool names ASCII-safe by sanitizing server+ names. Different raw server names can therefore collapse to the same local+ segment, such as ``foo-bar`` and ``foo_bar`` both becoming ``foo_bar``.+ When that happens, all members of the colliding group receive a stable hash+ suffix at the server-segment level so local tool names remain unique+ without depending on config order.++ Args:+ server_names: Ordered raw MCP server names from config.+ warn_callback: Optional callable invoked with the operator-facing+ warning message when a server-name collision is detected and+ disambiguated. Receives the same text as ``logger.warning`` so+ callers (CLI, SessionService) can surface it to operators.++ Returns:+ Mapping of raw server names to unique local server-name segments.+ """+ ordered_names = list(server_names)+ base_counts: dict[str, int] = {}+ for server_name in ordered_names:+ base_segment = _sanitize_name_segment(server_name)+ base_counts[base_segment] = base_counts.get(base_segment, 0) + 1++ resolved_segments: dict[str, str] = {}+ used_segments: set[str] = set()+ for server_name in ordered_names:+ base_segment = _sanitize_name_segment(server_name)+ if base_counts[base_segment] == 1 and base_segment not in used_segments:+ resolved_segments[server_name] = base_segment+ used_segments.add(base_segment)+ continue++ unique_segment = _dedupe_server_name_segment(base_segment, server_name, used_segments)+ warning_text = format_mcp_server_name_collision_warning(server_name, unique_segment)+ logger.warning(warning_text)+ if warn_callback is not None:+ warn_callback(warning_text)+ resolved_segments[server_name] = unique_segment+ used_segments.add(unique_segment)++ return resolved_segments+++def normalize_mcp_tool_schema(schema: dict[str, Any] | None) -> dict[str, Any]:+ """Normalize remote MCP input schemas into OpenAI-compatible objects.++ Args:+ schema: Raw MCP input schema.++ Returns:+ A JSON Schema object with top-level object semantics and nullable forms+ reduced to non-null branches where possible.+ """+ normalized = _normalize_schema_node(deepcopy(schema) if isinstance(schema, dict) else {})+ normalized = _collapse_nullable_union(normalized)++ if not isinstance(normalized, dict):+ return {"type": "object", "properties": {}, "required": []}++ if _schema_looks_object_like(normalized):+ normalized["type"] = "object"+ else:+ return {"type": "object", "properties": {}, "required": []}++ properties = normalized.get("properties")+ if properties is not None and not isinstance(properties, dict):+ normalized.pop("properties", None)+ elif not isinstance(properties, dict) and not _schema_uses_composed_top_level_rules(normalized):+ normalized["properties"] = {}++ required = normalized.get("required")+ if required is None and not _schema_uses_composed_top_level_rules(normalized):+ normalized["required"] = []+ elif isinstance(required, list):+ normalized["required"] = [item for item in required if isinstance(item, str)]+ elif required is not None:+ normalized.pop("required", None)++ return normalized+++class MCPServerAdapter:+ """Synchronous wrapper around the async FastMCP client."""++ def __init__(+ self,+ server_name: str,+ server_config: MCPServerConfig,+ *,+ local_server_name: str | None = None,+ client_factory: ClientFactory | None = None,+ ) -> None:+ """Initialize the MCP server adapter.++ Args:+ server_name: Logical server name from config.+ server_config: Validated MCP server config.+ local_server_name: Optional local naming override used only for the+ server portion of generated tool names.+ client_factory: Optional async client factory, mainly for tests.+ """+ self.server_name = server_name+ self.local_server_name = local_server_name or server_name+ self.server_config = server_config+ self._client_factory = client_factory or self._build_client++ def discover_tools(self) -> list[MCPRemoteToolSpec]:+ """Discover enabled tools from the remote MCP server.++ Returns:+ Resolved tool specs for enabled remote tools.++ Raises:+ Exception: Propagates discovery failures after retry exhaustion.+ """+ tools = _run_sync(self._list_tools)+ seen_names: dict[str, str] = {}+ specs: list[MCPRemoteToolSpec] = []++ for tool in tools:+ if not _tool_is_enabled(tool.name, self.server_config.enabled_tools):+ continue++ local_name = _dedupe_local_tool_name(+ make_mcp_tool_name(self.local_server_name, tool.name),+ tool.name,+ seen_names,+ )+ specs.append(+ MCPRemoteToolSpec(+ server_name=self.server_name,+ remote_name=tool.name,+ local_name=local_name,+ description=(tool.description or f"Remote MCP tool {tool.name} from {self.server_name}."),+ parameters=normalize_mcp_tool_schema(getattr(tool, "inputSchema", None)),+ )+ )++ if not specs:+ logger.warning(+ "Server '%s' produced 0 enabled tools β check the enabledTools allowlist in agent config.",+ self.server_name,+ )++ return specs++ def call_tool(+ self,+ remote_name: str,+ arguments: dict[str, Any],+ *,+ local_name: str | None = None,+ ) -> dict[str, Any]:+ """Call one remote MCP tool and normalize its result.++ Args:+ remote_name: Remote tool identifier.+ arguments: Tool arguments to forward.+ local_name: Optional local wrapper name for logging/payloads.++ Returns:+ Normalized result payload ready for JSON serialization.+ """+ try:+ result = _run_sync(lambda: self._call_tool(remote_name, arguments))+ payload = _normalize_call_tool_result(result)+ payload.update({+ "server": self.server_name,+ "remote_tool": remote_name,+ "tool": local_name or remote_name,+ })+ return payload+ except Exception as exc:+ return {+ "status": "error",+ "server": self.server_name,+ "remote_tool": remote_name,+ "tool": local_name or remote_name,+ "error": _format_exception_message(exc),+ "error_type": type(exc).__name__,+ }++ def _build_client(self) -> AsyncMCPClient:+ """Create the default FastMCP stdio client.++ Returns:+ Configured async FastMCP client.+ """+ env = os.environ.copy()+ env.update(self.server_config.env)+ transport = StdioTransport(+ command=self.server_config.command,+ args=list(self.server_config.args),+ env=env,+ keep_alive=False,+ )+ # Use a minimum of 30 s for init_timeout so cold-start servers (pip+ # install, docker pull, slow imports) do not trip the same short+ # deadline as a per-call tool_timeout.+ init_timeout = max(self.server_config.tool_timeout, 30.0)+ return Client(+ transport,+ name=self.server_name,+ timeout=self.server_config.tool_timeout,+ init_timeout=init_timeout,+ )++ async def _list_tools(self) -> list[mcp_types.Tool]:+ """List remote tools with a single retry on transient failures.++ Returns:+ Remote MCP tool definitions.++ Raises:+ Exception: Propagates non-transient or exhausted failures.+ """+ return await self._run_with_retry("list_tools", self._list_tools_once)++ async def _list_tools_once(self) -> list[mcp_types.Tool]:+ """List remote tools without retry handling.++ Returns:+ Remote MCP tool definitions.+ """+ async with self._client_factory() as client:+ return await client.list_tools()++ async def _call_tool(self, remote_name: str, arguments: dict[str, Any]) -> CallToolResult:+ """Call a remote tool with timeout and a single transient retry.++ Args:+ remote_name: Remote tool name.+ arguments: Arguments to forward.++ Returns:+ Parsed FastMCP call result.++ Raises:+ Exception: Propagates non-transient or exhausted failures.+ """+ async def _invoke() -> CallToolResult:+ async with self._client_factory() as client:+ return await client.call_tool(+ remote_name,+ arguments=arguments,+ timeout=self.server_config.tool_timeout,+ raise_on_error=False,+ )++ return await self._run_with_retry(f"call_tool:{remote_name}", _invoke)++ async def _run_with_retry(+ self,+ operation_name: str,+ operation: Callable[[], Awaitable[ResultT]],+ ) -> ResultT:+ """Run an async MCP operation with a single transient retry.++ Args:+ operation_name: Human-readable operation label.+ operation: Async operation to execute.++ Returns:+ Operation result.++ Raises:+ Exception: Re-raises the last failure when retry is not allowed or+ both attempts fail.+ """+ attempts = 2+ for attempt in range(1, attempts + 1):+ try:+ return await operation()+ except Exception as exc:+ if attempt >= attempts or not _is_retryable_error(exc):+ raise+ logger.warning(+ "Retrying MCP operation %s for server %s after transient failure: %s",+ operation_name,+ self.server_name,+ exc,+ )+++class MCPRemoteTool(BaseTool):+ """BaseTool wrapper for a discovered remote MCP tool."""++ name = ""+ description = ""+ parameters: dict[str, Any]+ repeatable = True+ is_readonly = False++ def __init__(self, adapter: MCPServerAdapter, spec: MCPRemoteToolSpec) -> None:+ """Initialize a remote MCP tool wrapper.++ Args:+ adapter: Adapter used to invoke the remote server.+ spec: Resolved local metadata for the remote tool.+ """+ self._adapter = adapter+ self._spec = spec+ self.name = spec.local_name+ self.description = spec.description+ self.parameters = spec.parameters++ def execute(self, **kwargs: Any) -> str:+ """Execute the remote MCP tool and return normalized JSON.++ Args:+ **kwargs: Tool arguments from the agent loop.++ Returns:+ JSON string with normalized success or error payload.+ """+ payload = self._adapter.call_tool(+ self._spec.remote_name,+ self._filter_arguments(kwargs),+ local_name=self.name,+ )+ return json.dumps(payload, ensure_ascii=False, default=_json_default)++ def _filter_arguments(self, arguments: dict[str, Any]) -> dict[str, Any]:+ """Drop local-only arguments before forwarding to the remote tool.++ Args:+ arguments: Raw arguments from the local agent loop.++ Returns:+ Filtered arguments compatible with the remote tool schema.+ """+ allowed_keys = _collect_top_level_property_names(self.parameters)+ allow_additional = _schema_allows_additional_top_level_keys(self.parameters)++ if allowed_keys:+ return {+ key: value+ for key, value in arguments.items()+ if key in allowed_keys or (allow_additional and key not in _LOCAL_ONLY_ARGUMENTS)+ }++ if allow_additional:+ return {+ key: value+ for key, value in arguments.items()+ if key not in _LOCAL_ONLY_ARGUMENTS+ }++ return {}+++def _run_sync(operation: Callable[[], Coroutine[Any, Any, ResultT]]) -> ResultT:+ """Run an async operation from sync code.++ Args:+ operation: Async callable to execute.++ Returns:+ Result returned by the async callable.++ Raises:+ BaseException: Re-raises exceptions from the async operation.+ """+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return asyncio.run(operation())++ result: dict[str, ResultT] = {}+ failure: dict[str, BaseException] = {}++ def _runner() -> None:+ try:+ result["value"] = asyncio.run(operation())+ except BaseException as exc:+ failure["error"] = exc++ thread = threading.Thread(target=_runner, daemon=True)+ thread.start()+ thread.join()++ if "error" in failure:+ raise failure["error"]+ return result["value"]+++def _sanitize_name_segment(value: str) -> str:+ """Normalize a server or tool name segment for stable local naming.++ Args:+ value: Raw server or tool name.++ Returns:+ Lowercase ASCII-safe identifier segment.+ """+ normalized = _NAME_SEGMENT_RE.sub("_", value.strip().lower()).strip("_")+ return normalized or "tool"+++def _dedupe_server_name_segment(base_segment: str, server_name: str, used_segments: set[str]) -> str:+ """Disambiguate colliding sanitized server-name segments.++ Args:+ base_segment: Preferred sanitized server-name segment.+ server_name: Raw server name from config.+ used_segments: Already-assigned local server-name segments.++ Returns:+ Unique local server-name segment.+ """+ suffix_source = server_name.encode("utf-8")+ unique_segment = f"{base_segment}_{hashlib.sha1(suffix_source).hexdigest()[:8]}"+ salt = 1+ while unique_segment in used_segments:+ unique_segment = (+ f"{base_segment}_{hashlib.sha1(suffix_source + f':{salt}'.encode('utf-8')).hexdigest()[:8]}"+ )+ salt += 1+ return unique_segment+++def _dedupe_local_tool_name(candidate: str, remote_name: str, seen_names: dict[str, str]) -> str:+ """Disambiguate colliding local MCP tool names deterministically.++ Args:+ candidate: Preferred local tool name.+ remote_name: Original remote tool name.+ seen_names: Mapping of assigned local names to remote names.++ Returns:+ Unique local tool name for one server.+ """+ existing_remote = seen_names.get(candidate)+ if existing_remote is None:+ seen_names[candidate] = remote_name+ return candidate+ if existing_remote == remote_name:+ return candidate++ suffix_source = remote_name.encode("utf-8")+ unique_name = f"{candidate}_{hashlib.sha1(suffix_source).hexdigest()[:8]}"+ salt = 1+ while unique_name in seen_names and seen_names[unique_name] != remote_name:+ unique_name = f"{candidate}_{hashlib.sha1(suffix_source + f':{salt}'.encode('utf-8')).hexdigest()[:8]}"+ salt += 1++ logger.warning("Disambiguated MCP tool name collision: %s -> %s", remote_name, unique_name)+ seen_names[unique_name] = remote_name+ return unique_name+++def _tool_is_enabled(tool_name: str, enabled_tools: list[str]) -> bool:+ """Check whether a remote tool passes the config allowlist.++ Args:+ tool_name: Remote tool name.+ enabled_tools: Configured allowlist.++ Returns:+ ``True`` when the tool should be exposed locally.+ """+ if not enabled_tools:+ return False+ return "*" in enabled_tools or tool_name in enabled_tools+++def _normalize_schema_node(value: Any) -> Any:+ """Recursively normalize nullable JSON Schema fragments.++ Args:+ value: Schema fragment.++ Returns:+ Normalized schema fragment.+ """+ if isinstance(value, dict):+ normalized = {key: _normalize_schema_node(item) for key, item in value.items()}+ normalized_type = normalized.get("type")+ if isinstance(normalized_type, list):+ non_null_types = [item for item in normalized_type if item != "null"]+ if not non_null_types:+ normalized.pop("type", None)+ elif len(non_null_types) == 1:+ normalized["type"] = non_null_types[0]+ else:+ normalized["type"] = non_null_types+ elif normalized_type == "null":+ normalized.pop("type", None)++ for key in ("anyOf", "oneOf"):+ norm_branches = normalized.get(key)+ orig_branches = value.get(key)+ if isinstance(norm_branches, list) and isinstance(orig_branches, list):+ # Check nullness against the *original* branch before recursive+ # normalization strips the "type" key from {"type": "null"} β {}.+ # This preserves Copilot's requirement: {} means "accept anything"+ # in JSON Schema and must NOT be treated as null-only.+ normalized[key] = [+ nb for nb, ob in zip(norm_branches, orig_branches)+ if not _is_null_schema(ob)+ ]++ return normalized++ if isinstance(value, list):+ return [_normalize_schema_node(item) for item in value]++ return value+++def _collapse_nullable_union(schema: dict[str, Any]) -> dict[str, Any]:+ """Collapse top-level nullable unions when a single non-null branch exists.++ Args:+ schema: Normalized schema.++ Returns:+ Collapsed schema when possible; otherwise the original schema.+ """+ for key in ("anyOf", "oneOf"):+ branches = schema.get(key)+ if isinstance(branches, list) and len(branches) == 1 and isinstance(branches[0], dict):+ merged = dict(schema)+ merged.pop(key, None)+ merged.update(branches[0])+ return merged+ return schema+++def _schema_looks_object_like(schema: dict[str, Any]) -> bool:+ """Return whether a schema appears to describe a top-level object."""+ if schema.get("type") == "object":+ return True+ if isinstance(schema.get("properties"), dict):+ return True+ if "additionalProperties" in schema or "patternProperties" in schema or "$ref" in schema:+ return True++ for key in _SCHEMA_COMPOSITION_KEYS:+ branches = schema.get(key)+ if isinstance(branches, list) and any(isinstance(branch, dict) and _schema_looks_object_like(branch) for branch in branches):+ return True++ return False+++def _schema_uses_composed_top_level_rules(schema: dict[str, Any]) -> bool:+ """Return whether a schema relies on top-level composition or refs."""+ if "$ref" in schema or "patternProperties" in schema:+ return True+ return any(isinstance(schema.get(key), list) and schema[key] for key in _SCHEMA_COMPOSITION_KEYS)+++def _collect_top_level_property_names(schema: dict[str, Any] | None) -> set[str]:+ """Collect top-level property names across composed object schemas."""+ if not isinstance(schema, dict):+ return set()++ names: set[str] = set()+ properties = schema.get("properties")+ if isinstance(properties, dict):+ names.update(key for key in properties if isinstance(key, str))++ for key in _SCHEMA_COMPOSITION_KEYS:+ branches = schema.get(key)+ if isinstance(branches, list):+ for branch in branches:+ names.update(_collect_top_level_property_names(branch))++ return names+++def _schema_allows_additional_top_level_keys(schema: dict[str, Any] | None) -> bool:+ """Return whether a schema may accept top-level keys beyond known properties."""+ if not isinstance(schema, dict):+ return False+ if "$ref" in schema:+ return True+ if _schema_keyword_allows_values(schema.get("additionalProperties")):+ return True++ pattern_properties = schema.get("patternProperties")+ if isinstance(pattern_properties, dict) and pattern_properties:+ return True++ for key in _SCHEMA_COMPOSITION_KEYS:+ branches = schema.get(key)+ if isinstance(branches, list) and any(_schema_allows_additional_top_level_keys(branch) for branch in branches):+ return True++ return False+++def _schema_keyword_allows_values(value: Any) -> bool:+ """Return whether a schema keyword encodes an open-ended allowance."""+ return value is not None and value is not False+++def _is_null_schema(schema: Any) -> bool:+ """Return whether a schema branch represents only ``null``.++ Args:+ schema: Candidate schema branch.++ Returns:+ ``True`` when the branch encodes a null-only schema.+ """+ if not isinstance(schema, dict):+ return False+ branch_type = schema.get("type")+ return branch_type == "null" or branch_type == ["null"]+++def _normalize_call_tool_result(result: CallToolResult) -> dict[str, Any]:+ """Convert a FastMCP call result into the local JSON payload shape.++ Args:+ result: Parsed FastMCP tool result.++ Returns:+ Normalized payload with ``status`` plus structured/text content.+ """+ if result.is_error:+ return {+ "status": "error",+ "error": _extract_result_error(result),+ }++ payload: dict[str, Any] = {"status": "ok"}+ if result.data is not None:+ payload["data"] = _make_jsonable(result.data)+ if result.structured_content is not None:+ payload["structured_content"] = _make_jsonable(result.structured_content)+ if result.content:+ payload["content"] = [_make_jsonable(block) for block in result.content]+ text = _extract_text_content(result.content)+ if text:+ payload["text"] = text+ return payload+++def _extract_result_error(result: CallToolResult) -> str:+ """Extract a readable error message from a failed MCP result.++ Args:+ result: Failed FastMCP result.++ Returns:+ Human-readable error text.+ """+ text = _extract_text_content(result.content)+ if text:+ return text+ if result.structured_content is not None:+ return _to_display_text(result.structured_content)+ if result.data is not None:+ return _to_display_text(result.data)+ return "Remote MCP tool returned an error"+++def _extract_text_content(content: list[Any]) -> str:+ """Join text content blocks from a FastMCP response.++ Args:+ content: Content block list.++ Returns:+ Joined text block content.+ """+ texts: list[str] = []+ for block in content:+ raw = _make_jsonable(block)+ if isinstance(raw, dict) and raw.get("type") == "text" and isinstance(raw.get("text"), str):+ texts.append(raw["text"])+ return "\n".join(texts).strip()+++def _is_retryable_error(exc: Exception) -> bool:+ """Determine whether a failure should receive a single retry.++ Args:+ exc: Exception raised by an MCP operation.++ Returns:+ ``True`` for transient timeout/connection failures.+ """+ if isinstance(exc, (asyncio.TimeoutError, TimeoutError, BrokenPipeError, ConnectionError, EOFError, OSError)):+ return True++ if isinstance(exc, McpError) and getattr(exc, "error", None) is not None:+ error_code = getattr(exc.error, "code", None)+ if error_code == mcp_types.CONNECTION_CLOSED:+ return True+ message = getattr(exc.error, "message", "")+ return _message_looks_transient(message)++ # ToolError signals a remote business / validation error, not a+ # connection-level transient failure. Do not retry these.+ if isinstance(exc, ToolError):+ return False++ return _message_looks_transient(str(exc))+++def _message_looks_transient(message: str) -> bool:+ """Check whether an exception message looks transient.++ Args:+ message: Exception message.++ Returns:+ ``True`` when the message matches common transient failure markers.+ """+ lowered = message.lower()+ return any(token in lowered for token in _TRANSIENT_ERROR_TOKENS)+++def _format_exception_message(exc: Exception) -> str:+ """Render an exception into a user-facing error string.++ Args:+ exc: Exception to format.++ Returns:+ Human-readable error message.+ """+ if isinstance(exc, McpError) and getattr(exc, "error", None) is not None:+ return getattr(exc.error, "message", str(exc))+ return str(exc) or type(exc).__name__+++def _make_jsonable(value: Any) -> Any:+ """Convert FastMCP response payloads into JSON-serializable objects.++ Args:+ value: Arbitrary response value.++ Returns:+ JSON-serializable equivalent.+ """+ if hasattr(value, "model_dump"):+ return value.model_dump(mode="json", by_alias=True, exclude_none=True)+ if isinstance(value, list):+ return [_make_jsonable(item) for item in value]+ if isinstance(value, dict):+ return {str(key): _make_jsonable(item) for key, item in value.items()}+ return value+++def _json_default(value: Any) -> Any:+ """Fallback serializer used by ``json.dumps``.++ Args:+ value: Value rejected by the standard encoder.++ Returns:+ JSON-serializable representation.+ """+ return _make_jsonable(value)+++def _to_display_text(value: Any) -> str:+ """Render structured values into compact human-readable text.++ Args:+ value: Structured response value.++ Returns:+ Human-readable string.+ """+ jsonable = _make_jsonable(value)+ if isinstance(jsonable, str):+ return jsonable+ return json.dumps(jsonable, ensure_ascii=False, sort_keys=True)+++__all__ = [+ "MCPRemoteTool",+ "MCPRemoteToolSpec",+ "MCPServerAdapter",+ "build_mcp_tool_wrappers",+ "format_mcp_server_name_collision_warning",+ "make_mcp_tool_name",+ "normalize_mcp_tool_schema",+ "resolve_mcp_server_tool_name_segments",+]\ No newline at end of filediff --git a/agent/tests/fixtures/fake_mcp_server.py b/agent/tests/fixtures/fake_mcp_server.pynew file mode 100644index 000000000..b160bd13e--- /dev/null+++ b/agent/tests/fixtures/fake_mcp_server.py@@ -0,0 +1,47 @@+"""Minimal fake MCP server for integration tests.++Launched as a stdio subprocess by test_mcp_stdio_integration.py.+Exposes two tools:+ - echo(message: str) -> str β returns "echo: <message>"+ - add(a: int, b: int) -> int β returns a + b++Usage (called by pytest, not directly):+ python agent/tests/fixtures/fake_mcp_server.py+"""++from __future__ import annotations++from fastmcp import FastMCP++mcp = FastMCP("fake-mcp-server")+++def echo(message: str) -> str:+ """Echo a message back with a prefix.++ Args:+ message: The message to echo.++ Returns:+ The message prefixed with "echo: ".+ """+ return f"echo: {message}"+++def add(a: int, b: int) -> int:+ """Add two integers.++ Args:+ a: First operand.+ b: Second operand.++ Returns:+ The sum a + b.+ """+ return a + b+++if __name__ == "__main__":+ mcp.run(transport="stdio")diff --git a/agent/tests/test_agent_config.py b/agent/tests/test_agent_config.pynew file mode 100644index 000000000..cb57a57e4--- /dev/null+++ b/agent/tests/test_agent_config.py@@ -0,0 +1,280 @@+"""Unit tests for structured agent config loading."""++from __future__ import annotations++import logging+from pathlib import Path++import pytest+from pydantic import ValidationError++from src.config import (+ AgentConfig,+ get_config_path,+ get_data_dir,+ get_runtime_root,+ load_agent_config,+ load_runtime_agent_config,+ sanitize_session_overrides,+)+++def test_load_agent_config_returns_defaults_when_file_missing(tmp_path: Path) -> None:+ config_path = tmp_path / "agent.json"++ config = load_agent_config(config_path)++ assert config == AgentConfig()+ assert get_config_path(config_path) == config_path+++def test_load_agent_config_accepts_camel_case_json(tmp_path: Path) -> None:+ config_path = tmp_path / "agent.json"+ config_path.write_text(+ """+ {+ "mcpServers": {+ "demo": {+ "command": "uvx",+ "args": ["demo-server"],+ "toolTimeout": 15,+ "enabledTools": ["alpha"]+ }+ }+ }+ """.strip(),+ encoding="utf-8",+ )++ config = load_agent_config(config_path)++ assert config.mcp_servers["demo"].command == "uvx"+ assert config.mcp_servers["demo"].args == ["demo-server"]+ assert config.mcp_servers["demo"].tool_timeout == 15+ assert config.mcp_servers["demo"].enabled_tools == ["alpha"]+++def test_load_agent_config_supports_yaml(tmp_path: Path) -> None:+ config_path = tmp_path / "agent.yaml"+ config_path.write_text(+ """+ mcpServers:+ demo:+ command: uvx+ args:+ - demo-server+ """.strip(),+ encoding="utf-8",+ )++ config = load_agent_config(config_path)++ assert config.mcp_servers["demo"].command == "uvx"+ assert config.mcp_servers["demo"].args == ["demo-server"]+++def test_schema_rejects_non_stdio_transports() -> None:+ with pytest.raises(ValidationError):+ AgentConfig.model_validate(+ {+ "mcpServers": {+ "demo": {+ "type": "sse",+ "url": "http://localhost:8900/sse",+ }+ }+ }+ )+++def test_load_agent_config_warns_and_falls_back_on_invalid_file(+ tmp_path: Path,+ caplog: pytest.LogCaptureFixture,+) -> None:+ config_path = tmp_path / "agent.json"+ config_path.write_text("{not-json}", encoding="utf-8")++ with caplog.at_level(logging.WARNING):+ config = load_agent_config(config_path)++ assert config == AgentConfig()+ assert "Failed to load agent config" in caplog.text+++def test_runtime_overrides_take_precedence_and_merge_nested_servers(tmp_path: Path) -> None:+ config_path = tmp_path / "agent.json"+ config_path.write_text(+ """+ {+ "mcpServers": {+ "demo": {+ "command": "base-server",+ "args": ["--base"],+ "enabledTools": ["alpha"]+ },+ "audit": {+ "command": "audit-server"+ }+ }+ }+ """.strip(),+ encoding="utf-8",+ )++ config = load_runtime_agent_config(+ config_path,+ overrides={+ "mcpServers": {+ "demo": {+ "tool_timeout": 45,+ },+ "research": {+ "command": "research-server",+ },+ }+ },+ )++ assert config.mcp_servers["demo"].command == "base-server"+ assert config.mcp_servers["demo"].args == ["--base"]+ assert config.mcp_servers["demo"].tool_timeout == 45+ assert config.mcp_servers["demo"].enabled_tools == ["alpha"]+ assert config.mcp_servers["audit"].command == "audit-server"+ assert config.mcp_servers["research"].command == "research-server"+++def test_explicit_config_path_does_not_mutate_default_runtime_root(tmp_path: Path) -> None:+ config_path = tmp_path / "nested" / "agent.json"+ load_agent_config(config_path)++ assert get_runtime_root(config_path) == config_path.parent+ assert get_runtime_root() == Path.home() / ".vibe-trading"+ assert get_config_path(config_path) == config_path+++def test_get_data_dir_uses_explicit_config_parent(tmp_path: Path) -> None:+ config_path = tmp_path / "nested" / "agent.json"++ assert get_runtime_root(config_path) == config_path.parent+ assert get_data_dir(config_path) == config_path.parent+ assert config_path.parent.exists()+++# ---------------------------------------------------------------------------+# sanitize_session_overrides β security gate for mcpServers+# ---------------------------------------------------------------------------++def test_sanitize_strips_mcp_servers_by_default() -> None:+ raw = {+ "mcpServers": {"evil": {"command": "/bin/sh", "args": ["-c", "id"]}},+ "include_shell_tools": True,+ }+ result = sanitize_session_overrides(raw)++ assert "mcpServers" not in result+ assert result["include_shell_tools"] is True+++def test_sanitize_strips_snake_case_key_by_default() -> None:+ raw = {"mcp_servers": {"evil": {"command": "bad"}}}+ result = sanitize_session_overrides(raw)++ assert "mcp_servers" not in result+++def test_sanitize_logs_warning_when_stripping(caplog: pytest.LogCaptureFixture) -> None:+ raw = {"mcpServers": {"s": {"command": "uvx"}}}++ with caplog.at_level(logging.WARNING, logger="src.config.loader"):+ sanitize_session_overrides(raw)++ assert "mcpServers" in caplog.text+ assert "ALLOW_SESSION_MCP_SERVERS" in caplog.text+++def test_sanitize_passes_through_when_env_opt_in(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("ALLOW_SESSION_MCP_SERVERS", "1")+ raw = {+ "mcpServers": {"search": {"command": "uvx", "args": ["search-mcp"]}},+ "include_shell_tools": False,+ }+ result = sanitize_session_overrides(raw)++ assert "mcpServers" in result+ assert result["mcpServers"] == raw["mcpServers"]+++def test_sanitize_passes_through_true_and_yes_opt_in(monkeypatch: pytest.MonkeyPatch) -> None:+ for val in ("true", "yes", "True", "YES"):+ monkeypatch.setenv("ALLOW_SESSION_MCP_SERVERS", val)+ result = sanitize_session_overrides({"mcpServers": {"s": {"command": "x"}}})+ assert "mcpServers" in result, f"Expected opt-in to work for ALLOW_SESSION_MCP_SERVERS={val!r}"+++def test_sanitize_empty_overrides_returns_empty() -> None:+ assert sanitize_session_overrides({}) == {}+++def test_sanitize_non_mcp_keys_always_pass_through() -> None:+ raw = {"include_shell_tools": True, "some_other_key": "value"}+ result = sanitize_session_overrides(raw)+ assert result == raw+++# ---------------------------------------------------------------------------+# End-to-end sanitize + load + merge regression+#+# Locks the `extra="ignore"` invariant on AgentConfigOverride: if it gets+# flipped back to "forbid", a session whose config carries unrelated keys+# (e.g. `include_shell_tools`, which SessionService injects at line ~118)+# would raise a ValidationError and silently drop the entire override,+# including any valid `mcpServers`. That regression would not show up in+# any test that only exercises sanitize_session_overrides in isolation.+# ---------------------------------------------------------------------------++def test_runtime_load_drops_mcp_servers_when_mixed_with_unknown_keys(+ tmp_path: Path,+) -> None:+ """Default path: session overrides with mcpServers + unknown keys must+ strip mcpServers and still merge cleanly on top of the disk config."""+ config_path = tmp_path / "agent.json"+ config_path.write_text(+ '{"mcpServers": {"trusted": {"command": "uvx", "args": ["t"]}}}',+ encoding="utf-8",+ )++ session_overrides = {+ "include_shell_tools": True,+ "mcpServers": {"evil": {"command": "/bin/sh", "args": ["-c", "id"]}},+ }+ safe = sanitize_session_overrides(session_overrides)+ merged = load_runtime_agent_config(config_path=config_path, overrides=safe)++ assert set(merged.mcp_servers.keys()) == {"trusted"}+ assert merged.mcp_servers["trusted"].command == "uvx"+++def test_runtime_load_preserves_mcp_servers_when_opted_in_with_unknown_keys(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Opt-in path: with ALLOW_SESSION_MCP_SERVERS=1, valid mcpServers must+ survive the merge even when the session payload also carries unknown+ keys like include_shell_tools. Guards AgentConfigOverride extra='ignore'."""+ monkeypatch.setenv("ALLOW_SESSION_MCP_SERVERS", "1")+ config_path = tmp_path / "agent.json"+ config_path.write_text(+ '{"mcpServers": {"base": {"command": "uvx", "args": ["base"]}}}',+ encoding="utf-8",+ )++ session_overrides = {+ "include_shell_tools": False,+ "some_future_field": "ignored",+ "mcpServers": {"session": {"command": "uvx", "args": ["session-mcp"]}},+ }+ safe = sanitize_session_overrides(session_overrides)+ merged = load_runtime_agent_config(config_path=config_path, overrides=safe)++ assert set(merged.mcp_servers.keys()) == {"base", "session"}+ assert merged.mcp_servers["session"].command == "uvx"+ assert merged.mcp_servers["session"].args == ["session-mcp"]\ No newline at end of filediff --git a/agent/tests/test_mcp_client_adapter.py b/agent/tests/test_mcp_client_adapter.pynew file mode 100644index 000000000..20b001ccc--- /dev/null+++ b/agent/tests/test_mcp_client_adapter.py@@ -0,0 +1,402 @@+"""Unit tests for the MCP client adapter core."""++from __future__ import annotations++import json+import logging+from typing import Any++from fastmcp.client.client import CallToolResult+from fastmcp.exceptions import McpError, ToolError+from mcp import types as mcp_types++from src.config.schema import MCPServerConfig+from src.tools.mcp import (+ build_mcp_tool_wrappers,+ format_mcp_server_name_collision_warning,+ make_mcp_tool_name,+ normalize_mcp_tool_schema,+ resolve_mcp_server_tool_name_segments,+)+++class _FakeClient:+ def __init__(self, state: dict[str, Any]) -> None:+ self._state = state++ async def __aenter__(self) -> "_FakeClient":+ return self++ async def __aexit__(self, exc_type, exc, tb) -> bool | None:+ return None++ async def list_tools(self) -> list[mcp_types.Tool]:+ self._state["list_calls"] += 1+ 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_calls"] += 1+ self._state["call_records"].append({+ "name": name,+ "arguments": arguments or {},+ "timeout": timeout,+ "raise_on_error": raise_on_error,+ })+ outcome = self._state["call_outcomes"].pop(0)+ if isinstance(outcome, Exception):+ raise outcome+ return outcome+++def _make_factory(state: dict[str, Any]):+ def _factory() -> _FakeClient:+ return _FakeClient(state)++ return _factory+++def _make_config(**overrides: Any) -> MCPServerConfig:+ payload = {+ "command": "uvx",+ "args": ["demo-server"],+ "enabled_tools": ["*"],+ "tool_timeout": 7,+ }+ payload.update(overrides)+ return MCPServerConfig.model_validate(payload)+++def test_make_mcp_tool_name_is_stable() -> None:+ assert make_mcp_tool_name("Demo Server", "Price Quote") == "mcp_demo_server_price_quote"+++def test_format_mcp_server_name_collision_warning_is_operator_facing() -> None:+ message = format_mcp_server_name_collision_warning("foo-bar", "foo_bar_deadbeef")++ assert message == (+ "Configured MCP server 'foo-bar' collides with another server after local name normalization. "+ "Using local tool prefix 'mcp_foo_bar_deadbeef_<tool>' to keep generated tool names unique. "+ "Rename the server in agent config if you want a different prefix."+ )+++def test_resolve_mcp_server_tool_name_segments_disambiguates_collisions_stably() -> None:+ resolved = resolve_mcp_server_tool_name_segments(["foo-bar", "foo_bar", "demo"])+ reversed_resolved = resolve_mcp_server_tool_name_segments(["demo", "foo_bar", "foo-bar"])++ assert resolved["demo"] == "demo"+ assert resolved["foo-bar"].startswith("foo_bar_")+ assert resolved["foo_bar"].startswith("foo_bar_")+ assert resolved["foo-bar"] != resolved["foo_bar"]+ assert resolved["foo-bar"] == reversed_resolved["foo-bar"]+ assert resolved["foo_bar"] == reversed_resolved["foo_bar"]+++def test_resolve_mcp_server_tool_name_segments_logs_operator_warning(+ caplog,+) -> None:+ with caplog.at_level(logging.WARNING):+ resolve_mcp_server_tool_name_segments(["foo-bar", "foo_bar"])++ assert any(+ "Using local tool prefix 'mcp_foo_bar_" in record.message+ and "Rename the server in agent config" in record.message+ for record in caplog.records+ )+++def test_normalize_mcp_tool_schema_collapses_nullable_object() -> None:+ schema = normalize_mcp_tool_schema(+ {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "symbol": {"type": ["string", "null"]},+ },+ "required": ["symbol"],+ },+ {"type": "null"},+ ]+ }+ )++ assert schema["type"] == "object"+ assert schema["properties"]["symbol"]["type"] == "string"+ assert schema["required"] == ["symbol"]+++def test_normalize_mcp_tool_schema_preserves_top_level_one_of_branches() -> None:+ schema = normalize_mcp_tool_schema(+ {+ "oneOf": [+ {+ "type": "object",+ "properties": {"symbol": {"type": "string"}},+ "required": ["symbol"],+ },+ {+ "type": "object",+ "properties": {"cusip": {"type": "string"}},+ "required": ["cusip"],+ },+ ]+ }+ )++ assert schema["type"] == "object"+ assert "oneOf" in schema+ assert schema["oneOf"][0]["properties"]["symbol"]["type"] == "string"+ assert schema["oneOf"][1]["properties"]["cusip"]["type"] == "string"+++def test_build_mcp_tool_wrappers_filters_enabled_tools() -> None:+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(name="allowed", description="Allowed", inputSchema={"type": "object"}),+ mcp_types.Tool(name="blocked", description="Blocked", inputSchema={"type": "object"}),+ ]],+ "call_outcomes": [],+ }++ tools = build_mcp_tool_wrappers(+ "demo",+ _make_config(enabled_tools=["allowed"]),+ client_factory=_make_factory(state),+ )++ assert [tool.name for tool in tools] == ["mcp_demo_allowed"]+ assert tools[0].is_readonly is False+++def test_build_mcp_tool_wrappers_honors_local_server_name_override() -> None:+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(name="quote", description="Quote", inputSchema={"type": "object"}),+ ]],+ "call_outcomes": [],+ }++ tools = build_mcp_tool_wrappers(+ "foo-bar",+ _make_config(),+ local_server_name="foo_bar_deadbeef",+ client_factory=_make_factory(state),+ )++ assert [tool.name for tool in tools] == ["mcp_foo_bar_deadbeef_quote"]+++def test_remote_tool_execute_retries_transient_timeout_and_strips_run_dir() -> None:+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(+ name="quote",+ description="Quote lookup",+ inputSchema={+ "type": "object",+ "properties": {"symbol": {"type": "string"}},+ "required": ["symbol"],+ },+ )+ ]],+ "call_outcomes": [+ TimeoutError("timed out"),+ CallToolResult(content=[], structured_content={"price": 12.3}, meta=None, data={"price": 12.3}),+ ],+ }++ tool = build_mcp_tool_wrappers("demo", _make_config(), client_factory=_make_factory(state))[0]++ payload = json.loads(tool.execute(symbol="AAPL", run_dir="/tmp/run"))++ assert payload["status"] == "ok"+ assert payload["server"] == "demo"+ assert payload["remote_tool"] == "quote"+ assert payload["tool"] == "mcp_demo_quote"+ assert payload["structured_content"] == {"price": 12.3}+ assert state["call_calls"] == 2+ assert state["call_records"][0]["arguments"] == {"symbol": "AAPL"}+ assert state["call_records"][0]["timeout"] == 7+ assert state["call_records"][0]["raise_on_error"] is False+++def test_remote_tool_execute_forwards_arguments_for_composed_schema() -> None:+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(+ name="lookup",+ description="Lookup by symbol or cusip",+ inputSchema={+ "oneOf": [+ {+ "type": "object",+ "properties": {"symbol": {"type": "string"}},+ "required": ["symbol"],+ },+ {+ "type": "object",+ "properties": {"cusip": {"type": "string"}},+ "required": ["cusip"],+ },+ ]+ },+ )+ ]],+ "call_outcomes": [+ CallToolResult(content=[], structured_content={"ok": True}, meta=None, data={"ok": True}),+ ],+ }++ tool = build_mcp_tool_wrappers("demo", _make_config(), client_factory=_make_factory(state))[0]++ payload = json.loads(tool.execute(symbol="AAPL", run_dir="/tmp/run"))++ assert payload["status"] == "ok"+ assert state["call_records"][0]["arguments"] == {"symbol": "AAPL"}+++def test_build_mcp_tool_wrappers_disambiguates_colliding_local_names() -> None:+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(name="price-quote", description="Hyphen", inputSchema={"type": "object"}),+ mcp_types.Tool(name="price quote", description="Space", inputSchema={"type": "object"}),+ ]],+ "call_outcomes": [],+ }++ tools = build_mcp_tool_wrappers("demo", _make_config(), client_factory=_make_factory(state))+ names = [tool.name for tool in tools]++ assert names[0] == "mcp_demo_price_quote"+ assert names[1].startswith("mcp_demo_price_quote_")+ assert len(set(names)) == 2+++def test_build_mcp_tool_wrappers_retries_transient_discovery_failure() -> None:+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [+ [McpError(mcp_types.ErrorData(code=mcp_types.CONNECTION_CLOSED, message="Connection closed"))][0],+ [mcp_types.Tool(name="quote", description="Quote", inputSchema={"type": "object"})],+ ],+ "call_outcomes": [],+ }++ tools = build_mcp_tool_wrappers("demo", _make_config(), client_factory=_make_factory(state))++ assert [tool.name for tool in tools] == ["mcp_demo_quote"]+ assert state["list_calls"] == 2+++def test_remote_tool_execute_returns_normalized_error_payload_without_retry() -> None:+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(name="quote", description="Quote", inputSchema={"type": "object"})+ ]],+ "call_outcomes": [ToolError("validation failed")],+ }++ tool = build_mcp_tool_wrappers("demo", _make_config(), client_factory=_make_factory(state))[0]++ payload = json.loads(tool.execute(symbol="AAPL"))++ assert payload == {+ "status": "error",+ "server": "demo",+ "remote_tool": "quote",+ "tool": "mcp_demo_quote",+ "error": "validation failed",+ "error_type": "ToolError",+ }+++def test_build_mcp_tool_wrappers_wildcard_enabled_tools_passes_all() -> None:+ """enabledTools: ["*"] must pass every tool through without filtering."""+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(name="alpha", description="A", inputSchema={"type": "object"}),+ mcp_types.Tool(name="beta", description="B", inputSchema={"type": "object"}),+ mcp_types.Tool(name="gamma", description="C", inputSchema={"type": "object"}),+ ]],+ "call_outcomes": [],+ }++ # enabled_tools=["*"] is the default in _make_config()+ tools = build_mcp_tool_wrappers("demo", _make_config(enabled_tools=["*"]), client_factory=_make_factory(state))++ assert [t.name for t in tools] == [+ "mcp_demo_alpha",+ "mcp_demo_beta",+ "mcp_demo_gamma",+ ]+++def test_normalize_mcp_tool_schema_strips_null_from_any_of_branches() -> None:+ """anyOf with a null-only branch should have that branch removed."""+ schema = normalize_mcp_tool_schema(+ {+ "type": "object",+ "properties": {+ "value": {+ "anyOf": [+ {"type": "integer"},+ {"type": "null"},+ ]+ }+ },+ }+ )++ # The null branch in the anyOf must be stripped.+ value_schema = schema["properties"]["value"]+ any_of_branches = value_schema["anyOf"]+ assert all(branch != {"type": "null"} for branch in any_of_branches)+ assert {"type": "integer"} in any_of_branches+++def test_normalize_mcp_tool_schema_collapses_nested_type_list_with_null() -> None:+ """type: ["string", "null"] at any nesting level must collapse to type: "string"."""+ schema = normalize_mcp_tool_schema(+ {+ "type": "object",+ "properties": {+ "label": {"type": ["string", "null"]},+ },+ }+ )++ assert schema["properties"]["label"]["type"] == "string"\ No newline at end of filediff --git a/agent/tests/test_mcp_regression.py b/agent/tests/test_mcp_regression.pynew file mode 100644index 000000000..d5d809411--- /dev/null+++ b/agent/tests/test_mcp_regression.py@@ -0,0 +1,168 @@+"""Regression tests: existing MCP server mode and no-config behavior.++These tests guard against regressions introduced by the MCP client integration:++1. no-config regression β build_registry() with no agent_config must behave+ identically to before this roadmap: local tools only, no exceptions.++2. MCP server mode regression β importing mcp_server.py must not raise, and+ the FastMCP instance must expose the expected well-known tool names. This+ confirms that the server-side MCP plugin (vibe-trading-mcp) is unaffected+ by the MCP client changes introduced in Phases 1-4.++IMPORTANT notes:+- These tests do NOT start the MCP server process (no mcp.run() call) β they+ only import the module and inspect the registered tool names, which is safe+ and fast.+- Do not add functional tests for individual mcp_server tools here; those+ belong in their own test files.+- TODO(v1): Add a live smoke test that spawns `vibe-trading-mcp` as a stdio+ subprocess once CI has network access and the SSE transport is tested end-+ to-end in Phase 6+.+"""++from __future__ import annotations++import importlib+import sys+from pathlib import Path++import pytest++# ---------------------------------------------------------------------------+# No-config regression+# ---------------------------------------------------------------------------+++def test_build_registry_without_agent_config_loads_local_tools_only() -> None:+ """build_registry() called with defaults must never raise and must return+ only local tools (no mcp_* names).++ This is the "zero-change" contract for callers that do not opt into MCP+ config yet.+ """+ from src.tools import build_registry++ registry = build_registry()++ names = registry.tool_names+ assert names, "Registry must not be empty when no agent_config is supplied"++ mcp_names = [n for n in names if n.startswith("mcp_")]+ assert mcp_names == [], (+ f"Expected no MCP tools without agent_config, got: {mcp_names}"+ )+++def test_build_registry_without_agent_config_does_not_raise() -> None:+ """build_registry() with default arguments must not raise any exception."""+ from src.tools import build_registry++ try:+ registry = build_registry()+ except Exception as exc: # noqa: BLE001+ pytest.fail(f"build_registry() raised unexpectedly: {exc!r}")++ assert registry is not None+++def test_build_registry_without_agent_config_returns_well_known_local_tools() -> None:+ """Well-known local tool names must survive a no-config build_registry call."""+ from src.tools import build_registry++ registry = build_registry()+ names = set(registry.tool_names)++ expected = {"load_skill", "backtest", "web_search", "read_file"}+ missing = expected - names+ assert not missing, (+ f"Expected well-known local tools in registry but these are missing: {missing}"+ )+++# ---------------------------------------------------------------------------+# MCP server mode regression (vibe-trading-mcp plugin)+# ---------------------------------------------------------------------------+++def _import_mcp_server():+ """Import agent/mcp_server.py without executing main().++ Returns:+ The imported mcp_server module.++ Raises:+ ImportError: If the module cannot be imported.+ """+ agent_dir = Path(__file__).resolve().parent.parent+ if str(agent_dir) not in sys.path:+ sys.path.insert(0, str(agent_dir))++ # Use importlib so we can re-import cleanly in tests.+ if "mcp_server" in sys.modules:+ return sys.modules["mcp_server"]+ return importlib.import_module("mcp_server")+++def test_mcp_server_imports_without_raising() -> None:+ """agent/mcp_server.py must import cleanly (no side-effects on import)."""+ try:+ mod = _import_mcp_server()+ except Exception as exc: # noqa: BLE001+ pytest.fail(f"import mcp_server raised: {exc!r}")++ assert mod is not None+++def test_mcp_server_exposes_expected_tool_count() -> None:+ """The MCP server FastMCP instance must expose the expected number of tools.++ 22 tools are documented. We use >= 20 as the floor to tolerate minor+ additions or future removals without breaking this regression gate.+ Uses the public async list_tools() API so this test is stable across+ fastmcp version upgrades.+ """+ import asyncio++ mod = _import_mcp_server()+ mcp_instance = mod.mcp++ tools = asyncio.run(mcp_instance.list_tools())+ tool_count = len(tools)++ assert tool_count >= 20, (+ f"Expected at least 20 MCP server tools, found {tool_count}. "+ "Check whether any tools were accidentally removed from mcp_server.py."+ )+++def test_mcp_server_exposes_well_known_tool_names() -> None:+ """Well-known tool names must be registered on the MCP server instance.++ Uses the public async list_tools() API for stability across fastmcp upgrades.+ """+ import asyncio++ mod = _import_mcp_server()+ mcp_instance = mod.mcp++ tools = asyncio.run(mcp_instance.list_tools())+ registered = {t.name for t in tools}++ expected = {+ "list_skills",+ "load_skill",+ "backtest",+ "web_search",+ "read_url",+ "read_document",+ "write_file",+ "read_file",+ "list_swarm_presets",+ "run_swarm",+ }+ missing = expected - registered+ assert not missing, (+ f"MCP server is missing well-known tools: {missing}. "+ "A tool may have been accidentally renamed or removed."+ )\ No newline at end of filediff --git a/agent/tests/test_mcp_stdio_integration.py b/agent/tests/test_mcp_stdio_integration.pynew file mode 100644index 000000000..a7c34dff3--- /dev/null+++ b/agent/tests/test_mcp_stdio_integration.py@@ -0,0 +1,219 @@+"""Integration tests: full-stack MCP client path with a real stdio subprocess.++These tests spawn an actual fake MCP server process (agent/tests/fixtures/+fake_mcp_server.py) over stdio and exercise the entire path:++ load_agent_config()+ -> build_registry(agent_config=...)+ -> MCPServerAdapter+ -> StdioTransport (real subprocess)+ -> remote tool callable from registry++Unlike test_mcp_client_adapter.py which stubs the fastmcp client, these tests+start a real subprocess and verify end-to-end tool discovery + execution.++IMPORTANT β v1 limits exercised here:+ - stdio transport only (no SSE / streamable HTTP)+ - serial execution (is_readonly == False on every remote tool)+ - tools-only exposure (resources / prompts excluded)+ - Swarm path NOT tested (excluded from MCP config propagation in v1)++TODO(v1): Add SSE / HTTP transport integration tests once those transports are+supported.+TODO(v1): Add Swarm-path integration tests once Swarm worker registries are+allowed to load MCP config.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+from typing import Any++import pytest++# ---------------------------------------------------------------------------+# Path helpers+# ---------------------------------------------------------------------------++_AGENT_DIR = Path(__file__).resolve().parent.parent+_FIXTURE_SERVER = Path(__file__).resolve().parent / "fixtures" / "fake_mcp_server.py"++# Use the same Python interpreter that is running the tests so the fake server+# has access to the same packages (e.g. fastmcp).+_PYTHON = sys.executable+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_agent_json(tmp_path: Path, server_name: str, **server_kwargs: Any) -> Path:+ """Write a minimal agent.json config pointing at the fake stdio server.++ Args:+ tmp_path: Temporary directory to place the config file in.+ server_name: Key name for the MCP server entry.+ **server_kwargs: Extra fields merged into the server config object.++ Returns:+ Path to the written config file.+ """+ config: dict[str, Any] = {+ "mcpServers": {+ server_name: {+ "command": _PYTHON,+ "args": [str(_FIXTURE_SERVER)],+ **server_kwargs,+ }+ }+ }+ cfg_path = tmp_path / "agent.json"+ cfg_path.write_text(json.dumps(config))+ return cfg_path+++# ---------------------------------------------------------------------------+# Integration tests+# ---------------------------------------------------------------------------+++def test_remote_tools_appear_in_registry_after_local_tools(tmp_path: Path) -> None:+ """Remote tools injected by MCP config appear in the registry.++ Verifies:+ - Registry contains at least the two fake server tools.+ - Tool names follow the stable mcp_<server>_<tool> convention.+ - Remote tools are positioned after all local tools.+ """+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ cfg_path = _make_agent_json(tmp_path, "fake")+ agent_config = load_agent_config(config_path=cfg_path)++ registry = build_registry(agent_config=agent_config)+ all_names = registry.tool_names++ assert "mcp_fake_echo" in all_names+ assert "mcp_fake_add" in all_names++ # Remote tools must come after all local tools (no MCP name before local tools end).+ first_mcp = next(i for i, name in enumerate(all_names) if name.startswith("mcp_"))+ local_after_first_mcp = [+ name for name in all_names[first_mcp:] if not name.startswith("mcp_")+ ]+ assert local_after_first_mcp == [], (+ "Local tools found after the first MCP tool β ordering guarantee violated"+ )+++def test_remote_tool_is_callable_and_returns_expected_result(tmp_path: Path) -> None:+ """The remote echo tool can be called and returns the correct result."""+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ cfg_path = _make_agent_json(tmp_path, "fake")+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ echo_tool = registry.get("mcp_fake_echo")+ assert echo_tool is not None, "mcp_fake_echo not found in registry"+ result = echo_tool.execute(message="hello")++ # The tool returns a JSON string with the text content.+ # Successful call: the raw return is the text content from the remote tool.+ assert "hello" in result+++def test_remote_tool_add_returns_correct_sum(tmp_path: Path) -> None:+ """The remote add tool computes the correct sum."""+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ cfg_path = _make_agent_json(tmp_path, "fake")+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ add_tool = registry.get("mcp_fake_add")+ assert add_tool is not None, "mcp_fake_add not found in registry"+ result = add_tool.execute(a=3, b=4)++ assert "7" in result+++def test_remote_tool_is_serial_only(tmp_path: Path) -> None:+ """Every MCP-injected tool must have is_readonly=False (serial-only).++ v1 design: MCP tools never enter the parallel readonly path.+ """+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ cfg_path = _make_agent_json(tmp_path, "fake")+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ mcp_tools = [registry.get(n) for n in registry.tool_names if n.startswith("mcp_fake_")]+ assert mcp_tools, "No MCP tools found in registry"+ for tool in mcp_tools:+ assert tool.is_readonly is False, (+ f"Tool {tool.name!r} has is_readonly=True; "+ "MCP tools must be serial-only in v1"+ )+++def test_enabled_tools_filter_limits_remote_tools(tmp_path: Path) -> None:+ """enabledTools allowlist restricts which remote tools appear in the registry."""+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ cfg_path = _make_agent_json(tmp_path, "fake", enabledTools=["echo"])+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_fake_")]+ assert "mcp_fake_echo" in mcp_names+ assert "mcp_fake_add" not in mcp_names, (+ "mcp_fake_add should be excluded by enabledTools filter"+ )+++def test_broken_server_command_does_not_block_local_tools(tmp_path: Path) -> None:+ """A server with an invalid command must be skipped; local tools still load.++ IMPORTANT: This verifies the safe degradation contract β a misconfigured+ external MCP server must never prevent the agent from using its built-in+ local toolset.+ """+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ config: dict[str, Any] = {+ "mcpServers": {+ "bad-server": {+ "command": "/this/binary/does/not/exist",+ "args": [],+ }+ }+ }+ cfg_path = tmp_path / "agent.json"+ cfg_path.write_text(json.dumps(config))+ agent_config = load_agent_config(config_path=cfg_path)++ # Must not raise even though the server command is invalid.+ warnings: list[str] = []+ registry = build_registry(agent_config=agent_config, warn_callback=warnings.append)++ # Local tools (e.g. list_skills) must still be present.+ local_names = registry.tool_names+ assert any("load_skill" in n or "web_search" in n or "backtest" in n for n in local_names), (+ "Expected at least one well-known local tool to survive a broken MCP server"+ )++ # The operator must receive a warning about the skipped server.+ assert any("bad-server" in w for w in warnings), (+ f"Expected a warning mentioning 'bad-server', got: {warnings}"+ )diff --git a/agent/tests/test_registry_mcp_integration.py b/agent/tests/test_registry_mcp_integration.pynew file mode 100644index 000000000..8b75a874b--- /dev/null+++ b/agent/tests/test_registry_mcp_integration.py@@ -0,0 +1,293 @@+"""Integration tests for MCP tool injection into the tool registry (Phase 3)."""++from __future__ import annotations++import logging+from typing import Any+from unittest.mock import MagicMock, patch++import pytest++from src.config.schema import AgentConfig, MCPServerConfig+from src.tools import build_registry+from src.tools.mcp import MCPRemoteTool+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_agent_config(servers: dict[str, dict[str, Any]]) -> AgentConfig:+ """Build an AgentConfig from a plain 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."""+ adapter = MagicMock()+ adapter.server_name = server_name+ wrappers = []+ 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]+++# ---------------------------------------------------------------------------+# Regression: no agent_config β unchanged behaviour+# ---------------------------------------------------------------------------+++def test_no_agent_config_produces_no_mcp_tools() -> None:+ """build_registry() with no agent_config must not add any mcp_ tools."""+ registry = build_registry()++ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_")]+ assert mcp_names == [], f"Unexpected MCP tools in registry: {mcp_names}"+++def test_empty_mcp_servers_produces_no_mcp_tools() -> None:+ """An AgentConfig with no mcp_servers must behave like no config at all."""+ empty_config = AgentConfig.model_validate({"mcpServers": {}})+ registry = build_registry(agent_config=empty_config)++ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_")]+ assert mcp_names == [], f"Unexpected MCP tools in registry: {mcp_names}"+++# ---------------------------------------------------------------------------+# Happy path: MCP tools appear after local tools+# ---------------------------------------------------------------------------+++def test_mcp_tools_are_injected_and_come_after_local_tools() -> None:+ """MCP tools must be appended after local tools, preserving local order."""+ fake_wrappers = _make_fake_wrappers("demo", ["price_quote", "search"])++ with patch("src.tools.mcp.build_mcp_tool_wrappers", return_value=fake_wrappers):+ config = _make_agent_config({"demo": {"command": "uvx", "args": []}})+ registry = build_registry(agent_config=config)++ all_names = registry.tool_names+ mcp_names = [n for n in all_names if n.startswith("mcp_")]+ local_names = [n for n in all_names if not n.startswith("mcp_")]++ assert "mcp_demo_price_quote" in mcp_names+ assert "mcp_demo_search" in mcp_names++ # Every local tool must appear before every MCP tool in the ordered list.+ if local_names and mcp_names:+ last_local_idx = max(all_names.index(n) for n in local_names)+ first_mcp_idx = min(all_names.index(n) for n in mcp_names)+ assert last_local_idx < first_mcp_idx, (+ "MCP tools must come after all local tools in the registry"+ )+++def test_mcp_tools_registration_order_matches_config_order() -> None:+ """Tools from the same server are registered in discovery order."""+ fake_wrappers = _make_fake_wrappers("alpha", ["tool_a", "tool_b", "tool_c"])++ with patch("src.tools.mcp.build_mcp_tool_wrappers", return_value=fake_wrappers):+ config = _make_agent_config({"alpha": {"command": "uvx", "args": []}})+ registry = build_registry(agent_config=config)++ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_alpha_")]+ assert mcp_names == ["mcp_alpha_tool_a", "mcp_alpha_tool_b", "mcp_alpha_tool_c"]+++def test_colliding_sanitized_server_names_receive_stable_unique_prefixes() -> None:+ """Different raw server names that sanitize identically must still stay unique."""++ def _wrapper_factory(+ server_name: str,+ server_config: MCPServerConfig,+ *,+ local_server_name: str | None = None,+ **_kw: Any,+ ):+ del server_name, server_config+ assert local_server_name is not None+ return _make_fake_wrappers(local_server_name, ["search"])++ with patch("src.tools.mcp.build_mcp_tool_wrappers", side_effect=_wrapper_factory):+ config = _make_agent_config({+ "foo-bar": {"command": "uvx", "args": []},+ "foo_bar": {"command": "uvx", "args": []},+ })+ registry = build_registry(agent_config=config)++ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_foo_bar_")]+ assert len(mcp_names) == 2+ assert len(set(mcp_names)) == 2+ assert "mcp_foo_bar_search" not in mcp_names+ assert all(name.endswith("_search") for name in mcp_names)+++# ---------------------------------------------------------------------------+# is_readonly enforcement+# ---------------------------------------------------------------------------+++def test_mcp_tools_are_not_readonly() -> None:+ """All MCP tools injected into the registry must have is_readonly=False."""+ fake_wrappers = _make_fake_wrappers("srv", ["query"])++ with patch("src.tools.mcp.build_mcp_tool_wrappers", return_value=fake_wrappers):+ config = _make_agent_config({"srv": {"command": "uvx", "args": []}})+ registry = build_registry(agent_config=config)++ mcp_tools = [registry.get(n) for n in registry.tool_names if n.startswith("mcp_")]+ assert mcp_tools, "Expected at least one MCP tool to be registered"+ for tool in mcp_tools:+ assert tool is not None+ assert tool.is_readonly is False, (+ f"Tool {tool.name} must have is_readonly=False to stay on the serial path"+ )+++# ---------------------------------------------------------------------------+# Failure isolation+# ---------------------------------------------------------------------------+++def test_failed_mcp_server_does_not_block_local_tools(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """A server that raises during discovery must be skipped with a warning."""+ with patch(+ "src.tools.mcp.build_mcp_tool_wrappers",+ side_effect=RuntimeError("connection refused"),+ ):+ config = _make_agent_config({"broken": {"command": "uvx", "args": []}})+ with caplog.at_level(logging.WARNING, logger="src.tools"):+ registry = build_registry(agent_config=config)++ # Local tools must still be present.+ assert len(registry) > 0++ # No MCP tools should appear.+ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_")]+ assert mcp_names == []++ # A warning must be emitted naming the skipped server.+ assert any("broken" in record.message for record in caplog.records), (+ "Expected a warning mentioning the skipped server name"+ )+++def test_one_failed_server_does_not_affect_other_mcp_servers() -> None:+ """Tools from a healthy server must be registered even if another server fails."""+ good_wrappers = _make_fake_wrappers("good", ["alpha"])++ def _selective_factory(server_name: str, server_config: MCPServerConfig, **_kw: Any):+ if server_name == "broken":+ raise RuntimeError("refused")+ return good_wrappers++ with patch("src.tools.mcp.build_mcp_tool_wrappers", side_effect=_selective_factory):+ config = _make_agent_config({+ "broken": {"command": "uvx", "args": []},+ "good": {"command": "uvx", "args": []},+ })+ registry = build_registry(agent_config=config)++ assert "mcp_good_alpha" in registry.tool_names+ broken_tools = [n for n in registry.tool_names if n.startswith("mcp_broken_")]+ assert broken_tools == []+++# ---------------------------------------------------------------------------+# No-config regression: existing call sites unaffected+# ---------------------------------------------------------------------------+++def test_build_registry_default_call_is_unchanged() -> None:+ """Calling build_registry() with no kwargs must produce identical results."""+ r1 = build_registry()+ r2 = build_registry(agent_config=None)++ assert set(r1.tool_names) == set(r2.tool_names)+++# ---------------------------------------------------------------------------+# Phase 4: warn_callback surfaces server-name collision warnings+# ---------------------------------------------------------------------------+++def test_warn_callback_called_on_server_name_collision() -> None:+ """build_registry() must invoke warn_callback when two servers collide after sanitization."""+ received: list[str] = []++ def _wrapper_factory(+ server_name: str,+ server_config: MCPServerConfig,+ *,+ local_server_name: str | None = None,+ **_kw: Any,+ ):+ del server_name, server_config+ return _make_fake_wrappers(local_server_name or "x", ["ping"])++ with patch("src.tools.mcp.build_mcp_tool_wrappers", side_effect=_wrapper_factory):+ config = _make_agent_config({+ "foo-bar": {"command": "uvx", "args": []},+ "foo_bar": {"command": "uvx", "args": []},+ })+ build_registry(agent_config=config, warn_callback=received.append)++ assert len(received) > 0, "warn_callback must be called at least once for a collision"+ assert any("foo" in msg for msg in received), (+ "warn_callback message must mention the colliding server name"+ )+++def test_warn_callback_not_called_when_no_collision() -> None:+ """build_registry() must NOT invoke warn_callback when server names are unique after sanitization."""+ received: list[str] = []+ fake_wrappers = _make_fake_wrappers("alpha", ["tool_a"])++ with patch("src.tools.mcp.build_mcp_tool_wrappers", return_value=fake_wrappers):+ config = _make_agent_config({"alpha": {"command": "uvx", "args": []}})+ build_registry(agent_config=config, warn_callback=received.append)++ assert received == [], f"warn_callback must not fire without a collision; got: {received}"+++def test_warn_callback_omitted_still_logs_collision(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """When warn_callback is absent, logger.warning must still fire for collisions."""++ def _wrapper_factory(+ server_name: str,+ server_config: MCPServerConfig,+ *,+ local_server_name: str | None = None,+ **_kw: Any,+ ):+ del server_name, server_config+ return _make_fake_wrappers(local_server_name or "x", ["ping"])++ with patch("src.tools.mcp.build_mcp_tool_wrappers", side_effect=_wrapper_factory):+ config = _make_agent_config({+ "foo-bar": {"command": "uvx", "args": []},+ "foo_bar": {"command": "uvx", "args": []},+ })+ with caplog.at_level(logging.WARNING, logger="src.tools"):+ registry = build_registry(agent_config=config) # no warn_callback β must not raise++ mcp_names = [n for n in registry.tool_names if n.startswith("mcp_")]+ assert len(mcp_names) == 2++ assert any("foo" in record.message for record in caplog.records), (+ "logger.warning must still fire for the collision even without warn_callback"+ )+