@rasteaks/grandma2-toolkit 0.0.0-stage → 0.1.1

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.
package/README.md CHANGED
@@ -1,3 +1,180 @@
1
- # Temporary Holding Version
1
+ # grandma2-toolkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 通过 Telnet 读取 grandMA2 onPC 的 Show、编排 Cue 和执行器,并在 MA3D 中调整灯位和相机。**MCP** 让 Agent 调用控台工具,**ma2-control Skill** 告诉 Agent 如何选灯、组织命令并核对回读结果,**CLI** 适合在终端或脚本中取得相同的 JSON 结果。
4
+
5
+ [快速安装](#快速开始) · [第一次只读查询](#第一次只读查询) · [MCP 工具](#mcp) · [CLI](#cli) · [配置](#配置) · [npm 包](https://www.npmjs.com/package/@rasteaks/grandma2-toolkit)
6
+
7
+ ## 快速开始
8
+
9
+ **想让 Agent 帮你安装?** 在目标项目目录打开 Codex 或 Claude Code,展开对应提示词,复制整段发送。两种方式都需要 Node.js(含 npx)和 [uv](https://docs.astral.sh/uv/)。安装和发现工具时无需控台密码。
10
+
11
+ <details>
12
+ <summary><strong>Codex</strong> · 复制安装提示词</summary>
13
+
14
+ ```text
15
+ 请在当前项目中安装 ma2-control Skill,并为 Codex 注册 grandma2-toolkit MCP。
16
+ 先检查 node、npx、uv 和 codex 是否可用,缺少哪一项就指出来。已有相同配置时复用。
17
+
18
+ 1. 在项目根目录执行:
19
+ npx --yes skills add RaSteaks/grandma2-toolkit --skill ma2-control --agent codex -y
20
+ 2. 注册 MCP 到 Codex 用户配置:
21
+ codex mcp add grandma2-toolkit -- npx --yes @rasteaks/grandma2-toolkit
22
+ 3. 检查 .agents/skills/ma2-control/SKILL.md,再运行 codex mcp get grandma2-toolkit。
23
+ 确认启动命令和参数正确。若当前会话已加载服务,列出它提供的工具。
24
+ 若需打开新会话才能发现工具,请明确说明。
25
+
26
+ 本次只安装和验证。保持默认只读,跳过控台登录和 Show 操作。
27
+ ```
28
+
29
+ </details>
30
+
31
+ <details>
32
+ <summary><strong>Claude Code</strong> · 复制安装提示词</summary>
33
+
34
+ ```text
35
+ 请在当前项目中安装 ma2-control Skill,并为 Claude Code 注册 grandma2-toolkit MCP。
36
+ 先检查 node、npx、uv 和 claude 是否可用,缺少哪一项就指出来。已有相同配置时复用。
37
+
38
+ 1. 在项目根目录执行:
39
+ npx --yes skills add RaSteaks/grandma2-toolkit --skill ma2-control --agent claude-code -y
40
+ 2. 以 local 作用域注册 stdio 服务,仅供我在当前项目使用:
41
+ claude mcp add --transport stdio --scope local grandma2-toolkit -- npx --yes @rasteaks/grandma2-toolkit
42
+ 3. 检查 .claude/skills/ma2-control/SKILL.md,再运行 claude mcp get grandma2-toolkit。
43
+ 核对服务状态。若当前会话已加载服务,列出它提供的工具。
44
+ 若需打开新会话才能发现工具,请明确说明。
45
+
46
+ 本次只安装和验证。保持默认只读,跳过控台登录和 Show 操作。
47
+ ```
48
+
49
+ Claude Code 的 `local` 配置只对当前用户的当前项目生效。[Claude Code MCP 作用域说明](https://code.claude.com/docs/en/mcp#mcp-installation-scopes)
50
+
51
+ </details>
52
+
53
+ **只需启动 MCP?** 在任意目录运行以下命令。首次确认安装后,uv 会按包内的 `uv.lock` 准备 Python 环境,服务随后通过标准输入输出(stdio)等待客户端请求。
54
+
55
+ ```sh
56
+ npx @rasteaks/grandma2-toolkit
57
+ ```
58
+
59
+ <details>
60
+ <summary>其他 MCP 客户端 · JSON 配置与源码启动</summary>
61
+
62
+ 支持 `mcpServers` 的客户端可直接使用以下配置。确保客户端的 `PATH` 能找到 npx 和 uv。
63
+
64
+ ```json
65
+ {
66
+ "mcpServers": {
67
+ "grandma2-toolkit": {
68
+ "command": "npx",
69
+ "args": ["--yes", "@rasteaks/grandma2-toolkit"]
70
+ }
71
+ }
72
+ }
73
+ ```
74
+
75
+ 从源码启动时,在仓库根目录执行 `uv run --locked grandma2-mcp`。使用 uv 配置模板时,将 `<REPO_DIR>` 换成仓库绝对路径,`<OUTPUT_DIR>` 换成保存备份和截图的绝对路径。省略 `MA2_OUTPUT_DIR` 即使用默认目录。[npx 配置](examples/mcp.npx.json) · [uv 配置](examples/mcp.json)
76
+
77
+ </details>
78
+
79
+ ## 第一次只读查询
80
+
81
+ 1. **连接控台。** 在 onPC 或 MA3D 启用 Telnet,通过 MCP 服务进程的环境变量提供 `MA2_PASSWORD`。控台位于另一台机器时,设置 `MA2_HOST` 为其地址。Telnet 使用明文传输,请在受信任的控制网络内使用。
82
+ 2. **确认 Show。** 调用 `ma2_connections`。当 `endpoints.onpc.connected` 为 `true` 时,从 `endpoints.onpc.show` 读取当前 Show 名称。工具会根据运行时路径识别 onPC 与 MA3D。要确认共享会话,还需检查两端的网络状态。
83
+ 3. **查看一个对象。** 例如,调用 `ma2_list` 查询第二屏的视图按钮。只传对象表达式,工具会补上 `List`,并在 `reply` 中返回控台原文。
84
+
85
+ ```json
86
+ {"target": "onpc", "object": "ViewButton 2.1 Thru 2.10 /screen=2"}
87
+ ```
88
+
89
+ ### Skill
90
+
91
+ 安装 Skill 后,可以直接在对话中描述要核对的灯光对象。例如:
92
+
93
+ > 使用 ma2-control,只读检查当前 Show 的第二页执行器。列出每根推杆绑定的 Sequence,以及该序列前五条 Cue 的触发方式。
94
+
95
+ Skill 优先使用已配置的 MCP。走本地 CLI 时,可将 `MA2_TOOLKIT_ROOT` 指向工具包源码根目录。[Skill 入口](.agents/skills/ma2-control/SKILL.md) · [配接、编组与推杆速查](.agents/skills/ma2-control/references/telnet-workflows.md) · [场景与播放命令](.agents/skills/ma2-control/references/commands.md)
96
+
97
+ ## MCP
98
+
99
+ | 工具 | 用途 | 可核对的结果 |
100
+ | --- | --- | --- |
101
+ | `ma2_connections` | 同时探测 onPC 与 MA3D | 各端的连接状态、运行时和 Show |
102
+ | `ma2_status` | 检查指定端点 | 当前 Show 和网络状态 |
103
+ | `ma2_list` | 读取灯型、Cue 范围、MAtricks 或 ViewButton | 原生 `List` 回显 |
104
+ | `ma2_execute` | 在指定 Show 中顺序执行命令 | 每条命令的回显和审计记录 |
105
+ | `ma2_export` | 在本机导出原生 XML | 原生路径 `native_file`、留存副本 `file` 和内容指纹 `fingerprint` |
106
+ | `ma2_backup` | 在本机保存并备份 onPC Show | 新备份文件和 SHA256 |
107
+ | `ma3d_transform` | 调整灯具安装位置、朝向或相机 | 修改前后的对象回读 |
108
+ | `ma3d_capture` | 截取 Windows 本机可见的 MA3D 窗口 | PNG 截图,供核对机位和灯光画面 |
109
+
110
+ **写入与回读。** 写入前设置 `MA2_ALLOW_WRITE=1`,并传入与当前 Show 完全匹配的 `expected_show`。批次遇错即停,此前的命令可能已经生效。超时后先回读对象。依赖 `EditSetup` 当前目录的命令应放在同一批次,因为每次工具调用都会新建连接。
111
+
112
+ **安装角与灯光画面。** `ma3d_transform` 操作机身或相机。Cue 中的灯头方向由 Pan/Tilt 控制。共享会话中的几何变更可能同步至 onPC。截图需要可见且未最小化的 MA3D 窗口,请结合截图中的机位、播放状态和实际光束判断效果。
113
+
114
+ ## CLI
115
+
116
+ 在仓库根目录安装依赖,并在当前 PowerShell 会话中输入 Telnet 凭据。CLI 默认操作 onPC,返回 JSON。
117
+
118
+ ```powershell
119
+ uv sync --locked
120
+ $credential = Get-Credential -Message 'MA2 Telnet 登录'
121
+ $env:MA2_USER = $credential.UserName
122
+ $env:MA2_PASSWORD = $credential.GetNetworkCredential().Password
123
+ uv run grandma2 connections
124
+ ```
125
+
126
+ ```powershell
127
+ uv run grandma2 list 'LiveSetup.FixtureTypes'
128
+ uv run grandma2 list 'MAtricks 1 Thru 10'
129
+ uv run grandma2 --target ma3d list 'Camera 50'
130
+ ```
131
+
132
+ <details>
133
+ <summary>导出效果、备份 Show 和调整相机</summary>
134
+
135
+ 将 Show 名称、相机编号和坐标换成现场已核对的值。`--target` 放在子命令前。位置单位为米,旋转为度,相机 FOV 为弧度。
136
+
137
+ ```powershell
138
+ uv run grandma2 export 'Effect 1 Thru 10'
139
+ uv run grandma2 capture --window-title 'MA 3D'
140
+
141
+ $env:MA2_ALLOW_WRITE = '1'
142
+ uv run grandma2 backup --expect-show '<SHOW_NAME>'
143
+ uv run grandma2 --target ma3d transform 'Camera 50' --expect-show '<SHOW_NAME>' --values '{"z":12.8,"rx":-2}'
144
+ uv run grandma2 execute --expect-show '<SHOW_NAME>' --commands-file examples/commands.readback.json
145
+ ```
146
+
147
+ </details>
148
+
149
+ ## 配置
150
+
151
+ 环境变量需传给实际运行 MCP 或 CLI 的进程。桌面客户端可能使用独立于终端的环境。
152
+
153
+ | 变量 | 默认值 | 用途 |
154
+ | --- | --- | --- |
155
+ | `MA2_HOST` | `127.0.0.1` | 控台或可视化主机地址 |
156
+ | `MA2_PORTS` | `30000,30001` | 探测的 Telnet 端口 |
157
+ | `MA2_USER` | `administrator` | Telnet 登录用户 |
158
+ | `MA2_PASSWORD` | 无 | 连接设备时必填 |
159
+ | `MA2_ALLOW_WRITE` | `0` | 设为 `1` 后,允许对匹配的 Show 执行写入命令,包括 Lua |
160
+ | `MA2_TIMEOUT` | `15` | 响应超时秒数,可设为 1–120 |
161
+ | `MA2_OUTPUT_DIR` | 依启动方式而定 | 审计日志、备份、XML 和截图的保存目录 |
162
+
163
+ npx 默认保存到用户主目录的 `.grandma2-toolkit/.data`,源码默认保存到仓库的 `.data`。使用 wheel 安装时建议显式设置输出目录。
164
+
165
+ ## 开发
166
+
167
+ ```sh
168
+ uv sync --locked --group dev
169
+ uv run ruff check .
170
+ uv run pytest
171
+ uv run pytest tests/npx_smoke.py
172
+ uv build
173
+ ```
174
+
175
+
176
+
177
+ ---
178
+
179
+ 本项目由个人独立开发,是面向 MA Lighting 产品的非官方工具。
180
+ 许可证为 [AGPL-3.0](LICENSE)。
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ const { spawn } = require("node:child_process")
3
+ const { homedir } = require("node:os")
4
+ const path = require("node:path")
5
+
6
+ // Resolve the Python project from the installed package, even when the MCP host
7
+ // starts in another directory. Keep evidence outside npx's disposable cache.
8
+ const project = path.resolve(__dirname, "..")
9
+ const child = spawn("uv", [
10
+ "run", "--locked", "--no-dev", "--project", project,
11
+ "python", "-m", "grandma2_toolkit.server",
12
+ ], {
13
+ stdio: "inherit",
14
+ env: {
15
+ ...process.env,
16
+ MA2_OUTPUT_DIR: process.env.MA2_OUTPUT_DIR || path.join(homedir(), ".grandma2-toolkit", ".data"),
17
+ },
18
+ })
19
+
20
+ for (const signal of ["SIGINT", "SIGTERM"]) {
21
+ process.on(signal, () => child.kill(signal))
22
+ }
23
+ child.on("error", (error) => {
24
+ console.error(error.code === "ENOENT" ? "grandma2-mcp: install uv and add it to PATH." : error.message)
25
+ process.exitCode = 1
26
+ })
27
+ child.on("exit", (code, signal) => {
28
+ process.exitCode = code ?? (signal === "SIGINT" ? 130 : 143)
29
+ })
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@rasteaks/grandma2-toolkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Launch the grandMA2 onPC and MA3D stdio MCP server with npx",
5
+ "license": "AGPL-3.0-only",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/RaSteaks/grandma2-toolkit.git"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "registry": "https://registry.npmjs.org/"
13
+ },
14
+ "bin": {
15
+ "grandma2-mcp": "bin/grandma2-mcp.cjs"
16
+ },
17
+ "files": [
18
+ "bin/grandma2-mcp.cjs",
19
+ "pyproject.toml",
20
+ "uv.lock",
21
+ "src/grandma2_toolkit/*.py"
22
+ ]
23
+ }
package/pyproject.toml ADDED
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "grandma2-toolkit"
7
+ version = "0.1.1"
8
+ description = "Telnet, CLI, MCP and agent skill for grandMA2 onPC"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "AGPL-3.0-only"
12
+ dependencies = ["mcp>=1.20,<2", "pillow>=11.2,<13; sys_platform == 'win32'"]
13
+
14
+ [project.scripts]
15
+ grandma2 = "grandma2_toolkit.cli:main"
16
+ grandma2-mcp = "grandma2_toolkit.server:main"
17
+
18
+ [dependency-groups]
19
+ dev = ["pytest>=8,<10", "ruff>=0.11,<1", "pyyaml>=6"]
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/grandma2_toolkit"]
23
+
24
+ [tool.pytest.ini_options]
25
+ testpaths = ["tests"]
26
+
27
+ [tool.ruff]
28
+ target-version = "py311"
29
+ line-length = 110
30
+
31
+ [tool.ruff.lint]
32
+ select = ["E4", "E7", "E9", "F"]
@@ -0,0 +1,3 @@
1
+ """Shared grandMA2 automation primitives for CLI and MCP clients."""
2
+
3
+ __version__ = "0.1.1"
@@ -0,0 +1,57 @@
1
+ """Optional Windows-only MA3D window capture, without UI input or desktop fallback."""
2
+
3
+ import ctypes
4
+ from ctypes import wintypes
5
+ from pathlib import Path
6
+ import sys
7
+
8
+
9
+ def capture_window(output: Path, title: str | None = None) -> dict:
10
+ if sys.platform != "win32":
11
+ raise RuntimeError("MA3D window capture requires Windows")
12
+ from PIL import ImageGrab, ImageStat
13
+
14
+ user32, kernel32 = ctypes.windll.user32, ctypes.windll.kernel32
15
+ kernel32.OpenProcess.restype = wintypes.HANDLE
16
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
17
+ kernel32.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
18
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
19
+ user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
20
+ user32.IsWindowVisible.argtypes = [wintypes.HWND]
21
+ user32.IsIconic.argtypes = [wintypes.HWND]
22
+ user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
23
+ candidates = []
24
+ callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
25
+
26
+ @callback_type
27
+ def visit(hwnd, _):
28
+ if not user32.IsWindowVisible(hwnd) or user32.IsIconic(hwnd):
29
+ return True
30
+ text = ctypes.create_unicode_buffer(512)
31
+ user32.GetWindowTextW(hwnd, text, len(text))
32
+ if not text.value or (title is not None and text.value != title):
33
+ return True
34
+ pid = wintypes.DWORD()
35
+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
36
+ handle = kernel32.OpenProcess(0x1000, False, pid.value)
37
+ if handle:
38
+ try:
39
+ path, size = ctypes.create_unicode_buffer(32768), wintypes.DWORD(32768)
40
+ if kernel32.QueryFullProcessImageNameW(handle, 0, path, ctypes.byref(size)):
41
+ if Path(path.value).name.lower() == "ma3d.exe":
42
+ candidates.append((hwnd, text.value, path.value))
43
+ finally:
44
+ kernel32.CloseHandle(handle)
45
+ return True
46
+
47
+ user32.EnumWindows.argtypes = [callback_type, wintypes.LPARAM]
48
+ user32.EnumWindows(visit, 0)
49
+ if len(candidates) != 1:
50
+ raise RuntimeError(f"Expected one visible, non-minimized MA3D window; found {[c[1] for c in candidates]}. Supply an exact window_title if needed.")
51
+ hwnd, name, exe = candidates[0]
52
+ # Pillow uses the selected HWND. Never fall back to a full-desktop capture.
53
+ shot = ImageGrab.grab(window=hwnd)
54
+ if shot.width < 100 or shot.height < 100 or max(ImageStat.Stat(shot.convert("RGB")).stddev) < 1:
55
+ raise RuntimeError("MA3D capture is empty/blank; restore the window and inspect through computer use")
56
+ shot.save(output)
57
+ return {"file": str(output), "window_title": name, "process": exe, "width": shot.width, "height": shot.height}
@@ -0,0 +1,67 @@
1
+ """JSON CLI mirroring MCP operations; never prints login credentials."""
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ from .service import Toolkit
9
+
10
+
11
+ def main():
12
+ if hasattr(sys.stdout, "reconfigure"):
13
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
14
+ parser = argparse.ArgumentParser(description=__doc__)
15
+ parser.add_argument("--target", choices=("onpc", "ma3d"), default="onpc")
16
+ sub = parser.add_subparsers(dest="action", required=True)
17
+ sub.add_parser("connections")
18
+ sub.add_parser("status")
19
+ for action in ("list", "export"):
20
+ sub.add_parser(action).add_argument("object")
21
+ backup = sub.add_parser("backup")
22
+ backup.add_argument("--expect-show", required=True)
23
+ execute = sub.add_parser("execute")
24
+ execute.add_argument("--expect-show", required=True)
25
+ execute.add_argument("--command", "-c", action="append", default=[])
26
+ execute.add_argument("--commands-file", type=Path)
27
+ transform = sub.add_parser("transform")
28
+ transform.add_argument("object")
29
+ transform.add_argument("--expect-show", required=True)
30
+ transform.add_argument("--values", required=True, help='JSON object, e.g. {"rx": -180}')
31
+ sub.add_parser("capture").add_argument("--window-title")
32
+ args = parser.parse_args()
33
+ toolkit = Toolkit()
34
+ try:
35
+ if args.action == "connections":
36
+ result = toolkit.connections()
37
+ elif args.action == "status":
38
+ result = toolkit.status(args.target)
39
+ elif args.action == "list":
40
+ result = toolkit.list_objects(args.object, args.target)
41
+ elif args.action == "export":
42
+ result = toolkit.export_object(args.object, args.target)
43
+ elif args.action == "backup":
44
+ result = toolkit.backup_show(args.expect_show)
45
+ elif args.action == "execute":
46
+ commands = args.command
47
+ if args.commands_file:
48
+ batch = json.loads(args.commands_file.read_text(encoding="utf-8-sig"))
49
+ if not isinstance(batch, list) or not all(isinstance(c, str) for c in batch):
50
+ raise ValueError("commands-file must contain a JSON array of strings")
51
+ commands += batch
52
+ result = toolkit.execute(commands, args.expect_show, args.target)
53
+ elif args.action == "transform":
54
+ values = json.loads(args.values)
55
+ if not isinstance(values, dict) or not all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values.values()):
56
+ raise ValueError("values must be a JSON object of numbers")
57
+ result = toolkit.set_transform(args.object, args.expect_show, values, args.target)
58
+ else:
59
+ result = toolkit.capture_ma3d(args.window_title)
60
+ print(json.dumps(result, ensure_ascii=False, indent=2))
61
+ except Exception as exc:
62
+ print(json.dumps({"error": toolkit._redact(str(exc))}, ensure_ascii=False), file=sys.stderr)
63
+ raise SystemExit(1) from None
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main()
@@ -0,0 +1,42 @@
1
+ """Environment-only credentials and explicit write policy; no embedded passwords."""
2
+
3
+ from dataclasses import dataclass, field
4
+ import os
5
+ from pathlib import Path
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Config:
10
+ host: str = "127.0.0.1"
11
+ ports: tuple[int, ...] = (30000, 30001)
12
+ user: str = "administrator"
13
+ password: str = field(default="", repr=False)
14
+ timeout: float = 15.0
15
+ allow_write: bool = False
16
+ output_dir: Path = field(default_factory=lambda: Path.cwd() / ".data")
17
+
18
+ @classmethod
19
+ def from_env(cls) -> "Config":
20
+ """Resolve paths at startup so MCP hosts need not share the repository cwd."""
21
+ root = Path(__file__).resolve().parents[2]
22
+ return cls(
23
+ host=os.getenv("MA2_HOST", "127.0.0.1"),
24
+ ports=tuple(int(p.strip()) for p in os.getenv("MA2_PORTS", os.getenv("MA2_PORT", "30000,30001")).split(",")),
25
+ user=os.getenv("MA2_USER", "administrator"),
26
+ password=os.getenv("MA2_PASSWORD", ""),
27
+ timeout=float(os.getenv("MA2_TIMEOUT", "15")),
28
+ allow_write=os.getenv("MA2_ALLOW_WRITE", "0") == "1",
29
+ output_dir=Path(os.getenv("MA2_OUTPUT_DIR", str(root / ".data"))).resolve(),
30
+ )
31
+
32
+ def validate(self) -> None:
33
+ """Reject credentials that could escape the console Login command."""
34
+ if not self.password:
35
+ raise ValueError("Set MA2_PASSWORD in the server/CLI process environment")
36
+ for value in (self.user, self.password):
37
+ if not value or any(c in value for c in '\"\r\n;\\') or any(ord(c) < 32 for c in value):
38
+ raise ValueError("Credentials contain unsupported console characters")
39
+ if not self.ports or any(not 1 <= p <= 65535 for p in self.ports):
40
+ raise ValueError("Invalid MA2_PORTS")
41
+ if not 1 <= self.timeout <= 120:
42
+ raise ValueError("MA2_TIMEOUT must be between 1 and 120 seconds")
@@ -0,0 +1,97 @@
1
+ """Official MCP SDK stdio server. Stdout is reserved for MCP JSON-RPC."""
2
+
3
+ import base64
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from mcp.server.fastmcp import FastMCP
9
+ from mcp.types import CallToolResult, ImageContent, TextContent, ToolAnnotations
10
+
11
+ from .service import Toolkit
12
+
13
+ mcp = FastMCP("grandma2-toolkit")
14
+ # Typed dictionary returns produce MCP structuredContent as well as readable text.
15
+ toolkit = Toolkit()
16
+ READ = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
17
+ WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=True, idempotentHint=False, openWorldHint=False)
18
+ FILE = ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False)
19
+
20
+
21
+ @mcp.tool(annotations=READ)
22
+ def ma2_connections() -> dict[str, Any]:
23
+ """Connect onPC and MA3D simultaneously; return runtime identity, Show and session state for each."""
24
+ return toolkit.connections()
25
+
26
+
27
+ @mcp.tool(annotations=READ)
28
+ def ma2_status(target: str = "onpc") -> dict[str, Any]:
29
+ """Inspect one verified runtime: target is onpc or ma3d. Does not change the Show."""
30
+ return toolkit.status(target)
31
+
32
+
33
+ @mcp.tool(annotations=READ)
34
+ def ma2_list(object: str, target: str = "onpc") -> dict[str, Any]:
35
+ """Read a native object, range, or children. Examples: Root 10.4.*, Sequence 121 Cue 1 Thru 5,
36
+ MAtricks 1 Thru 10, LiveSetup.FixtureTypes, Screen 2.*, ViewButton 2.1 Thru 2.10 /screen=2.
37
+ Pass the object expression without the List keyword. Returns the console's native text.
38
+ """
39
+ return toolkit.list_objects(object, target)
40
+
41
+
42
+ @mcp.tool(annotations=WRITE)
43
+ def ma2_execute(commands: list[str], expected_show: str, target: str = "onpc") -> dict[str, Any]:
44
+ """Execute up to 100 authorized commands sequentially; requires MA2_ALLOW_WRITE=1 and matching Show.
45
+
46
+ Not transactional. Stops at first failure; prior commands may already be applied.
47
+ Do not retry after a timeout without querying state. User scope still governs every command.
48
+ """
49
+ return toolkit.execute(commands, expected_show, target)
50
+
51
+
52
+ @mcp.tool(annotations=FILE)
53
+ def ma2_export(object: str, target: str = "onpc") -> dict[str, Any]:
54
+ """Export a local object or pool range (including Effect, MAtricks and Macro) to XML and fingerprint it."""
55
+ return toolkit.export_object(object, target)
56
+
57
+
58
+ @mcp.tool(annotations=FILE)
59
+ def ma2_backup(expected_show: str) -> dict[str, Any]:
60
+ """Save onPC Show, wait for asynchronous completion, copy a new backup and return SHA256. Write gate applies."""
61
+ return toolkit.backup_show(expected_show)
62
+
63
+
64
+ @mcp.tool(annotations=WRITE)
65
+ def ma3d_transform(object: str, expected_show: str, values: dict[str, float], target: str = "ma3d") -> dict[str, Any]:
66
+ """Set x/y/z (metres), rx/ry/rz (degrees), or camera fov (radians), and return before/after List.
67
+
68
+ Requires an inspected scene Root address or Camera number. Installation orientation is NOT
69
+ programmed Pan/Tilt. MA3D edits can synchronize into onPC. Use target=onpc if its shared scene
70
+ is the intended authority. Requires write gate and expected Show; no visual pass is implied.
71
+ """
72
+ return toolkit.set_transform(object, expected_show, values, target)
73
+
74
+
75
+ @mcp.tool(annotations=FILE)
76
+ def ma3d_capture(window_title: str | None = None) -> CallToolResult:
77
+ """Save the uniquely identified visible local MA3D window as PNG, without UI input.
78
+
79
+ Windows only. Read the returned image to inspect the camera and beams. Does not start
80
+ playback, select Front, or certify visual acceptance. Minimized/blank/ambiguous windows fail.
81
+ """
82
+ result = toolkit.capture_ma3d(window_title)
83
+ # Return both a persistent evidence path and native MCP image content for visual hosts.
84
+ data = Path(result["file"]).read_bytes()
85
+ content = [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
86
+ if len(data) <= 10 * 1024 * 1024:
87
+ content.append(ImageContent(type="image", mimeType="image/png", data=base64.b64encode(data).decode("ascii")))
88
+ return CallToolResult(content=content, structuredContent=result)
89
+
90
+
91
+ def main():
92
+ """Start only the stdio transport; there is no unauthenticated HTTP control port."""
93
+ mcp.run(transport="stdio")
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()