@rasteaks/grandma2-toolkit 0.0.0-stage → 0.1.0

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,143 @@
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
+ 通过 **MCP、CLI 和 Agent Skill** 控制 grandMA2 onPC 与 MA3D。
4
+
5
+ - **双端连接**:自动识别 onPC / MA3D,查询 Show、灯具和播放对象。
6
+ - **场景与编程**:执行命令,调整灯具位置、安装方向和相机。
7
+ - **备份与验收**:导出 XML、备份 Show、保存 MA3D 截图和操作记录。
8
+
9
+ ## 快速开始
10
+
11
+ 准备 Node.js(含 npx)和 [uv](https://docs.astral.sh/uv/),在任意目录运行:
12
+
13
+ ```sh
14
+ npx @rasteaks/grandma2-toolkit
15
+ ```
16
+
17
+ 首次运行时确认 npx 的安装提示,uv 会按包内的 `uv.lock` 准备 Python 环境。服务启动后通过标准输入输出(stdio)等待 MCP 请求。
18
+
19
+ 要从 MCP 客户端调用工具,将以下配置加入客户端。后台启动使用 `--yes` 自动确认安装。
20
+
21
+ ```json
22
+ {
23
+ "mcpServers": {
24
+ "grandma2-toolkit": {
25
+ "command": "npx",
26
+ "args": ["--yes", "@rasteaks/grandma2-toolkit"]
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ 确保客户端能从 `PATH` 找到 npx 和 uv。启动后可直接列出工具。要连接控台,请启用 onPC 或 MA3D 的 Telnet,并通过客户端的服务进程环境提供 `MA2_PASSWORD`。默认只读,连接地址为 `127.0.0.1`,候选端口为 `30000`、`30001`。远程控台用 `MA2_HOST` 指定地址。调用 `ma2_connections`,查看 `endpoints.onpc.connected` 和 `endpoints.onpc.show` 确认编程端和当前 Show。
33
+
34
+ ## 使用方式
35
+
36
+ ### MCP
37
+
38
+ 客户端可直接使用 [npx 配置示例](examples/mcp.npx.json)。npx 入口默认将审计记录、导出和备份保存在用户主目录的 `.grandma2-toolkit/.data`,可通过 `MA2_OUTPUT_DIR` 指定其他目录。
39
+
40
+ 从源码运行 MCP 时,可在仓库根目录执行 `uv run --locked grandma2-mcp`。使用绝对仓库路径的客户端配置见 [uv 配置示例](examples/mcp.json)。
41
+
42
+ <details>
43
+ <summary>查看 8 个 MCP 工具</summary>
44
+
45
+ | 工具 | 功能 |
46
+ |---|---|
47
+ | `ma2_connections` | 同时连接 onPC 与 MA3D |
48
+ | `ma2_status` | 读取 Show、运行时和网络状态 |
49
+ | `ma2_list` | 查询灯型、灯层子项、Cue 范围、MAtricks 和指定屏幕的 ViewButton 等对象 |
50
+ | `ma2_execute` | 批量执行命令,遇错停止 |
51
+ | `ma2_export` | 导出原生 XML 并计算内容指纹 |
52
+ | `ma2_backup` | 保存、备份 Show 并计算 SHA256 |
53
+ | `ma3d_transform` | 调整灯具安装位置、朝向或相机 |
54
+ | `ma3d_capture` | 保存 MA3D 窗口截图并返回图片 |
55
+
56
+ </details>
57
+
58
+ 在 MCP 客户端调用 `ma2_list` 时,`object` 只填写对象表达式。以下参数查询第二屏视图按钮的实际绑定,返回的 `reply` 保留控台原文:
59
+
60
+ ```json
61
+ {"target": "onpc", "object": "ViewButton 2.1 Thru 2.10 /screen=2"}
62
+ ```
63
+
64
+ ### Skill
65
+
66
+ 入口:[ma2-control / SKILL.md](.agents/skills/ma2-control/SKILL.md)。支持项目 Skill 的客户端可直接发现,也可让 Agent 读取该文件。
67
+
68
+ > 使用 $ma2-control,只读检查当前 Show 第二页的执行器,列出每根推杆绑定的 Sequence 和前五条 Cue 的触发方式。
69
+
70
+ > 使用 $ma2-control,保留 Page 3 编程,先备份,再调整指定地面灯的安装方向并截图验收。
71
+
72
+ ### CLI
73
+
74
+ CLI 示例使用仓库源码。在仓库根目录安装依赖,并给当前 PowerShell 会话设置 Telnet 凭据:
75
+
76
+ ```powershell
77
+ uv sync --locked
78
+ $credential = Get-Credential -UserName administrator -Message 'MA2 Telnet 登录'
79
+ $env:MA2_USER = $credential.UserName
80
+ $env:MA2_PASSWORD = $credential.GetNetworkCredential().Password
81
+ uv run grandma2 connections
82
+ ```
83
+
84
+ ```powershell
85
+ # 查看当前 Show 已提交的灯型节点和 MAtricks 池位
86
+ uv run grandma2 list 'LiveSetup.FixtureTypes'
87
+ uv run grandma2 list 'MAtricks 1 Thru 10'
88
+
89
+ # 查看 MA3D 相机,在本机导出效果或截图
90
+ uv run grandma2 --target ma3d list 'Camera 50'
91
+ uv run grandma2 export 'Effect 1 Thru 10'
92
+ uv run grandma2 capture --window-title 'MA 3D'
93
+
94
+ # 开启写入;将 Show 名称和对象编号替换为现场实际值
95
+ $env:MA2_ALLOW_WRITE = '1'
96
+ uv run grandma2 backup --expect-show codex
97
+ uv run grandma2 --target ma3d transform 'Camera 50' --expect-show codex --values '{"z":12.8,"rx":-2}'
98
+ uv run grandma2 execute --expect-show codex --commands-file examples/commands.readback.json
99
+ ```
100
+
101
+ `--target` 放在子命令前,默认 `onpc`。位置单位为米、旋转为度、相机 FOV 为弧度。
102
+
103
+ 进入 `EditSetup` 修改配接时,把依赖当前目录的命令放在同一次 `execute` 调用中。每次调用都会建立新连接。提交后从 `LiveSetup` 回读灯号、灯型和实例地址。配接、像素编组与推杆绑定的完整示例见 [Telnet 操作速查](.agents/skills/ma2-control/references/telnet-workflows.md)。相机、安装角和播放示例见 [场景与播放命令](.agents/skills/ma2-control/references/commands.md)。
104
+
105
+ 在 onPC 本机导出对象时,工具按对象类型到 `effects`、`matricks` 或 `macros` 等原生目录读取 XML。`native_file` 指向原生文件,`file` 指向本次操作留存的副本,`fingerprint` 可用于比较两次导出的对象内容。
106
+
107
+ ## 配置
108
+
109
+ 通过进程环境变量配置,无内置密码。
110
+
111
+ | 变量 | 默认值 | 说明 |
112
+ |---|---|---|
113
+ | `MA2_HOST` | `127.0.0.1` | 目标主机 |
114
+ | `MA2_PORTS` | `30000,30001` | 候选 Telnet 端口 |
115
+ | `MA2_USER` | `administrator` | 登录用户 |
116
+ | `MA2_PASSWORD` | — | 必填 |
117
+ | `MA2_ALLOW_WRITE` | `0` | 设为 `1` 启用写入 |
118
+ | `MA2_TIMEOUT` | `15` | 响应超时,单位秒 |
119
+ | `MA2_OUTPUT_DIR` | 源码启动为仓库 `.data`;npx 启动为用户主目录下的 `.grandma2-toolkit/.data` | 日志、备份、导出和截图目录;安装 wheel 后建议显式设置 |
120
+
121
+ MCP 客户端不一定继承终端环境变量,请确认密码已传给服务进程。
122
+
123
+ ## 使用须知
124
+
125
+ - **写入需匹配 Show**:开启写入后仍需提供 `expected_show`。批次失败不会回滚,超时后应先查询状态再决定是否重试。
126
+ - **区分场景与编程**:安装朝向不是 Cue 的 Pan/Tilt;MA3D 场景修改可能同步到 onPC。两端同名 Show 不代表已加入同一会话。
127
+ - **本机能力**:文件导出、备份仅支持本机运行时;截图需要 Windows 上可见、未最小化的 MA3D 窗口,效果仍需查看图片确认。
128
+ - **控制网络**:Telnet 明文传输,仅用于受信任网络。通用命令接口可执行 Lua、删除等操作,写入开关不是权限沙箱。
129
+
130
+ ## 开发
131
+
132
+ ```powershell
133
+ uv sync --locked --group dev
134
+ uv run pytest
135
+ uv run ruff check .
136
+ uv build
137
+ ```
138
+
139
+ 修改 npx 入口后运行 `uv run pytest tests/npx_smoke.py`,通过本地 npm 压缩包验证安装、stdio 握手和工具发现。
140
+
141
+ ---
142
+
143
+ [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,20 @@
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.0",
4
+ "description": "Launch the grandMA2 onPC and MA3D stdio MCP server with npx",
5
+ "license": "AGPL-3.0-only",
6
+ "repository": "github:RaSteaks/grandma2-toolkit",
7
+ "publishConfig": {
8
+ "access": "public",
9
+ "registry": "https://registry.npmjs.org/"
10
+ },
11
+ "bin": {
12
+ "grandma2-mcp": "bin/grandma2-mcp.cjs"
13
+ },
14
+ "files": [
15
+ "bin/grandma2-mcp.cjs",
16
+ "pyproject.toml",
17
+ "uv.lock",
18
+ "src/grandma2_toolkit/*.py"
19
+ ]
20
+ }
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.0"
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.0"
@@ -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()