From b2f5ac58d7819beeba5d61cfd7c268f22261eff0 Mon Sep 17 00:00:00 2001 From: hzqst <113660872@qq.com> Date: Sun, 22 Nov 2026 22:08:01 +0800 Subject: [PATCH] feat(mcp): connect to native Sven Co-op HLCLI Co-Authored-By: Codex --- mcp/find_game.py | 10 +- mcp/game_process.py | 22 ++++- mcp/halflife_mcp.py | 16 ++- mcp/halflifecli/manager.py | 34 +++++-- mcp/halflifecli/models.py | 3 + mcp/halflifecli/plugin_config.py | 54 ++++++++-- mcp/halflifecli/usermsg.py | 16 ++- mcp/tests/test_native_endpoint.py | 159 ++++++++++++++++++++++++++++++ 8 files changed, 282 insertions(+), 32 deletions(-) create mode 100644 mcp/tests/test_native_endpoint.py diff --git a/mcp/find_game.py b/mcp/find_game.py index f195584..a3bea47 100644 --- a/mcp/find_game.py +++ b/mcp/find_game.py @@ -38,7 +38,7 @@ import subprocess import sys -from game_process import GameTarget +from game_process import GameTarget, LINUX_EXECUTABLES MARKER = "svencoop.exe" CONFIG_NAME = "game_dir.txt" @@ -244,6 +244,14 @@ def resolve_target(explicit=None, appid=None, mod=None): value = explicit.strip().strip('"') if explicit is not None else None if selected_appid == DEFAULT_APPID: + if sys.platform.startswith("linux"): + if value: + directory = os.path.abspath(value) + for name in LINUX_EXECUTABLES: + launcher = os.path.join(directory, name) + if os.path.isfile(launcher) and os.access(launcher, os.X_OK): + return GameTarget(directory, launcher=launcher, source="--dir", native=True), None + return None, "Linux Sven Co-op requires an explicit game directory with an executable launcher" if value is None: directory, source = _resolve_sven_directory() if directory is None: diff --git a/mcp/game_process.py b/mcp/game_process.py index 73b7a91..3886f44 100644 --- a/mcp/game_process.py +++ b/mcp/game_process.py @@ -23,6 +23,7 @@ log = logging.getLogger(__name__) EXECUTABLE_NAME = "svencoop.exe" +LINUX_EXECUTABLES = ("svencoop_linux", "svencoop") MOD_DIR_NAME = "svencoop" # The plugin keeps its config, port file and usermsg schemas in its own # subfolder of MetaHook's configs directory (src/core/plugins.cpp writes there). @@ -106,6 +107,7 @@ class GameTarget: launcher: str = "" launch_args: tuple = () source: str = "" + native: bool = False @property def launcher_path(self): @@ -125,7 +127,9 @@ def mod_dir(target): def plugin_config_dir(target): - """The plugin's own config subfolder inside MetaHook's configs dir.""" + """The automation data directory for the selected engine integration.""" + if isinstance(target, GameTarget) and target.native: + return os.path.join(mod_dir(target), PLUGIN_DATA_DIR_NAME) return os.path.join(mod_dir(target), "metahook", "configs", PLUGIN_DATA_DIR_NAME) @@ -170,6 +174,13 @@ def process_liveness(pid): which has already terminated; its launcher mutex is released, so callers treat it as gone. """ + if os.name == "posix": + try: + with open(f"/proc/{pid}/stat", encoding="utf-8", errors="replace") as stream: + state = stream.read().rsplit(")", 1)[1].split()[0] + return 'exited' if state in ("Z", "X", "x") else 'live' + except (OSError, IndexError): + return 'absent' try: import win32api import win32con @@ -297,8 +308,15 @@ def start(self): raise RuntimeError("game process already started") # stdout/stderr must be pipes, never inherited: when this runs inside # the MCP server, its own stdout is the protocol channel. + env = None + if os.name == "posix": + env = os.environ.copy() + library_dirs = [self.cwd, os.path.join(self.cwd, MOD_DIR_NAME, "cl_dlls")] + if env.get("LD_LIBRARY_PATH"): + library_dirs.append(env["LD_LIBRARY_PATH"]) + env["LD_LIBRARY_PATH"] = os.pathsep.join(library_dirs) self._proc = subprocess.Popen( - self.argv, cwd=self.cwd, + self.argv, cwd=self.cwd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self._job = _kill_on_close_job(self._proc.pid) threading.Thread(target=self._drain_stdout, name="game-stdout", daemon=True).start() diff --git a/mcp/halflife_mcp.py b/mcp/halflife_mcp.py index 164752f..6165463 100644 --- a/mcp/halflife_mcp.py +++ b/mcp/halflife_mcp.py @@ -82,8 +82,8 @@ "max_lines (default 200) and the full text of a capped command is saved to " "the file path it returns, so grep that file instead of raising the cap. " "Inspect VGUI2 structure with vgui2_tree / vgui2_inspect; follow next_cursor. " - "Use returned references with vgui2_click / vgui2_focus. Semantic text/state " - "and vgui2_set_text are currently unsupported; VGUI1 is excluded. " + "Use returned references with vgui2_click / vgui2_focus. VGUI2 text and state " + "are available on controls that report semantic_support; VGUI1 is excluded. " "To press keys or mouse buttons in the game use send_key / send_mouse. " "For UI pointing use move_mouse, or send_mouse with x/y, measured in " "snapshot's original_size pixels (returned_size describes the scaled image); " @@ -138,8 +138,8 @@ def vgui2_tree( """Read VGUI2 structure, names and geometry. Default: visible nodes, embedded root. Follow next_cursor for the same frozen snapshot. References expire on destruction/restart. - Bounds use original screenshot pixels; visible does not mean unobstructed. VGUI1 and - semantic text/state are unsupported (semantic_support=false). + Bounds use original screenshot pixels. A visible control can be obstructed. + The semantic_support field reports whether the control provides text or state. """ result = _vgui2_call(vgui2_client.tree, root, include_hidden, max_depth, cursor) text = result.pop("text_tree") @@ -148,8 +148,7 @@ def vgui2_tree( @mcp.tool(annotations=ToolAnnotations(read_only_hint=True)) def vgui2_inspect(ref: str, text_offset: Annotated[int, Field(ge=0)] = 0) -> CallToolResult: - """Read current VGUI2 geometry, visibility and input flags. Semantic text/state is - unsupported; text_offset is retained for compatibility and returns no text. + """Read current VGUI2 geometry, visibility and input flags, and page text when supported. """ return _vgui2_result(_vgui2_call(vgui2_client.inspect, ref, text_offset)) @@ -184,10 +183,7 @@ def vgui2_focus(ref: str) -> CallToolResult: @mcp.tool() def vgui2_set_text(ref: str, text: str) -> CallToolResult: - """Compatibility placeholder: returns unsupported until RequestInfo automation is available. - - Does not type, upload or modify text in this plugin version. - """ + """Set text on an editable VGUI2 control that advertises the set_text action.""" return _vgui2_result(_vgui2_call(vgui2_client.set_text, ref, text)) diff --git a/mcp/halflifecli/manager.py b/mcp/halflifecli/manager.py index c633fc9..3337acf 100644 --- a/mcp/halflifecli/manager.py +++ b/mcp/halflifecli/manager.py @@ -6,6 +6,7 @@ threads. """ +import dataclasses import glob import logging import os @@ -170,7 +171,8 @@ def _probe_attached(self): endpoint = read_endpoint_file(target) if endpoint is None: return None - password = plugin_rcon_password(target) + config_target = dataclasses.replace(target, native=True) if endpoint.native else target + password = plugin_rcon_password(config_target) key = (target.directory, target.mod, endpoint, password) if self._attached_key != key: if self._attached_rcon is not None: @@ -194,9 +196,20 @@ def _refresh_managed_endpoint_locked(self): if endpoint is None: raise ToolError("game RCON endpoint is not ready or belongs to a stale process") if endpoint != self._endpoint: + connection = None + if endpoint.native: + password = plugin_rcon_password(self._target) + connection = rcon_client.RconConnection( + endpoint.host, endpoint.port, password, protocol=endpoint.protocol) + try: + connection.open() + except Exception as error: + connection.close() + raise ToolError(f"could not reconnect to game: {error}") from error + self._password = password if self._rcon is not None: self._rcon.close() - self._rcon = None + self._rcon = connection self._endpoint = endpoint self._host, self._port, self._protocol = endpoint.host, endpoint.port, endpoint.protocol @@ -234,7 +247,8 @@ def _target_locked(self): if self._proc is not None and self._proc.alive and self._target is not None: return self._target if self._probe_attached() is not None: - return self._target + endpoint = self._attached_key[2] + return dataclasses.replace(self._target, native=True) if endpoint.native else self._target raise ToolError("no game running; call launch_game first") # -- tools --------------------------------------------------------------- @@ -259,7 +273,8 @@ def attach_game(self, game_dir=None, appid=None, mod=None): endpoint = read_endpoint_file(target) if endpoint is None: raise ToolError("game RCON endpoint is missing, not ready, or belongs to a stale process") - password = plugin_rcon_password(target) + config_target = dataclasses.replace(target, native=True) if endpoint.native else target + password = plugin_rcon_password(config_target) connection = rcon_client.RconConnection( endpoint.host, endpoint.port, password, timeout=2, protocol=endpoint.protocol) try: @@ -303,6 +318,10 @@ def launch_game(self, extra_args, game_dir, timeout_s, appid=None, mod=None): target, reason = resolve_target(game_dir, appid, mod) if target is None: raise ToolError(f"no game directory resolved ({reason})") + if any(arg.lower() == "-hlcli" for arg in extra_args): + target = dataclasses.replace(target, native=True) + elif target.native: + extra_args = [*extra_args, "-hlcli"] proc = GameProcess(build_game_argv(target, extra_args), cwd=target.directory) proc.start() try: @@ -333,6 +352,11 @@ def launch_game(self, extra_args, game_dir, timeout_s, appid=None, mod=None): detail = ("; last console output: " + " | ".join(tail)) if tail else "" raise ToolError( f"the game exited (code {code}) before the plugin printed its RCON banner{detail}") + except TimeoutError as error: + tail = proc.tail(LAUNCH_FAILURE_TAIL_LINES) + proc.stop(timeout=EXIT_CODE_GRACE_S) + detail = ("; last console output: " + " | ".join(tail)) if tail else "" + raise ToolError(f"{error}{detail}") from error except Exception: proc.stop(timeout=EXIT_CODE_GRACE_S) raise @@ -445,8 +469,6 @@ def read_console(self, max_lines, cursor): if proc is None: return ConsoleWindow(lines=[], next_cursor=cursor or 0, note="no game launched by this server (attached games expose no console stream)") - if cursor is None: - cursor = proc.next_cursor sl = proc.lines_since(cursor, max_lines) return ConsoleWindow(lines=sl.lines, next_cursor=sl.next_cursor, dropped=sl.dropped) diff --git a/mcp/halflifecli/models.py b/mcp/halflifecli/models.py index e6a912b..0a0accf 100644 --- a/mcp/halflifecli/models.py +++ b/mcp/halflifecli/models.py @@ -30,6 +30,9 @@ class UserMsgStatus(BaseModel): wrapped: int # hooked on top of the game DLL's own hook self_registered: int # no game DLL hook; monitor-created display-only entry pending: int # not yet resolvable in the engine's usermsg list + monitored: int | None = None # direct engine dispatch coverage + absent: int | None = None + unknown: int | None = None class UserMsgEvent(BaseModel): diff --git a/mcp/halflifecli/plugin_config.py b/mcp/halflifecli/plugin_config.py index ec3f868..75e1d44 100644 --- a/mcp/halflifecli/plugin_config.py +++ b/mcp/halflifecli/plugin_config.py @@ -1,9 +1,7 @@ -"""Reads the plugin's halflifecli.toml and RCON port file from a game install. +"""Reads HLCLI configuration and validated RCON endpoints from a game install. -Both files live under //metahook/configs/; paths are built by -game_process from a GameTarget (or a bare game root, which means the Sven -default). Everything here tolerates absence: a missing or broken file reads -as "no setting", like the plugin's own compiled-in defaults. +Native engines use //halflifecli/ and plugins use +//metahook/configs/. Paths come from game_process and GameTarget. """ import os @@ -13,7 +11,7 @@ import time import tomllib -from game_process import plugin_config_path, port_file_path, plugin_config_dir, rcon_connect_host +from game_process import GameTarget, plugin_config_path, port_file_path, plugin_config_dir, rcon_connect_host from rcon_client import PROTOCOLS @@ -24,6 +22,9 @@ class Endpoint: port: int pid: int | None = None process_start_filetime: str | None = None + native: bool = False + linux_identity: tuple[str, str] | None = None + published_at: float | None = None def process_start_filetime(pid): @@ -53,6 +54,19 @@ def process_start_filetime(pid): kernel.CloseHandle(handle) +def linux_process_identity(pid): + try: + with open("/proc/sys/kernel/random/boot_id", encoding="ascii") as stream: + boot_id = stream.read().strip() + with open(f"/proc/{pid}/stat", encoding="utf-8", errors="replace") as stream: + fields = stream.read().rsplit(")", 1)[1].split() + if fields[0] not in ("Z", "X", "x"): + return boot_id, fields[19] + except (OSError, IndexError): + pass + return None + + def read_endpoint_file(target, expected_pid=None): """Validated metadata, or an explicitly Source-TCP legacy single-line file. @@ -60,6 +74,15 @@ def read_endpoint_file(target, expected_pid=None): a stale port file or guess the protocol by sending a command twice. Callers must still actively probe authentication before reporting ready. """ + if isinstance(target, GameTarget) and not target.native and expected_pid is None: + native = _read_endpoint(dataclasses.replace(target, native=True), None) + if native is not None: + return native + return _read_endpoint(target, expected_pid) + + +def _read_endpoint(target, expected_pid): + native = isinstance(target, GameTarget) and target.native path = os.path.join(plugin_config_dir(target), "halflifecli.endpoint.json") try: with open(path, encoding="utf-8") as stream: @@ -72,16 +95,27 @@ def read_endpoint_file(target, expected_pid=None): if type(pid) is not int or pid <= 0 or (expected_pid is not None and expected_pid != pid): return None bind = str(ipaddress.IPv4Address(data["bind"])) + if native and protocol != "goldsrc-udp": + return None + published = data.get("published_at") + if type(published) not in (int, float) or not 0 < published <= time.time() + 5: + return None + if native and os.name == "posix": + identity = (data.get("boot_id"), data.get("process_start_ticks")) + if linux_process_identity(pid) != identity: + return None + return Endpoint(protocol, rcon_connect_host(bind), port, pid, native=True, + linux_identity=identity, published_at=published) start = data.get("process_start_filetime") if not isinstance(start, str) or not start.isdecimal() or process_start_filetime(pid) != start: return None - published = data.get("published_at") started = int(start) / 10000000 - 11644473600 - if type(published) not in (int, float) or not started <= published + 1 <= time.time() + 6: + if not started <= published + 1: return None - return Endpoint(protocol, rcon_connect_host(bind), port, pid, start) + return Endpoint(protocol, rcon_connect_host(bind), port, pid, start, native=native, + published_at=published if native else None) except FileNotFoundError: - port = read_port_file(target) + port = None if native else read_port_file(target) if port is not None: return Endpoint("source-tcp", rcon_connect_host(plugin_rcon_bind(target)), port) except (OSError, ValueError, KeyError, TypeError, OverflowError): diff --git a/mcp/halflifecli/usermsg.py b/mcp/halflifecli/usermsg.py index 235927c..e0c716a 100644 --- a/mcp/halflifecli/usermsg.py +++ b/mcp/halflifecli/usermsg.py @@ -19,9 +19,13 @@ # "cli.usermsg: schema=svencoop.toml coord_size=4 messages=101 display=on # hooks: 85 wrapped, 16 self-registered, 0 pending" -USERMSG_STATUS_RE = re.compile( +USERMSG_STATUS_PREFIX = ( r"cli\.usermsg: schema=(\S+) coord_size=(\d+) messages=(\d+) display=(on|off) " - r"hooks: (\d+) wrapped, (\d+) self-registered, (\d+) pending", re.MULTILINE) +) +USERMSG_STATUS_RE = re.compile( + USERMSG_STATUS_PREFIX + r"hooks: (\d+) wrapped, (\d+) self-registered, (\d+) pending") +NATIVE_USERMSG_STATUS_RE = re.compile( + USERMSG_STATUS_PREFIX + r"registered: (\d+) monitored, (\d+) absent, (\d+) unknown") # "#17 [usermsg] CurWeapon size=5 state=1 weaponId=18 clip=35" USERMSG_EVENT_RE = re.compile(r"#(\d+) \[usermsg\] (\S+) size=(\d+)(?: (.*))?$", re.MULTILINE) @@ -37,7 +41,13 @@ def parse_usermsg_status(text): """UserMsgStatus from `cli.usermsg` output, or None when unrecognized.""" m = USERMSG_STATUS_RE.search(text) if not m: - return None + m = NATIVE_USERMSG_STATUS_RE.search(text) + if not m: + return None + return UserMsgStatus( + schema_file=m.group(1), coord_size=int(m.group(2)), messages=int(m.group(3)), + display=m.group(4) == "on", wrapped=0, self_registered=0, pending=0, + monitored=int(m.group(5)), absent=int(m.group(6)), unknown=int(m.group(7))) return UserMsgStatus( schema_file=m.group(1), coord_size=int(m.group(2)), messages=int(m.group(3)), display=m.group(4) == "on", wrapped=int(m.group(5)), diff --git a/mcp/tests/test_native_endpoint.py b/mcp/tests/test_native_endpoint.py new file mode 100644 index 0000000..ab93c97 --- /dev/null +++ b/mcp/tests/test_native_endpoint.py @@ -0,0 +1,159 @@ +import dataclasses +import json +import os +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from game_process import GameTarget, plugin_config_dir +from halflifecli.plugin_config import ( + linux_process_identity, + process_start_filetime, + read_endpoint_file, +) + + +class NativeEndpointTests(unittest.TestCase): + def test_validates_identity_and_refreshes_within_the_same_process(self): + with tempfile.TemporaryDirectory() as root, subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(20)"], + ) as child: + try: + target = GameTarget(root, native=True) + directory = Path(plugin_config_dir(target)) + directory.mkdir(parents=True) + file = directory / "halflifecli.endpoint.json" + record = dict(version=1, status="ready", protocol="goldsrc-udp", + bind="0.0.0.0", port=27015, pid=child.pid, published_at=time.time()) + if os.name == "nt": + record["process_start_filetime"] = process_start_filetime(child.pid) + start_field = "process_start_filetime" + else: + record["boot_id"], record["process_start_ticks"] = linux_process_identity(child.pid) + start_field = "process_start_ticks" + self.assertTrue(record[start_field]) + + def publish(**changes): + file.write_text(json.dumps({**record, **changes}), encoding="utf-8") + + publish() + endpoint = read_endpoint_file(target, expected_pid=child.pid) + self.assertEqual(("127.0.0.1", 27015, child.pid, True), + (endpoint.host, endpoint.port, endpoint.pid, endpoint.native)) + self.assertEqual(endpoint, read_endpoint_file(dataclasses.replace(target, native=False))) + self.assertIsNone(read_endpoint_file(target, expected_pid=child.pid + 1)) + publish(**{start_field: "0"}) + self.assertIsNone(read_endpoint_file(target)) + publish(status="stopped") + self.assertIsNone(read_endpoint_file(target)) + publish(published_at=record["published_at"] + 0.1) + self.assertNotEqual(endpoint, read_endpoint_file(target)) + publish(port=27016) + self.assertEqual(27016, read_endpoint_file(target).port) + finally: + child.terminate() + child.wait() + self.assertIsNone(read_endpoint_file(target)) + + def test_native_port_file_is_not_a_legacy_tcp_endpoint(self): + with tempfile.TemporaryDirectory() as root: + target = GameTarget(root, native=True) + directory = Path(plugin_config_dir(target)) + directory.mkdir(parents=True) + (directory / "halflifecli.port").write_text("27015\n127.0.0.1\n", encoding="ascii") + self.assertIsNone(read_endpoint_file(target)) + + @unittest.skipUnless(sys.platform.startswith("linux"), "requires the Linux launcher") + def test_managed_linux_launcher_refreshes_a_live_udp_endpoint(self): + from halflifecli.manager import Manager + from rcon_client import RconConnection + + launcher_source = textwrap.dedent("""\ + #!/usr/bin/env python3 + import json + import os + import socket + import sys + import time + from pathlib import Path + + assert "-hlcli" in sys.argv + assert os.environ["LD_LIBRARY_PATH"].split(":")[0] == os.getcwd() + record = dict(version=1, protocol="goldsrc-udp", bind="127.0.0.1", + pid=os.getpid(), boot_id=Path("/proc/sys/kernel/random/boot_id").read_text().strip(), + process_start_ticks=Path("/proc/self/stat").read_text().rsplit(")", 1)[1].split()[19]) + endpoint = Path("svencoop/halflifecli/halflifecli.endpoint.json") + + def publish(status, port): + temp = endpoint.with_suffix(".tmp") + temp.write_text(json.dumps(dict(record, status=status, port=port, published_at=time.time()))) + temp.replace(endpoint) + + def open_udp(): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(("127.0.0.1", 0)) + return sock + + sock = open_udp() + port = sock.getsockname()[1] + publish("ready", port) + print(f"halflife-cli: RCON listening on 127.0.0.1:{port} (goldsrc-udp, password: set)", flush=True) + prefix = bytes([255]) * 4 + while True: + data, peer = sock.recvfrom(4096) + if data == prefix + b"challenge rcon\\n\\0": + sock.sendto(prefix + b"challenge rcon 12345\\n\\0", peer) + continue + expected = prefix + b'rcon 12345 "fixture" ' + if not data.startswith(expected): + sock.sendto(prefix + b"lBad rcon_password.\\n\\0\\0", peer) + continue + command = data[len(expected):-1] + sock.sendto(prefix + b"l" + command + b"\\0\\0", peer) + if command in (b"_restart", b"quit"): + publish("stopped", 0) + if command == b"quit": + break + new_socket = open_udp() + sock.close() + sock = new_socket + publish("ready", sock.getsockname()[1]) + sock.close() + """) + + with tempfile.TemporaryDirectory() as root: + launcher = Path(root) / "svencoop_linux" + launcher.write_text(launcher_source, encoding="utf-8") + launcher.chmod(0o700) + target = GameTarget(root, native=True) + directory = Path(plugin_config_dir(target)) + directory.mkdir(parents=True) + (directory / "halflifecli.toml").write_text('[rcon]\npassword="fixture"\n', encoding="utf-8") + manager = Manager() + try: + before = manager.launch_game([], root, 5) + wrong = RconConnection(before.host, before.port, "wrong", protocol="goldsrc-udp") + try: + with self.assertRaises(PermissionError): + wrong.open() + finally: + wrong.close() + self.assertEqual("_restart", manager.run_command("_restart")) + after = manager.game_status() + self.assertEqual(before.pid, after.pid) + self.assertNotEqual(before.port, after.port) + self.assertEqual("echo ready", manager.run_command("echo ready")) + self.assertIn("exit code 0", manager.quit_game(5)) + self.assertIsNone(read_endpoint_file(target)) + finally: + manager.shutdown() + + +if __name__ == "__main__": + unittest.main()