mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-11-25 23:01:09 -05:00
The MCP command descriptions, docs and code called an entry of the app's menus a "row", the word they also use for the rows of the object list and the app's other lists. They now say "menu item", so a row is only ever a row of a list or table. Command names, arguments and Speed Dial tile ids are unchanged.
211 lines
11 KiB
Python
211 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Write the skill's list of the Speed Dial's tiles 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 tile 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 (a tile's group, or the tile_group of a
|
|
command's own tile), and each tile has a row with its key, its title, the command and arguments it
|
|
runs and its description. In the Design section a command with a tile of its own (in_palette) has a
|
|
row with its key, title, arguments and description, and each Design menu item folded into a command
|
|
(its tiles) a row after it, with the command's key, the tile'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 tiles 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 a tile as a call with the
|
|
tile'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 a tile's arguments is the tile's own call: where the tile asks in a dialog, the call opens
|
|
it, which it reports as `blocked_by_dialog`, and where the tile acts on the selection, so does the call. A
|
|
tile 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 a tile 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 a tile; `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 tile is in the Speed Dial, and `action_run` runs it, only while
|
|
the Design tab is shown in the tile's mode (in a sketch or outside one); `tool_call` runs its command from any
|
|
tab. Called with no arguments, a tile'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 tile does, and any
|
|
other call runs the command from its arguments. The tile 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 a tile of
|
|
their own that need a value (a top-level `required`), and the commands of tiles the tool list does not show."""
|
|
needs = [c for c in design if c["in_palette"] 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, tile):
|
|
"""The call a tile runs: its command with the tile's arguments, and the value an input tile collects under the
|
|
argument that takes it."""
|
|
args = json.dumps(tile["args"]) if tile else "{}"
|
|
if tile and tile.get("input"):
|
|
args = '{"%s": <%s>}' % (tile.get("input_arg") or tile["input"], tile["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 palette with a tile of its own, or through the tiles folded into it. Outside the Design tab
|
|
# each tile is a row of its Speed Dial section; a Design command's rows stay together in the Design section.
|
|
palette = [command for command in reference["commands"] if command["in_palette"] or command.get("tiles")]
|
|
sections = {}
|
|
for c in palette:
|
|
if c["group"] == DESIGN:
|
|
rows = sections.setdefault(DESIGN, [])
|
|
if c["in_palette"]:
|
|
rows.append(row(c["key"], c["title"], arguments(c["input_schema"]), c["description"]))
|
|
for tile in c.get("tiles", []):
|
|
rows.append(row(c["key"], tile["title"], "`%s`" % json.dumps(tile["args"]), tile["description"]))
|
|
continue
|
|
if c["in_palette"]:
|
|
sections.setdefault(c.get("tile_group") or c["group"], []).append(row(c["key"], c["title"], runs(c, None),
|
|
c["description"]))
|
|
for tile in c.get("tiles", []):
|
|
sections.setdefault(tile.get("group") or c["group"], []).append(row(tile["key"], tile["title"], runs(c, tile),
|
|
tile["description"]))
|
|
unlisted = [c for c in palette if c["group"] != DESIGN and not c["listed"]]
|
|
out = [header([c for c in palette 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())
|