plcsharp/Tests/mcp_smoke.py

69 lines
2.7 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"
print(f'{summary["Id"]}: {len(summary["recipes"])} recipes, {workflow["name"]}, {variable["name"]}')
finally:
client.close()
if __name__ == "__main__":
verify(*sys.argv[1:])