Repository navigation
Expand file tree
/
Copy pathtest-new-tools.py
More file actions
264 lines (219 loc) · 10.7 KB
/
Copy pathtest-new-tools.py
File metadata and controls
264 lines (219 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
"""
Real-game validation of the three tools added in 0.4.0:
• archive_stats — histogram by extension of a .archive
• validate_redmod — info.json schema of a REDmod
• inspect_app — structural summary of a .app
Drives the MCP server over stdio (JSON-RPC 2.0), like test-mcp-server.py /
validate-windows.py. Each tool is exercised with real game data
(base archives, extracted .app) plus, for validate_redmod, a valid case AND a
deliberately broken case.
Usage:
python test-new-tools.py "C:\\path\\to\\Cyberpunk 2077"
or set WKMCP_GAME=... then python test-new-tools.py
The server DLL path is taken from WKMCP_DLL, otherwise the Release
build (generated by build-mcpb.ps1), otherwise the Debug build.
Exit code: 0 if all cases PASS, 1 otherwise.
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
HERE = os.path.dirname(os.path.abspath(__file__))
def _first_existing(*paths):
for p in paths:
if p and os.path.exists(p):
return p
return paths[-1]
SERVER_DLL = os.environ.get("WKMCP_DLL") or _first_existing(
os.path.join(HERE, "src", "WkMcp", "bin", "Release", "net10.0", "WkMcp.dll"),
os.path.join(HERE, "src", "WkMcp", "bin", "Debug", "net10.0", "WkMcp.dll"))
DOTNET = os.environ.get("WKMCP_DOTNET") or shutil.which("dotnet") or "dotnet"
GAME = (sys.argv[1] if len(sys.argv) > 1
else os.environ.get("WKMCP_GAME", r"C:\Cyberpunk\Cyberpunk 2077")).rstrip("\\/")
CONTENT = os.path.join(GAME, "archive", "pc", "content")
MODS_DIR = os.path.join(GAME, "mods") # installed REDmods (post-1.6 format)
# Base archive rich in file types (meshes + textures) → good histogram.
ARCH_ENGINE = os.path.join(CONTENT, "basegame_1_engine.archive")
WORK = os.path.join(tempfile.gettempdir(), "wknewtools")
# ── Minimal MCP client ───────────────────────────────────────────────────────
class Server:
def __init__(self):
self.proc = subprocess.Popen(
[DOTNET, SERVER_DLL],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding="utf-8", errors="replace", bufsize=1)
self._id = 0
def _send(self, obj):
self.proc.stdin.write(json.dumps(obj) + "\n")
self.proc.stdin.flush()
def _recv(self):
while True:
line = self.proc.stdout.readline()
if not line:
raise IOError("the MCP server closed stdout")
line = line.strip()
if line:
return json.loads(line)
def request(self, method, params):
self._id += 1
rid = self._id
self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
while True:
resp = self._recv()
if resp.get("id") == rid:
return resp
def initialize(self):
r = self.request("initialize", {
"protocolVersion": "2024-11-05", "capabilities": {},
"clientInfo": {"name": "wk-newtools", "version": "1.0"}})
self._send({"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}})
return r
def call(self, name, args):
r = self.request("tools/call", {"name": name, "arguments": args})
if "error" in r:
return {"ok": False, "status": "error", "errors": [str(r["error"])],
"summary": f"JSON-RPC: {r['error']}"}
res = r.get("result", {})
txt = "\n".join(c.get("text", "") for c in res.get("content", [])
if c.get("type") == "text")
try:
return json.loads(txt)
except json.JSONDecodeError:
return {"ok": False, "status": "error", "errors": [txt[:300]],
"summary": txt[:300] or "(empty response)"}
def close(self):
try:
self.proc.stdin.close()
self.proc.wait(timeout=15)
except Exception:
self.proc.kill()
# ── Results ──────────────────────────────────────────────────────────────────
results = []
MARK = {"PASS": "✓", "WARN": "!", "FAIL": "✗", "SKIP": "–"}
def record(target, status, detail):
results.append((target, status, detail))
print(f"[{MARK.get(status, '?')}] {status:5} {target} — {detail}")
def find_extracted(root, suffix):
for dirpath, _, files in os.walk(root):
for f in files:
if f.lower().endswith(suffix):
return os.path.join(dirpath, f)
return None
# ── Tests ────────────────────────────────────────────────────────────────────
def test_archive_stats(srv):
if not os.path.isfile(ARCH_ENGINE):
record("archive_stats", "SKIP", f"archive missing: {ARCH_ENGINE}")
return
res = srv.call("archive_stats", {"archivePath": ARCH_ENGINE})
ok = (res.get("ok") and res.get("fileCount", 0) > 0
and res.get("categoryCount", 0) > 1 and res.get("byExtension"))
top = ", ".join(f"{e['extension']}={e['count']}" for e in res.get("byExtension", [])[:5])
record("archive_stats", "PASS" if ok else "FAIL",
f"{res.get('fileCount')} files, {res.get('categoryCount')} types — top: {top}")
# 2nd call: must come from the LRU cache.
res2 = srv.call("archive_stats", {"archivePath": ARCH_ENGINE})
record("archive_stats (warm cache)", "PASS" if res2.get("fromCache") else "WARN",
f"fromCache={res2.get('fromCache')}")
def test_validate_redmod(srv):
# a) valid case: REDmod project scaffolded by the tool.
parent = os.path.join(WORK, "redmod_valid")
shutil.rmtree(parent, ignore_errors=True)
os.makedirs(parent, exist_ok=True)
res = srv.call("create_redmod_project",
{"parentFolder": parent, "modName": "ValidationRedmod", "version": "1.0.0"})
root = res.get("redmodRoot") or os.path.join(parent, "ValidationRedmod")
if not res.get("ok") or not os.path.isfile(os.path.join(root, "info.json")):
record("validate_redmod (valid)", "FAIL", f"scaffold failed: {res.get('summary')}")
else:
v = srv.call("validate_redmod", {"modPath": root})
ok = v.get("ok") and v.get("status") == "success" and not v.get("errors")
record("validate_redmod (valid)", "PASS" if ok else "FAIL",
f"status={v.get('status')}, {len(v.get('errors', []))} error(s)")
# b) broken case: info.json without version field.
broken = os.path.join(WORK, "redmod_broken")
shutil.rmtree(broken, ignore_errors=True)
os.makedirs(broken, exist_ok=True)
with open(os.path.join(broken, "info.json"), "w", encoding="utf-8") as f:
json.dump({"name": "Broken", "description": "no version"}, f)
v = srv.call("validate_redmod", {"modPath": broken})
ok = (not v.get("ok")) and any("version" in e for e in v.get("errors", []))
record("validate_redmod (broken)", "PASS" if ok else "FAIL",
f"detects the version error: {ok} ({len(v.get('errors', []))} error(s))")
# c) bonus: first installed REDmod, if there is one.
installed = ([d for d in os.listdir(MODS_DIR)
if os.path.isfile(os.path.join(MODS_DIR, d, "info.json"))]
if os.path.isdir(MODS_DIR) else [])
if installed:
target = os.path.join(MODS_DIR, installed[0])
v = srv.call("validate_redmod", {"modPath": target})
record(f"validate_redmod ({installed[0]})",
"PASS" if v.get("status") in ("success", "partial") else "FAIL",
f"status={v.get('status')}, {len(v.get('errors', []))} error(s)")
else:
record("validate_redmod (installed REDmod)", "SKIP", "no REDmod in mods/")
def test_inspect_app(srv):
if not os.path.isdir(CONTENT):
record("inspect_app", "SKIP", f"content folder missing: {CONTENT}")
return
# 1) locate a .app in the base archives.
found = srv.call("find_in_archives", {"archivesFolder": CONTENT,
"pattern": "*.app", "maxMatches": 5})
matches = found.get("matches", [])
if not matches:
record("inspect_app", "SKIP", "no .app found in the base content")
return
# matches[i] = "internal\\path.app (archive_name.archive)"
internal, _, arch_part = matches[0].partition(" (")
internal = internal.strip()
archive = os.path.join(CONTENT, arch_part.rstrip(") ").strip())
basename = internal.replace("/", "\\").split("\\")[-1]
# 2) extract that .app.
extract_dir = os.path.join(WORK, "appextract")
shutil.rmtree(extract_dir, ignore_errors=True)
os.makedirs(extract_dir, exist_ok=True)
srv.call("extract_files", {"archivePath": archive, "outputPath": extract_dir,
"pattern": "*" + basename})
app_file = find_extracted(extract_dir, ".app")
if not app_file:
record("inspect_app", "FAIL", f"extraction of {basename} failed from {arch_part}")
return
# 3) inspect.
res = srv.call("inspect_app", {"appFile": app_file})
ok = res.get("ok") and res.get("appearanceCount", 0) >= 1
record("inspect_app", "PASS" if ok else "FAIL",
f"{basename} → {res.get('appearanceCount')} appearance(s), "
f"{res.get('meshComponentCount')} mesh component(s), "
f"{res.get('distinctMeshCount')} distinct mesh(es)")
def main():
if not os.path.exists(SERVER_DLL):
sys.exit(f"Server DLL not found: {SERVER_DLL}\n"
"Build first: dotnet build src\\WkMcp -c Release")
if not os.path.isdir(GAME):
sys.exit(f"Cyberpunk 2077 installation not found: {GAME}\n"
"Pass the path as an argument or via WKMCP_GAME.")
shutil.rmtree(WORK, ignore_errors=True)
os.makedirs(WORK, exist_ok=True)
print(f"=== Testing the 0.4.0 tools — game: {GAME} ===")
print(f" server: {SERVER_DLL}\n")
srv = Server()
try:
srv.initialize()
test_archive_stats(srv)
test_validate_redmod(srv)
test_inspect_app(srv)
finally:
srv.close()
passed = sum(1 for _, s, _ in results if s == "PASS")
failed = sum(1 for _, s, _ in results if s == "FAIL")
skipped = sum(1 for _, s, _ in results if s == "SKIP")
warned = sum(1 for _, s, _ in results if s == "WARN")
print(f"\n=== Summary: {passed} PASS · {failed} FAIL · {warned} WARN · {skipped} SKIP ===")
sys.exit(1 if failed else 0)
if __name__ == "__main__":
main()