|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Minimal mock MCP server for E2E tests with OAuth support. |
| 3 | +
|
| 4 | +Responds to GET (OAuth probe) with 401 and WWW-Authenticate. Accepts POST |
| 5 | +(MCP JSON-RPC) when Authorization: Bearer <token> is present; otherwise 401. |
| 6 | +Uses only Python stdlib. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +from http.server import HTTPServer, BaseHTTPRequestHandler |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +# Standard OAuth-style challenge so the client can drive an OAuth flow |
| 14 | +WWW_AUTHENTICATE = 'Bearer realm="mock-mcp", error="invalid_token"' |
| 15 | + |
| 16 | + |
| 17 | +class Handler(BaseHTTPRequestHandler): |
| 18 | + """HTTP handler: GET/POST without valid Bearer → 401; POST with Bearer → MCP.""" |
| 19 | + |
| 20 | + def _require_oauth(self) -> None: |
| 21 | + """Send 401 with WWW-Authenticate.""" |
| 22 | + self.send_response(401) |
| 23 | + self.send_header("WWW-Authenticate", WWW_AUTHENTICATE) |
| 24 | + self.send_header("Content-Type", "application/json") |
| 25 | + body = b'{"error":"unauthorized"}' |
| 26 | + self.send_header("Content-Length", str(len(body))) |
| 27 | + self.end_headers() |
| 28 | + self.wfile.write(body) |
| 29 | + |
| 30 | + def _parse_auth(self) -> str | None: |
| 31 | + """Return Bearer token if present, else None.""" |
| 32 | + auth = self.headers.get("Authorization") |
| 33 | + if auth and auth.startswith("Bearer "): |
| 34 | + return auth[7:].strip() |
| 35 | + return None |
| 36 | + |
| 37 | + def _json_response(self, data: dict) -> None: |
| 38 | + """Send JSON response.""" |
| 39 | + body = json.dumps(data).encode() |
| 40 | + self.send_response(200) |
| 41 | + self.send_header("Content-Type", "application/json") |
| 42 | + self.send_header("Content-Length", str(len(body))) |
| 43 | + self.end_headers() |
| 44 | + self.wfile.write(body) |
| 45 | + |
| 46 | + def do_GET(self) -> None: # pylint: disable=invalid-name |
| 47 | + """OAuth probe: always 401 with WWW-Authenticate.""" |
| 48 | + if self.path == "/health": |
| 49 | + self._json_response({"status": "ok"}) |
| 50 | + else: |
| 51 | + self._require_oauth() |
| 52 | + |
| 53 | + def do_POST(self) -> None: # pylint: disable=invalid-name |
| 54 | + """MCP JSON-RPC: 401 without valid Bearer; 200 with minimal responses otherwise.""" |
| 55 | + if self._parse_auth() is None: |
| 56 | + self._require_oauth() |
| 57 | + return |
| 58 | + |
| 59 | + length = int(self.headers.get("Content-Length", 0)) |
| 60 | + raw = self.rfile.read(length) if length else b"{}" |
| 61 | + try: |
| 62 | + req = json.loads(raw.decode("utf-8")) |
| 63 | + req_id = req.get("id", 1) |
| 64 | + method = req.get("method", "") |
| 65 | + except (json.JSONDecodeError, UnicodeDecodeError): |
| 66 | + req_id = 1 |
| 67 | + method = "" |
| 68 | + |
| 69 | + if method == "initialize": |
| 70 | + self._json_response( |
| 71 | + { |
| 72 | + "jsonrpc": "2.0", |
| 73 | + "id": req_id, |
| 74 | + "result": { |
| 75 | + "protocolVersion": "2024-11-05", |
| 76 | + "capabilities": {"tools": {}}, |
| 77 | + "serverInfo": {"name": "mock-mcp-e2e", "version": "1.0.0"}, |
| 78 | + }, |
| 79 | + } |
| 80 | + ) |
| 81 | + elif method == "tools/list": |
| 82 | + self._json_response( |
| 83 | + { |
| 84 | + "jsonrpc": "2.0", |
| 85 | + "id": req_id, |
| 86 | + "result": { |
| 87 | + "tools": [ |
| 88 | + { |
| 89 | + "name": "mock_tool", |
| 90 | + "description": "Mock tool for E2E", |
| 91 | + "inputSchema": {"type": "object"}, |
| 92 | + } |
| 93 | + ], |
| 94 | + }, |
| 95 | + } |
| 96 | + ) |
| 97 | + else: |
| 98 | + self._json_response({"jsonrpc": "2.0", "id": req_id, "result": {}}) |
| 99 | + |
| 100 | + def log_message(self, format: str, *args: Any) -> None: |
| 101 | + """Suppress request logging for minimal output.""" |
| 102 | + |
| 103 | + |
| 104 | +if __name__ == "__main__": |
| 105 | + server = HTTPServer(("0.0.0.0", 3000), Handler) |
| 106 | + print("Mock MCP server on :3000") |
| 107 | + server.serve_forever() |
0 commit comments