|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Minimal MCP stdio client for response capture.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import json |
| 7 | +import os |
| 8 | +import select |
| 9 | +import shlex |
| 10 | +import subprocess |
| 11 | +import sys |
| 12 | +from pathlib import Path |
| 13 | +from types import TracebackType |
| 14 | +from typing import Any |
| 15 | + |
| 16 | +REPO_ROOT = Path(__file__).resolve().parents[2] |
| 17 | +PROTOCOL_VERSION = "2025-06-18" |
| 18 | + |
| 19 | + |
| 20 | +class MCPServer: |
| 21 | + def __init__( |
| 22 | + self, |
| 23 | + server_cmd: str = "go run ./cmd/github-mcp-server stdio", |
| 24 | + extra_args: list[str] | None = None, |
| 25 | + timeout: float = 180.0, |
| 26 | + ) -> None: |
| 27 | + self.cmd = shlex.split(server_cmd) + list(extra_args or []) |
| 28 | + self.timeout = timeout |
| 29 | + self.proc: subprocess.Popen[str] | None = None |
| 30 | + self._id = 0 |
| 31 | + |
| 32 | + def __enter__(self) -> "MCPServer": |
| 33 | + self.start() |
| 34 | + return self |
| 35 | + |
| 36 | + def __exit__( |
| 37 | + self, |
| 38 | + _exc_type: type[BaseException] | None, |
| 39 | + _exc_value: BaseException | None, |
| 40 | + _traceback: TracebackType | None, |
| 41 | + ) -> None: |
| 42 | + self.close() |
| 43 | + |
| 44 | + def start(self) -> None: |
| 45 | + if not os.environ.get("GITHUB_PERSONAL_ACCESS_TOKEN"): |
| 46 | + raise RuntimeError("GITHUB_PERSONAL_ACCESS_TOKEN is required for live captures") |
| 47 | + |
| 48 | + print(f"[mcp] starting: {' '.join(self.cmd)}", file=sys.stderr) |
| 49 | + self.proc = subprocess.Popen( |
| 50 | + self.cmd, |
| 51 | + cwd=REPO_ROOT, |
| 52 | + stdin=subprocess.PIPE, |
| 53 | + stdout=subprocess.PIPE, |
| 54 | + stderr=sys.stderr, |
| 55 | + text=True, |
| 56 | + env=os.environ.copy(), |
| 57 | + ) |
| 58 | + self._request( |
| 59 | + "initialize", |
| 60 | + { |
| 61 | + "protocolVersion": PROTOCOL_VERSION, |
| 62 | + "capabilities": {}, |
| 63 | + "clientInfo": {"name": "markdown-response-eval", "version": "0"}, |
| 64 | + }, |
| 65 | + ) |
| 66 | + self._notify("notifications/initialized") |
| 67 | + |
| 68 | + def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: |
| 69 | + return self._request("tools/call", {"name": name, "arguments": arguments}) |
| 70 | + |
| 71 | + def close(self) -> None: |
| 72 | + if self.proc is None: |
| 73 | + return |
| 74 | + if self.proc.stdin is not None: |
| 75 | + try: |
| 76 | + self.proc.stdin.close() |
| 77 | + except BrokenPipeError: |
| 78 | + pass |
| 79 | + self.proc.terminate() |
| 80 | + try: |
| 81 | + self.proc.wait(timeout=10) |
| 82 | + except subprocess.TimeoutExpired: |
| 83 | + self.proc.kill() |
| 84 | + self.proc.wait(timeout=10) |
| 85 | + self.proc = None |
| 86 | + |
| 87 | + def _send(self, payload: dict[str, Any]) -> None: |
| 88 | + if self.proc is None or self.proc.stdin is None: |
| 89 | + raise RuntimeError("MCP server is not running") |
| 90 | + self.proc.stdin.write(json.dumps(payload) + "\n") |
| 91 | + self.proc.stdin.flush() |
| 92 | + |
| 93 | + def _notify(self, method: str, params: dict[str, Any] | None = None) -> None: |
| 94 | + self._send({"jsonrpc": "2.0", "method": method, "params": params or {}}) |
| 95 | + |
| 96 | + def _read(self) -> dict[str, Any]: |
| 97 | + if self.proc is None or self.proc.stdout is None: |
| 98 | + raise RuntimeError("MCP server is not running") |
| 99 | + while True: |
| 100 | + ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout) |
| 101 | + if not ready: |
| 102 | + raise TimeoutError("timed out waiting for the MCP server") |
| 103 | + line = self.proc.stdout.readline() |
| 104 | + if line == "": |
| 105 | + raise EOFError("MCP server closed stdout unexpectedly") |
| 106 | + line = line.strip() |
| 107 | + if not line: |
| 108 | + continue |
| 109 | + try: |
| 110 | + return json.loads(line) |
| 111 | + except json.JSONDecodeError: |
| 112 | + continue |
| 113 | + |
| 114 | + def _request(self, method: str, params: dict[str, Any]) -> dict[str, Any]: |
| 115 | + self._id += 1 |
| 116 | + request_id = self._id |
| 117 | + self._send( |
| 118 | + { |
| 119 | + "jsonrpc": "2.0", |
| 120 | + "id": request_id, |
| 121 | + "method": method, |
| 122 | + "params": params, |
| 123 | + } |
| 124 | + ) |
| 125 | + while True: |
| 126 | + message = self._read() |
| 127 | + if message.get("id") != request_id: |
| 128 | + continue |
| 129 | + if "error" in message: |
| 130 | + raise RuntimeError(f"{method} error: {message['error']}") |
| 131 | + result = message.get("result") |
| 132 | + if not isinstance(result, dict): |
| 133 | + raise RuntimeError(f"{method} returned a non-object result") |
| 134 | + return result |
0 commit comments