diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index a0666e6cec..ad1253ebaa 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -226,6 +226,32 @@ bool arg_bool(const nlohmann::json& args, const char* key, bool fallback) // Any thread. nlohmann::json search_commands(const CommandCatalog& catalog, const nlohmann::json& args); +// Where tool_describe's manual sends an agent for the values a built-in command's parameter takes when its schema does +// not list them. Source: the tools that list them, in order ("tools/list" stands for the tool list); Described: the +// parameter's own description lists them; Free: the caller's own value (a number, text, a path, a new name, a shape to +// draw). Only a parameter without fields of its own is classified; one with fields is read through its fields. +struct ParameterClass +{ + enum Kind { Source, Described, Free }; + Kind kind = Free; + std::vector tools; +}; +// The class of parameter `path` of the built-in command `command`, `path` dotted with [] for an array's items +// ("add[].layer"): the entry for that command and path, else the class of the path's last name, else nullopt. +std::optional parameter_class(const std::string& command, const std::string& path); + +// tool_describe's reply, `command`'s manual: {name, title, group, heading?, listed, call, access, description, +// parameters, rules, menu_items, examples, complete, input_schema?}. parameters follow the schema at every depth, each +// {name, type, required, default?, values?, min?, max?, exclusive_min?, min_items?, max_items?, min_length?, +// max_length?, pattern?, format?, goes_with?, values_from?, items?, properties?, other_keys?, schema?, description}. +// required and default are the schema's alone; what a handler requires or supplies is in the description. A part of the +// schema the manual can't express is kept raw under the parameter's schema, and the manual is then not complete and +// carries the whole input_schema. Any thread. +nlohmann::json command_manual(const NativeCommand& command); +// tool_describe's answer for `name` in `catalog`: the manual of the command lookup() resolves, else ToolFailure with the +// catalog's text and code for the name (a left-out command's reason and code) and the closest names. Any thread. +nlohmann::json describe_command(const CommandCatalog& catalog, const std::string& name); + // The Speed Dial actions of `listed` (ActionRegistry::describe()'s items: id, title, group, description) // that `words` (of query_words()) describe, best first: those matching more of the words, then those // matching more of them in what the action is called (the name inside its id, its title and its group), diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index f01a9c85cf..93166f0ef6 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -21,9 +21,13 @@ #include #include +#include #include #include +#include +#include #include +#include #include #include #include @@ -284,6 +288,420 @@ json search_commands(const CommandCatalog& catalog, const json& args) {"use", "call a listed command by its name; tool_call {tool, args} runs one that is not listed"}}; } +namespace { + +ParameterClass source(std::vector tools) { return {ParameterClass::Source, std::move(tools)}; } +const ParameterClass kDescribed{ParameterClass::Described, {}}; +const ParameterClass kFree{ParameterClass::Free, {}}; + +// The classes of a command's own parameters, which come before a name's: a name that means something else there, or +// that no other command shares. +const std::map& classes_by_path() +{ + static const std::map rows{ + // Finding and calling commands and actions. + {"tool_search.tool", source({"tools/list", "tool_search"})}, + {"tool_describe.tool", source({"tools/list", "tool_search"})}, + {"tool_call.tool", source({"tools/list", "tool_search"})}, + {"tool_call.args", source({"tool_describe"})}, + {"action_run.id", source({"action_search"})}, + {"action_run.args", source({"action_search"})}, + {"action_search.section", source({"action_search"})}, + {"script_run.args", kFree}, + {"replay_run.vars", kFree}, + // Settings and preferences: the keys a tool takes are those its reader lists. + {"settings_get.keys", source({"settings_list"})}, + {"settings_set.values", source({"settings_list"})}, + {"settings_list.where", kDescribed}, + {"settings_get.min_z", source({"object_list"})}, + {"settings_get.max_z", source({"object_list"})}, + {"settings_set.min_z", source({"object_list"})}, + {"settings_set.max_z", source({"object_list"})}, + {"project_get_settings.keys", source({"project_get_settings"})}, + {"project_set_settings.values", source({"project_get_settings"})}, + {"plate_get_settings.keys", source({"plate_get_settings"})}, + {"plate_set_settings.values", source({"plate_get_settings"})}, + {"preferences_get.keys", source({"preferences_get"})}, + {"preferences_set.values", source({"preferences_get"})}, + {"window_open.key", source({"preferences_get"})}, + // Presets and printer models. + {"preset_select.name", source({"preset_list"})}, + {"preset_delete.name", source({"preset_list"})}, + {"settings_get.compare", source({"preset_list"})}, + {"printer_list_models.vendor", source({"printer_list_models"})}, + {"printer_install.models[].vendor", source({"printer_list_models"})}, + {"printer_uninstall.models[].vendor", source({"printer_list_models"})}, + // Input: a chord is the caller's; the menu an input opens is listed by the same call made without popup_item. + {"keyboard_press.keys", kFree}, + {"widget_click.popup_item", source({"widget_click"})}, + {"keyboard_press.popup_item", source({"keyboard_press"})}, + {"mouse_gesture.popup_item", source({"mouse_gesture"})}, + {"widget_list.target", source({"window_list"})}, + {"window_set.target", source({"window_list"})}, + {"window_screenshot.target", source({"window_list", "widget_list"})}, + {"dialog_auto_answer.rules[].button", kDescribed}, + // A sliced plate's layers, by height too. + {"plate_set_custom_gcode.add[].z", source({"plate_slice_stats"})}, + {"plate_set_custom_gcode.remove[].z", source({"plate_slice_stats"})}, + // The Design tab: the shapes a sketch draws are new; a sketch line as a mirror axis; a hole's point is the + // caller's, a thread's may be a face; what a feature's card picks; the bodies a boolean takes. + {"sketch_draw.entities", kFree}, + {"sketch_mirror.axis", source({"sketch_describe"})}, + {"hole.at", kFree}, + {"thread.at", source({"body_describe"})}, + {"feature_edit.refs", source({"feature_describe"})}, + {"boolean.target", source({"describe_design"})}, + {"boolean.tool", source({"describe_design"})}, + {"sweep.path", source({"describe_design"})}, + }; + return rows; +} + +// The classes of the names the built-in commands give their parameters, every name but those that only a command's +// own entry classifies (classes_by_path()). +const std::map& classes_by_name() +{ + const ParameterClass objects = source({"object_list"}), plates = source({"plate_list"}); + const ParameterClass slots = source({"filament_list"}), presets = source({"preset_list"}); + const ParameterClass design = source({"describe_design"}), geometry = source({"body_describe"}); + const ParameterClass sketch = source({"sketch_describe"}), layers = source({"plate_slice_stats"}); + static const std::map rows{ + // The project. + {"object", objects}, {"objects", objects}, {"object_id", objects}, {"object_ids", objects}, {"part", objects}, + {"parts", objects}, {"part_id", objects}, {"part_ids", objects}, {"instance", objects}, {"instances", objects}, + {"instance_object_ids", objects}, {"fill_object", objects}, {"order", objects}, {"replace", objects}, + {"plate", plates}, {"plates", plates}, + {"filament_slot", slots}, {"filament", slots}, {"components", slots}, {"merge_into", slots}, + {"layer", layers}, {"layer_range", layers}, {"layer_z", layers}, + // Presets, printer models and plugins. + {"preset", presets}, {"printer", presets}, {"names", presets}, {"vendor", presets}, {"filament_type", presets}, + {"model", source({"printer_list_models"})}, {"nozzles", source({"printer_list_models"})}, + {"plugin", source({"plugin_list"})}, {"capability", source({"plugin_list"})}, + // The app's jobs, dialogs and widgets. + {"job", source({"app_state"})}, {"button", source({"app_state"})}, {"title", source({"app_state"})}, + {"target", source({"widget_list"})}, + // The Design document: features, bodies, their faces and edges, and a sketch's entities. + {"body", design}, {"source_body", design}, {"face_body", design}, {"feature", design}, {"before", design}, + {"sketch", design}, {"profiles", design}, {"cs_a", design}, {"cs_b", design}, {"plane_a", design}, + {"plane_b", design}, {"reference", design}, {"base", design}, + {"generation", source({"describe_design", "body_describe"})}, {"plane", source({"describe_design", "body_describe"})}, + {"face", geometry}, {"faces", geometry}, {"face_a", geometry}, {"face_b", geometry}, {"edge", geometry}, + {"edges", geometry}, {"edge_a", geometry}, {"edge_b", geometry}, {"vertex", geometry}, {"up_to_face", geometry}, + {"a", geometry}, {"b", geometry}, + {"entities", sketch}, {"entity", sketch}, {"refs", sketch}, {"ent_a", sketch}, {"ent_b", sketch}, + {"axis_entity", sketch}, {"loop", sketch}, + {"index", source({"sketch_list_constraints"})}, + {"field", source({"feature_describe"})}, {"fields", source({"feature_describe"})}, + // Described: the parameter's own description, or its items' values, lists what it takes. + {"edge_kinds", kDescribed}, {"kinds", kDescribed}, {"include", kDescribed}, {"legend", kDescribed}, + {"modifiers", kDescribed}, {"prime_volume_mode", kDescribed}, {"shaper_type", kDescribed}, {"tab", kDescribed}, + {"group", kDescribed}, + // Free: the caller's own numbers, points, text, paths, names and shapes. + {"accelerations", kFree}, {"across_flats", kFree}, {"angle", kFree}, {"angle_deg", kFree}, {"at", kFree}, + {"axis_a", kFree}, {"axis_b", kFree}, {"axis_x", kFree}, {"axis_y", kFree}, {"axis_z", kFree}, {"c0", kFree}, + {"c1", kFree}, {"cbore_depth", kFree}, {"cbore_diameter", kFree}, {"center", kFree}, {"code", kFree}, + {"color", kFree}, {"colour", kFree}, {"corner", kFree}, {"count", kFree}, {"crf", kFree}, + {"csink_angle", kFree}, {"csink_diameter", kFree}, {"ctrl", kFree}, {"damping", kFree}, {"delta", kFree}, + {"depth", kFree}, {"designation", kFree}, {"diameter", kFree}, {"direction", kFree}, {"distance", kFree}, + {"distance2", kFree}, {"dx", kFree}, {"dy", kFree}, {"dz", kFree}, {"end", kFree}, {"end_angle", kFree}, + {"end_angle_deg", kFree}, {"end_y", kFree}, {"entries", kFree}, {"expr", kFree}, {"filename", kFree}, + {"flush_multiplier", kFree}, {"flush_volumes_matrix", kFree}, {"font", kFree}, {"fps", kFree}, + {"freq_x", kFree}, {"freq_y", kFree}, {"gcode", kFree}, {"height", kFree}, {"jpeg_quality", kFree}, + {"keys", source({"settings_list"})}, {"layer_percent", kFree}, {"length", kFree}, {"limit", kFree}, + {"lines", kFree}, {"look_at", kFree}, {"match", kFree}, {"max_dim", kFree}, {"max_nodes", kFree}, + {"max_seconds", kFree}, {"max_web_nodes", kFree}, {"max_z", kFree}, {"merge_angle_deg", kFree}, + {"min_volume", kFree}, {"min_z", kFree}, {"move", kFree}, {"name", kFree}, {"normal", kFree}, + {"offset", kFree}, {"on_arc", kFree}, {"orbit", kFree}, {"out_dir", kFree}, {"p", kFree}, {"p0", kFree}, + {"p1", kFree}, {"p2", kFree}, {"path", kFree}, {"paths", kFree}, {"pitch", kFree}, {"pivot", kFree}, + {"pivot_x", kFree}, {"pivot_y", kFree}, {"pivot_z", kFree}, {"point", kFree}, {"points", kFree}, + {"position", kFree}, {"profile", kFree}, {"quality", kFree}, {"query", kFree}, {"radius", kFree}, + {"ratios", kFree}, {"replay", kFree}, {"rminor", kFree}, {"rotate", kFree}, {"rotation", kFree}, + {"rotation_deg", kFree}, {"save_path", kFree}, {"scale", kFree}, {"sidebar_width", kFree}, {"sides", kFree}, + {"size", kFree}, {"spacing", kFree}, {"speeds", kFree}, {"standard", kFree}, {"start", kFree}, + {"start_angle", kFree}, {"start_angle_deg", kFree}, {"start_y", kFree}, {"step", kFree}, {"steps", kFree}, + {"taper", kFree}, {"taper_deg", kFree}, {"text", kFree}, {"thickness", kFree}, {"timeout_s", kFree}, + {"to", kFree}, {"tolerance", kFree}, {"translate", kFree}, {"value", kFree}, {"waypoints", kFree}, + {"width", kFree}, {"x", kFree}, {"x_hint", kFree}, {"y", kFree}, {"z", kFree}, {"zoom", kFree}, + }; + return rows; +} + +// A plugin's operation (plugin..), whose parameters are named by the plugin and classified by nobody. +bool is_plugin_operation(const NativeCommand& command) { return command.key.rfind("plugin.", 0) == 0; } + +// "number", or "number or null" for a list of types. +std::string type_text(const json& type) +{ + if (type.is_string()) + return type.get(); + std::string out; + for (const json& t : type) + out += (out.empty() ? "" : " or ") + (t.is_string() ? t.get() : t.dump()); + return out; +} + +// Whether `schema` takes only true or false, null aside: such a parameter, as one with an enum, lists its values. +bool lists_its_values(const json& schema) +{ + if (schema.contains("enum")) + return true; + const json type = schema.value("type", json()); + if (type.is_string()) + return type == "boolean"; + if (!type.is_array() || type.empty()) + return false; + return std::all_of(type.begin(), type.end(), [](const json& t) { return t == "boolean" || t == "null"; }); +} + +// Whether `schema` has fields of its own: an object's properties, or its items'. +bool has_fields(const json& schema) +{ + const auto items = schema.find("items"); + return schema.contains("properties") || (items != schema.end() && items->is_object() && items->contains("properties")); +} + +// Builds the manual's parameters of one command. +struct ManualBuilder +{ + const NativeCommand& command; + bool classify; + bool complete = true; + + // The value `X` of "Type X:" or "Target X:" that starts `description`, when it is one of the command's own `type` + // or `target` values: the parameter goes with it. + json goes_with(const std::string& description) const + { + for (const char* arg : {"type", "target"}) { + std::string lead = arg; + lead[0] = char(std::toupper(static_cast(lead[0]))); + lead += ' '; + if (description.rfind(lead, 0) != 0) + continue; + const std::size_t colon = description.find(':', lead.size()); + if (colon == std::string::npos) + continue; + const std::string value = description.substr(lead.size(), colon - lead.size()); + const json own = command.input_schema.value("properties", json::object()).value(arg, json::object()); + const json values = own.value("enum", json::array()); + if (std::find(values.begin(), values.end(), value) != values.end()) + return {{arg, value}}; + } + return nullptr; + } + + // The shape of `schema`, the parameter at `path`, required as `required` says (null for an array's items or the + // values of other keys). `classified`: whether `path` names a parameter parameter_class() reads, false for the + // values of other keys and inside a plugin operation. + json shape(const json& schema, const std::string& path, const json& required, bool classified) + { + json out = json::object(); + if (!schema.is_object()) { + // A boolean subschema takes anything or nothing. + out["schema"] = schema; + complete = false; + return out; + } + static const char* const kExpressed[] = {"type", "description", "default", "enum", "minimum", + "maximum", "exclusiveMinimum", "minItems", "maxItems", "minLength", + "maxLength", "pattern", "format", "items", "properties", + "required", "additionalProperties"}; + bool raw = false; + for (const auto& [key, value] : schema.items()) { + const bool expressed = std::find(std::begin(kExpressed), std::end(kExpressed), key) != std::end(kExpressed); + // A draft-04 exclusiveMinimum is a boolean that qualifies minimum. + if (!expressed || (key == "exclusiveMinimum" && !value.is_number()) || + (key == "type" && !value.is_string() && !value.is_array())) + raw = true; + } + if (!required.is_null()) + out["required"] = required; + if (const auto type = schema.find("type"); type != schema.end() && (type->is_string() || type->is_array())) + out["type"] = type_text(*type); + const std::string description = schema.value("description", std::string()); + if (schema.contains("description")) + out["description"] = description; + if (schema.contains("default")) + out["default"] = schema["default"]; + if (schema.contains("enum")) + out["values"] = schema["enum"]; + static const std::pair kBounds[] = { + {"minimum", "min"}, {"maximum", "max"}, {"minItems", "min_items"}, {"maxItems", "max_items"}, + {"minLength", "min_length"}, {"maxLength", "max_length"}, {"pattern", "pattern"}, {"format", "format"}}; + for (const auto& [from, to] : kBounds) + if (schema.contains(from)) + out[to] = schema[from]; + if (const auto excl = schema.find("exclusiveMinimum"); excl != schema.end() && excl->is_number()) + out["exclusive_min"] = *excl; + if (json with = goes_with(description); !with.is_null()) + out["goes_with"] = std::move(with); + if (const auto props = schema.find("properties"); props != schema.end()) { + if (props->is_object()) + out["properties"] = fields(*props, schema.value("required", json::array()), path, classified); + else + raw = true; + } + if (const auto other = schema.find("additionalProperties"); other != schema.end()) { + if (other->is_boolean()) { + if (!other->get()) + out["other_keys"] = false; + } else + out["other_keys"] = shape(*other, path, nullptr, false); + } + if (const auto items = schema.find("items"); items != schema.end()) + out["items"] = shape(*items, path + "[]", nullptr, classified); + // A parameter without fields names where its values come from, unless it lists them itself. An array's items + // are read through the array, which is the parameter. + if (classified && required != nullptr && !has_fields(schema) && !lists_its_values(schema)) + if (const std::optional c = parameter_class(command.key, path); c && c->kind == ParameterClass::Source) + out["values_from"] = c->tools; + if (raw) { + out["schema"] = schema; + complete = false; + } + return out; + } + + // The parameters of the object whose properties are `props` and whose required are `required`, at `path` (empty + // at the top, "[]" for an array's items). + json fields(const json& props, const json& required, const std::string& path, bool classified) + { + json out = json::array(); + for (const auto& [name, schema] : props.items()) { + const bool needed = required.is_array() && std::find(required.begin(), required.end(), name) != required.end(); + json p = shape(schema, path.empty() ? name : path + "." + name, needed, classified); + p["name"] = name; + out.push_back(std::move(p)); + } + return out; + } +}; + +// A list of names as a sentence's subject: "a", "a and b", "a, b and c". +std::string names_text(const json& names) +{ + std::string out; + for (std::size_t i = 0; i < names.size(); ++i) + out += (i == 0 ? "" : i + 1 == names.size() ? " and " : ", ") + names[i].get(); + return out; +} + +// The menu items that run `command`: its own Speed Dial item first, then the items folded into it with their arguments. +json menu_items(const NativeCommand& command) +{ + json out = json::array(); + if (command.has_own_action) + out.push_back({{"title", command.title}, + {"section", command.action_group.empty() ? command.group : command.action_group}, + {"args", json::object()}}); + if (command.actions.is_array()) + for (const json& action : command.actions) { + json item{{"title", action.value("title", std::string())}, + {"section", action.value("group", command.group)}, + {"args", action.value("args", json::object())}}; + if (const std::string input = action.value("input", std::string()); !input.empty()) + item["asks_for"] = {{"value", input}, {"argument", action.value("input_arg", input)}}; + out.push_back(std::move(item)); + } + return out; +} + +} // namespace + +std::optional parameter_class(const std::string& command, const std::string& path) +{ + if (const auto it = classes_by_path().find(command + "." + path); it != classes_by_path().end()) + return it->second; + const std::size_t dot = path.rfind('.'); + const std::string name = dot == std::string::npos ? path : path.substr(dot + 1); + if (const auto it = classes_by_name().find(name); it != classes_by_name().end()) + return it->second; + return std::nullopt; +} + +json command_manual(const NativeCommand& command) +{ + ManualBuilder builder{command, !is_plugin_operation(command)}; + const json& schema = command.input_schema; + json rules = json::array(); + json params = json::array(); + if (!schema.is_object() || (schema.contains("type") && schema["type"] != "object")) { + builder.complete = false; + } else { + json required = schema.value("required", json::array()); + // with_silent()'s two shapes: what the silent form requires once the call is not a person's. + std::map conditional; + const auto cond = schema.find("if"), then = schema.find("then"); + if (cond != schema.end() || then != schema.end()) { + const json needs = then != schema.end() && then->is_object() ? then->value("required", json()) : json(); + const bool shaped = cond != schema.end() && needs.is_array() && !needs.empty() && then->size() == 1; + if (shaped && *cond == json{{"minProperties", 1}}) { + rules.push_back("With any argument, " + names_text(needs) + (needs.size() == 1 ? " is" : " are") + " required."); + for (const json& n : needs) + conditional[n.get()] = "when any argument is given"; + } else if (const json forms = shaped && cond->size() == 1 && cond->contains("not") && (*cond)["not"].is_object() && + (*cond)["not"].size() == 1 ? + (*cond)["not"].value("enum", json()) : + json(); + forms.is_array()) { + std::string listed; + for (std::size_t i = 0; i < forms.size(); ++i) + listed += (i == 0 ? "" : i + 1 == forms.size() ? " or " : ", ") + forms[i].dump(); + rules.push_back("Unless the arguments are exactly " + listed + ", " + names_text(needs) + + (needs.size() == 1 ? " is" : " are") + " required."); + for (const json& n : needs) + conditional[n.get()] = "unless the arguments are exactly one of the forms rules gives"; + } else + builder.complete = false; + } + for (const auto& [key, value] : schema.items()) + if (key != "type" && key != "properties" && key != "required" && key != "additionalProperties" && key != "if" && + key != "then" && key != "description") + builder.complete = false; + if (const auto props = schema.find("properties"); props != schema.end() && props->is_object()) { + params = builder.fields(*props, required, std::string(), builder.classify); + for (json& p : params) + if (p.value("required", false) == false) + if (const auto c = conditional.find(p["name"].get()); c != conditional.end()) + p["required"] = c->second; + } + if (const auto other = schema.find("additionalProperties"); other != schema.end()) { + if (*other == false) + rules.push_back("No other arguments are accepted."); + else if (!other->is_boolean()) + builder.complete = false; + } + } + json out{{"name", command.key}, + {"title", command.title}, + {"group", command.group}, + {"listed", command.listed}, + {"call", command.listed ? command.key + " {args}" : "tool_call {tool: \"" + command.key + "\", args}"}, + {"access", + {{"read_only", command.read_only}, + {"destructive", command.destructive}, + {"idempotent", command.idempotent}, + {"open_world", command.open_world}}}, + {"description", command.description}, + {"parameters", std::move(params)}, + {"rules", std::move(rules)}, + {"menu_items", menu_items(command)}, + {"examples", command.examples.is_null() ? json::array() : command.examples}, + {"complete", builder.complete}}; + if (!command.heading.empty()) + out["heading"] = command.heading; + if (!builder.complete) + out["input_schema"] = schema; + return out; +} + +json describe_command(const CommandCatalog& catalog, const std::string& name) +{ + if (const std::shared_ptr def = catalog.lookup(name)) + return command_manual(*def); + throw ToolFailure(catalog.unknown_command(name), + {{"code", catalog.unknown_command_code(name)}, {"did_you_mean", catalog.similar(name)}}); +} + void register_plugin_operations(CommandCatalog& catalog) { // Plugin operations resolve by name, beside the catalog's commands, without being listed. @@ -337,6 +755,20 @@ void register_api_tools(CommandCatalog& catalog, const std::string& design_index return ToolResult::ok(std::move(out)); })); + catalog.add(inspect_tool( + "tool_describe", L("Describe a tool"), + "One command's manual, listed or not: a tool, a Design tab command, a menu item that takes no arguments, or an " + "operation a plugin offers (plugin..). It gives the description; every parameter, at every depth, " + "with its type, whether the schema requires it, its default, its allowed values or range, the type or target it " + "goes with, and values_from, the tools that list a value the schema can't; the schema's rules as sentences; the " + "Speed Dial items that run it, with their arguments; its examples; how to call it; and access, its read-only, " + "destructive, idempotent and open-world labels. What a handler requires or supplies beyond the schema is in the " + "description. A part of a schema it can't express is kept raw: complete is false and input_schema is the whole schema.", + object_schema({{"tool", prop("string", "A command's name.")}}, {"tool"}), + [](const json& args, ToolContext&) { + return ToolResult::ok(describe_command(NativeCommands::instance(), arg_string(args, "tool"))); + })); + // Dispatched before it runs (resolve_call): the call runs as the target's own, with its guard, // mode, budget and journal flag, and is journaled as the target's call. This handler is never reached. NativeCommand call = mutate_tool( diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index 06d1bbd40b..c973dd82b6 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -91,6 +91,34 @@ "read_only": true, "title": "Get app state" }, + { + "completion": "immediate", + "description": "One command's manual, listed or not: a tool, a Design tab command, a menu item that takes no arguments, or an operation a plugin offers (plugin..). It gives the description; every parameter, at every depth, with its type, whether the schema requires it, its default, its allowed values or range, the type or target it goes with, and values_from, the tools that list a value the schema can't; the schema's rules as sentences; the Speed Dial items that run it, with their arguments; its examples; how to call it; and access, its read-only, destructive, idempotent and open-world labels. What a handler requires or supplies beyond the schema is in the description. A part of a schema it can't express is kept raw: complete is false and input_schema is the whole schema.", + "destructive": false, + "group": "Tools and actions", + "guard": "inspect", + "has_own_action": false, + "idempotent": true, + "input_schema": { + "additionalProperties": false, + "properties": { + "tool": { + "description": "A command's name.", + "type": "string" + } + }, + "required": [ + "tool" + ], + "type": "object" + }, + "key": "tool_describe", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Describe a tool" + }, { "completion": "immediate", "description": "Search everything the Speed Dial can run: built-in commands (slice, export, views, object operations, plates, calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for action_run, its section (where the Speed Dial lists it), a description, the command's key for a built-in command, and, when it takes arguments, their input_schema. A query ranks them, best match first, as tool_search does; without one they are listed by section and title. section keeps them to one of the Speed Dial's sections, which are not tool_search's groups; one no action is in is refused with the sections there are, but Recent Projects and Design list nothing while there are no recent projects or the Design tab is not shown. include_settings also lists settings (each jumps to that setting in the sidebar; use settings_get / settings_set to read or change values).", diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index a9bb7f998d..baf81b9557 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -153,7 +153,7 @@ std::string first_difference(const std::string& actual, const std::string& expec // Print button's Print, the print host's test, and the Device tab's status, Pause, Resume and Stop). // A part that adds a command adds it here. const std::vector>> kPlaces{ - {"Tools and actions", {"tool_search", "tool_call", "action_search", "action_run"}}, + {"Tools and actions", {"tool_search", "tool_describe", "tool_call", "action_search", "action_run"}}, {"The app", {"app_state", "app_log", "app_wait", "job_cancel", "undo", "redo", "app_open_web_page", "app_check_for_updates", "app_show_config_folder", "app_benchmark_3d_scene", "preferences_get", "preferences_set"}}, @@ -455,9 +455,9 @@ TEST_CASE("outside the Design tab the catalog has its commands and 129 actions", } // The commands outside the Design tab: the typed tools, the commands made from menu items, the seven Parts 4a to 4c // add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four, the seven gizmo commands, the six printing - // commands and the four of the filament list (filament_list, filament_edit_mixed, filament_set_colour and - // filament_set_flushing). - CHECK(commands == 135); + // commands, the four of the filament list (filament_list, filament_edit_mixed, filament_set_colour and + // filament_set_flushing) and tool_describe. + CHECK(commands == 136); // The eight commands named as their menu items keep an action of their own; the other 121 actions are items. CHECK(own == std::set{"plate_add", "plate_delete", "plate_duplicate", "plate_rename", "filament_add", "filament_delete", "undo", "redo"}); @@ -484,7 +484,7 @@ TEST_CASE("the commands outside the Design tab are the design's, under its headi commands += keys.size(); } CHECK(by_heading.size() == kPlaces.size()); - CHECK(commands == 135); + CHECK(commands == 136); // tool_search's group says which there are. const NativeCommand* search = NativeCommands::find("tool_search"); @@ -525,8 +525,8 @@ TEST_CASE("every command that runs from arguments is in the tool list, by place" // The three menu items with no argument form, which tool_search finds and tool_call runs. CHECK(unlisted == std::set{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode"}); // Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four, the - // seven gizmo commands, the six printing commands and the filament list's four. - CHECK(listed.size() == 132); + // seven gizmo commands, the six printing commands, the filament list's four and tool_describe. + CHECK(listed.size() == 133); // The search, the generic call and the app's state first; then each heading's commands together, in the // design's order, Driving the GUI last. @@ -551,7 +551,7 @@ TEST_CASE("every command that runs from arguments is in the tool list, by place" TEST_CASE("only deleting a preset, uninstalling a plugin and stopping a print are labelled destructive", "[CommandCatalog]") { // The reads: they change nothing in the app or the project. - const std::set reads{"app_state", "app_wait", "app_log", "tool_search", + const std::set reads{"app_state", "app_wait", "app_log", "tool_search", "tool_describe", "preset_list", "settings_list", "settings_get", "preferences_get", "plate_get_settings", "project_get_settings", "plate_list", "object_list", "window_screenshot", "plate_slice_stats", "script_search_api", "action_search", diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index a514eaa5f4..88a21381f1 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -708,14 +709,14 @@ TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") CHECK(first_sentence(command->description) == r.first_sentence); } - // Outside the Design group 132 commands are listed: every one that runs from its arguments, all but the three menu + // Outside the Design group 133 commands are listed: every one that runs from its arguments, all but the three menu // items that take none (Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one, - // Part 5d's four, the seven gizmo commands, the six printing commands and the filament list's four). + // Part 5d's four, the seven gizmo commands, the six printing commands, the filament list's four and tool_describe). std::size_t listed = 0; for (const NativeCommand& c : catalog.commands()) if (c.listed && c.group != Slic3r::GUI::kDesignGroup) ++listed; - CHECK(listed == 132); + CHECK(listed == 133); } TEST_CASE("opening a project and importing models are two commands", "[Mcp]") @@ -993,6 +994,373 @@ TEST_CASE("tool_search finds a Design command by the name of a menu item folded } } +namespace { + +// The built-in commands with the Design tab's among them. +CommandCatalog catalog_with_cad() +{ + CommandCatalog catalog; + NativeCommands::register_all_commands(catalog, {true}); + catalog.seal(); + return catalog; +} + +bool lists_values(const json& schema) +{ + if (schema.contains("enum")) + return true; + const json type = schema.value("type", json()); + if (type.is_string()) + return type == "boolean"; + return type.is_array() && !type.empty() && + std::all_of(type.begin(), type.end(), [](const json& t) { return t == "boolean" || t == "null"; }); +} + +bool with_fields(const json& schema) +{ + return schema.contains("properties") || (schema.contains("items") && schema["items"].is_object() && schema["items"].contains("properties")); +} + +void check_shape(const json& param, const json& schema, const std::string& where); + +// That `params`, a manual's, follow `props`, the schema's properties they were made from, with `required`. +void check_parameters(const json& params, const json& props, const json& required, const std::string& where) +{ + REQUIRE(params.is_array()); + std::set named, in_schema; + for (const json& p : params) + named.insert(p.at("name").get()); + for (auto it = props.begin(); it != props.end(); ++it) + in_schema.insert(it.key()); + CHECK(named == in_schema); + for (const json& p : params) { + const std::string name = p.at("name").get(); + INFO(where + name); + check_shape(p, props.at(name), where + name); + if (std::find(required.begin(), required.end(), name) != required.end()) + CHECK(p.at("required") == true); + } +} + +void check_shape(const json& param, const json& schema, const std::string& where) +{ + INFO(where); + CHECK_FALSE(param.contains("schema")); + if (schema.contains("enum")) + CHECK(param.at("values") == schema["enum"]); + else + CHECK_FALSE(param.contains("values")); + if (schema.contains("default")) + CHECK(param.at("default") == schema["default"]); + else + CHECK_FALSE(param.contains("default")); + if (schema.contains("minimum")) + CHECK(param.at("min") == schema["minimum"]); + if (schema.contains("maximum")) + CHECK(param.at("max") == schema["maximum"]); + if (schema.contains("properties")) + check_parameters(param.at("properties"), schema["properties"], schema.value("required", json::array()), where + "."); + if (schema.contains("additionalProperties")) { + if (schema["additionalProperties"] == false) + CHECK(param.at("other_keys") == false); + else if (schema["additionalProperties"].is_object()) + CHECK(param.at("other_keys").is_object()); + } + if (schema.contains("items")) + check_shape(param.at("items"), schema["items"], where + "[]"); +} + +// Calls `f` with the path and schema of each parameter of `props` that has no fields of its own, at every depth. +void each_leaf(const json& props, const std::string& prefix, const std::function& f) +{ + for (auto it = props.begin(); it != props.end(); ++it) { + const std::string path = prefix + it.key(); + const json& schema = it.value(); + if (schema.contains("properties")) + each_leaf(schema["properties"], path + ".", f); + if (schema.contains("items") && schema["items"].is_object() && schema["items"].contains("properties")) + each_leaf(schema["items"]["properties"], path + "[].", f); + if (!with_fields(schema)) + f(path, schema); + } +} + +// The parameter at `path` (dotted, [] for an array's items) of `manual`, or nullptr. +const json* manual_parameter(const json& manual, const std::string& path) +{ + const json* params = &manual.at("parameters"); + std::size_t at = 0; + for (;;) { + const std::size_t end = path.find('.', at); + std::string segment = path.substr(at, end == std::string::npos ? std::string::npos : end - at); + const bool items = segment.size() > 2 && segment.compare(segment.size() - 2, 2, "[]") == 0; + if (items) + segment.resize(segment.size() - 2); + const json* found = nullptr; + for (const json& p : *params) + if (p.at("name") == segment) + found = &p; + if (found == nullptr || end == std::string::npos) + return found; + const json* holder = items ? (found->contains("items") ? &found->at("items") : nullptr) : found; + if (holder == nullptr || !holder->contains("properties")) + return nullptr; + params = &holder->at("properties"); + at = end + 1; + } +} + +json manual_of(const CommandCatalog& catalog, const char* key) +{ + const NativeCommand* command = catalog.find(key); + REQUIRE(command != nullptr); + return command_manual(*command); +} + +} // namespace + +TEST_CASE("tool_describe's manual follows every built-in command's schema at every depth", "[Mcp][CAD]") +{ + const CommandCatalog catalog = catalog_with_cad(); + std::size_t ruled = 0; + for (const NativeCommand& c : catalog.commands()) { + INFO(c.key); + const json manual = command_manual(c); + CHECK(manual.at("complete") == true); + CHECK_FALSE(manual.contains("input_schema")); + check_parameters(manual.at("parameters"), c.input_schema.value("properties", json::object()), + c.input_schema.value("required", json::array()), ""); + // One sentence per rule of with_silent()'s, and one for the arguments a closed schema refuses. + const json& rules = manual.at("rules"); + if (c.input_schema.contains("if")) { + ++ruled; + CHECK(std::count_if(rules.begin(), rules.end(), [](const json& r) { + const std::string text = r.get(); + return text.rfind("With any argument, ", 0) == 0 || text.rfind("Unless the arguments are exactly ", 0) == 0; + }) == 1); + } + if (c.input_schema.value("additionalProperties", true) == false) + CHECK(std::find(rules.begin(), rules.end(), "No other arguments are accepted.") != rules.end()); + CHECK(manual.at("examples") == (c.examples.is_null() ? json::array() : c.examples)); + CHECK(manual.at("menu_items").size() == (c.actions.is_array() ? c.actions.size() : 0) + (c.has_own_action ? 1 : 0)); + CHECK(manual.at("access").at("read_only") == c.read_only); + CHECK(manual.at("listed") == c.listed); + } + CHECK(ruled == 38); + + // A rule's requirement comes out in words on the parameter it makes required. + const json constrain = manual_of(catalog, "sketch_constrain"); + const json* type = manual_parameter(constrain, "type"); + REQUIRE(type != nullptr); + CHECK(type->at("required") == "when any argument is given"); + CHECK(constrain.at("rules")[0] == "With any argument, type is required."); + // A parameter tied to a target says so, and stays as the schema requires it: the handler asks for the rest. + const json set = manual_of(catalog, "settings_set"); + const json* min_z = manual_parameter(set, "min_z"); + REQUIRE(min_z != nullptr); + CHECK(min_z->at("goes_with") == json{{"target", "height_range"}}); + CHECK(min_z->at("required") == false); + // A nested object's own required fields and closure, and other keys' values. + const json cut = manual_of(catalog, "object_cut"); + const json* point = manual_parameter(cut, "plane.point"); + REQUIRE(point != nullptr); + CHECK(point->at("required") == true); + const json answer = manual_of(catalog, "dialog_auto_answer"); + const json* match = manual_parameter(answer, "rules[].match"); + REQUIRE(match != nullptr); + CHECK(match->at("required") == true); + const json view = manual_of(catalog, "view_set"); + const json* legend = manual_parameter(view, "legend"); + REQUIRE(legend != nullptr); + CHECK(legend->at("other_keys").at("type") == "boolean"); +} + +TEST_CASE("tool_describe's manual names a command's menu items with their arguments", "[Mcp]") +{ + const CommandCatalog catalog = catalog_with_cad(); + const json exports = manual_of(catalog, "project_export").at("menu_items"); + const auto gcode = std::find_if(exports.begin(), exports.end(), [](const json& i) { return i.at("title") == "Export G-code"; }); + REQUIRE(gcode != exports.end()); + CHECK(gcode->at("args") == json{{"format", "gcode"}}); + CHECK(gcode->at("section") == "Slice & Export"); + CHECK_FALSE(gcode->contains("asks_for")); + // An item that collects a value first says which, and the argument it goes to. + const json views = manual_of(catalog, "view_set").at("menu_items"); + const auto layer = std::find_if(views.begin(), views.end(), [](const json& i) { return i.at("title") == "Go to layer (percent)"; }); + REQUIRE(layer != views.end()); + CHECK(layer->at("asks_for") == json{{"value", "percent"}, {"argument", "layer_percent"}}); + const auto tab = std::find_if(views.begin(), views.end(), [](const json& i) { return i.at("title") == "Go to tab..."; }); + REQUIRE(tab != views.end()); + CHECK(tab->at("asks_for") == json{{"value", "tab"}, {"argument", "tab"}}); + // How to call it: by name when the tool list shows it, through tool_call when not. + CHECK(manual_of(catalog, "plate_slice").at("call") == "plate_slice {args}"); + CHECK(manual_of(catalog, "fillet").at("call") == "tool_call {tool: \"fillet\", args}"); +} + +TEST_CASE("every parameter of a built-in command is classified for the manual", "[Mcp][CAD]") +{ + const CommandCatalog catalog = catalog_with_cad(); + for (const NativeCommand& c : catalog.commands()) { + const json manual = command_manual(c); + each_leaf(c.input_schema.value("properties", json::object()), "", [&](const std::string& path, const json& schema) { + if (lists_values(schema)) + return; + INFO(c.key + "." + path); + const std::optional cls = parameter_class(c.key, path); + REQUIRE(cls.has_value()); + const json* param = manual_parameter(manual, path); + REQUIRE(param != nullptr); + if (cls->kind == ParameterClass::Source) + CHECK(param->at("values_from") == json(cls->tools)); + else + CHECK_FALSE(param->contains("values_from")); + }); + } + // The sources of names that mean different things in different commands, and of the contested ones. + const std::vector>> sources{ + {"tool_call.args", {"tool_describe"}}, + {"tool_call.tool", {"tools/list", "tool_search"}}, + {"action_run.id", {"action_search"}}, + {"action_run.args", {"action_search"}}, + {"settings_set.values", {"settings_list"}}, + {"project_set_settings.values", {"project_get_settings"}}, + {"preferences_set.values", {"preferences_get"}}, + {"settings_get.compare", {"preset_list"}}, + {"preset_select.name", {"preset_list"}}, + {"preset_list.vendor", {"preset_list"}}, + {"printer_install.models[].vendor", {"printer_list_models"}}, + {"job_cancel.job", {"app_state"}}, + {"dialog_answer.button", {"app_state"}}, + {"widget_click.popup_item", {"widget_click"}}, + {"fillet.edges", {"body_describe"}}, + {"sketch_constrain.entities", {"sketch_describe"}}, + {"rib.entity", {"sketch_describe"}}, + {"pattern.entity", {"sketch_describe"}}, + {"loft.profiles", {"describe_design"}}, + {"align.cs_a", {"describe_design"}}, + {"body_compare.reference", {"describe_design"}}, + {"view_set.layer", {"plate_slice_stats"}}, + {"view_set.layer_z", {"plate_slice_stats"}}, + {"plate_set_custom_gcode.add[].layer", {"plate_slice_stats"}}, + {"window_open.key", {"preferences_get"}}, + }; + for (const auto& [where, tools] : sources) { + INFO(where); + const std::size_t dot = where.find('.'); + const std::string command = where.substr(0, dot); + const json manual = manual_of(catalog, command.c_str()); + const json* param = manual_parameter(manual, where.substr(dot + 1)); + REQUIRE(param != nullptr); + CHECK(param->at("values_from") == json(tools)); + } + // The caller's own values name no source. + for (const char* where : {"script_run.args", "replay_run.vars", "keyboard_press.keys", "sketch_draw.entities", "preset_save.name"}) { + INFO(where); + const std::string w = where; + const std::size_t dot = w.find('.'); + const std::optional cls = parameter_class(w.substr(0, dot), w.substr(dot + 1)); + REQUIRE(cls.has_value()); + CHECK(cls->kind == ParameterClass::Free); + } + // A plugin's operation names its parameters itself: none is classified, whatever it is called. + NativeCommand operation; + operation.key = "plugin.fixture.measure"; + operation.input_schema = object_schema({{"object", prop("integer", "An object.")}}); + const json described = command_manual(operation); + const json* object = manual_parameter(described, "object"); + REQUIRE(object != nullptr); + CHECK_FALSE(object->contains("values_from")); +} + +TEST_CASE("tool_describe keeps raw what it can't express, and says the manual is not complete", "[Mcp]") +{ + const auto manual = [](json schema) { + NativeCommand operation; + operation.key = "plugin.fixture.op"; + operation.input_schema = std::move(schema); + return command_manual(operation); + }; + const json root_any = json::parse(R"({"type": "object", "properties": {"a": {"type": "number"}}, "anyOf": [{"required": ["a"]}]})"); + const json any_root = manual(root_any); + CHECK(any_root.at("complete") == false); + CHECK(any_root.at("input_schema") == root_any); + + const json sub = json::parse(R"({"anyOf": [{"type": "number"}, {"type": "string"}]})"); + const json any_sub = manual(json{{"type", "object"}, {"properties", {{"a", sub}}}}); + CHECK(any_sub.at("complete") == false); + CHECK(any_sub.at("parameters")[0].at("schema") == sub); + CHECK(any_sub.contains("input_schema")); + + const json defs = json::parse(R"({"type": "object", "$defs": {"n": {"type": "number"}}, "properties": {"a": {"$ref": "#/$defs/n"}}})"); + const json ref = manual(defs); + CHECK(ref.at("complete") == false); + CHECK(ref.at("input_schema").contains("$defs")); + + const json anything = manual(json::parse(R"({"type": "object", "properties": {"a": true}})")); + CHECK(anything.at("complete") == false); + CHECK(anything.at("parameters")[0].at("schema") == true); + + // A draft-04 exclusiveMinimum qualifies minimum: kept raw, beside the minimum it reads. + const json draft4 = manual(json::parse(R"({"type": "object", "properties": {"a": {"type": "number", "minimum": 0, "exclusiveMinimum": true}}})")); + CHECK(draft4.at("complete") == false); + CHECK(draft4.at("parameters")[0].at("min") == 0); + CHECK(draft4.at("parameters")[0].contains("schema")); + + // A rule of with_silent()'s shape reads its forms as the schema writes them, menu items or none. + const json forms = manual(json::parse(R"({"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "string"}}, + "if": {"not": {"enum": [{}, {"a": 1}]}}, "then": {"required": ["b"]}})")); + CHECK(forms.at("complete") == true); + CHECK(forms.at("rules") == json::array({"Unless the arguments are exactly {} or {\"a\":1}, b is required."})); + const json* b = manual_parameter(forms, "b"); + REQUIRE(b != nullptr); + CHECK(b->at("required") == "unless the arguments are exactly one of the forms rules gives"); +} + +TEST_CASE("tool_describe describes any command a lookup finds, and refuses a name with its reason", "[Mcp]") +{ + CommandCatalog catalog; + NativeCommand listed; + listed.key = "measure_bed"; + listed.listed = true; + catalog.add(listed); + NativeCommand operation; + operation.key = "plugin.fixture.measure"; + operation.group = "Plugins"; + operation.description = "Offered by a plugin. Doubles a."; + catalog.add_source(std::make_unique(operation)); + catalog.seal(); + CHECK(describe_command(catalog, "measure_bed").at("call") == "measure_bed {args}"); + const json described = describe_command(catalog, "plugin.fixture.measure"); + CHECK(described.at("group") == "Plugins"); + CHECK(described.at("listed") == false); + try { + describe_command(catalog, "measure_bedd"); + FAIL("an unknown tool was not refused"); + } catch (const ToolFailure& f) { + CHECK_THAT(std::string(f.what()), Catch::Matchers::StartsWith("Unknown tool: measure_bedd")); + CHECK(f.details.at("code") == "invalid_argument"); + CHECK(f.details.at("did_you_mean") == json::array({"measure_bed"})); + } +#ifdef SLIC3R_CAD + // A Design command that this run's catalog leaves out is refused with the reason a call of it gets. + for (const bool editor : {true, false}) { + INFO(editor); + CommandCatalog left_out; + NativeCommands::register_all_commands(left_out, {false, editor}); + left_out.seal(); + try { + describe_command(left_out, "fillet"); + FAIL("a left-out Design command was described"); + } catch (const ToolFailure& f) { + CHECK(std::string(f.what()) == left_out.unknown_command("fillet")); + CHECK(f.details.at("code") == "design_unavailable"); + CHECK_THAT(std::string(f.what()), + Catch::Matchers::ContainsSubstring(editor ? "the CAD feature was off" : "the G-code viewer has no Design tab")); + } + } +#endif +} + TEST_CASE("window_set refuses a request the window can't take, before changing anything", "[Mcp]") { WindowAbilities main; main.main = true;