simrig-mcp 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
simrig_mcp/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.1"
simrig_mcp/__main__.py ADDED
@@ -0,0 +1,21 @@
1
+ import sys
2
+
3
+ USAGE = "usage: simrig-mcp {acconfig|pimax}"
4
+
5
+
6
+ def main(argv: list[str] | None = None) -> int:
7
+ args = sys.argv[1:] if argv is None else argv
8
+ if not args or args[0] not in {"acconfig", "pimax"}:
9
+ print(USAGE, file=sys.stderr)
10
+ return 2
11
+ if args[0] == "acconfig":
12
+ from .acconfig.server import main as run
13
+ else:
14
+ from .pimax.server import main as run
15
+ sys.argv = [f"simrig-mcp {args[0]}", *args[1:]]
16
+ run()
17
+ return 0
18
+
19
+
20
+ if __name__ == "__main__":
21
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,99 @@
1
+ """Line-preserving INI editing: comments, BOM and line endings survive a round trip."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ BOM = b"\xef\xbb\xbf"
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class TextFormat:
12
+ bom: bool = False
13
+ newline: str = "\r\n"
14
+
15
+
16
+ def load(path: Path) -> tuple[list[str], TextFormat]:
17
+ raw = path.read_bytes() if path.exists() else b""
18
+ bom = raw.startswith(BOM)
19
+ text = raw[len(BOM):] if bom else raw
20
+ decoded = text.decode("utf-8", errors="surrogateescape")
21
+ if not decoded:
22
+ return [], TextFormat(bom=bom)
23
+ newline = "\r\n" if "\r\n" in decoded else "\n"
24
+ return decoded.splitlines(), TextFormat(bom=bom, newline=newline)
25
+
26
+
27
+ def save(path: Path, lines: list[str], fmt: TextFormat) -> None:
28
+ data = (fmt.newline.join(lines) + fmt.newline).encode("utf-8", errors="surrogateescape")
29
+ path.parent.mkdir(parents=True, exist_ok=True)
30
+ path.write_bytes((BOM if fmt.bom else b"") + data)
31
+
32
+
33
+ def _strip_inline_comment(value: str) -> str:
34
+ return value.split(" ;")[0].strip()
35
+
36
+
37
+ def parse(lines: list[str]) -> dict[str, dict[str, str]]:
38
+ data: dict[str, dict[str, str]] = {}
39
+ section = ""
40
+ for line in lines:
41
+ s = line.strip()
42
+ if not s or s.startswith((";", "#")):
43
+ continue
44
+ if s.startswith("[") and s.endswith("]"):
45
+ section = s[1:-1]
46
+ data.setdefault(section, {})
47
+ elif "=" in s:
48
+ key, _, value = s.partition("=")
49
+ data.setdefault(section, {})[key.strip()] = _strip_inline_comment(value)
50
+ return data
51
+
52
+
53
+ def parse_sections(lines: list[str]) -> list[tuple[str, list[str]]]:
54
+ sections: list[tuple[str, list[str]]] = []
55
+ current: tuple[str, list[str]] | None = None
56
+ for line in lines:
57
+ s = line.strip()
58
+ if not s or s.startswith(";"):
59
+ continue
60
+ if s.startswith("[") and s.endswith("]"):
61
+ current = (s[1:-1], [])
62
+ sections.append(current)
63
+ elif current is not None and "=" in s:
64
+ current[1].append(s)
65
+ return sections
66
+
67
+
68
+ def _is_section(line: str) -> bool:
69
+ s = line.strip()
70
+ return s.startswith("[") and s.endswith("]")
71
+
72
+
73
+ def set_key(lines: list[str], section: str, key: str, value: str) -> tuple[list[str], str | None]:
74
+ """Replace or insert key=value inside section. Returns (new_lines, previous_value)."""
75
+ out = list(lines)
76
+ if section == "":
77
+ start = -1
78
+ else:
79
+ start = next((i for i, line in enumerate(out) if line.strip() == f"[{section}]"), None)
80
+ if start is None:
81
+ while out and not out[-1].strip():
82
+ out.pop()
83
+ out += ["", f"[{section}]", f"{key}={value}"] if out else [f"[{section}]", f"{key}={value}"]
84
+ return out, None
85
+ end = next((j for j in range(start + 1, len(out)) if _is_section(out[j])), len(out))
86
+ for j in range(start + 1, end):
87
+ s = out[j].strip()
88
+ if not s or s.startswith((";", "#")):
89
+ continue
90
+ k, sep, v = s.partition("=")
91
+ if sep and k.strip() == key:
92
+ indent = out[j][: len(out[j]) - len(out[j].lstrip())]
93
+ out[j] = f"{indent}{key}={value}"
94
+ return out, _strip_inline_comment(v)
95
+ insert_at = end
96
+ while insert_at > start + 1 and not out[insert_at - 1].strip():
97
+ insert_at -= 1
98
+ out.insert(insert_at, f"{key}={value}")
99
+ return out, None
@@ -0,0 +1,122 @@
1
+ """Where Assetto Corsa, its user config and Content Manager presets live on this PC."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import re
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ DEFAULT_STEAM = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Steam"
11
+
12
+
13
+ def _known_documents_dir() -> Path | None:
14
+ if sys.platform != "win32":
15
+ return None
16
+ import ctypes
17
+ import uuid
18
+ from ctypes import wintypes
19
+
20
+ class GUID(ctypes.Structure):
21
+ _fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD), ("Data3", wintypes.WORD),
22
+ ("Data4", ctypes.c_ubyte * 8)]
23
+
24
+ u = uuid.UUID("FDD39AD0-238F-46AF-ADB4-6C85480369C7") # FOLDERID_Documents (follows OneDrive redirection)
25
+ guid = GUID(u.fields[0], u.fields[1], u.fields[2], (ctypes.c_ubyte * 8).from_buffer_copy(u.bytes[8:]))
26
+ out = ctypes.c_wchar_p()
27
+ try:
28
+ if ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0, None, ctypes.byref(out)) != 0:
29
+ return None
30
+ return Path(out.value) if out.value else None
31
+ finally:
32
+ ctypes.windll.ole32.CoTaskMemFree(out)
33
+
34
+
35
+ def documents_dir() -> Path:
36
+ return _known_documents_dir() or Path.home() / "Documents"
37
+
38
+
39
+ def _steam_dir() -> Path:
40
+ if sys.platform == "win32":
41
+ try:
42
+ import winreg
43
+
44
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam") as key:
45
+ return Path(winreg.QueryValueEx(key, "SteamPath")[0])
46
+ except OSError:
47
+ pass
48
+ return DEFAULT_STEAM
49
+
50
+
51
+ def steam_libraries(steam: Path | None = None) -> list[Path]:
52
+ steam = steam or _steam_dir()
53
+ libraries = [steam]
54
+ vdf = steam / "steamapps" / "libraryfolders.vdf"
55
+ if vdf.exists():
56
+ text = vdf.read_text(encoding="utf-8", errors="replace")
57
+ for match in re.finditer(r'"path"\s+"([^"]+)"', text):
58
+ path = Path(match.group(1).replace("\\\\", "\\"))
59
+ if path not in libraries:
60
+ libraries.append(path)
61
+ return libraries
62
+
63
+
64
+ def find_ac_root(libraries: list[Path] | None = None) -> Path:
65
+ candidates = [lib / "steamapps" / "common" / "assettocorsa" for lib in (libraries or steam_libraries())]
66
+ return next((c for c in candidates if (c / "acs.exe").exists()), candidates[0])
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class AcPaths:
71
+ ac_root: Path
72
+ documents_cfg: Path
73
+ cm_presets: Path
74
+ data_dir: Path
75
+
76
+ @classmethod
77
+ def from_env(cls) -> AcPaths:
78
+ env = os.environ
79
+ local = Path(env.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
80
+ ac_docs = Path(env["AC_DOCUMENTS"]) if env.get("AC_DOCUMENTS") else documents_dir() / "Assetto Corsa"
81
+ return cls(
82
+ ac_root=Path(env["AC_ROOT"]) if env.get("AC_ROOT") else find_ac_root(),
83
+ documents_cfg=ac_docs / "cfg",
84
+ cm_presets=Path(env["CM_PRESETS"]) if env.get("CM_PRESETS") else local / "AcTools Content Manager" / "Presets",
85
+ data_dir=Path(env["AC_CONFIG_MCP_HOME"]) if env.get("AC_CONFIG_MCP_HOME") else local / "ac-config-mcp",
86
+ )
87
+
88
+ @property
89
+ def roots(self) -> dict[str, Path]:
90
+ return {
91
+ "cfg": self.documents_cfg,
92
+ "ext": self.documents_cfg / "extension",
93
+ "pure": self.ac_root / "extension" / "config-ext" / "Pure",
94
+ "sys": self.ac_root / "system" / "cfg",
95
+ "acroot": self.ac_root,
96
+ "apps": self.ac_root / "apps",
97
+ "extcfg": self.ac_root / "extension" / "config-ext",
98
+ }
99
+
100
+ @property
101
+ def ppfilters(self) -> Path:
102
+ return self.ac_root / "system" / "cfg" / "ppfilters"
103
+
104
+ @property
105
+ def csp_defaults(self) -> Path:
106
+ return self.ac_root / "extension" / "config"
107
+
108
+ @property
109
+ def video_presets(self) -> Path:
110
+ return self.cm_presets / "Video Settings"
111
+
112
+ @property
113
+ def csp_presets(self) -> Path:
114
+ return self.cm_presets / "Custom Shaders Patch Presets"
115
+
116
+ @property
117
+ def backups(self) -> Path:
118
+ return self.data_dir / "backups"
119
+
120
+ @property
121
+ def changes_log(self) -> Path:
122
+ return self.data_dir / "changes.log"
@@ -0,0 +1,40 @@
1
+ """MCP server "acconfig": read and tune Assetto Corsa / CSP / Content Manager configuration."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+
6
+ from ..compat import FastMCP, env_flag
7
+ from .paths import AcPaths
8
+ from .store import AcConfig
9
+
10
+
11
+ def build_server(config: AcConfig | None = None, read_only: bool | None = None) -> FastMCP:
12
+ config = config or AcConfig(AcPaths.from_env())
13
+ if read_only is None:
14
+ read_only = env_flag(os.environ.get("AC_CONFIG_MCP_READ_ONLY"))
15
+ mcp = FastMCP("acconfig")
16
+ reads = {
17
+ "ac_status": config.status, "ac_list_files": config.list_files, "ac_read": config.read,
18
+ "ac_csp_doc": config.csp_doc, "ac_list_presets": config.list_presets,
19
+ "ac_read_video_preset": config.read_video_preset, "ac_list_apps": config.list_apps,
20
+ "ac_list_pp_filters": config.list_pp_filters, "ac_read_text": config.read_text,
21
+ "ac_list_backups": config.list_backups,
22
+ }
23
+ writes = {
24
+ "ac_set": config.set, "ac_set_many": config.set_many, "ac_apply_video_preset": config.apply_video_preset,
25
+ "ac_save_video_preset": config.save_video_preset, "ac_apply_csp_preset": config.apply_csp_preset,
26
+ "ac_save_csp_preset": config.save_csp_preset, "ac_set_python_app": config.set_python_app,
27
+ "ac_set_pp_filter": config.set_pp_filter, "ac_write_text": config.write_text,
28
+ "ac_replace_text": config.replace_text, "ac_install_mod": config.install_mod, "ac_undo": config.undo,
29
+ }
30
+ for name, fn in {**reads, **({} if read_only else writes)}.items():
31
+ mcp.tool(name=name)(fn)
32
+ return mcp
33
+
34
+
35
+ def main() -> None:
36
+ build_server().run()
37
+
38
+
39
+ if __name__ == "__main__":
40
+ main()
@@ -0,0 +1,414 @@
1
+ """Assetto Corsa configuration operations. Every write is backed up first, logged, and reversible with undo()."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ import zipfile
9
+ from collections.abc import Callable
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+
13
+ from . import ini
14
+ from .paths import AcPaths
15
+
16
+ ACROOT_FILES = {"opencomposite.ini"}
17
+ TEXT_SUFFIXES = {".ini", ".txt", ".lut", ".lua", ".py", ".json", ".cfg"}
18
+ AC_ROOT_DIRS = {"apps", "extension", "content", "system"}
19
+ NEVER_INSTALL = {".exe", ".msi", ".bat", ".cmd", ".ps1", ".scr", ".dll"}
20
+ INFO_SECTION_PREFIXES = ("ℹ", "ℹ") # CSP's informational header, also as cp1252 mojibake
21
+
22
+
23
+ def running_processes() -> dict[str, bool]:
24
+ try:
25
+ p = subprocess.run(["tasklist", "/fo", "csv", "/nh"], capture_output=True, text=True, timeout=20,
26
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
27
+ except (OSError, subprocess.SubprocessError):
28
+ return {}
29
+ names = {line.split(",")[0].strip('"').lower() for line in p.stdout.splitlines() if line}
30
+ return {"assetto_corsa_running": "acs.exe" in names, "content_manager_running": "content manager.exe" in names}
31
+
32
+
33
+ class AcConfig:
34
+ def __init__(self, paths: AcPaths, running: Callable[[], dict[str, bool]] = running_processes):
35
+ self.paths = paths
36
+ self._running = running
37
+
38
+ # ---------- internals ----------
39
+
40
+ def resolve(self, file_id: str) -> Path:
41
+ file_id = file_id.replace("\\", "/").strip("/")
42
+ prefix, _, rel = file_id.partition("/")
43
+ roots = self.paths.roots
44
+ if prefix not in roots or not rel:
45
+ raise ValueError(f"invalid id '{file_id}'. Use one of {', '.join(f'{r}/' for r in roots)} + relative path.")
46
+ root = roots[prefix].resolve()
47
+ path = (root / rel).resolve()
48
+ if root != path and root not in path.parents:
49
+ raise ValueError("path escapes its root")
50
+ if prefix == "acroot" and (path.parent != root or path.name.lower() not in ACROOT_FILES):
51
+ raise ValueError(f"acroot/ only accepts: {', '.join(sorted(ACROOT_FILES))}")
52
+ if path.suffix.lower() not in TEXT_SUFFIXES:
53
+ raise ValueError(f"only {', '.join(sorted(TEXT_SUFFIXES))} files")
54
+ return path
55
+
56
+ def _backup(self, paths: list[Path], reason: str) -> str:
57
+ dest = self.paths.backups / datetime.now().strftime("%Y%m%d-%H%M%S-%f")
58
+ dest.mkdir(parents=True, exist_ok=True)
59
+ manifest = []
60
+ for i, p in enumerate(paths):
61
+ entry: dict = {"original": str(p), "existed": p.exists()}
62
+ if p.exists():
63
+ copy = dest / f"{i:03d}_{p.name}"
64
+ shutil.copy2(p, copy)
65
+ entry["copy"] = copy.name
66
+ manifest.append(entry)
67
+ (dest / "manifest.json").write_text(json.dumps({"reason": reason, "files": manifest}, ensure_ascii=False, indent=1),
68
+ encoding="utf-8")
69
+ return dest.name
70
+
71
+ def _log(self, entry: dict) -> None:
72
+ self.paths.data_dir.mkdir(parents=True, exist_ok=True)
73
+ with self.paths.changes_log.open("a", encoding="utf-8") as f:
74
+ f.write(json.dumps({"at": datetime.now().isoformat(timespec="seconds"), **entry}, ensure_ascii=False) + "\n")
75
+
76
+ def _warning(self) -> str | None:
77
+ if self._running().get("assetto_corsa_running"):
78
+ return "Assetto Corsa is running: most changes apply on the next session (some CSP options apply live)."
79
+ return None
80
+
81
+ # ---------- read ----------
82
+
83
+ def status(self) -> dict:
84
+ """Whether AC and Content Manager are running, the file roots, and the last recorded changes."""
85
+ log = self.paths.changes_log
86
+ last = log.read_text(encoding="utf-8").splitlines()[-5:] if log.exists() else []
87
+ return {**self._running(), "roots": {k: str(v) for k, v in self.paths.roots.items()},
88
+ "backups": str(self.paths.backups), "last_changes": [json.loads(line) for line in last]}
89
+
90
+ def list_files(self, root: str = "") -> dict:
91
+ """Editable .ini files per root (cfg | ext | pure | sys | acroot | extcfg). Empty root = all, top level only."""
92
+ result = {}
93
+ for prefix, base in self.paths.roots.items():
94
+ if (root and prefix != root) or (not root and prefix == "apps"):
95
+ continue
96
+ files = sorted(p.relative_to(base).as_posix() for p in base.glob("*.ini"))
97
+ if prefix == "acroot":
98
+ files = [f for f in files if f.lower() in ACROOT_FILES]
99
+ result[prefix] = files
100
+ return result
101
+
102
+ def read(self, file: str, section: str = "") -> dict:
103
+ """Read an ini as values, e.g. 'cfg/video.ini', 'ext/extra_fx.ini', 'pure/pure_config.ini'. section filters one."""
104
+ path = self.resolve(file)
105
+ if not path.exists():
106
+ return {"ok": False, "error": f"not found: {path}"}
107
+ data = ini.parse(ini.load(path)[0])
108
+ if section:
109
+ return {"ok": True, "file": file, "section": section, "values": data.get(section)}
110
+ return {"ok": True, "file": file, "values": data}
111
+
112
+ def csp_doc(self, module: str, section: str = "", key: str = "") -> dict:
113
+ """Default value and inline docs of a CSP option, read from CSP's shipped config, plus the user's override
114
+ (e.g. module='vr_tweaks', section='OPENXR_TWEAKS', key='EYE_TRACKING'). Without key: the whole section."""
115
+ name = f"{module.removesuffix('.ini')}.ini"
116
+ path = self.paths.csp_defaults / name
117
+ if not path.exists():
118
+ return {"ok": False, "error": f"CSP module not found: {name}"}
119
+ out, current = [], ""
120
+ for line in ini.load(path)[0]:
121
+ s = line.strip()
122
+ if s.startswith("[") and s.endswith("]"):
123
+ current = s[1:-1]
124
+ continue
125
+ if section and current != section:
126
+ continue
127
+ if "=" in s and not s.startswith(";"):
128
+ if key and s.partition("=")[0].strip() != key:
129
+ continue
130
+ out.append({"section": current, "line": s})
131
+ override_path = self.paths.roots["ext"] / name
132
+ user = ini.parse(ini.load(override_path)[0]) if override_path.exists() else {}
133
+ return {"ok": True, "module": name, "csp_default": out[:200],
134
+ "user_override": {s: v for s, v in user.items() if not section or s == section}}
135
+
136
+ def list_presets(self) -> dict:
137
+ """Content Manager presets: video (.cmpreset) and CSP (.ini)."""
138
+ return {"video": sorted(p.stem for p in self.paths.video_presets.glob("*.cmpreset")),
139
+ "csp": sorted(p.stem for p in self.paths.csp_presets.glob("*.ini"))}
140
+
141
+ def read_video_preset(self, name: str) -> dict:
142
+ """The video.ini stored inside a Content Manager video preset."""
143
+ path = self.paths.video_presets / f"{name}.cmpreset"
144
+ if not path.exists():
145
+ return {"ok": False, "error": "preset not found", "available": self.list_presets()["video"]}
146
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
147
+ return {"ok": True, "video": ini.parse(data.get("VideoData", "").splitlines())}
148
+
149
+ def list_apps(self) -> dict:
150
+ """AC apps: Python (apps/python, active per cfg/python.ini) and CSP Lua apps (apps/lua)."""
151
+ py_ini = self.paths.roots["cfg"] / "python.ini"
152
+ py_state = ini.parse(ini.load(py_ini)[0]) if py_ini.exists() else {}
153
+ apps_dir = self.paths.ac_root / "apps"
154
+ python = [{"app": d.name, "active": py_state.get(d.name.upper(), {}).get("ACTIVE") == "1"}
155
+ for d in sorted((apps_dir / "python").glob("*")) if d.is_dir() and d.name.lower() != "system"]
156
+ lua = []
157
+ for d in sorted((apps_dir / "lua").glob("*")):
158
+ if d.is_dir():
159
+ manifest = d / "manifest.ini"
160
+ about = ini.parse(ini.load(manifest)[0]).get("ABOUT", {}) if manifest.exists() else {}
161
+ lua.append({"app": d.name, "name": about.get("NAME"), "version": about.get("VERSION")})
162
+ return {"python": python, "lua": lua}
163
+
164
+ def list_pp_filters(self) -> dict:
165
+ """Post-processing filters available (system/cfg/ppfilters) and the one active in video.ini."""
166
+ video = self.paths.roots["cfg"] / "video.ini"
167
+ active = ini.parse(ini.load(video)[0]).get("POST_PROCESS", {}).get("FILTER") if video.exists() else None
168
+ return {"active": active, "available": sorted(p.stem for p in self.paths.ppfilters.glob("*.ini"))}
169
+
170
+ def read_text(self, file: str, max_chars: int = 20000) -> dict:
171
+ """Read a text/script file, e.g. 'apps/lua/MyApp/MyApp.lua' or 'sys/ppfilters/pureVR.ini'."""
172
+ path = self.resolve(file)
173
+ if not path.exists():
174
+ return {"ok": False, "error": f"not found: {path}"}
175
+ lines = ini.load(path)[0]
176
+ text = "\n".join(lines)
177
+ return {"ok": True, "file": file, "lines": len(lines), "content": text[:max_chars], "truncated": len(text) > max_chars}
178
+
179
+ def list_backups(self, limit: int = 10) -> list[dict]:
180
+ """Most recent backups made by this server, newest first."""
181
+ out = []
182
+ for d in self._backup_dirs()[: max(1, limit)]:
183
+ manifest = d / "manifest.json"
184
+ m = json.loads(manifest.read_text(encoding="utf-8")) if manifest.exists() else {}
185
+ out.append({"backup": d.name, "reason": m.get("reason"), "files": [f["original"] for f in m.get("files", [])]})
186
+ return out
187
+
188
+ # ---------- write ----------
189
+
190
+ def set(self, file: str, section: str, key: str, value: str) -> dict:
191
+ """Set one key in an ini (backup + log). section='' for files without sections.
192
+ Example: ac_set('ext/vr_tweaks.ini', 'OPENXR_TWEAKS', 'EYE_TRACKING', '1')."""
193
+ return self.set_many([{"file": file, "section": section, "key": key, "value": value}])
194
+
195
+ def set_many(self, changes: list[dict]) -> dict:
196
+ """Several changes with a single backup. changes: [{file, section, key, value}, ...]."""
197
+ by_path: dict[Path, list[dict]] = {}
198
+ for c in changes:
199
+ by_path.setdefault(self.resolve(c["file"]), []).append(c)
200
+ planned: dict[Path, tuple[list[str], ini.TextFormat]] = {}
201
+ results = []
202
+ for path, items in by_path.items():
203
+ lines, fmt = ini.load(path)
204
+ for c in items:
205
+ value = str(c["value"])
206
+ lines, old = ini.set_key(lines, c.get("section", ""), c["key"], value)
207
+ if old != value:
208
+ planned[path] = (lines, fmt)
209
+ results.append({"file": c["file"], "section": c.get("section", ""), "key": c["key"],
210
+ "before": old, "after": value, "changed": old != value})
211
+ if not planned:
212
+ return {"ok": True, "changes": results, "unchanged": True}
213
+ backup = self._backup(list(planned), f"set {len(changes)} key(s)")
214
+ for path, (lines, fmt) in planned.items():
215
+ ini.save(path, lines, fmt)
216
+ self._log({"action": "set", "changes": [r for r in results if r["changed"]], "backup": backup})
217
+ return {"ok": True, "changes": results, "backup": backup, "warning": self._warning()}
218
+
219
+ def apply_video_preset(self, name: str) -> dict:
220
+ """Apply a Content Manager video preset (writes cfg/video.ini the way CM does). Backup first."""
221
+ path = self.paths.video_presets / f"{name}.cmpreset"
222
+ if not path.exists():
223
+ return {"ok": False, "error": "preset not found", "available": self.list_presets()["video"]}
224
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
225
+ target = self.paths.roots["cfg"] / "video.ini"
226
+ backup = self._backup([target], f"apply video preset {name}")
227
+ ini.save(target, data["VideoData"].replace("\r\n", "\n").rstrip("\n").split("\n"), ini.load(target)[1])
228
+ self._log({"action": "apply_video_preset", "preset": name, "backup": backup})
229
+ return {"ok": True, "preset": name, "backup": backup,
230
+ "warning": "If Content Manager is open it may show old values until it reloads. " + (self._warning() or "")}
231
+
232
+ def save_video_preset(self, name: str) -> dict:
233
+ """Save the current cfg/video.ini as a Content Manager video preset."""
234
+ lines, _ = ini.load(self.paths.roots["cfg"] / "video.ini")
235
+ target = self.paths.video_presets / f"{name}.cmpreset"
236
+ backup = self._backup([target], f"save video preset {name}")
237
+ target.parent.mkdir(parents=True, exist_ok=True)
238
+ target.write_text(json.dumps({"VideoData": "\r\n".join(lines) + "\r\n"}, ensure_ascii=False), encoding="utf-8")
239
+ self._log({"action": "save_video_preset", "preset": name, "backup": backup})
240
+ return {"ok": True, "preset": str(target), "backup": backup}
241
+
242
+ def _csp_preset_modules(self, path: Path) -> dict[str, list[tuple[str, list[str]]]]:
243
+ modules: dict[str, list[tuple[str, list[str]]]] = {}
244
+ current: tuple[str, list[str]] | None = None
245
+ for line in ini.load(path)[0]:
246
+ s = line.strip()
247
+ if s.startswith("[") and s.endswith("]") and ":" in s:
248
+ module, _, section = s[1:-1].partition(":")
249
+ current = (section, [])
250
+ modules.setdefault(module, []).append(current)
251
+ elif s.startswith("[") and s.endswith("]"):
252
+ current = None
253
+ elif current is not None and "=" in s and not s.startswith(";"):
254
+ current[1].append(s)
255
+ return modules
256
+
257
+ def apply_csp_preset(self, name: str) -> dict:
258
+ """Apply a Content Manager CSP preset: rewrites the ext/*.ini overrides of the modules it covers. Backup first."""
259
+ path = self.paths.csp_presets / f"{name}.ini"
260
+ if not path.exists():
261
+ return {"ok": False, "error": "preset not found", "available": self.list_presets()["csp"]}
262
+ modules = self._csp_preset_modules(path)
263
+ targets = {module: self.paths.roots["ext"] / f"{module.lower()}.ini" for module in modules}
264
+ backup = self._backup(list(targets.values()), f"apply csp preset {name}")
265
+ for module, sections in modules.items():
266
+ out: list[str] = []
267
+ for section, kv in sections:
268
+ if section.startswith(INFO_SECTION_PREFIXES) or not kv:
269
+ continue
270
+ out += [f"[{section}]", *kv, ""]
271
+ ini.save(targets[module], out, ini.TextFormat())
272
+ self._log({"action": "apply_csp_preset", "preset": name, "modules": sorted(modules), "backup": backup})
273
+ return {"ok": True, "preset": name, "modules": sorted(modules), "backup": backup, "warning": self._warning()}
274
+
275
+ def save_csp_preset(self, name: str) -> dict:
276
+ """Save the current CSP overrides (ext/*.ini) as a Content Manager CSP preset."""
277
+ affected, body = [], []
278
+ for override in sorted(self.paths.roots["ext"].glob("*.ini")):
279
+ sections = [(s, kv) for s, kv in ini.parse_sections(ini.load(override)[0])
280
+ if kv and not s.startswith(INFO_SECTION_PREFIXES)]
281
+ if not sections:
282
+ continue
283
+ module = override.stem.upper()
284
+ affected.append(module)
285
+ for section, kv in sections:
286
+ body += [f"[{module}:{section}]", *kv, ""]
287
+ target = self.paths.csp_presets / f"{name}.ini"
288
+ backup = self._backup([target], f"save csp preset {name}")
289
+ ini.save(target, ["[CONFIGURATION]", "VERSION=1", "AFFECTED_SECTIONS=" + ",".join(affected), "", *body], ini.TextFormat())
290
+ self._log({"action": "save_csp_preset", "preset": name, "modules": affected, "backup": backup})
291
+ return {"ok": True, "preset": str(target), "modules": affected, "backup": backup}
292
+
293
+ def set_python_app(self, app: str, active: bool) -> dict:
294
+ """Enable or disable an AC Python app (cfg/python.ini [APP] ACTIVE)."""
295
+ if not (self.paths.ac_root / "apps" / "python" / app).is_dir():
296
+ return {"ok": False, "error": "app not found", "apps": [a["app"] for a in self.list_apps()["python"]]}
297
+ return self.set("cfg/python.ini", app.upper(), "ACTIVE", "1" if active else "0")
298
+
299
+ def set_pp_filter(self, name: str) -> dict:
300
+ """Switch the active post-processing filter (video.ini [POST_PROCESS] FILTER), e.g. a VR-specific one."""
301
+ if not (self.paths.ppfilters / f"{name}.ini").exists():
302
+ return {"ok": False, "error": "filter not found", "available": self.list_pp_filters()["available"]}
303
+ return self.set("cfg/video.ini", "POST_PROCESS", "FILTER", name)
304
+
305
+ def write_text(self, file: str, content: str) -> dict:
306
+ """Replace the whole content of a text/script file (creates it if missing). Backup + log."""
307
+ path = self.resolve(file)
308
+ fmt = ini.load(path)[1]
309
+ backup = self._backup([path], f"write_text {file}")
310
+ ini.save(path, content.replace("\r\n", "\n").rstrip("\n").split("\n"), fmt)
311
+ self._log({"action": "write_text", "file": file, "chars": len(content), "backup": backup})
312
+ return {"ok": True, "file": str(path), "backup": backup, "warning": self._warning()}
313
+
314
+ def replace_text(self, file: str, old: str, new: str) -> dict:
315
+ """Replace one exact, unique snippet inside a text/script file. Backup + log."""
316
+ path = self.resolve(file)
317
+ lines, fmt = ini.load(path)
318
+ text = "\n".join(lines)
319
+ count = text.count(old)
320
+ if count != 1:
321
+ return {"ok": False, "error": f"snippet found {count} times (must be exactly 1)"}
322
+ backup = self._backup([path], f"replace_text {file}")
323
+ ini.save(path, text.replace(old, new).split("\n"), fmt)
324
+ self._log({"action": "replace_text", "file": file, "backup": backup})
325
+ return {"ok": True, "file": str(path), "backup": backup}
326
+
327
+ def _plan_install(self, extracted: Path) -> list[tuple[Path, Path]]:
328
+ ac_root = self.paths.ac_root
329
+ for d in [extracted, *sorted(p for p in extracted.rglob("*") if p.is_dir())]:
330
+ names = {c.name.lower() for c in d.iterdir()}
331
+ if names & AC_ROOT_DIRS and not (d / "data.acd").exists():
332
+ return [(c, ac_root / c.name.lower()) for c in d.iterdir() if c.is_dir() and c.name.lower() in AC_ROOT_DIRS]
333
+ plan: list[tuple[Path, Path]] = []
334
+ for d in sorted(p for p in extracted.rglob("*") if p.is_dir()):
335
+ if any(d.is_relative_to(src) for src, _ in plan):
336
+ continue
337
+ names = {c.name.lower() for c in d.iterdir()}
338
+ if "ui" not in names:
339
+ continue
340
+ if "data.acd" in names or (d / "data" / "car.ini").exists():
341
+ plan.append((d, ac_root / "content" / "cars" / d.name))
342
+ elif any(n.endswith(".kn5") for n in names) or "models.ini" in names or (d / "data" / "surfaces.ini").exists():
343
+ plan.append((d, ac_root / "content" / "tracks" / d.name))
344
+ return plan
345
+
346
+ def install_mod(self, zip_path: str, dry_run: bool = True) -> dict:
347
+ """Install a mod from an already-downloaded .zip (CSP/Pure-style folders, apps, cars, tracks).
348
+ dry_run=True only shows the plan. Real install: AC must be closed; every overwritten file is backed up and
349
+ undo() restores them and removes files that did not exist. Executables and scripts are never copied."""
350
+ src = Path(zip_path)
351
+ if not src.is_file() or src.suffix.lower() != ".zip":
352
+ return {"ok": False, "error": "give an existing .zip (extract .7z/.rar and re-zip, or use Content Manager)"}
353
+ self.paths.data_dir.mkdir(parents=True, exist_ok=True)
354
+ tmp = Path(tempfile.mkdtemp(prefix="acmod_", dir=str(self.paths.data_dir))).resolve()
355
+ try:
356
+ with zipfile.ZipFile(src) as z:
357
+ for info in z.infolist():
358
+ target = (tmp / info.filename).resolve()
359
+ if target != tmp and tmp not in target.parents:
360
+ return {"ok": False, "error": f"zip entry escapes the target folder: {info.filename}"}
361
+ z.extractall(tmp)
362
+ plan = self._plan_install(tmp)
363
+ if not plan:
364
+ return {"ok": False, "error": "unrecognized layout (no apps/extension/content/system, car or track folder)"}
365
+ files = [(f, dst / f.relative_to(s)) for s, dst in plan for f in sorted(s.rglob("*")) if f.is_file()]
366
+ skipped = [f for f, _ in files if f.suffix.lower() in NEVER_INSTALL]
367
+ to_copy = [(f, t) for f, t in files if f not in skipped]
368
+ summary = {"destinations": sorted({str(dst) for _, dst in plan}), "files": len(to_copy),
369
+ "overwrites": sum(1 for _, t in to_copy if t.exists()),
370
+ "skipped_executables": [f.relative_to(tmp).as_posix() for f in skipped]}
371
+ if dry_run:
372
+ return {"ok": True, "dry_run": True, **summary}
373
+ if self._running().get("assetto_corsa_running"):
374
+ return {"ok": False, "error": "close Assetto Corsa before installing"}
375
+ backup = self._backup([t for _, t in to_copy], f"install {src.name}")
376
+ for f, t in to_copy:
377
+ t.parent.mkdir(parents=True, exist_ok=True)
378
+ shutil.copy2(f, t)
379
+ self._log({"action": "install_mod", "zip": src.name, **summary, "backup": backup})
380
+ return {"ok": True, **summary, "backup": backup}
381
+ finally:
382
+ shutil.rmtree(tmp, ignore_errors=True)
383
+
384
+ def _backup_dirs(self) -> list[Path]:
385
+ if not self.paths.backups.exists():
386
+ return []
387
+ return sorted((d for d in self.paths.backups.iterdir() if d.is_dir()), reverse=True)
388
+
389
+ def undo(self, backup: str = "") -> dict:
390
+ """Restore a backup (empty = the most recent). The current state is backed up first, so undo is undoable."""
391
+ dirs = self._backup_dirs()
392
+ if not dirs:
393
+ return {"ok": False, "error": "no backups"}
394
+ if backup:
395
+ matches = [d for d in dirs if d.name == backup]
396
+ if not matches:
397
+ return {"ok": False, "error": "backup not found", "recent": [d.name for d in dirs[:10]]}
398
+ d = matches[0]
399
+ else:
400
+ d = dirs[0]
401
+ manifest = json.loads((d / "manifest.json").read_text(encoding="utf-8"))
402
+ safety = self._backup([Path(f["original"]) for f in manifest["files"]], f"before undo of {d.name}")
403
+ restored = []
404
+ for f in manifest["files"]:
405
+ original = Path(f["original"])
406
+ if f.get("copy"):
407
+ original.parent.mkdir(parents=True, exist_ok=True)
408
+ shutil.copy2(d / f["copy"], original)
409
+ restored.append(str(original))
410
+ elif original.exists():
411
+ original.unlink()
412
+ restored.append(f"{original} (removed; did not exist before)")
413
+ self._log({"action": "undo", "backup": d.name, "safety_backup": safety})
414
+ return {"ok": True, "restored_from": d.name, "files": restored, "safety_backup": safety}
simrig_mcp/compat.py ADDED
@@ -0,0 +1,10 @@
1
+ try:
2
+ from mcp.server.mcpserver import MCPServer as FastMCP
3
+ except ImportError: # mcp 1.x
4
+ from mcp.server.fastmcp import FastMCP
5
+
6
+ __all__ = ["FastMCP"]
7
+
8
+
9
+ def env_flag(value: str | None) -> bool:
10
+ return (value or "").strip().lower() in {"1", "true", "yes", "on"}
File without changes
@@ -0,0 +1,67 @@
1
+ """Wrapper around the official Pimax Play CLI (pimax.exe). Needs Pimax Play (PimaxClient) running."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import subprocess
7
+ from collections.abc import Callable
8
+ from pathlib import Path
9
+
10
+ DEFAULT_CLI = (Path(os.environ.get("ProgramFiles", r"C:\Program Files"))
11
+ / "Pimax" / "PimaxClient" / "pimaxui" / "resources" / "pimaxcli" / "pimax.exe")
12
+
13
+
14
+ def _float_between(lo: float, hi: float) -> Callable[[str], bool]:
15
+ def check(v: str) -> bool:
16
+ try:
17
+ return lo <= float(v) <= hi
18
+ except ValueError:
19
+ return False
20
+ return check
21
+
22
+
23
+ def _int_between(lo: int, hi: int) -> Callable[[str], bool]:
24
+ return lambda v: v.isdigit() and lo <= int(v) <= hi
25
+
26
+
27
+ SETTINGS: dict[str, tuple[list[str], list[str], Callable[[str], bool]]] = {
28
+ "quality": (["graphics", "quality", "get"], ["graphics", "quality", "set"],
29
+ lambda v: v in {"auto", "low", "mid", "high", "custom"}),
30
+ "brightness": (["display", "brightness", "get"], ["display", "brightness", "set"], _int_between(0, 100)),
31
+ "local_dimming": (["display", "local-dimming", "get"], ["display", "local-dimming", "set"], _int_between(0, 100)),
32
+ "overlay_scale": (["graphics", "overlay-scale", "get"], ["graphics", "overlay-scale", "set"], _float_between(0.5, 1.5)),
33
+ "eye_tracking": (["eye-tracking", "status"], ["eye-tracking"], lambda v: v in {"on", "off"}),
34
+ }
35
+
36
+
37
+ class PimaxCli:
38
+ def __init__(self, exe: Path | None = None, runner: Callable[..., subprocess.CompletedProcess] = subprocess.run):
39
+ self.exe = exe or Path(os.environ.get("PIMAX_CLI") or DEFAULT_CLI)
40
+ self._runner = runner
41
+
42
+ def run(self, args: list[str], json_out: bool = True, timeout: int = 30) -> dict:
43
+ cmd = [str(self.exe), *args, *(["--json"] if json_out else [])]
44
+ try:
45
+ p = self._runner(cmd, capture_output=True, text=True, timeout=timeout,
46
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
47
+ except FileNotFoundError:
48
+ return {"ok": False, "error": f"pimax.exe not found at {self.exe} (set PIMAX_CLI)"}
49
+ except subprocess.TimeoutExpired:
50
+ return {"ok": False, "error": "timeout: is Pimax Play running?"}
51
+ out = (p.stdout or "").strip()
52
+ if json_out:
53
+ for line in reversed(out.splitlines()):
54
+ line = line.strip()
55
+ if line.startswith("{"):
56
+ try:
57
+ return json.loads(line)
58
+ except json.JSONDecodeError:
59
+ break
60
+ err = "\n".join(line for line in (p.stderr or "").splitlines() if "[transport]" not in line).strip()
61
+ return {"ok": p.returncode == 0, "stdout": out, "error": err or None}
62
+
63
+ def read_setting(self, name: str) -> dict:
64
+ return self.run(SETTINGS[name][0])
65
+
66
+ def write_setting(self, name: str, value: str) -> dict:
67
+ return self.run([*SETTINGS[name][1], value], json_out=False)
@@ -0,0 +1,137 @@
1
+ """Read-only parsing of Pimax runtime logs.
2
+
3
+ PiService logs every setting it reads ("Get*Config appId=<app>, key=<key>, result=<r>, val=<v>"), which is the only
4
+ place the per-app render settings in effect are visible. The compositor log (pvr_srv_log_*.txt) writes one line per
5
+ second per VR session with app/compositor FPS and missed/stale/discarded frames. The PimaxClient config.json holds
6
+ the login token and is never read.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import statistics
14
+ import subprocess
15
+ from pathlib import Path
16
+
17
+ LOCAL = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
18
+ PISERVICE_LOG_DIR = LOCAL / "Pimax" / "PiService" / "Log"
19
+ RUNTIME_DIR = LOCAL / "Pimax" / "runtime"
20
+
21
+ SETTING_LINE = re.compile(r"^(\S+ \S+) .*Get\w*Config appId=([^,]+), key=([^,]+), result=([^,]+), val=(\S*)")
22
+ FPS_LINE = re.compile(
23
+ r"^\[(\d\d-\d\d-\d\d \d\d:\d\d:\d\d)\.\d+\]\[\d+\]\[\w+\]\[PSRV\] (\d+) (\w+) rendering "
24
+ r"fps:\(a:([\d.]+),c:([\d.]+)\) Missed:\(a:(\d+),c:(\d+),bl:(\d+)\) Stale:\(a:(\d+)\) Discard:\(a:(\d+)\) "
25
+ r"GPU: (\d+)% CPU: (\d+)%")
26
+
27
+ KEY_ORDER = [
28
+ "runtime_pixels_per_display_pixel_rate", "piplay_display_quality_level", "runtime_fov_level",
29
+ "runtime_enable_foveated_rendering", "runtime_foveated_rendering_level",
30
+ "runtime_quadviews_rendering_level", "piplay_quadviews_fine_type",
31
+ "runtime_dbg_asw_enable", "runtime_dbg_force_framerate_divide_by",
32
+ "runtime_gpu_upscaling_algorithm", "runtime_gpu_upscaling_sharpness",
33
+ ]
34
+
35
+
36
+ def newest(directory: Path, pattern: str, n: int) -> list[Path]:
37
+ return sorted(directory.glob(pattern), key=lambda p: p.stat().st_mtime)[-max(1, n):]
38
+
39
+
40
+ def settings_state(log_dir: Path = PISERVICE_LOG_DIR, runtime_dir: Path = RUNTIME_DIR, n_logs: int = 3) -> dict:
41
+ logs = newest(log_dir, "PiService__*.log", n_logs)
42
+ last: dict[tuple[str, str], dict] = {}
43
+ for log in logs:
44
+ with log.open(encoding="utf-8", errors="replace") as fh:
45
+ for line in fh:
46
+ m = SETTING_LINE.match(line)
47
+ if m:
48
+ ts, app, key, result, val = m.groups()
49
+ last[(app, key)] = {"value": val, "read_at": ts, "result": result}
50
+ apps: dict[str, dict] = {}
51
+ for (app, key), v in last.items():
52
+ apps.setdefault(app, {})[key] = v
53
+ rank = {k: i for i, k in enumerate(KEY_ORDER)}
54
+ apps = {app: dict(sorted(keys.items(), key=lambda kv: (rank.get(kv[0], 99), kv[0]))) for app, keys in apps.items()}
55
+ profile_path = runtime_dir / "profile.json"
56
+ profile = None
57
+ if profile_path.exists():
58
+ profile = json.loads(profile_path.read_text(encoding="utf-8-sig"))
59
+ profile.pop("GpuMeasure", None)
60
+ return {"logs_read": [str(p) for p in logs], "settings_by_app": apps, "runtime_profile": profile,
61
+ "note": "Values observed in the PiService log. A missing key was not observed; it does not mean off."}
62
+
63
+
64
+ def parse_sessions(files: list[Path]) -> dict[int, list[dict]]:
65
+ sessions: dict[int, list[dict]] = {}
66
+ for f in files:
67
+ with f.open(encoding="utf-8", errors="replace") as fh:
68
+ for line in fh:
69
+ m = FPS_LINE.match(line)
70
+ if not m:
71
+ continue
72
+ ts, pid, level, fa, fc, ma, mc, _mbl, st, dc, gpu, cpu = m.groups()
73
+ sessions.setdefault(int(pid), []).append({
74
+ "t": ts, "warn": level == "Warning", "fps_app": float(fa), "fps_comp": float(fc),
75
+ "missed_app": int(ma), "missed_comp": int(mc), "stale": int(st), "discard": int(dc),
76
+ "gpu": int(gpu), "cpu": int(cpu)})
77
+ return sessions
78
+
79
+
80
+ def _pct(values: list[float], q: float) -> float:
81
+ s = sorted(values)
82
+ return s[min(len(s) - 1, int(q * (len(s) - 1)))]
83
+
84
+
85
+ def summarize(rows: list[dict]) -> dict:
86
+ seconds = len(rows)
87
+ frames = sum(r["fps_app"] for r in rows)
88
+ fps = [r["fps_app"] for r in rows]
89
+ missed = sum(r["missed_app"] for r in rows)
90
+ return {
91
+ "start": rows[0]["t"], "end": rows[-1]["t"], "seconds": seconds,
92
+ "fps_app_mean": round(statistics.fmean(fps), 2), "fps_app_1pct_low": _pct(fps, 0.01),
93
+ "fps_compositor_mean": round(statistics.fmean(r["fps_comp"] for r in rows), 2),
94
+ "app_frames_missed": missed,
95
+ "pct_frames_missed": round(100 * missed / frames, 3) if frames else None,
96
+ "compositor_frames_missed": sum(r["missed_comp"] for r in rows),
97
+ "frames_stale": sum(r["stale"] for r in rows),
98
+ "frames_discarded": sum(r["discard"] for r in rows),
99
+ "pct_seconds_with_warning": round(100 * sum(r["warn"] for r in rows) / seconds, 2),
100
+ "gpu_pct_mean": round(statistics.fmean(r["gpu"] for r in rows), 1), "gpu_pct_p95": _pct([r["gpu"] for r in rows], .95),
101
+ "cpu_pct_mean": round(statistics.fmean(r["cpu"] for r in rows), 1), "cpu_pct_p95": _pct([r["cpu"] for r in rows], .95),
102
+ }
103
+
104
+
105
+ def pid_of(exe: str) -> int | None:
106
+ name = exe if exe.lower().endswith(".exe") else f"{exe}.exe"
107
+ try:
108
+ out = subprocess.run(["tasklist", "/FO", "CSV", "/NH", "/FI", f"IMAGENAME eq {name}"], capture_output=True,
109
+ text=True, timeout=20, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)).stdout
110
+ except (OSError, subprocess.SubprocessError):
111
+ return None
112
+ m = re.search(r'"[^"]+","(\d+)"', out)
113
+ return int(m.group(1)) if m else None
114
+
115
+
116
+ def runtime_stats(exe: str = "", pid: int = 0, list_sessions: bool = False, logs: int = 3,
117
+ runtime_dir: Path = RUNTIME_DIR) -> dict:
118
+ files = newest(runtime_dir, "pvr_srv_log_*.txt", max(1, min(logs, 10)))
119
+ sessions = parse_sessions(files)
120
+ if not sessions:
121
+ return {"ok": False, "error": f"no 'rendering fps' lines in {runtime_dir}"}
122
+ home = pid_of("PimaxHome-Win64-Shipping")
123
+ if list_sessions:
124
+ return {"ok": True, "sessions": [
125
+ {"pid": p, "start": rows[0]["t"], "end": rows[-1]["t"], "seconds": len(rows), "pimax_home": p == home}
126
+ for p, rows in sorted(sessions.items(), key=lambda kv: kv[1][0]["t"])]}
127
+ if not pid and exe:
128
+ pid = pid_of(exe) or 0
129
+ if not pid:
130
+ return {"ok": False, "error": f"{exe} is not running; pass pid (see list_sessions=True)"}
131
+ if not pid:
132
+ candidates = {k: v for k, v in sessions.items() if k != home} or sessions
133
+ pid = max(candidates, key=lambda k: (candidates[k][-1]["t"], len(candidates[k])))
134
+ if pid not in sessions:
135
+ return {"ok": False, "error": f"PID {pid} not in the newest {len(files)} logs (raise logs or use list_sessions)"}
136
+ return {"ok": True, "pid": pid, "logs_read": [str(f) for f in files], **summarize(sessions[pid]),
137
+ "note": "1 sample per second from the Pimax compositor. Missed = frames the app did not deliver in time."}
@@ -0,0 +1,94 @@
1
+ """MCP server "pimax": inspect and adjust a Pimax headset through the official Pimax Play CLI and runtime logs."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+
9
+ from ..compat import FastMCP, env_flag
10
+ from . import logs
11
+ from .cli import SETTINGS, PimaxCli
12
+
13
+ DATA_DIR = Path(os.environ.get("PIMAX_MCP_HOME") or logs.LOCAL / "pimax-mcp")
14
+
15
+
16
+ class PimaxTools:
17
+ def __init__(self, cli: PimaxCli | None = None, data_dir: Path = DATA_DIR,
18
+ piservice_log_dir: Path = logs.PISERVICE_LOG_DIR, runtime_dir: Path = logs.RUNTIME_DIR):
19
+ self.cli = cli or PimaxCli()
20
+ self.changes_log = data_dir / "changes.log"
21
+ self.piservice_log_dir = piservice_log_dir
22
+ self.runtime_dir = runtime_dir
23
+
24
+ def pimax_status(self) -> dict:
25
+ """Connection to Pimax Play, service and headset (name, connected)."""
26
+ return self.cli.run(["status"])
27
+
28
+ def pimax_doctor(self) -> dict:
29
+ """Pimax Play's own diagnostics (WebSocket, service, DLL, headset, USB, DisplayPort)."""
30
+ return self.cli.run(["doctor"])
31
+
32
+ def pimax_settings(self) -> dict:
33
+ """Render quality, brightness, local dimming, overlay scale and eye-tracking status."""
34
+ return {name: self.cli.read_setting(name) for name in SETTINGS}
35
+
36
+ def pimax_runtime_state(self, logs_to_read: int = 3) -> dict:
37
+ """Per-app runtime settings in effect (render scale, FOV, foveated, quad views, smart smoothing, upscaling),
38
+ read from the PiService log. Shows what the CLI cannot. Read-only."""
39
+ return logs.settings_state(self.piservice_log_dir, self.runtime_dir, max(1, min(logs_to_read, 10)))
40
+
41
+ def pimax_runtime_stats(self, exe: str = "", pid: int = 0, list_sessions: bool = False, logs_to_read: int = 3) -> dict:
42
+ """App and compositor FPS, missed/stale/discarded frames, GPU% and CPU% for one VR session, from the Pimax
43
+ compositor log. exe='acs' picks Assetto Corsa (run while the game is open or right after). list_sessions=True
44
+ lists sessions by PID. Read-only."""
45
+ return logs.runtime_stats(exe, pid, list_sessions, logs_to_read, self.runtime_dir)
46
+
47
+ def pimax_set(self, setting: str, value: str, confirm: bool = False) -> dict:
48
+ """Change one Pimax setting: quality (auto|low|mid|high|custom), brightness (0-100), local_dimming (0-100),
49
+ overlay_scale (0.5-1.5), eye_tracking (on|off). Without confirm=True it only shows the current value; pass
50
+ confirm=True only after the user approved the change. Before/after are appended to changes.log."""
51
+ if setting not in SETTINGS:
52
+ return {"ok": False, "error": f"unknown setting. Use: {', '.join(SETTINGS)}"}
53
+ value = str(value).strip().lower()
54
+ if not SETTINGS[setting][2](value):
55
+ return {"ok": False, "error": f"invalid value for {setting}: {value}"}
56
+ before = self.cli.read_setting(setting)
57
+ if not confirm:
58
+ return {"ok": False, "dry_run": True, "current": before,
59
+ "error": "Not applied: confirm with the user, then call again with confirm=True."}
60
+ result = self.cli.write_setting(setting, value)
61
+ after = self.cli.read_setting(setting)
62
+ self.changes_log.parent.mkdir(parents=True, exist_ok=True)
63
+ with self.changes_log.open("a", encoding="utf-8") as f:
64
+ f.write(json.dumps({"at": datetime.now().isoformat(timespec="seconds"), "setting": setting, "value": value,
65
+ "before": before, "result": result, "after": after}, ensure_ascii=False) + "\n")
66
+ return {"ok": bool(result.get("ok")), "before": before, "after": after, "result": result}
67
+
68
+
69
+ def build_server(tools: PimaxTools | None = None, read_only: bool | None = None) -> FastMCP:
70
+ tools = tools or PimaxTools()
71
+ if read_only is None:
72
+ read_only = env_flag(os.environ.get("PIMAX_MCP_READ_ONLY"))
73
+ mcp = FastMCP("pimax")
74
+ fns = [tools.pimax_status, tools.pimax_doctor, tools.pimax_settings, tools.pimax_runtime_state,
75
+ tools.pimax_runtime_stats]
76
+ if not read_only:
77
+ fns.append(tools.pimax_set)
78
+ for fn in fns:
79
+ mcp.tool(name=fn.__name__)(fn)
80
+ return mcp
81
+
82
+
83
+ def main() -> None:
84
+ import sys
85
+
86
+ if "--selftest" in sys.argv:
87
+ t = PimaxTools()
88
+ print(json.dumps({"status": t.pimax_status(), "settings": t.pimax_settings()}, ensure_ascii=False, indent=1))
89
+ return
90
+ build_server().run()
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.5
2
+ Name: simrig-mcp
3
+ Version: 0.1.1
4
+ Summary: MCP servers for sim racing on Windows: Assetto Corsa / CSP / Content Manager config and Pimax VR headsets.
5
+ Project-URL: Homepage, https://github.com/luangrezende/simrig-mcp
6
+ Project-URL: Issues, https://github.com/luangrezende/simrig-mcp/issues
7
+ Project-URL: Guide, https://github.com/luangrezende/simrig-mcp/blob/main/docs/assetto-corsa-csp-openxr-eye-tracked-vrs.md
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: assetto-corsa,content-manager,csp,mcp,openxr,pimax,sim-racing,vr
11
+ Classifier: Operating System :: Microsoft :: Windows
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Games/Entertainment :: Simulation
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: mcp>=1.2
16
+ Description-Content-Type: text/markdown
17
+
18
+ # simrig-mcp
19
+
20
+ [![CI](https://github.com/luangrezende/simrig-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/luangrezende/simrig-mcp/actions/workflows/ci.yml)
21
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
22
+
23
+ Two [MCP](https://modelcontextprotocol.io) servers that let an AI assistant (Claude Code, Claude Desktop, Cursor, ...)
24
+ work on a Windows sim racing rig the way a careful engineer would: read the real configuration, change one thing,
25
+ keep a backup, measure, and roll back if it got worse.
26
+
27
+ | Server | What it does |
28
+ |---|---|
29
+ | **`ac-config-mcp`** | Reads and edits **Assetto Corsa**, **Custom Shaders Patch** and **Content Manager** configuration: `video.ini`, CSP overrides, Pure config, CM video/CSP presets, post-processing filters, Python/Lua apps, mod install from a zip. Every write is backed up and undoable. |
30
+ | **`pimax-mcp`** | Reads and adjusts a **Pimax** headset through the official Pimax Play CLI, and parses the Pimax runtime logs for what the CLI does not show: the render settings actually in effect per game, and per-session app/compositor FPS with missed, stale and discarded frames. |
31
+
32
+ ## Why I built this
33
+
34
+ I'm a huge sim racing fan. My rig is a Fanatec direct drive wheel, a Pimax Crystal in VR and a SimHub setup with
35
+ bass shakers, vibration motors, wind and an active belt tensioner, mostly driving Assetto Corsa with CSP.
36
+
37
+ Anyone with a rig like that knows the pain: hundreds of settings spread across `video.ini`, CSP overrides, Content
38
+ Manager presets, Pimax Play and the runtime, and every forum thread swears by a different combination. I wanted an
39
+ AI assistant to help me tune it like an engineer would: look at the real config, change one thing at a time,
40
+ measure, and roll back if it got worse. So I built these servers to give it exactly that, safely.
41
+
42
+ The first thing it helped me find was something I couldn't find written anywhere: a guide to
43
+ [running AC in CSP's native OpenXR mode with eye-tracked foveated rendering on a Pimax](docs/assetto-corsa-csp-openxr-eye-tracked-vrs.md).
44
+ I'm sharing it all in case it saves other sim racers some evenings of trial and error.
45
+
46
+ ## Why not just edit the files?
47
+
48
+ You can. The point is letting an assistant do it **safely**:
49
+
50
+ - **Backup before every write**, one folder per change with a manifest, plus a JSON-lines `changes.log`.
51
+ - **`ac_undo`** restores any backup (and backs up the current state first, so undo is undoable).
52
+ Files a change created are removed on undo.
53
+ - **Edits are surgical**: comments, BOM and CRLF line endings survive; only the key you set changes.
54
+ - **Paths are fenced** to known roots and text extensions. No `..`, no executables, no arbitrary files.
55
+ - **Mod install is dry-run by default**, refuses zip-slip paths, never copies `.exe/.dll/.bat/.ps1/...`,
56
+ and refuses to run while the game is open.
57
+ - **Pimax changes need `confirm=True`**, which the tool description tells the model to pass only after you approve.
58
+ Values are validated against a closed list.
59
+ - **Read-only mode**: set `AC_CONFIG_MCP_READ_ONLY=1` / `PIMAX_MCP_READ_ONLY=1` and the write tools are not even registered.
60
+
61
+ ## Requirements
62
+
63
+ - Windows, Python 3.10+
64
+ - `ac-config-mcp`: Assetto Corsa (Steam). CSP and Content Manager are optional but most tools assume them.
65
+ - `pimax-mcp`: Pimax Play running (tested with Pimax Play 2.0.4 and a Crystal OG). The CLI ships with Pimax Play.
66
+
67
+ ## Install
68
+
69
+ Published on [PyPI](https://pypi.org/project/simrig-mcp/) and in the official
70
+ [MCP Registry](https://registry.modelcontextprotocol.io) as `io.github.luangrezende/ac-config-mcp` and
71
+ `io.github.luangrezende/pimax-mcp`. With [uv](https://docs.astral.sh/uv/) there is nothing to install by hand:
72
+ the client runs `uvx simrig-mcp acconfig` / `uvx simrig-mcp pimax`.
73
+
74
+ ### Claude Code
75
+
76
+ ```powershell
77
+ claude mcp add acconfig -- uvx simrig-mcp acconfig
78
+ claude mcp add pimax -- uvx simrig-mcp pimax
79
+ ```
80
+
81
+ ### Any MCP client (JSON)
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "acconfig": { "command": "uvx", "args": ["simrig-mcp", "acconfig"] },
87
+ "pimax": { "command": "uvx", "args": ["simrig-mcp", "pimax"] }
88
+ }
89
+ }
90
+ ```
91
+
92
+ Without uv: `pip install simrig-mcp` puts `ac-config-mcp` and `pimax-mcp` on your PATH.
93
+ From source: `git clone https://github.com/luangrezende/simrig-mcp`, then `uv sync` (servers end up in `.venv\Scripts\`).
94
+
95
+ <!-- mcp-name: io.github.luangrezende/ac-config-mcp -->
96
+ <!-- mcp-name: io.github.luangrezende/pimax-mcp -->
97
+
98
+ ## Configuration
99
+
100
+ Everything is auto-detected; override only if needed.
101
+
102
+ | Variable | Default |
103
+ |---|---|
104
+ | `AC_ROOT` | Steam library containing `steamapps\common\assettocorsa` (reads `libraryfolders.vdf`) |
105
+ | `AC_DOCUMENTS` | `<Documents>\Assetto Corsa` (follows OneDrive folder redirection) |
106
+ | `CM_PRESETS` | `%LOCALAPPDATA%\AcTools Content Manager\Presets` |
107
+ | `AC_CONFIG_MCP_HOME` | `%LOCALAPPDATA%\ac-config-mcp` (backups and `changes.log`) |
108
+ | `AC_CONFIG_MCP_READ_ONLY` | off |
109
+ | `PIMAX_CLI` | `%ProgramFiles%\Pimax\PimaxClient\pimaxui\resources\pimaxcli\pimax.exe` |
110
+ | `PIMAX_MCP_HOME` | `%LOCALAPPDATA%\pimax-mcp` (`changes.log`) |
111
+ | `PIMAX_MCP_READ_ONLY` | off |
112
+
113
+ ## Tools
114
+
115
+ ### ac-config-mcp
116
+
117
+ Files are addressed as `<root>/<relative path>`:
118
+ `cfg/` (Documents\Assetto Corsa\cfg), `ext/` (CSP overrides), `pure/`, `sys/` (game `system\cfg`),
119
+ `apps/`, `extcfg/` (`extension\config-ext`), `acroot/` (only `opencomposite.ini`).
120
+
121
+ | Read | Write (backup + log + undo) |
122
+ |---|---|
123
+ | `ac_status` - AC/CM running, roots, last changes | `ac_set`, `ac_set_many` - set ini keys |
124
+ | `ac_list_files`, `ac_read` - ini files as values | `ac_apply_video_preset`, `ac_save_video_preset` |
125
+ | `ac_csp_doc` - CSP default + inline docs + your override | `ac_apply_csp_preset`, `ac_save_csp_preset` |
126
+ | `ac_list_presets`, `ac_read_video_preset` | `ac_set_pp_filter`, `ac_set_python_app` |
127
+ | `ac_list_pp_filters`, `ac_list_apps` | `ac_write_text`, `ac_replace_text` - Lua/Python/config text |
128
+ | `ac_read_text`, `ac_list_backups` | `ac_install_mod` (dry run by default), `ac_undo` |
129
+
130
+ Notes: Content Manager does not watch these files, so an open CM may show old values until it reloads.
131
+ With AC running, most changes apply on the next session.
132
+
133
+ ### pimax-mcp
134
+
135
+ | Tool | Source |
136
+ |---|---|
137
+ | `pimax_status`, `pimax_doctor` | Pimax CLI |
138
+ | `pimax_settings` | Pimax CLI: quality, brightness, local dimming, overlay scale, eye tracking |
139
+ | `pimax_runtime_state` | PiService log: per-app render scale, FOV, foveated/quad views, smart smoothing, upscaling actually read by the runtime |
140
+ | `pimax_runtime_stats` | Compositor log: app vs compositor FPS, % missed frames, stale/discarded, GPU%/CPU% per session (`exe="acs"` for AC) |
141
+ | `pimax_set` | Pimax CLI, closed list of settings, `confirm=True` required |
142
+
143
+ Refresh rate, FOV, foveated rendering and Smart Smoothing are not exposed by the Pimax CLI; change them in Pimax Play.
144
+ The PimaxClient `config.json` (login token) is never read.
145
+
146
+ ## Example session
147
+
148
+ > "AC in VR feels choppy on the straight after turn 1. Check what the Pimax runtime is doing and suggest one change."
149
+
150
+ The assistant reads `pimax_runtime_stats(exe="acs")` (missed frames, GPU%), `pimax_runtime_state` and
151
+ `ac_read("ext/vr_tweaks.ini")`, proposes a single change, applies it with `ac_set` after you agree, and after
152
+ your next stint compares the stats again. If it got worse: `ac_undo`.
153
+
154
+ ## Development
155
+
156
+ ```powershell
157
+ uv sync
158
+ uv run pytest
159
+ uv run ruff check .
160
+ ```
161
+
162
+ Tests run against temporary folders and fake processes; they never touch a real game or headset.
163
+
164
+ ## License
165
+
166
+ MIT. Not affiliated with Kunos Simulazioni, Ilja Jusupov (CSP / Content Manager) or Pimax.
@@ -0,0 +1,17 @@
1
+ simrig_mcp/__init__.py,sha256=rnObPjuBcEStqSO0S6gsdS_ot8ITOQjVj_-P1LUUYpg,22
2
+ simrig_mcp/__main__.py,sha256=wWQG5e3aG2nlMOXg2T4gET5DZbcehXgOJlnZRSgYvqU,537
3
+ simrig_mcp/compat.py,sha256=Xe33b95bRZsMDHGIyLUjOhSPU6Iq6enH7Y4c4suSSa4,274
4
+ simrig_mcp/acconfig/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ simrig_mcp/acconfig/ini.py,sha256=oVoV1KKDAIPhC7KSp-31g652H-24hJUi8BwFZFh0ISA,3429
6
+ simrig_mcp/acconfig/paths.py,sha256=2DrvtmlJ3lrW8cyldeYghXTRxGCLGRHgPfLX6PESnK8,4165
7
+ simrig_mcp/acconfig/server.py,sha256=n6vp28QaNjOhIjdm7aQxoufFibc5vbaiwk-W2EjP_1A,1674
8
+ simrig_mcp/acconfig/store.py,sha256=FfzlK_yFszs7H1lxyQjLfeFjWczPoGTq8zhab5wPUAk,23190
9
+ simrig_mcp/pimax/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ simrig_mcp/pimax/cli.py,sha256=ql49QW6x0hdgHWudj-mjlRfMvKRDcHLui4zO6Wg2Jew,3017
11
+ simrig_mcp/pimax/logs.py,sha256=GiFuF4x3lLFPQRvrLESyJYynxxHKQ2vd7AvYJWs72sc,6841
12
+ simrig_mcp/pimax/server.py,sha256=cRb84wJAXp2RMSFPuT9lGe4_MC4_q1-uvP1ZL7oJpE8,4526
13
+ simrig_mcp-0.1.1.dist-info/METADATA,sha256=OCMR3lSyV1AZwGAFqF9-NavzjU65pcZ-_594aJLcXvc,8401
14
+ simrig_mcp-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
15
+ simrig_mcp-0.1.1.dist-info/entry_points.txt,sha256=ENsFGPXlJJg-bS3wk4VKkP41OEkh_LkxChrGybVOWQ4,145
16
+ simrig_mcp-0.1.1.dist-info/licenses/LICENSE,sha256=acogYfOHBoDhsR36sBEc1R_oU_gexNeMnQzgPmect6I,1067
17
+ simrig_mcp-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ ac-config-mcp = simrig_mcp.acconfig.server:main
3
+ pimax-mcp = simrig_mcp.pimax.server:main
4
+ simrig-mcp = simrig_mcp.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Luan Gomes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.