Files
OrcaSlicer/tools/mcp/gen_skill_reference.py
T
SoftFever 924a9dad9c Correct what command descriptions and the skill reference tell agents
A Design tile's command says it follows its right-click menu row and may
decline, export_config says how its rows are named, and the generated skill
reference says which commands are the person's own and how the Design tab is
turned on.
2026-11-14 00:21:37 +08:00

168 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Write the skill's list of the Speed Dial's commands 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 command a person can pick (in_palette), section by section in the order the
catalog adds them, with its key, title, arguments and 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"
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 commands a person picks in the Speed Dial, by section. Call one with
`call_tool {"tool": "<key>", "args": {...}}`, or run its tile with `run_action {"id": "<key>", "args": {...}}`;
`search_tools {"tool": "<key>"}` gives its whole schema, and its examples when it has some. Some are the
person's own. Action Replay, Run Script, Take Screenshot and the calibration dialogs have a tool for agents
(`run_replay`, `run_script`, `screenshot`, `generate_calibration_test`); the wiki and YouTube links, About,
the plugin hub and the configuration folder (`open_wiki`, `open_youtube`, `help_about`, `install_plugin`,
`help_open_config_folder`) are left to the person.
A command whose schema has `silent`, or whose description says what it does with no arguments, does what a
person's pick does when called with none: one that asks in a dialog opens it, which a call reports as
`blocked_by_dialog`. Given its arguments, or `silent: true` if it takes `silent`, it runs without asking and
needs the arguments marked required. A command whose schema requires an argument has no person's form
(`go_to_tab {}` is refused), and one whose dialog is what it does opens it with arguments too
(`export_config {"path": "/abs/dir"}` only spares it the folder question).
The Design section lists the Design tab's commands that have a tile; `search_tools {"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: `get_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 `run_action` runs it, only while
the Design tab is shown in the tile's mode (in a sketch or outside one); `call_tool` runs its command from any
tab. Called with no arguments, a tile's command does what its right-click menu row does, which may be to act
at once (a Delete row deletes what is selected) or to decline.
"""
# 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(palette):
"""HEADER, with what it says of particular commands read from the reference: the commands with one form,
which needs a value (a top-level `required`), and the typed tools that are tiles too (`listed`)."""
needs = [c for c in palette if c["input_schema"].get("required")]
both = [c for c in palette if c["listed"]]
facts = []
if needs:
facts.append("%s %s." % (names(needs), "needs its value" if len(needs) == 1 else "need their value"))
if both:
facts.append("A typed tool that is also a tile (%s) is in the tool list too." % names(both))
if not facts:
return HEADER
return HEADER + "\n" + "\n".join(textwrap.wrap(" ".join(facts), width=110)) + "\n"
def render(reference):
palette = [command for command in reference["commands"] if command["in_palette"]]
sections = {}
for command in palette:
sections.setdefault(command["group"], []).append(command)
out = [header(palette)]
for group, commands in sections.items():
out.append("\n## %s\n\n| key | title | arguments | does |\n|---|---|---|---|\n" % group)
for c in commands:
out.append("| `%s` | %s | %s | %s |\n" % (c["key"], cell(c["title"]), cell(arguments(c["input_schema"])),
cell(c["description"])))
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())