Files
OrcaSlicer/tools/mcp/gen_skill_reference.py
T
SoftFever 1d63e52dec Say action and Speed Dial, not tile and palette, in the MCP commands and docs
The MCP commands, their catalog and the docs called a command's Speed Dial entry a "tile" and the Speed
Dial itself "the palette", words the app already uses for an entry's icon and for sets of colours. They now
say "action" and "Speed Dial", as action_search and action_run do, and the catalog's tiles, tile_group and
in_palette fields are now actions, action_group and has_own_action. Speed Dial ids, and the pins people
stored under them, are unchanged.
2026-11-19 01:39:50 +08:00

213 lines
11 KiB
Python

#!/usr/bin/env python3
"""Write the skill's list of the commands' Speed Dial actions from the command reference.
python tools/mcp/gen_skill_reference.py <skills-checkout> # rewrite actions.md
python tools/mcp/gen_skill_reference.py <skills-checkout> --check # exit 1 when it differs
Reads tests/data/command_catalog.json, the reference of the command catalog that the unit test
"the checked-in command reference matches the catalog" keeps current, and writes
skills/orcaslicer-mcp-skills/references/actions.md in the checkout of the orcaslicer-mcp-skills
repository: every action a person can pick, section by section in the order the catalog adds them.
Outside the Design tab a section is a Speed Dial section (an action's group, or the action_group of
a command's own action), and each action has a row with its key, its title, the command and
arguments it runs and its description. In the Design section a command with an action of its own
(has_own_action) has a row with its key, title, arguments and description, and each Design menu item
folded into a command (its actions) a row after it, with the command's key, the action's title, the
arguments that open it and its description. The file is generated: edit the commands in OrcaSlicer
and regenerate it. A header that names a command the reference does not have is an error, so that a
renamed or removed command cannot leave it stale. Standard library only.
"""
import argparse
import difflib
import json
import re
import sys
import textwrap
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
REFERENCE = REPO / "tests" / "data" / "command_catalog.json"
TARGET = Path("skills") / "orcaslicer-mcp-skills" / "references" / "actions.md"
DESIGN = "Design"
HEADER = """\
# Speed Dial commands
Generated by OrcaSlicer's `tools/mcp/gen_skill_reference.py` from its command reference
(`tests/data/command_catalog.json`); do not edit it by hand.
These are the actions a person picks in the Speed Dial, by section. Each runs a command with the arguments
its row gives. Call the command by its name, with those arguments or others, and one the tool list does not
show with `tool_call {"tool": "<command>", "args": {...}}`; `tool_search {"tool": "<command>"}` gives its whole
schema, and its examples when it has some. `action_run {"id": "<key>"}` runs an action as a call with the
action's arguments does. Action Replay, Run Script, Take Screenshot and the calibration dialogs have a command
for agents (`replay_run`, `script_run`, `window_screenshot`, `calibration_generate_test`); the wiki and
YouTube links, About, the plugin hub and the configuration folder (`app_open_web_page`,
`window_open {"window": "about"}`, `app_show_config_folder`) are left to the person.
A call with exactly an action's arguments is the action's own call: where the action asks in a dialog, the call
opens it, which it reports as `blocked_by_dialog`, and where the action acts on the selection, so does the call.
An action whose menu item does what its command does (a camera view, Select All, Deselect All, Auto-Arrange,
Auto-Orient, Refresh Plugins) runs the command's own function and replies as the command does. Any other
arguments, or `silent: true` where the schema has `silent`, run the command without asking, with the arguments
its schema marks required. Go to tab and Go to layer collect their value in the Speed Dial: `action_run` gives
such an action its one value (`{"tab": "preview"}`, `{"percent": 50}`), and the command takes it as the argument
its row names. A command whose dialog is what it does opens it with arguments too
(`preset_export {"path": "/abs/dir"}` only spares it the folder question).
The Design section lists the Design tab's commands that have an action; `tool_search {"group": "Design"}` lists
them all, and `references/cad.md` covers them. They run only with the CAD feature on, which a person turns on
in Preferences > Features before restarting OrcaSlicer: `app_state.design_tab` says whether the Design tab
is on, and `cad_note`, while its commands cannot run, how to turn it on (a test instance gets it with
`tools/mcp/orca_mcp.py launch --cad`). A Design tab action is in the Speed Dial, and `action_run` runs it, only
while the Design tab is shown in the action's mode (in a sketch or outside one); `tool_call` runs its command
from any tab. Called with no arguments, an action's command does what its right-click menu item does, which may
be to act at once (a Delete item deletes what is selected) or to decline.
A Design row whose arguments are written as a call's own (`{"type": "linear"}`, or `{}`) is one tool of its
command: `tool_call` given exactly those arguments opens that tool, as a person's pick of its action does, and
any other call runs the command from its arguments. The action has an id of its own, which `action_search`
gives, and `action_run` runs it with no arguments or with exactly those.
"""
# The words HEADER writes in backticks that name no command: an argument, a reply's status and a field.
NOT_COMMANDS = {"silent", "blocked_by_dialog", "cad_note"}
def unknown_names(reference):
"""The commands and tools HEADER names that `reference` does not have: the name a span in backticks starts
with, unless the span is a path or the name is one of NOT_COMMANDS."""
keys = {command["key"] for command in reference["commands"]}
spans = re.findall(r"`([^`]*)`", HEADER)
named = {m.group() for m in (re.match(r"[a-z_][a-z0-9_]*\b(?!/)", span) for span in spans) if m}
return sorted(named - keys - NOT_COMMANDS)
def cell(text):
"""`text` as one Markdown table cell: on one line, its pipes escaped."""
return " ".join(str(text).split()).replace("|", "\\|")
def argument(name, schema, required):
"""One argument of a command's schema: `name` (type, required): description, one of its values."""
kind = schema.get("type", "any")
if isinstance(kind, list):
kind = " or ".join(kind)
if kind == "array" and isinstance(schema.get("items"), dict) and "type" in schema["items"]:
kind = "array of " + str(schema["items"]["type"])
notes = [kind] + (["required"] if required else [])
text = "`%s` (%s)" % (name, ", ".join(notes))
if schema.get("description"):
text += ": " + schema["description"]
if "enum" in schema and not (kind == "boolean" and schema["enum"] == [True]):
text += " One of " + ", ".join("`%s`" % json.dumps(value) for value in schema["enum"]) + "."
return text
def arguments(schema):
"""A command's arguments for its table row, those its silent form requires marked so."""
required = set(schema.get("required", [])) | set(schema.get("then", {}).get("required", []))
properties = schema.get("properties", {})
return "<br>".join(argument(name, properties[name], name in required) for name in properties)
def names(commands):
"""The keys of `commands`, in backticks and joined as a sentence lists them."""
keys = ["`%s`" % c["key"] for c in commands]
return keys[0] if len(keys) == 1 else ", ".join(keys[:-1]) + " and " + keys[-1]
def header(design, unlisted):
"""HEADER, with what it says of particular commands read from the reference: the Design commands with an action
of their own that need a value (a top-level `required`), and the commands of actions the tool list does not
show."""
needs = [c for c in design if c["has_own_action"] and c["input_schema"].get("required")]
facts = []
if needs:
facts.append("%s %s." % (names(needs), "needs its value" if len(needs) == 1 else "need their value"))
if unlisted:
facts.append("The tool list does not show %s, menu items that take no arguments: call %s with `tool_call`." %
(names(unlisted), "it" if len(unlisted) == 1 else "them"))
if not facts:
return HEADER
return HEADER + "\n" + "\n".join(textwrap.wrap(" ".join(facts), width=110)) + "\n"
def runs(command, action):
"""The call an action runs: its command with the action's arguments, and the value an input action collects
under the argument that takes it."""
args = json.dumps(action["args"]) if action else "{}"
if action and action.get("input"):
args = '{"%s": <%s>}' % (action.get("input_arg") or action["input"], action["input"])
return "`%s %s`" % (command["key"], args)
def row(key, title, args, does):
"""One row of a section's table."""
return "| `%s` | %s | %s | %s |\n" % (key, cell(title), cell(args), cell(does))
def render(reference):
# A command is in the Speed Dial with an action of its own, or through the actions folded into it. Outside the
# Design tab each action is a row of its Speed Dial section; a Design command's rows stay together in the Design
# section.
in_speed_dial = [command for command in reference["commands"] if command["has_own_action"] or command.get("actions")]
sections = {}
for c in in_speed_dial:
if c["group"] == DESIGN:
rows = sections.setdefault(DESIGN, [])
if c["has_own_action"]:
rows.append(row(c["key"], c["title"], arguments(c["input_schema"]), c["description"]))
for action in c.get("actions", []):
rows.append(row(c["key"], action["title"], "`%s`" % json.dumps(action["args"]), action["description"]))
continue
if c["has_own_action"]:
sections.setdefault(c.get("action_group") or c["group"], []).append(row(c["key"], c["title"], runs(c, None),
c["description"]))
for action in c.get("actions", []):
sections.setdefault(action.get("group") or c["group"], []).append(
row(action["key"], action["title"], runs(c, action), action["description"]))
unlisted = [c for c in in_speed_dial if c["group"] != DESIGN and not c["listed"]]
out = [header([c for c in in_speed_dial if c["group"] == DESIGN], unlisted)]
for section, rows in sections.items():
columns = "arguments" if section == DESIGN else "runs"
out.append("\n## %s\n\n| key | title | %s | does |\n|---|---|---|---|\n" % (section, columns))
out.extend(rows)
return "".join(out)
def main():
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("skills", type=Path, help="the orcaslicer-mcp-skills checkout")
parser.add_argument("--check", action="store_true", help="write nothing; exit 1 when actions.md differs")
args = parser.parse_args()
target = args.skills / TARGET
if not target.parent.is_dir():
parser.error("%s is not an orcaslicer-mcp-skills checkout: it has no %s" % (args.skills, TARGET.parent))
with REFERENCE.open(encoding="utf-8") as f:
reference = json.load(f)
unknown = unknown_names(reference)
if unknown:
parser.error("the header names %s, which the command reference does not have" % ", ".join(unknown))
text = render(reference)
if not args.check:
with target.open("w", encoding="utf-8", newline="\n") as f:
f.write(text)
print("wrote %s" % target)
return 0
# A checkout may have turned the file's line ends into CRLF.
current = target.read_text(encoding="utf-8").replace("\r\n", "\n") if target.exists() else ""
if current == text:
print("%s is current" % target)
return 0
sys.stdout.writelines(difflib.unified_diff(current.splitlines(True), text.splitlines(True), str(target), "generated"))
print("\n%s differs from the command reference; run without --check to rewrite it" % target)
return 1
if __name__ == "__main__":
sys.exit(main())