Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions docs/guides/coordinator.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
9 changes: 0 additions & 9 deletions orchestrator/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
76 changes: 8 additions & 68 deletions orchestrator/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -65,99 +62,43 @@ 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__(
self,
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

self.tool_handler = CoordinatorToolHandler(orchestrator_url=orchestrator_url)
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

Expand All @@ -181,7 +122,6 @@ def call_tool():
)

@app.route("/mcp/v1/sse")
@require_auth
def sse_stream():
"""SSE endpoint for MCP protocol events."""

Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
65 changes: 13 additions & 52 deletions orchestrator/tests/test_coordinator_gaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
14 changes: 4 additions & 10 deletions orchestrator/tests/test_coordinator_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down
Loading
Loading