Files
OrcaSlicer/tools/mcp/gen_skill_reference.py
T
SoftFever 1ef24b7d34 Hold Speed Dial commands, MCP tools and Design tools in one command catalog
Every command takes JSON arguments and has one function for a person and for
automation: with no arguments it does what a person's pick does, and with
arguments it runs silently. The Design tab's CAD tools are commands that
call_tool runs, and they show as Speed Dial tiles on the Design tab.
2026-11-13 20:59:31 +08:00

135 lines
6.1 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. Standard library only.
"""
import argparse
import difflib
import json
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. A command called
with no arguments does what a person's pick does: one that asks in a dialog opens it, which a call reports as
`blocked_by_dialog`. A command that takes `silent` has a second form: given any argument, or `silent: true`,
it runs without asking and needs the arguments marked required. The Design section's commands need the
Design tab on (`launch --cad`), and their tiles are the Speed Dial's only while that tab is shown;
`references/cad.md` covers them.
"""
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:
text = render(json.load(f))
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())