diff --git a/docker-compose.yml b/docker-compose.yml index 7cceff107b..cfaf527a4d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -103,7 +103,7 @@ services: # Orchestrator API - used by sandbox for pipeline state management - "${ORCHESTRATOR_API_PORT:-9849}:9849" # MCP server - used by external Claude Code sessions - - "${EGG_MCP_SERVER_PORT:-9850}:9850" + - "127.0.0.1:${EGG_MCP_SERVER_PORT:-9850}:9850" environment: # Core configuration - ORCHESTRATOR_PORT=9849 diff --git a/docs/guides/coordinator.md b/docs/guides/coordinator.md index e1bed45130..a29603e752 100644 --- a/docs/guides/coordinator.md +++ b/docs/guides/coordinator.md @@ -60,12 +60,17 @@ Configure Claude Code to connect to the MCP server: { "mcpServers": { "egg-coordinator": { + "type": "sse", "url": "http://localhost:9850/mcp/v1/sse" } } } ``` +The MCP server is accessible only from localhost — the Docker port mapping +restricts access to `127.0.0.1`. No authentication is required because +access is already restricted to the local machine via this port binding. + ### Available Tools | Tool | Description | Required Parameters | Optional Parameters | diff --git a/orchestrator/api.py b/orchestrator/api.py index e88ed65004..150742b370 100644 --- a/orchestrator/api.py +++ b/orchestrator/api.py @@ -159,18 +159,9 @@ def _maybe_start_mcp_server() -> None: mcp_port = int(os.environ.get("EGG_MCP_SERVER_PORT", "9850")) mcp_rate_limit = int(os.environ.get("EGG_MCP_RATE_LIMIT", "30")) - try: - from egg_config import GATEWAY_PORT - except ImportError: - GATEWAY_PORT = 9848 # noqa: EGG002 - - gateway_url = os.environ.get("GATEWAY_URL", f"http://egg-gateway:{GATEWAY_PORT}") - launcher_secret = os.environ.get("EGG_LAUNCHER_SECRET", "") start_mcp_server( port=mcp_port, rate_limit=mcp_rate_limit, - gateway_url=gateway_url, - launcher_secret=launcher_secret, ) logger.info("MCP server started", port=mcp_port) except ImportError: diff --git a/orchestrator/mcp_server.py b/orchestrator/mcp_server.py index 5277d07a3e..e073e61500 100644 --- a/orchestrator/mcp_server.py +++ b/orchestrator/mcp_server.py @@ -7,12 +7,9 @@ """ import json -import os import sys import threading import time -import urllib.parse -import urllib.request from pathlib import Path _shared_path = Path(__file__).parent.parent / "shared" @@ -65,7 +62,9 @@ class MCPServer: - Tool execution endpoint - Health check endpoint - Rate limiting - - Gateway token authentication + + No authentication required — localhost-only access is enforced via + Docker port mapping (127.0.0.1 binding in docker-compose.yml). """ def __init__( @@ -73,14 +72,10 @@ def __init__( orchestrator_url: str = "http://localhost:9849", port: int = DEFAULT_MCP_PORT, rate_limit: int = DEFAULT_RATE_LIMIT, - gateway_url: str | None = None, - launcher_secret: str | None = None, ): self.orchestrator_url = orchestrator_url self.port = port self.rate_limiter = RateLimiter(max_requests=rate_limit) - self.gateway_url = gateway_url - self.launcher_secret = launcher_secret or os.environ.get("EGG_LAUNCHER_SECRET", "") from mcp_tools import COORDINATOR_TOOLS, CoordinatorToolHandler @@ -88,76 +83,22 @@ def __init__( self.tools = COORDINATOR_TOOLS self._app = None - def _validate_gateway_token(self, token: str) -> bool: - """Validate a session token against the gateway. - - Args: - token: Bearer token from Authorization header - - Returns: - True if the token is valid - """ - if not self.gateway_url: - logger.warning("No gateway_url configured, skipping token validation") - return False - - try: - encoded_token = urllib.parse.quote(token, safe="") - url = f"{self.gateway_url}/api/v1/sessions/{encoded_token}" - req = urllib.request.Request(url, method="GET") - req.add_header("Content-Type", "application/json") - if self.launcher_secret: - req.add_header("Authorization", f"Bearer {self.launcher_secret}") - with urllib.request.urlopen(req, timeout=5) as resp: - data = json.loads(resp.read()) - return data.get("valid", False) - except Exception: - logger.warning("Gateway token validation failed", gateway_url=self.gateway_url) - return False - def create_app(self): """Create the Flask application for the MCP server.""" - import functools - from flask import Flask, Response, jsonify, request app = Flask("egg-mcp-server") - server = self - - def require_auth(f): - """Decorator that validates gateway session tokens on protected endpoints.""" - - @functools.wraps(f) - def decorated(*args, **kwargs): - if not server.gateway_url: - # No gateway configured — reject all requests - return jsonify({"error": "Authentication not configured"}), 503 - - auth_header = request.headers.get("Authorization", "") - if not auth_header.startswith("Bearer "): - return jsonify({"error": "Missing or invalid Authorization header"}), 401 - - token = auth_header[7:] # Remove "Bearer " prefix - if not server._validate_gateway_token(token): - return jsonify({"error": "Invalid or expired session token"}), 401 - - return f(*args, **kwargs) - - return decorated @app.route("/health") def health(): return jsonify({"status": "healthy", "service": "egg-mcp-server"}) @app.route("/mcp/v1/tools", methods=["GET"]) - @require_auth def list_tools(): return jsonify({"tools": self.tools}) @app.route("/mcp/v1/tools/call", methods=["POST"]) - @require_auth def call_tool(): - # Rate limiting if not self.rate_limiter.allow(): return jsonify({"error": "Rate limit exceeded"}), 429 @@ -181,7 +122,6 @@ def call_tool(): ) @app.route("/mcp/v1/sse") - @require_auth def sse_stream(): """SSE endpoint for MCP protocol events.""" @@ -209,7 +149,11 @@ def generate(): return app def run(self, host: str = "0.0.0.0", debug: bool = False): - """Start the MCP server.""" + """Start the MCP server. + + Binds to 0.0.0.0 inside the container so Docker port forwarding works. + Localhost-only access is enforced by the docker-compose port mapping. + """ app = self.create_app() logger.info("Starting MCP server", port=self.port, host=host) app.run(host=host, port=self.port, debug=debug, threaded=True) @@ -219,16 +163,12 @@ def start_mcp_server( orchestrator_url: str = "http://localhost:9849", port: int = DEFAULT_MCP_PORT, rate_limit: int = DEFAULT_RATE_LIMIT, - gateway_url: str | None = None, - launcher_secret: str | None = None, ) -> MCPServer: """Start the MCP server in a background thread.""" server = MCPServer( orchestrator_url=orchestrator_url, port=port, rate_limit=rate_limit, - gateway_url=gateway_url, - launcher_secret=launcher_secret, ) thread = threading.Thread(target=server.run, daemon=True) diff --git a/orchestrator/tests/test_coordinator_gaps.py b/orchestrator/tests/test_coordinator_gaps.py index ca7d6e1480..e6c20ff1fc 100644 --- a/orchestrator/tests/test_coordinator_gaps.py +++ b/orchestrator/tests/test_coordinator_gaps.py @@ -870,15 +870,11 @@ def test_mcp_server_health_endpoint(self): assert resp.status_code == 200 assert resp.get_json()["status"] == "healthy" - @patch.object(MCPServer, "_validate_gateway_token", return_value=True) - def test_mcp_server_list_tools_returns_all_five(self, _mock_validate): - server = MCPServer(gateway_url="http://fake-gateway:9848") # noqa: EGG002 + def test_mcp_server_list_tools_returns_all_five(self): + server = MCPServer() app = server.create_app() with app.test_client() as client: - resp = client.get( - "/mcp/v1/tools", - headers={"Authorization": "Bearer test-token"}, - ) + resp = client.get("/mcp/v1/tools") assert resp.status_code == 200 tools = resp.get_json()["tools"] assert len(tools) == 5 @@ -891,95 +887,60 @@ def test_mcp_server_list_tools_returns_all_five(self, _mock_validate): "cancel_task", } - def test_mcp_server_call_tool_missing_auth(self): - server = MCPServer(gateway_url="http://fake-gateway:9848") # noqa: EGG002 - app = server.create_app() - with app.test_client() as client: - resp = client.post( - "/mcp/v1/tools/call", - json={"name": "test"}, - ) - assert resp.status_code == 401 - - def test_mcp_server_call_tool_no_gateway_returns_503(self): + def test_mcp_server_call_tool_missing_body(self): server = MCPServer() app = server.create_app() - with app.test_client() as client: - resp = client.post( - "/mcp/v1/tools/call", - json={"name": "test"}, - headers={"Authorization": "Bearer test-token"}, - ) - assert resp.status_code == 503 - - @patch.object(MCPServer, "_validate_gateway_token", return_value=True) - def test_mcp_server_call_tool_missing_body(self, _mock_validate): - server = MCPServer(gateway_url="http://fake-gateway:9848") # noqa: EGG002 - app = server.create_app() with app.test_client() as client: # Send with JSON content type but empty body triggers 400 resp = client.post( "/mcp/v1/tools/call", json=None, content_type="application/json", - headers={"Authorization": "Bearer valid-token"}, ) assert resp.status_code == 400 - @patch.object(MCPServer, "_validate_gateway_token", return_value=True) - def test_mcp_server_call_tool_missing_name(self, _mock_validate): - server = MCPServer(gateway_url="http://fake-gateway:9848") # noqa: EGG002 + def test_mcp_server_call_tool_missing_name(self): + server = MCPServer() app = server.create_app() with app.test_client() as client: resp = client.post( "/mcp/v1/tools/call", json={"arguments": {}}, - headers={"Authorization": "Bearer valid-token"}, ) assert resp.status_code == 400 - @patch.object(MCPServer, "_validate_gateway_token", return_value=True) - def test_mcp_server_call_tool_unknown_returns_error(self, _mock_validate): - server = MCPServer(gateway_url="http://fake-gateway:9848") # noqa: EGG002 + def test_mcp_server_call_tool_unknown_returns_error(self): + server = MCPServer() app = server.create_app() with app.test_client() as client: resp = client.post( "/mcp/v1/tools/call", json={"name": "bogus_tool", "arguments": {}}, - headers={"Authorization": "Bearer valid-token"}, ) assert resp.status_code == 200 data = resp.get_json() assert data["isError"] is True - @patch.object(MCPServer, "_validate_gateway_token", return_value=True) - def test_mcp_server_sse_content_type(self, _mock_validate): - server = MCPServer(gateway_url="http://fake-gateway:9848") # noqa: EGG002 + def test_mcp_server_sse_content_type(self): + server = MCPServer() app = server.create_app() with app.test_client() as client: - resp = client.get( - "/mcp/v1/sse", - headers={"Authorization": "Bearer valid-token"}, - ) + resp = client.get("/mcp/v1/sse") assert resp.content_type.startswith("text/event-stream") - @patch.object(MCPServer, "_validate_gateway_token", return_value=True) - def test_mcp_server_rate_limit_returns_429(self, _mock_validate): - server = MCPServer(rate_limit=1, gateway_url="http://fake-gateway:9848") # noqa: EGG002 + def test_mcp_server_rate_limit_returns_429(self): + server = MCPServer(rate_limit=1) app = server.create_app() - auth_headers = {"Authorization": "Bearer valid-token"} with app.test_client() as client: # First call should succeed client.post( "/mcp/v1/tools/call", json={"name": "get_status", "arguments": {"task_id": "test"}}, - headers=auth_headers, ) # Second call should be rate limited resp2 = client.post( "/mcp/v1/tools/call", json={"name": "get_status", "arguments": {"task_id": "test"}}, - headers=auth_headers, ) assert resp2.status_code == 429 diff --git a/orchestrator/tests/test_coordinator_mcp.py b/orchestrator/tests/test_coordinator_mcp.py index 8cc86e1211..e2636b3040 100644 --- a/orchestrator/tests/test_coordinator_mcp.py +++ b/orchestrator/tests/test_coordinator_mcp.py @@ -2,7 +2,7 @@ Tests for MCP server (Phase 4). Tests the SSE-based MCP server sidecar for Claude Code integration, -including MCP tool definitions and authentication. +including MCP tool definitions and security model. """ import sys @@ -53,20 +53,14 @@ def test_mcp_server_has_health_endpoint(self): has_health = "health" in content.lower() assert has_health, "MCP server should have a health endpoint" - def test_mcp_server_has_authentication(self): - """MCP server must validate gateway session tokens. - - Gap: Authentication middleware. - """ + def test_mcp_server_localhost_security_model(self): + """MCP server relies on localhost-only access (docker-compose port mapping).""" mcp_path = _project_root / "orchestrator" / "mcp_server.py" if not mcp_path.exists(): pytest.skip("mcp_server.py not yet created") content = mcp_path.read_text() - has_auth = any( - keyword in content.lower() for keyword in ["auth", "token", "session", "validate"] - ) - assert has_auth, "MCP server should have authentication" + assert "localhost" in content.lower(), "MCP server should document localhost security model" def test_mcp_server_has_rate_limiting(self): """MCP server must have rate limiting (default 30 req/min). diff --git a/orchestrator/tests/test_coordinator_mcp_functional.py b/orchestrator/tests/test_coordinator_mcp_functional.py index fc416c62ad..9685ca0480 100644 --- a/orchestrator/tests/test_coordinator_mcp_functional.py +++ b/orchestrator/tests/test_coordinator_mcp_functional.py @@ -75,21 +75,17 @@ def try_request(): class TestMCPServerApp: """Tests for MCPServer Flask endpoints.""" - AUTH_HEADERS = {"Authorization": "Bearer test-token"} - @pytest.fixture def mcp_client(self): - """Create an MCP server test client with mocked auth.""" + """Create an MCP server test client.""" server = MCPServer( orchestrator_url="http://localhost:9849", port=9850, rate_limit=100, - gateway_url="http://fake-gateway:9848", # noqa: EGG002 ) app = server.create_app() app.config["TESTING"] = True - with patch.object(server, "_validate_gateway_token", return_value=True): - yield app.test_client() + yield app.test_client() def test_health_endpoint(self, mcp_client): response = mcp_client.get("/health") @@ -99,7 +95,7 @@ def test_health_endpoint(self, mcp_client): assert data["service"] == "egg-mcp-server" def test_list_tools(self, mcp_client): - response = mcp_client.get("/mcp/v1/tools", headers=self.AUTH_HEADERS) + response = mcp_client.get("/mcp/v1/tools") assert response.status_code == 200 data = response.get_json() tools = data["tools"] @@ -117,7 +113,6 @@ def test_call_tool_missing_body(self, mcp_client): response = mcp_client.post( "/mcp/v1/tools/call", content_type="application/json", - headers=self.AUTH_HEADERS, ) assert response.status_code == 400 @@ -125,7 +120,6 @@ def test_call_tool_missing_name(self, mcp_client): response = mcp_client.post( "/mcp/v1/tools/call", json={"arguments": {}}, - headers=self.AUTH_HEADERS, ) assert response.status_code == 400 @@ -133,7 +127,6 @@ def test_call_tool_unknown_tool(self, mcp_client): response = mcp_client.post( "/mcp/v1/tools/call", json={"name": "nonexistent_tool", "arguments": {}}, - headers=self.AUTH_HEADERS, ) assert response.status_code == 200 data = response.get_json() @@ -151,7 +144,6 @@ def test_call_tool_success(self, mock_handler, mcp_client): "name": "submit_task", "arguments": {"description": "Fix the bug"}, }, - headers=self.AUTH_HEADERS, ) assert response.status_code == 200 data = response.get_json() @@ -166,61 +158,39 @@ def test_call_tool_error_result(self, mock_handler, mcp_client): response = mcp_client.post( "/mcp/v1/tools/call", json={"name": "get_status", "arguments": {"task_id": "bad"}}, - headers=self.AUTH_HEADERS, ) assert response.status_code == 200 data = response.get_json() assert data["isError"] is True - def test_call_tool_missing_auth_returns_401(self): - """Requests without auth header should be rejected.""" - server = MCPServer( - orchestrator_url="http://localhost:9849", - gateway_url="http://fake-gateway:9848", # noqa: EGG002 - ) - app = server.create_app() - app.config["TESTING"] = True - client = app.test_client() - response = client.post( - "/mcp/v1/tools/call", - json={"name": "test"}, - ) - assert response.status_code == 401 - def test_rate_limiting(self): """Server should return 429 when rate limit exceeded.""" server = MCPServer( orchestrator_url="http://localhost:9849", port=9850, rate_limit=2, - gateway_url="http://fake-gateway:9848", # noqa: EGG002 ) app = server.create_app() app.config["TESTING"] = True client = app.test_client() - with ( - patch.object(server, "_validate_gateway_token", return_value=True), - patch.object(CoordinatorToolHandler, "handle_tool_call", return_value={"ok": True}), - ): + with patch.object(CoordinatorToolHandler, "handle_tool_call", return_value={"ok": True}): for _ in range(2): response = client.post( "/mcp/v1/tools/call", json={"name": "get_status", "arguments": {"task_id": "x"}}, - headers=self.AUTH_HEADERS, ) assert response.status_code == 200 response = client.post( "/mcp/v1/tools/call", json={"name": "get_status", "arguments": {"task_id": "x"}}, - headers=self.AUTH_HEADERS, ) assert response.status_code == 429 def test_sse_endpoint_returns_event_stream(self, mcp_client): """SSE endpoint should return event-stream content type.""" - response = mcp_client.get("/mcp/v1/sse", headers=self.AUTH_HEADERS) + response = mcp_client.get("/mcp/v1/sse") assert response.content_type.startswith("text/event-stream")