"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(agent): support remote MCP transports
shadowinlife51148d71ee46
diff --git a/README.md b/README.mdindex ec1f0f307..cad5fb560 100644--- a/README.md+++ b/README.md@@ -780,14 +780,19 @@ vibe-trading run "use my-server to do X"| 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 |+| `type` | string | inferred for stdio; required for HTTP | Omit for stdio, or set to `sse` / `streamableHttp` for URL-based servers. |+| `command` | string | required for stdio | Executable to spawn for stdio servers. Invalid for `sse` / `streamableHttp` servers. |+| `args` | array | `[]` | Command-line arguments for stdio servers only. |+| `env` | object | `{}` | Extra environment variables merged into the subprocess env for stdio servers only. |+| `url` | string | required for `sse` / `streamableHttp` | Remote SSE / streamable HTTP endpoint URL. Not used for stdio servers. |+| `headers` | object | `{}` | Extra HTTP headers for `sse` / `streamableHttp` servers only. || `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).+For URL-based transports, `type` is required. The agent no longer guesses between SSE and streamable HTTP from the URL suffix.+### 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:@@ -822,7 +827,7 @@ tool names unique. Rename the server in agent config if you want a different pre| Limit | Detail ||-------|--------|-| Transport | stdio only (SSE / streamable HTTP excluded in v1) |+| Transport | stdio, SSE, and streamable HTTP || 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 |diff --git a/agent/SKILL.md b/agent/SKILL.mdindex 5010b9e3a..6edc5c865 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -187,12 +187,17 @@ Remote tools appear automatically in every `vibe-trading run` / `vibe-trading ch| Field | Required | Default | Description ||-------|----------|---------|-------------|-| `command` | yes | — | Executable to launch |+| `type` | stdio: no, HTTP: yes | inferred only for stdio | Transport type. Use `sse` or `streamableHttp` for URL-based servers. |+| `command` | stdio: yes | — | Executable to launch || `args` | no | `[]` | Command arguments || `env` | no | `{}` | Extra env vars for the subprocess |+| `url` | HTTP: yes | — | Remote SSE / streamable HTTP endpoint URL |+| `headers` | no | `{}` | Extra HTTP headers for SSE / streamable HTTP servers || `toolTimeout` | no | `30` | Seconds before a tool call is cancelled || `enabledTools` | no | `["*"]` | Allowlist of remote tool names. `["*"]` enables all |+For URL-based transports, `type` is required. The agent no longer guesses between SSE and streamable HTTP from the URL suffix.+### 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.@@ -223,7 +228,7 @@ Without `ALLOW_SESSION_MCP_SERVERS=1`, any `mcpServers` key in `session.config`### v1 limits-- **Transport:** stdio only. SSE and HTTP transports are rejected.+- **Transport:** stdio, SSE, and streamable HTTP.- **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.diff --git a/agent/src/config/loader.py b/agent/src/config/loader.pyindex 3f4422c72..543da7ae7 100644--- a/agent/src/config/loader.py+++ b/agent/src/config/loader.py@@ -11,7 +11,7 @@ from typing import Any, Mappingfrom pydantic import ValidationErrorfrom src.config.paths import get_config_path-from src.config.schema import AgentConfig, AgentConfigOverride+from src.config.schema import AgentConfig, AgentConfigOverride, MCPServerConfiglogger = logging.getLogger(__name__)@@ -80,11 +80,19 @@ def merge_agent_config_overrides()return config- merged = _merge_dicts(+ merged = _merge_agent_config_dicts(config.model_dump(mode="json"),override_model.model_dump(mode="json", exclude_unset=True),)- return AgentConfig.model_validate(merged)+ try:+ return AgentConfig.model_validate(merged)+ except ValidationError as exc:+ logger.warning(+ "Ignoring merged agent config overrides after validation failure (%s): %s — using base config",+ type(exc).__name__,+ [str(e["loc"]) for e in exc.errors()],+ )+ return config# Keys in session overrides that carry subprocess definitions and therefore@@ -169,6 +177,70 @@ def _read_config_file(path: Path) -> dict[str, Any]:return data+def _merge_agent_config_dicts(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:+ """Merge top-level agent config payloads with MCP-aware server replacement."""+ non_mcp_override = {key: value for key, value in override.items() if key != "mcp_servers"}+ merged = _merge_dicts(base, non_mcp_override)++ override_servers = override.get("mcp_servers")+ if not isinstance(override_servers, dict):+ if "mcp_servers" in override:+ merged["mcp_servers"] = override_servers+ return merged++ merged_servers = dict(base.get("mcp_servers", {}))+ for server_name, server_override in override_servers.items():+ current_server = merged_servers.get(server_name)+ if isinstance(current_server, dict) and isinstance(server_override, dict):+ merged_servers[server_name] = _merge_mcp_server_dicts(current_server, server_override)+ else:+ merged_servers[server_name] = server_override++ merged["mcp_servers"] = merged_servers+ return merged+++def _merge_mcp_server_dicts(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:+ """Merge one MCP server payload, resetting incompatible transport fields when needed."""+ if _override_switches_transport(base, override):+ return _merge_dicts(_default_mcp_server_payload(base), override)+ return _merge_dicts(base, override)+++def _override_switches_transport(base: dict[str, Any], override: dict[str, Any]) -> bool:+ """Return whether a partial override changes the server transport family."""+ override_transport = _resolve_override_transport(override)+ if override_transport is None:+ return False+ base_transport = MCPServerConfig.model_validate(base).resolved_transport()+ return override_transport != base_transport+++def _resolve_override_transport(override: dict[str, Any]) -> str | None:+ """Infer transport intent from a partial MCP server override."""+ explicit_type = override.get("type")+ if explicit_type in {"stdio", "sse", "streamableHttp"}:+ return str(explicit_type)+ if any(key in override for key in ("command", "args", "env")):+ return "stdio"+ return None+++def _default_mcp_server_payload(base: dict[str, Any]) -> dict[str, Any]:+ """Return a transport-neutral MCP server payload preserving non-transport defaults."""+ enabled_tools = base.get("enabled_tools")+ return {+ "type": None,+ "command": "",+ "args": [],+ "env": {},+ "url": "",+ "headers": {},+ "tool_timeout": base.get("tool_timeout", 30.0),+ "enabled_tools": list(enabled_tools) if isinstance(enabled_tools, list) else ["*"],+ }++def _merge_dicts(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:"""Recursively merge two plain dictionaries.diff --git a/agent/src/config/schema.py b/agent/src/config/schema.pyindex 9124e1269..01d4f9ccd 100644--- a/agent/src/config/schema.py+++ b/agent/src/config/schema.py@@ -38,30 +38,40 @@ class MCPServerConfig(ConfigBase):tool_timeout: float = Field(default=30.0, ge=0.1)enabled_tools: list[str] = Field(default_factory=lambda: ["*"])+ def resolved_transport(self) -> Literal["stdio", "sse", "streamableHttp"]:+ """Resolve the effective transport from explicit type or implied fields."""+ if self.type is not None:+ return self.type+ if self.command.strip() or self.args or self.env:+ return "stdio"+ if self.url.strip():+ raise ValueError("HTTP MCP servers require an explicit type of 'sse' or 'streamableHttp'")+ return "stdio"+@model_validator(mode="after")- def validate_v1_stdio_only(self) -> "MCPServerConfig":- """Reject non-stdio transports for the first release.+ def validate_transport_config(self) -> "MCPServerConfig":+ """Validate transport-specific MCP server configuration.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.+ ValueError: If required fields are missing for the resolved+ transport or conflicting fields are provided."""- 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")+ transport = self.resolved_transport()++ if transport == "stdio":+ if not self.command.strip():+ raise ValueError("stdio MCP servers require a command")+ if self.url.strip() or self.headers:+ raise ValueError("stdio MCP servers do not accept url/headers")+ return self++ if not self.url.strip():+ raise ValueError(f"{transport} MCP servers require a url")+ if self.command.strip() or self.args or self.env:+ raise ValueError(f"{transport} MCP servers do not accept command/args/env")return selfdiff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex f8f1c6bd3..81d2bca58 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -265,6 +265,7 @@ class SessionService:session_id = attempt.session_idattempt_id = attempt.attempt_id+ loop = asyncio.get_running_loop()safe_overrides = sanitize_session_overrides(session_config) if session_config else session_configagent_config = load_runtime_agent_config(overrides=safe_overrides)@@ -278,13 +279,18 @@ class SessionService:"""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(+ registry = await loop.run_in_executor(+ _AGENT_EXECUTOR,+ lambda: build_registry(persistent_memory=pm,include_shell_tools=include_shell_tools,agent_config=agent_config,warn_callback=_mcp_collision_warn,),+ )++ agent = AgentLoop(+ registry=registry,llm=llm,event_callback=event_callback,max_iterations=50,@@ -296,7 +302,6 @@ class SessionService:history = self._convert_messages_to_history(messages) if messages else Nonetry:- loop = asyncio.get_running_loop()result = await loop.run_in_executor(_AGENT_EXECUTOR,lambda: agent.run(diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex 2bdfac869..616bfbfde 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -15,6 +15,8 @@ from typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, Typefrom fastmcp.client import Clientfrom fastmcp.client.client import CallToolResult+from fastmcp.client.transports.http import StreamableHttpTransport+from fastmcp.client.transports.sse import SSETransportfrom fastmcp.client.transports.stdio import StdioTransportfrom fastmcp.exceptions import McpError, ToolErrorfrom mcp import types as mcp_types@@ -343,19 +345,33 @@ class MCPServerAdapter:}def _build_client(self) -> AsyncMCPClient:- """Create the default FastMCP stdio client.+ """Create the default FastMCP client from MCP transport config.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,- )+ transport_type = self.server_config.resolved_transport()++ if transport_type == "stdio":+ 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,+ )+ elif transport_type == "sse":+ transport = SSETransport(+ url=self.server_config.url,+ headers=dict(self.server_config.headers) or None,+ )+ else:+ transport = StreamableHttpTransport(+ url=self.server_config.url,+ headers=dict(self.server_config.headers) or None,+ )+# 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.@@ -388,7 +404,7 @@ class MCPServerAdapter: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.+ """Call a remote tool with timeout and no automatic retry.Args:remote_name: Remote tool name.@@ -409,7 +425,10 @@ class MCPServerAdapter:raise_on_error=False,)- return await self._run_with_retry(f"call_tool:{remote_name}", _invoke)+ # Remote MCP tools are arbitrary and may mutate external state. If a+ # timeout / connection drop happens after the server has already+ # committed the action, retrying here would duplicate the side effect.+ return await _invoke()async def _run_with_retry(self,diff --git a/agent/tests/fixtures/fake_mcp_sse_server.py b/agent/tests/fixtures/fake_mcp_sse_server.pynew file mode 100644index 000000000..cd16dfa05--- /dev/null+++ b/agent/tests/fixtures/fake_mcp_sse_server.py@@ -0,0 +1,53 @@+"""Minimal FastMCP SSE server for integration tests.++Launched as an HTTP subprocess by test_mcp_sse_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_sse_server.py --port 0 --port-file /tmp/fake-mcp-sse.port+"""++from __future__ import annotations++import argparse+import asyncio+from pathlib import Path++from fastmcp import FastMCP+import uvicorn++mcp = FastMCP("fake-mcp-sse-server")+++def echo(message: str) -> str:+ """Echo a message back with a prefix."""+ return f"echo: {message}"+++def add(a: int, b: int) -> int:+ """Add two integers."""+ return a + b+++def main() -> None:+ parser = argparse.ArgumentParser(description="Minimal FastMCP SSE test server")+ parser.add_argument("--port", type=int, default=18900, help="SSE port")+ parser.add_argument("--path", default="/sse", help="SSE path")+ parser.add_argument("--port-file", default="", help="Optional file to write the bound port")+ args = parser.parse_args()++ app = mcp.http_app(path=args.path, transport="sse")+ config = uvicorn.Config(app, host="127.0.0.1", port=args.port, log_level="warning")+ server = uvicorn.Server(config)+ sock = config.bind_socket()+ if args.port_file:+ Path(args.port_file).write_text(str(sock.getsockname()[1]), encoding="utf-8")+ asyncio.run(server.serve(sockets=[sock]))+++if __name__ == "__main__":+ main()diff --git a/agent/tests/fixtures/fake_mcp_streamable_http_server.py b/agent/tests/fixtures/fake_mcp_streamable_http_server.pynew file mode 100644index 000000000..fb851e27d--- /dev/null+++ b/agent/tests/fixtures/fake_mcp_streamable_http_server.py@@ -0,0 +1,53 @@+"""Minimal FastMCP streamable HTTP server for integration tests.++Launched as an HTTP subprocess by test_mcp_streamable_http_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_streamable_http_server.py --port 0 --path /mcp --port-file /tmp/fake-mcp-http.port+"""++from __future__ import annotations++import argparse+import asyncio+from pathlib import Path++from fastmcp import FastMCP+import uvicorn++mcp = FastMCP("fake-mcp-streamable-http-server")+++def echo(message: str) -> str:+ """Echo a message back with a prefix."""+ return f"echo: {message}"+++def add(a: int, b: int) -> int:+ """Add two integers."""+ return a + b+++def main() -> None:+ parser = argparse.ArgumentParser(description="Minimal FastMCP streamable HTTP test server")+ parser.add_argument("--port", type=int, default=18910, help="HTTP port")+ parser.add_argument("--path", default="/mcp", help="HTTP path")+ parser.add_argument("--port-file", default="", help="Optional file to write the bound port")+ args = parser.parse_args()++ app = mcp.http_app(path=args.path, transport="streamable-http")+ config = uvicorn.Config(app, host="127.0.0.1", port=args.port, log_level="warning")+ server = uvicorn.Server(config)+ sock = config.bind_socket()+ if args.port_file:+ Path(args.port_file).write_text(str(sock.getsockname()[1]), encoding="utf-8")+ asyncio.run(server.serve(sockets=[sock]))+++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/agent/tests/mcp_http_test_helpers.py b/agent/tests/mcp_http_test_helpers.pynew file mode 100644index 000000000..c8b44ada9--- /dev/null+++ b/agent/tests/mcp_http_test_helpers.py@@ -0,0 +1,252 @@+"""Shared helpers for HTTP-based MCP integration tests."""++from __future__ import annotations++import json+import socket+import subprocess+import sys+import tempfile+import time+from contextlib import contextmanager+from pathlib import Path+from typing import Any, Callable, Iterator++import requests++_PYTHON = sys.executable+++def make_single_server_agent_json(+ tmp_path: Path,+ server_name: str,+ *,+ transport_type: str,+ url: str,+ **server_kwargs: Any,+) -> Path:+ """Write a minimal agent.json with one remote MCP server."""+ config: dict[str, Any] = {+ "mcpServers": {+ server_name: {+ "type": transport_type,+ "url": url,+ **server_kwargs,+ }+ }+ }+ cfg_path = tmp_path / "agent.json"+ cfg_path.write_text(json.dumps(config))+ return cfg_path+++@contextmanager+def reserved_local_port() -> Iterator[int]:+ """Reserve a loopback port for the lifetime of the context."""+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ yield int(sock.getsockname()[1])+++def stop_http_mcp_server(proc: subprocess.Popen[str]) -> None:+ """Terminate an HTTP MCP subprocess and wait for clean exit."""+ if proc.poll() is not None:+ return+ proc.terminate()+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout=5)+++def _collect_process_output(proc: subprocess.Popen[str]) -> str:+ """Return subprocess stdout after ensuring the process has exited."""+ if proc.poll() is None:+ stop_http_mcp_server(proc)+ return proc.stdout.read() if proc.stdout is not None else ""+++def start_http_mcp_server(+ fixture_server: Path,+ *,+ ready_url: str,+ service_name: str,+ extra_args: list[str],+ ready_statuses: set[int] | None = None,+ ready_request_kwargs: dict[str, Any] | None = None,+) -> subprocess.Popen[str]:+ """Start an HTTP MCP subprocess and wait until the endpoint is reachable."""+ proc = subprocess.Popen(+ [_PYTHON, str(fixture_server), *extra_args],+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ )+ request_kwargs = dict(ready_request_kwargs or {})+ accepted_statuses = set(ready_statuses or {200})++ for _ in range(40):+ if proc.poll() is not None:+ output = proc.stdout.read() if proc.stdout is not None else ""+ raise RuntimeError(f"{service_name} failed to start with exit code {proc.returncode}: {output}")+ try:+ response = requests.get(ready_url, timeout=0.5, **request_kwargs)+ if response.status_code in accepted_statuses:+ response.close()+ return proc+ response.close()+ except requests.RequestException:+ time.sleep(0.2)++ stop_http_mcp_server(proc)+ output = proc.stdout.read() if proc.stdout is not None else ""+ raise RuntimeError(f"{service_name} did not become ready within 8 seconds: {output}")+++def start_http_mcp_server_on_random_port(+ fixture_server: Path,+ *,+ service_name: str,+ ready_url_builder: Callable[[int], str],+ extra_args_builder: Callable[[int], list[str]],+ ready_statuses: set[int] | None = None,+ ready_request_kwargs: dict[str, Any] | None = None,+ max_attempts: int = 5,+) -> tuple[subprocess.Popen[str], int]:+ """Start an HTTP MCP subprocess on an OS-assigned port."""+ last_error: RuntimeError | None = None++ for _ in range(max_attempts):+ with tempfile.TemporaryDirectory(prefix="mcp-port-") as temp_dir:+ port_file = Path(temp_dir) / "port.txt"+ proc = subprocess.Popen(+ [_PYTHON, str(fixture_server), *extra_args_builder(0), "--port-file", str(port_file)],+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ )+ try:+ port = _wait_for_server_port(proc, port_file, service_name=service_name)+ _wait_for_http_ready(+ proc,+ ready_url=ready_url_builder(port),+ service_name=service_name,+ ready_statuses=ready_statuses,+ ready_request_kwargs=ready_request_kwargs,+ )+ return proc, port+ except RuntimeError as exc:+ last_error = exc+ stop_http_mcp_server(proc)++ if last_error is not None:+ raise last_error+ raise RuntimeError(f"{service_name} could not obtain an available port")+++def _wait_for_server_port(+ proc: subprocess.Popen[str],+ port_file: Path,+ *,+ service_name: str,+ timeout_seconds: float = 8.0,+) -> int:+ """Wait until the fixture writes back its bound port."""+ deadline = time.time() + timeout_seconds+ while time.time() < deadline:+ if proc.poll() is not None:+ output = _collect_process_output(proc)+ raise RuntimeError(f"{service_name} failed to start with exit code {proc.returncode}: {output}")+ if port_file.exists():+ try:+ return int(port_file.read_text(encoding="utf-8").strip())+ except ValueError:+ pass+ time.sleep(0.05)++ output = _collect_process_output(proc)+ raise RuntimeError(f"{service_name} did not write its listening port within 8 seconds: {output}")+++def _wait_for_http_ready(+ proc: subprocess.Popen[str],+ *,+ ready_url: str,+ service_name: str,+ ready_statuses: set[int] | None = None,+ ready_request_kwargs: dict[str, Any] | None = None,+ timeout_seconds: float = 8.0,+) -> None:+ """Poll the fixture endpoint until it is reachable."""+ request_kwargs = dict(ready_request_kwargs or {})+ accepted_statuses = set(ready_statuses or {200})+ deadline = time.time() + timeout_seconds++ while time.time() < deadline:+ if proc.poll() is not None:+ output = _collect_process_output(proc)+ raise RuntimeError(f"{service_name} failed to start with exit code {proc.returncode}: {output}")+ try:+ response = requests.get(ready_url, timeout=0.5, **request_kwargs)+ if response.status_code in accepted_statuses:+ response.close()+ return+ response.close()+ except requests.RequestException:+ time.sleep(0.2)++ output = _collect_process_output(proc)+ raise RuntimeError(f"{service_name} did not become ready within 8 seconds: {output}")+++@contextmanager+def running_http_mcp_server(+ fixture_server: Path,+ *,+ ready_url: str,+ service_name: str,+ extra_args: list[str],+ ready_statuses: set[int] | None = None,+ ready_request_kwargs: dict[str, Any] | None = None,+) -> Iterator[subprocess.Popen[str]]:+ """Context manager that runs a FastMCP HTTP server for one test."""+ proc = start_http_mcp_server(+ fixture_server,+ ready_url=ready_url,+ service_name=service_name,+ extra_args=extra_args,+ ready_statuses=ready_statuses,+ ready_request_kwargs=ready_request_kwargs,+ )+ try:+ yield proc+ finally:+ stop_http_mcp_server(proc)+++@contextmanager+def running_http_mcp_server_on_random_port(+ fixture_server: Path,+ *,+ service_name: str,+ ready_url_builder: Callable[[int], str],+ extra_args_builder: Callable[[int], list[str]],+ ready_statuses: set[int] | None = None,+ ready_request_kwargs: dict[str, Any] | None = None,+ max_attempts: int = 5,+) -> Iterator[tuple[subprocess.Popen[str], int]]:+ """Context manager that runs a FastMCP HTTP server on a retryable free port."""+ proc, port = start_http_mcp_server_on_random_port(+ fixture_server,+ service_name=service_name,+ ready_url_builder=ready_url_builder,+ extra_args_builder=extra_args_builder,+ ready_statuses=ready_statuses,+ ready_request_kwargs=ready_request_kwargs,+ max_attempts=max_attempts,+ )+ try:+ yield proc, port+ finally:+ stop_http_mcp_server(proc)\ No newline at end of filediff --git a/agent/tests/test_agent_config.py b/agent/tests/test_agent_config.pyindex cb57a57e4..4a8a3ec79 100644--- a/agent/tests/test_agent_config.py+++ b/agent/tests/test_agent_config.py@@ -73,7 +73,53 @@ def test_load_agent_config_supports_yaml(tmp_path: Path) -> None:assert config.mcp_servers["demo"].args == ["demo-server"]-def test_schema_rejects_non_stdio_transports() -> None:+def test_schema_accepts_sse_transport() -> None:+ config = AgentConfig.model_validate(+ {+ "mcpServers": {+ "demo": {+ "type": "sse",+ "url": "http://localhost:8900/sse",+ "headers": {"Authorization": "Bearer demo"},+ }+ }+ }+ )++ assert config.mcp_servers["demo"].type == "sse"+ assert config.mcp_servers["demo"].url == "http://localhost:8900/sse"+++def test_schema_accepts_streamable_http_transport() -> None:+ config = AgentConfig.model_validate(+ {+ "mcpServers": {+ "demo": {+ "type": "streamableHttp",+ "url": "http://localhost:8900/mcp",+ }+ }+ }+ )++ assert config.mcp_servers["demo"].type == "streamableHttp"+ assert config.mcp_servers["demo"].url == "http://localhost:8900/mcp"+++def test_schema_rejects_url_only_http_transport_without_type() -> None:+ with pytest.raises(ValidationError):+ AgentConfig.model_validate(+ {+ "mcpServers": {+ "demo": {+ "url": "http://localhost:8900/events",+ }+ }+ }+ )+++def test_schema_rejects_http_transport_with_stdio_fields() -> None:with pytest.raises(ValidationError):AgentConfig.model_validate({@@ -81,6 +127,22 @@ def test_schema_rejects_non_stdio_transports() -> None:"demo": {"type": "sse","url": "http://localhost:8900/sse",+ "command": "uvx",+ }+ }+ }+ )+++def test_schema_rejects_stdio_with_http_fields() -> None:+ with pytest.raises(ValidationError):+ AgentConfig.model_validate(+ {+ "mcpServers": {+ "demo": {+ "type": "stdio",+ "command": "uvx",+ "url": "http://localhost:8900/sse",}}}@@ -143,6 +205,68 @@ def test_runtime_overrides_take_precedence_and_merge_nested_servers(tmp_path: Paassert config.mcp_servers["research"].command == "research-server"+def test_runtime_overrides_can_replace_server_transport(tmp_path: Path) -> None:+ config_path = tmp_path / "agent.json"+ config_path.write_text(+ """+ {+ "mcpServers": {+ "demo": {+ "command": "base-server",+ "args": ["--base"],+ "toolTimeout": 45,+ "enabledTools": ["alpha"]+ }+ }+ }+ """.strip(),+ encoding="utf-8",+ )++ config = load_runtime_agent_config(+ config_path,+ overrides={+ "mcpServers": {+ "demo": {+ "type": "sse",+ "url": "http://localhost:8900/sse",+ "headers": {"Authorization": "Bearer demo"},+ }+ }+ },+ )++ assert config.mcp_servers["demo"].type == "sse"+ assert config.mcp_servers["demo"].url == "http://localhost:8900/sse"+ assert config.mcp_servers["demo"].headers == {"Authorization": "Bearer demo"}+ assert config.mcp_servers["demo"].command == ""+ assert config.mcp_servers["demo"].args == []+ assert config.mcp_servers["demo"].tool_timeout == 45+ assert config.mcp_servers["demo"].enabled_tools == ["alpha"]+++def test_runtime_overrides_fall_back_to_base_config_when_merge_is_invalid(tmp_path: Path) -> None:+ config_path = tmp_path / "agent.json"+ config_path.write_text(+ '{"mcpServers": {"demo": {"command": "base-server", "args": ["--base"]}}}',+ encoding="utf-8",+ )++ config = load_runtime_agent_config(+ config_path,+ overrides={+ "mcpServers": {+ "demo": {+ "url": "http://localhost:8900/events",+ }+ }+ },+ )++ assert config.mcp_servers["demo"].command == "base-server"+ assert config.mcp_servers["demo"].args == ["--base"]++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)diff --git a/agent/tests/test_mcp_client_adapter.py b/agent/tests/test_mcp_client_adapter.pyindex 20b001ccc..9129d878b 100644--- a/agent/tests/test_mcp_client_adapter.py+++ b/agent/tests/test_mcp_client_adapter.py@@ -6,12 +6,14 @@ import jsonimport loggingfrom typing import Any+import pytestfrom fastmcp.client.client import CallToolResultfrom fastmcp.exceptions import McpError, ToolErrorfrom mcp import types as mcp_typesfrom src.config.schema import MCPServerConfigfrom src.tools.mcp import (+ MCPServerAdapter,build_mcp_tool_wrappers,format_mcp_server_name_collision_warning,make_mcp_tool_name,@@ -203,7 +205,7 @@ def test_build_mcp_tool_wrappers_honors_local_server_name_override() -> None: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:+def test_remote_tool_execute_does_not_retry_timeout_and_strips_run_dir() -> None:state = {"list_calls": 0,"call_calls": 0,@@ -219,22 +221,19 @@ def test_remote_tool_execute_retries_transient_timeout_and_strips_run_dir() -> N},)]],- "call_outcomes": [- TimeoutError("timed out"),- CallToolResult(content=[], structured_content={"price": 12.3}, meta=None, data={"price": 12.3}),- ],+ "call_outcomes": [TimeoutError("timed out")],}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["status"] == "error"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 payload["error"] == "timed out"+ assert state["call_calls"] == 1assert state["call_records"][0]["arguments"] == {"symbol": "AAPL"}assert state["call_records"][0]["timeout"] == 7assert state["call_records"][0]["raise_on_error"] is False@@ -399,4 +398,100 @@ def test_normalize_mcp_tool_schema_collapses_nested_type_list_with_null() -> Non})- assert schema["properties"]["label"]["type"] == "string"\ No newline at end of file+ assert schema["properties"]["label"]["type"] == "string"+++def test_build_client_uses_stdio_transport(monkeypatch) -> None:+ captured: dict[str, Any] = {}++ class _DummyClient:+ pass++ def _fake_stdio_transport(**kwargs: Any) -> object:+ captured["transport"] = "stdio"+ captured["transport_kwargs"] = kwargs+ return object()++ def _fake_client(transport: object, **kwargs: Any) -> _DummyClient:+ captured["client_transport"] = transport+ captured["client_kwargs"] = kwargs+ return _DummyClient()++ monkeypatch.setattr("src.tools.mcp.StdioTransport", _fake_stdio_transport)+ monkeypatch.setattr("src.tools.mcp.Client", _fake_client)++ adapter = MCPServerAdapter("demo", _make_config(command="uvx", args=["demo-server"]))+ adapter._build_client()++ assert captured["transport"] == "stdio"+ assert captured["transport_kwargs"]["command"] == "uvx"+ assert captured["transport_kwargs"]["args"] == ["demo-server"]+++def test_build_client_uses_sse_transport(monkeypatch) -> None:+ captured: dict[str, Any] = {}++ class _DummyClient:+ pass++ def _fake_sse_transport(**kwargs: Any) -> object:+ captured["transport"] = "sse"+ captured["transport_kwargs"] = kwargs+ return object()++ def _fake_client(transport: object, **kwargs: Any) -> _DummyClient:+ captured["client_transport"] = transport+ captured["client_kwargs"] = kwargs+ return _DummyClient()++ monkeypatch.setattr("src.tools.mcp.SSETransport", _fake_sse_transport)+ monkeypatch.setattr("src.tools.mcp.Client", _fake_client)++ adapter = MCPServerAdapter(+ "demo",+ _make_config(type="sse", command="", args=[], url="http://localhost:8900/sse", headers={"X-Test": "1"}),+ )+ adapter._build_client()++ assert captured["transport"] == "sse"+ assert captured["transport_kwargs"]["url"] == "http://localhost:8900/sse"+ assert captured["transport_kwargs"]["headers"] == {"X-Test": "1"}+++def test_build_client_uses_streamable_http_transport(monkeypatch) -> None:+ captured: dict[str, Any] = {}++ class _DummyClient:+ pass++ def _fake_http_transport(**kwargs: Any) -> object:+ captured["transport"] = "streamableHttp"+ captured["transport_kwargs"] = kwargs+ return object()++ def _fake_client(transport: object, **kwargs: Any) -> _DummyClient:+ captured["client_transport"] = transport+ captured["client_kwargs"] = kwargs+ return _DummyClient()++ monkeypatch.setattr("src.tools.mcp.StreamableHttpTransport", _fake_http_transport)+ monkeypatch.setattr("src.tools.mcp.Client", _fake_client)++ adapter = MCPServerAdapter(+ "demo",+ _make_config(type="streamableHttp", command="", args=[], url="http://localhost:8900/mcp"),+ )+ adapter._build_client()++ assert captured["transport"] == "streamableHttp"+ assert captured["transport_kwargs"]["url"] == "http://localhost:8900/mcp"+++def test_build_client_rejects_url_only_config_without_explicit_type() -> None:+ config = _make_config(type="sse", command="", args=[], url="http://localhost:8900/sse")+ config.type = None++ adapter = MCPServerAdapter("demo", config)++ with pytest.raises(ValueError, match="explicit type"):+ adapter._build_client()\ No newline at end of filediff --git a/agent/tests/test_mcp_sse_integration.py b/agent/tests/test_mcp_sse_integration.pynew file mode 100644index 000000000..53c7b1607--- /dev/null+++ b/agent/tests/test_mcp_sse_integration.py@@ -0,0 +1,103 @@+"""Integration tests: full-stack SSE MCP client path with a real FastMCP server.++These tests spawn an actual FastMCP SSE server process+(agent/tests/fixtures/fake_mcp_sse_server.py) and exercise the entire path:++ load_agent_config()+ -> build_registry(agent_config=...)+ -> MCPServerAdapter+ -> SSETransport (real HTTP subprocess)+ -> remote tool callable from registry+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from tests.mcp_http_test_helpers import (+ make_single_server_agent_json,+ running_http_mcp_server_on_random_port,+)++_FIXTURE_SERVER = Path(__file__).resolve().parent / "fixtures" / "fake_mcp_sse_server.py"++pytestmark = pytest.mark.integration+++def _sse_url(port: int) -> str:+ return f"http://127.0.0.1:{port}/sse"+++def _make_agent_json(tmp_path: Path, server_name: str, *, port: int, **server_kwargs: Any) -> Path:+ return make_single_server_agent_json(+ tmp_path,+ server_name,+ transport_type="sse",+ url=_sse_url(port),+ **server_kwargs,+ )+++def test_remote_sse_tool_appears_in_registry(tmp_path: Path) -> None:+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ with running_http_mcp_server_on_random_port(+ _FIXTURE_SERVER,+ service_name="FastMCP SSE service",+ ready_url_builder=_sse_url,+ extra_args_builder=lambda port: ["--port", str(port)],+ ready_request_kwargs={"stream": True},+ ) as (_, port):+ cfg_path = _make_agent_json(tmp_path, "fake_sse", port=port)+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ assert "mcp_fake_sse_echo" in registry.tool_names+++def test_remote_sse_tool_is_callable_and_returns_expected_result(tmp_path: Path) -> None:+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ with running_http_mcp_server_on_random_port(+ _FIXTURE_SERVER,+ service_name="FastMCP SSE service",+ ready_url_builder=_sse_url,+ extra_args_builder=lambda port: ["--port", str(port)],+ ready_request_kwargs={"stream": True},+ ) as (_, port):+ cfg_path = _make_agent_json(tmp_path, "fake_sse", port=port)+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ echo_tool = registry.get("mcp_fake_sse_echo")+ assert echo_tool is not None, "mcp_fake_sse_echo not found in registry"++ result = echo_tool.execute(message="hello")+ assert "echo: hello" in result+++def test_enabled_tools_filter_limits_remote_sse_tools(tmp_path: Path) -> None:+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ with running_http_mcp_server_on_random_port(+ _FIXTURE_SERVER,+ service_name="FastMCP SSE service",+ ready_url_builder=_sse_url,+ extra_args_builder=lambda port: ["--port", str(port)],+ ready_request_kwargs={"stream": True},+ ) as (_, port):+ cfg_path = _make_agent_json(tmp_path, "fake_sse", port=port, enabledTools=["echo"])+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ mcp_names = [name for name in registry.tool_names if name.startswith("mcp_fake_sse_")]+ assert "mcp_fake_sse_echo" in mcp_names+ assert "mcp_fake_sse_add" not in mcp_names, (+ "mcp_fake_sse_add should be excluded by enabledTools filter"+ )diff --git a/agent/tests/test_mcp_stdio_integration.py b/agent/tests/test_mcp_stdio_integration.pyindex a7c34dff3..36cad24fd 100644--- a/agent/tests/test_mcp_stdio_integration.py+++ b/agent/tests/test_mcp_stdio_integration.py@@ -18,8 +18,6 @@ IMPORTANT — v1 limits exercised here:- 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 areallowed to load MCP config."""@@ -33,6 +31,8 @@ from typing import Anyimport pytest+pytestmark = pytest.mark.integration+# ---------------------------------------------------------------------------# Path helpers# ---------------------------------------------------------------------------diff --git a/agent/tests/test_mcp_streamable_http_integration.py b/agent/tests/test_mcp_streamable_http_integration.pynew file mode 100644index 000000000..b5ede38df--- /dev/null+++ b/agent/tests/test_mcp_streamable_http_integration.py@@ -0,0 +1,137 @@+"""Integration tests: full-stack streamable HTTP MCP client path with FastMCP.++These tests spawn an actual FastMCP streamable HTTP server process+(agent/tests/fixtures/fake_mcp_streamable_http_server.py) and exercise the+entire path:++ load_agent_config()+ -> build_registry(agent_config=...)+ -> MCPServerAdapter+ -> StreamableHttpTransport (real HTTP subprocess)+ -> remote tool callable from registry+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from tests.mcp_http_test_helpers import (+ make_single_server_agent_json,+ reserved_local_port,+ running_http_mcp_server_on_random_port,+)++_FIXTURE_SERVER = Path(__file__).resolve().parent / "fixtures" / "fake_mcp_streamable_http_server.py"++HTTP_PATH = "/mcp"++pytestmark = pytest.mark.integration+++def _http_url(port: int) -> str:+ return f"http://127.0.0.1:{port}{HTTP_PATH}"+++def _make_agent_json(tmp_path: Path, server_name: str, *, port: int, **server_kwargs: Any) -> Path:+ return make_single_server_agent_json(+ tmp_path,+ server_name,+ transport_type="streamableHttp",+ url=_http_url(port),+ **server_kwargs,+ )+++def test_remote_streamable_http_tool_appears_in_registry(tmp_path: Path) -> None:+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ with running_http_mcp_server_on_random_port(+ _FIXTURE_SERVER,+ service_name="FastMCP streamable HTTP service",+ ready_url_builder=_http_url,+ extra_args_builder=lambda port: ["--port", str(port), "--path", HTTP_PATH],+ ready_statuses={200, 400, 405, 406},+ ) as (_, port):+ cfg_path = _make_agent_json(tmp_path, "fake_http", port=port)+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ assert "mcp_fake_http_echo" in registry.tool_names+++def test_remote_streamable_http_tool_is_callable_and_returns_expected_result(tmp_path: Path) -> None:+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ with running_http_mcp_server_on_random_port(+ _FIXTURE_SERVER,+ service_name="FastMCP streamable HTTP service",+ ready_url_builder=_http_url,+ extra_args_builder=lambda port: ["--port", str(port), "--path", HTTP_PATH],+ ready_statuses={200, 400, 405, 406},+ ) as (_, port):+ cfg_path = _make_agent_json(tmp_path, "fake_http", port=port)+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ echo_tool = registry.get("mcp_fake_http_echo")+ assert echo_tool is not None, "mcp_fake_http_echo not found in registry"++ result = echo_tool.execute(message="hello")+ assert "echo: hello" in result+++def test_enabled_tools_filter_limits_remote_streamable_http_tools(tmp_path: Path) -> None:+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ with running_http_mcp_server_on_random_port(+ _FIXTURE_SERVER,+ service_name="FastMCP streamable HTTP service",+ ready_url_builder=_http_url,+ extra_args_builder=lambda port: ["--port", str(port), "--path", HTTP_PATH],+ ready_statuses={200, 400, 405, 406},+ ) as (_, port):+ cfg_path = _make_agent_json(tmp_path, "fake_http", port=port, enabledTools=["echo"])+ agent_config = load_agent_config(config_path=cfg_path)+ registry = build_registry(agent_config=agent_config)++ mcp_names = [name for name in registry.tool_names if name.startswith("mcp_fake_http_")]+ assert "mcp_fake_http_echo" in mcp_names+ assert "mcp_fake_http_add" not in mcp_names, (+ "mcp_fake_http_add should be excluded by enabledTools filter"+ )+++def test_unreachable_streamable_http_server_does_not_block_local_tools(tmp_path: Path) -> None:+ """An unreachable streamable HTTP server must be skipped with a warning."""+ from src.config.loader import load_agent_config+ from src.tools import build_registry++ with reserved_local_port() as unused_port:+ bad_url = f"http://127.0.0.1:{unused_port}{HTTP_PATH}"+ cfg_path = make_single_server_agent_json(+ tmp_path,+ "bad-http",+ transport_type="streamableHttp",+ url=bad_url,+ )+ agent_config = load_agent_config(config_path=cfg_path)++ warnings: list[str] = []+ registry = build_registry(agent_config=agent_config, warn_callback=warnings.append)++ local_names = registry.tool_names+ assert any("load_skill" in name or "web_search" in name or "backtest" in name for name in local_names), (+ "Expected at least one well-known local tool to survive an unreachable HTTP MCP server"+ )++ mcp_names = [name for name in local_names if name.startswith("mcp_")]+ assert mcp_names == []+ assert any("bad-http" in warning for warning in warnings), (+ f"Expected a warning mentioning 'bad-http', got: {warnings}"+ )\ No newline at end of filediff --git a/agent/tests/test_session_service_mcp.py b/agent/tests/test_session_service_mcp.pynew file mode 100644index 000000000..a9a913b94--- /dev/null+++ b/agent/tests/test_session_service_mcp.py@@ -0,0 +1,72 @@+"""SessionService regressions for remote MCP startup paths."""++from __future__ import annotations++import asyncio+import time+from pathlib import Path++from src.session.events import EventBus+from src.session.models import Attempt+from src.session.service import SessionService+from src.session.store import SessionStore+++class _DummyIndex:+ def index_session(self, session_id: str, title: str) -> None:+ del session_id, title++ def index_message(self, session_id: str, role: str, content: str) -> None:+ del session_id, role, content+++class _DummyAgentLoop:+ def __init__(self, *, registry, llm, event_callback, max_iterations, persistent_memory) -> None:+ del registry, llm, event_callback, max_iterations, persistent_memory++ def run(self, *, user_message: str, history, session_id: str) -> dict[str, str]:+ del user_message, history, session_id+ return {"status": "completed"}+++def test_run_with_agent_keeps_event_loop_responsive_during_registry_build(+ monkeypatch,+ tmp_path: Path,+) -> None:+ def _slow_build_registry(**kwargs):+ del kwargs+ time.sleep(0.25)+ return object()++ monkeypatch.setattr("src.session.service.get_shared_index", lambda: _DummyIndex())+ monkeypatch.setattr("src.tools.build_registry", _slow_build_registry)+ monkeypatch.setattr("src.providers.chat.ChatLLM", lambda: object())+ monkeypatch.setattr("src.memory.persistent.PersistentMemory", lambda: object())+ monkeypatch.setattr("src.agent.loop.AgentLoop", _DummyAgentLoop)+ monkeypatch.setattr("src.config.loader.load_runtime_agent_config", lambda overrides=None: object())+ monkeypatch.setattr("src.config.loader.sanitize_session_overrides", lambda overrides: dict(overrides))++ service = SessionService(+ store=SessionStore(tmp_path / "sessions"),+ event_bus=EventBus(),+ runs_dir=tmp_path / "runs",+ )+ attempt = Attempt(session_id="session-1", prompt="hello")++ async def _ticker(events: list[float], start: float) -> None:+ await asyncio.sleep(0.05)+ events.append(time.perf_counter() - start)++ async def _exercise() -> tuple[list[float], dict[str, str]]:+ events: list[float] = []+ start = time.perf_counter()+ asyncio.create_task(_ticker(events, start))+ result = await service._run_with_agent(attempt, messages=[], session_config={})+ await asyncio.sleep(0.01)+ return events, result++ tick_times, result = asyncio.run(_exercise())++ assert result["status"] == "completed"+ assert tick_times, "Expected the event loop ticker to run while registry build was pending"+ assert tick_times[0] < 0.18, f"Registry build blocked the event loop for too long: {tick_times[0]:.3f}s"\ No newline at end of file