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
10 changes: 9 additions & 1 deletion mcp/find_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down
22 changes: 20 additions & 2 deletions mcp/game_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -106,6 +107,7 @@ class GameTarget:
launcher: str = ""
launch_args: tuple = ()
source: str = ""
native: bool = False

@property
def launcher_path(self):
Expand All @@ -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)


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
16 changes: 6 additions & 10 deletions mcp/halflife_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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); "
Expand Down Expand Up @@ -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")
Expand All @@ -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))

Expand Down Expand Up @@ -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))


Expand Down
34 changes: 28 additions & 6 deletions mcp/halflifecli/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
threads.
"""

import dataclasses
import glob
import logging
import os
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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 ---------------------------------------------------------------
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
3 changes: 3 additions & 0 deletions mcp/halflifecli/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
54 changes: 44 additions & 10 deletions mcp/halflifecli/plugin_config.py
Original file line number Diff line number Diff line change
@@ -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 <game>/<mod>/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 <game>/<mod>/halflifecli/ and plugins use
<game>/<mod>/metahook/configs/. Paths come from game_process and GameTarget.
"""

import os
Expand All @@ -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


Expand All @@ -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):
Expand Down Expand Up @@ -53,13 +54,35 @@ 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.

Present but invalid/non-ready metadata is authoritative: never downgrade to
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:
Expand All @@ -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):
Expand Down
16 changes: 13 additions & 3 deletions mcp/halflifecli/usermsg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)),
Expand Down
Loading