"""MCP stdio server for the show tools. Cursor starts this with `python3 -m showfile.mcp`. The process speaks MCP over Content-Length framing and does not require the third-party mcp package. """ from __future__ import annotations import json import sys from typing import Any from .tools import list_fixtures, run_script, sample_animation, show_schema, validate_show, write_show _TOOLS = [ { "name": "list_fixtures", "description": ( "List fixture definitions in fixtures/. Each mode includes channel index, name, " "preset, and which channels are pan and tilt. Use these channel numbers in a show spec." ), "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, }, { "name": "show_schema", "description": "Return the JSON Schema for a QLC+ show spec. Keys are strings; ids are assigned on write.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, }, { "name": "validate_show", "description": ( "Validate a show spec. Returns {ok, errors: [{path, message}]} and writes nothing. " "Error paths look like functions.eight.fixtures." ), "inputSchema": { "type": "object", "properties": {"spec": {"type": "object", "description": "Show spec."}}, "required": ["spec"], }, }, { "name": "write_show", "description": ( "Write a show spec to a .qxw inside the project. Returns {ok, path, fixtures, functions, widgets} " "with the QLC+ ids that were assigned. Refuses paths outside the project." ), "inputSchema": { "type": "object", "properties": { "spec": {"type": "object"}, "path": {"type": "string", "description": "Project-relative .qxw path, for example shows/look.qxw."}, }, "required": ["spec", "path"], }, }, { "name": "sample_animation", "description": ( "Sample pan/tilt for one efx or path block so the shape can be checked before writing a show. " "Returns tracks of points. Relative EFX points are the fixture's real pan/tilt, including its home." ), "inputSchema": { "type": "object", "properties": { "block": {"type": "object", "description": "An efx or path function object."}, "steps": {"type": "integer", "minimum": 1, "maximum": 128, "description": "EFX samples along one loop. Default 32."}, }, "required": ["block"], }, }, { "name": "run_animation", "description": ( "Run an animation Python script (a file that defines build() -> Show) or a JSON show spec. " "Without ip, returns DMX samples for testing and sends nothing. " "With ip, streams Art-Net for `seconds` (or until the client cancels — prefer a short seconds value)." ), "inputSchema": { "type": "object", "properties": { "path": {"type": "string", "description": "Project-relative .py script or .json spec."}, "seconds": {"type": "number"}, "ip": {"type": "string", "description": "Art-Net destination. Omit for a dry run."}, "universe": {"type": "integer"}, "hz": {"type": "number"}, }, "required": ["path"], }, }, ] def serve() -> None: framed = False while True: message, framed = _read(framed) if message is None: return response = _handle(message) if response is not None: _write(response, framed) def _handle(message: dict[str, Any]) -> dict[str, Any] | None: method = message.get("method") mid = message.get("id") if method == "notifications/initialized" or method and method.startswith("notifications/"): return None if method == "initialize": return _result( mid, { "protocolVersion": "2024-11-05", "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": "qlcplus-show", "version": "1.0.0"}, }, ) if method == "ping": return _result(mid, {}) if method == "tools/list": return _result(mid, {"tools": _TOOLS}) if method == "tools/call": params = message.get("params") or {} try: payload = _call(str(params.get("name")), params.get("arguments") or {}) return _result(mid, {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}], "isError": False}) except Exception as exc: # noqa: BLE001 — reported to the MCP client return _result(mid, {"content": [{"type": "text", "text": str(exc)}], "isError": True}) if mid is not None: return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"unknown method {method}"}} return None def _call(name: str, arguments: dict[str, Any]) -> Any: if name == "list_fixtures": return list_fixtures() if name == "show_schema": return show_schema() if name == "validate_show": return validate_show(arguments["spec"]) if name == "write_show": return write_show(arguments["spec"], arguments["path"]) if name == "sample_animation": return sample_animation(arguments["block"], int(arguments.get("steps", 32))) if name == "run_animation": return run_script( arguments["path"], seconds=arguments.get("seconds"), ip=arguments.get("ip"), universe=int(arguments.get("universe", 0)), hz=float(arguments.get("hz", 40)), ) raise KeyError(f"unknown tool {name}") def _result(mid: Any, result: Any) -> dict[str, Any]: return {"jsonrpc": "2.0", "id": mid, "result": result} def _read(framed: bool) -> tuple[dict[str, Any] | None, bool]: line = sys.stdin.buffer.readline() if not line: return None, framed if line.lower().startswith(b"content-length:"): length = int(line.split(b":", 1)[1].strip()) while True: header = sys.stdin.buffer.readline() if header in (b"\r\n", b"\n", b""): break body = sys.stdin.buffer.read(length) return json.loads(body), True if not line.strip(): return _read(framed) return json.loads(line), framed def _write(message: dict[str, Any], framed: bool) -> None: data = json.dumps(message).encode() if framed: sys.stdout.buffer.write(f"Content-Length: {len(data)}\r\n\r\n".encode() + data) else: sys.stdout.buffer.write(data + b"\n") sys.stdout.buffer.flush() if __name__ == "__main__": serve()