plcsharp/Tests/mcp_smoke.py

112 lines
5.5 KiB
Python

"""Run the stdio acceptance check against a copy of the portable QA project."""
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
class Client:
def __init__(self, exe, project, *options):
self.process = subprocess.Popen(
[exe, "--project", project, *options], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, text=True, encoding="utf-8")
self.sequence = 0
self.request("initialize", {"protocolVersion": "2025-11-25", "capabilities": {},
"clientInfo": {"name": "PLCSharp-QA", "version": "1"}})
self.send({"method": "notifications/initialized"})
def send(self, message):
message["jsonrpc"] = "2.0"
self.process.stdin.write(json.dumps(message) + "\n")
self.process.stdin.flush()
def request(self, method, params):
self.sequence += 1
self.send({"id": self.sequence, "method": method, "params": params})
while line := self.process.stdout.readline():
result = json.loads(line)
if result.get("id") == self.sequence:
assert "error" not in result, result
return result["result"]
raise RuntimeError("MCP server closed stdout")
def call(self, tool, **args):
result = self.request("tools/call", {"name": tool, "arguments": args})
assert not result.get("isError"), result
return json.loads(result["content"][0]["text"])
def close(self):
self.process.stdin.close()
self.process.wait(timeout=15)
assert self.process.returncode == 0
def verify(exe, source):
with tempfile.TemporaryDirectory() as folder:
project = Path(folder) / "工程副本"
shutil.copytree(source, project)
client = Client(exe, project)
try:
names = {tool["name"] for tool in client.request("tools/list", {})["tools"]}
assert {"get_project_summary", "list_objects", "get_object"} <= names
summary = client.call("get_project_summary")
recipe = summary["DefaultRecipeId"]
workflow, = client.call("list_objects", kind="Workflows", recipeId=recipe)["items"]
variable, = client.call("list_objects", kind="Variables", recipeId=recipe)["items"]
assert variable["name"] == "计数"
source_object = client.call("get_object", kind="Workflows", id=workflow["id"])
assert source_object["Code"] == "// portability fixture"
assert client.call("find_references", kind="Variables", id=variable["id"])["hits"] == []
script = next(project.rglob("*.cs"))
script.write_text('''using PLCSharp.Models;
class Sample {
void Inspect(GlobalModel model, string runtimeName) {
// model.GetVariable("计数");
model.GetVariable("计数");
model.GetVariable(runtimeName);
model.GetTask("搬运");
}
}''', encoding="utf-8")
hits = client.call("find_references", kind="Variables", id=variable["id"])["hits"]
assert [(h["line"], h["confidence"]) for h in hits] == [(5, "confirmed"), (6, "dynamic")], hits
flow_hit, = client.call("find_references", kind="Workflows", id=workflow["id"])["hits"]
assert flow_hit["line"] == 7 and flow_hit["confidence"] == "confirmed", flow_hit
script.write_text(source_object["Code"], encoding="utf-8")
args = {"kind": "Variables", "id": variable["id"], "comment": "已核对计数变量"}
draft = client.call("preview_changes", **args)
denied = client.request("tools/call", {"name": "apply_changes", "arguments": {"draftId": draft["DraftId"]}})
assert denied["isError"]
client.close()
client = Client(exe, project, "--allow-write")
snapshot = {p: p.read_bytes() for p in project.rglob("*") if p.is_file()}
draft = client.call("preview_changes", **args)
assert draft["Before"] == "A" and draft["After"] == args["comment"]
assert all(p.read_bytes() == old for p, old in snapshot.items())
key = {"draftId": draft["DraftId"]}
assert client.call("apply_changes", **key)["Status"] == "saved"
assert client.call("apply_changes", **key)["Status"] == "saved"
assert client.call("get_change_status", **key)["Status"] == "saved"
changed = [p.relative_to(project).as_posix() for p, old in snapshot.items() if p.read_bytes() != old]
assert changed == ["configuration/variables.json"], changed
client.close()
client = Client(exe, project, "--allow-write")
assert client.call("get_object", kind="Variables", id=variable["id"])["Comment"] == args["comment"]
pending = client.call("preview_changes", **(args | {"comment": "stale draft"}))
file = project / changed[0]
external = file.read_bytes() + b"\n"
file.write_bytes(external)
conflict = client.request("tools/call", {"name": "apply_changes", "arguments": {"draftId": pending["DraftId"]}})
assert conflict["isError"] and file.read_bytes() == external
assert client.call("get_change_status", draftId=pending["DraftId"])["Status"] == "conflict"
print(f'{summary["Id"]}: {len(summary["recipes"])} recipes, {workflow["name"]}, {variable["name"]}; '
f'confirmed variable line 5 / workflow line 7; saved {changed[0]} and reopened')
finally:
client.close()
if __name__ == "__main__":
verify(*sys.argv[1:])