From 3c6752abf91e06fd172928e5f11fde35c4a05d45 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Sun, 22 Nov 2026 18:08:23 +0800 Subject: [PATCH] Browse the Python API a module at a time with script_list_api and script_describe_api script_search_api ranked the API by an agent's words, so a goal phrased in other words found the wrong entries. Agents now list what a module or class holds with script_list_api and read one entry's whole documentation with script_describe_api. --- docs/HLSD/mcp-server.md | 13 ++- docs/HLSD/mcp-tools.md | 7 +- src/slic3r/GUI/Mcp/McpServerInfo.cpp | 2 +- src/slic3r/GUI/Mcp/McpTools.hpp | 15 ++- src/slic3r/GUI/Mcp/McpToolsApi.cpp | 2 + src/slic3r/GUI/Mcp/McpToolsPython.cpp | 129 ++++++++++++++------- tests/data/command_catalog.json | 41 ++++++- tests/slic3rutils/test_command_catalog.cpp | 16 +-- tests/slic3rutils/test_mcp_tools.cpp | 83 +++++++++++-- tests/slic3rutils/test_plugin_host_api.cpp | 4 +- tools/mcp/test-entries/commands.md | 5 +- tools/mcp/test_plugin_tools.py | 4 + 12 files changed, 234 insertions(+), 87 deletions(-) diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 5a03bf3a61..cbc765383d 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -269,7 +269,7 @@ window isn't being drawn when it isn't. | Class | Tools | Runs behind a modal or inside another call | |---|---|---| -| `Inspect` | app_state, app_wait, app_log, the lists (tool_list, action_list, object_list, plate_list, preset_list, settings_list, printer_list_models, plugin_list, window_list), the reads (tool_describe, settings_get, plate_get_settings, project_get_settings, preferences_get, plate_slice_stats, script_search_api), window_screenshot, widget_list, replay_export, recording_start, recording_stop, recording_encode | yes | +| `Inspect` | app_state, app_wait, app_log, the lists (tool_list, action_list, object_list, plate_list, preset_list, settings_list, printer_list_models, plugin_list, window_list), the reads (tool_describe, settings_get, plate_get_settings, project_get_settings, preferences_get, plate_slice_stats, script_list_api, script_describe_api), window_screenshot, widget_list, replay_export, recording_start, recording_stop, recording_encode | yes | | `Recover` | dialog_answer, dialog_auto_answer, job_cancel, GUI input aimed at the topmost modal, window_set | yes | | `Mutate` | everything else | no | @@ -4388,7 +4388,8 @@ agent's idle wait, and a `tools/mcp` driver run from the panel against the same partway; its tool calls are not journaled. In a replay a `script_run` step's `code` is never substituted, and a step whose outcome is not `finished` fails. -**The reference.** `script_search_api` serves the reference `python_api_reference()` builds from the running +**The reference.** `script_list_api` and `script_describe_api` serve the reference `python_api_reference()` builds +from the running build's `orca` package: `orca.host`, and the classes, events and pages plugins build on. It walks the modules and lists each public class, function, method, property, named instance (such as `orca.host.preset.process`) and constant (such as `orca.host.ui.PD_CAN_ABORT`) with its signature and @@ -4398,9 +4399,11 @@ where a module exports them. The documentation is the bindings' own docstrings, its constructors say of their arguments; a constant can't carry one, so its documentation names the entries whose documentation names it. The reference is only as good as the docstrings: a test requires every entry to have documentation, every constructor that takes arguments to say what they are, and every parameter a -name (pybind11 names an unnamed one `arg0`). A query ranks the -entries as the settings search does (`query_words()`, `match_score()`); without one the whole package is -listed with each entry's first sentence. The reply says whether numpy is installed, which the mesh and +name (pybind11 names an unnamed one `arg0`). `script_list_api {within}` lists the entries directly inside a +module or class, `orca` without one (`python_api_children()`), each with its documentation's first sentence, so +an agent walks the package a module at a time and picks what it reads; `script_describe_api {name}` gives one +entry whole (`python_api_entry()`), and a name no entry has is answered with the three closest. +`script_list_api`'s reply says whether numpy is installed, which the mesh and matrix arrays need and which the bundled Python lacks unless a file run's PEP 723 block installs it. ### Run Script panel diff --git a/docs/HLSD/mcp-tools.md b/docs/HLSD/mcp-tools.md index a4796a9034..2b79dd4989 100644 --- a/docs/HLSD/mcp-tools.md +++ b/docs/HLSD/mcp-tools.md @@ -278,7 +278,8 @@ them and `tool_call` runs them. | `replay_run` | Run a replay, a list of calls, and report each step | `path` or `replay`; `vars`, `out_dir` | | `replay_export` | Turn this session's calls into a replay | `path`, `overwrite`, `name`; `clear` | | `script_run` | Run Python inside the app as its main program, against the orca API | `code`; `args`, `filename`, `timeout_s` | -| `script_search_api` | Search the orca Python API of the running build | `query` | +| `script_list_api` | List the orca Python API of the running build, one module or class at a time | `within` | +| `script_describe_api` | Read one entry of the orca Python API whole: its kind, signature and documentation | `name` | | `script_toggle_panel` | Show or hide the Run Script panel; a menu item, not listed | | | `recording_start` | Record a video of the main window or the 3D view | `target`: main, canvas; `captions`, `pointer`; `max_seconds`, `fps`, `max_dim`; `encode` and the encoder's options; `save_path`, `overwrite` | | `recording_stop` | Stop the recording; with `silent: true`, wait for its file and report it | `silent` | @@ -653,10 +654,10 @@ Each command runs under a guard (mcp-server.md, Threading): Access labels, which `tools/list` sends as MCP's annotations (mcp-server.md, Tool catalog, says why each is set as it is): -- **read_only**, 23 commands: `tool_list`, `tool_describe`, `action_list`, `app_state`, `app_wait`, `app_log`, +- **read_only**, 24 commands: `tool_list`, `tool_describe`, `action_list`, `app_state`, `app_wait`, `app_log`, `preferences_get`, `project_get_settings`, `filament_list`, `object_list`, `plate_get_settings`, `plate_list`, `plate_slice_stats`, `preset_list`, `settings_list`, `settings_get`, `printer_list_models`, `printer_status`, - `plugin_list`, `window_list`, `window_screenshot`, `script_search_api` and `widget_list`. These are idempotent too, and so + `plugin_list`, `window_list`, `window_screenshot`, `script_list_api`, `script_describe_api` and `widget_list`. These are idempotent too, and so is `dialog_auto_answer`. - **destructive**, 3: `preset_delete` and `plugin_uninstall`, whose every call removes what a person made, with no undo, and `print_stop`, which ends a print with no question. diff --git a/src/slic3r/GUI/Mcp/McpServerInfo.cpp b/src/slic3r/GUI/Mcp/McpServerInfo.cpp index 4cf13c2cfb..8501ea4056 100644 --- a/src/slic3r/GUI/Mcp/McpServerInfo.cpp +++ b/src/slic3r/GUI/Mcp/McpServerInfo.cpp @@ -23,7 +23,7 @@ const char* kInstructions = "- During an operation (slicing, exporting, arranging, another job) other changes are refused: app_wait or " "job_cancel.\n" "- replay_export saves this session's calls as a replay that replay_run runs.\n" - "- script_run runs Python against orca.host, the plugin API (script_search_api searches it), to compute over " + "- script_run runs Python against orca.host, the plugin API (script_list_api lists it), to compute over " "meshes and settings and call tools (orca.host.tools); its file, program, thread and network use is restricted " "unless app_state.python.scripts_unrestricted.\n" "- tool_list lists the commands the tool list does not show (the Design tab's, menu items with no arguments, " diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index b9bb3f9fd2..33c37a7d03 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -277,7 +277,7 @@ std::string to_config_string(const nlohmann::json& value, const std::string& key // ---- Python (McpToolsPython.cpp) ------------------------------------------------------------- -// script_search_api's reference: every public module, class, function, method, property, named instance (such +// The Python API reference script_list_api and script_describe_api read: every public module, class, function, method, property, named instance (such // as orca.host.preset.process) and constant (such as orca.host.ui.PD_CAN_ABORT) of the orca package, in // the order the package lists them, each {name, kind, signature, doc}. signature holds the signature lines // pybind11 starts a docstring with (a class's are its constructors, joined with " | "), and doc the rest @@ -287,9 +287,16 @@ std::string to_config_string(const nlohmann::json& value, const std::string& key // the package can't be read. nlohmann::json python_api_reference(); -// The entries of python_api_reference() that `query` describes, best first: those matching more of its -// words (in the name, signature or doc), then those matching more of them in their name. -nlohmann::json rank_python_api(const nlohmann::json& reference, const std::string& query); +// The module script_list_api lists without `within`. +inline constexpr const char* kPythonApiRoot = "orca"; +// script_list_api's items: the entries of `reference` (python_api_reference()) directly inside `within`, a module's or a +// class's dotted name (a module's modules, classes, functions, constants and named instances; a class's methods and +// properties), in the reference's order, each {name, kind, signature, summary}, the summary its doc's first sentence. +// ToolFailure (invalid_argument) with the package's `modules` when `within` names no module or class. Any thread. +nlohmann::json python_api_children(const nlohmann::json& reference, const std::string& within); +// script_describe_api's answer: the entry of `reference` called `name`, else ToolFailure (invalid_argument) with the three +// closest names by edit distance under `did_you_mean`. Any thread. +nlohmann::json python_api_entry(const nlohmann::json& reference, const std::string& name); // Whether numpy is installed in OrcaSlicer's Python, which the mesh and matrix arrays of orca.host need. // Takes the GIL, as python_api_reference() does. diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index d7e93d6994..47766a4702 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -183,6 +183,8 @@ const std::map& classes_by_path() {"action_run.id", source({"action_list"})}, {"action_run.args", source({"action_list"})}, {"action_list.section", source({"action_list"})}, + {"script_list_api.within", source({"script_list_api"})}, + {"script_describe_api.name", source({"script_list_api"})}, {"script_run.args", kFree}, {"replay_run.vars", kFree}, // Settings and preferences: the keys a tool takes are those its reader lists. diff --git a/src/slic3r/GUI/Mcp/McpToolsPython.cpp b/src/slic3r/GUI/Mcp/McpToolsPython.cpp index 75a6597015..9b1a22e7b9 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPython.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsPython.cpp @@ -1,5 +1,5 @@ -// script_run and script_search_api: Python scripts against orca.host, the plugin API, and the orca package's -// reference. +// script_run, script_list_api and script_describe_api: Python scripts against orca.host, the plugin API, and the orca +// package's reference, read one module or class at a time. #include "JobRegistry.hpp" #include "McpArguments.hpp" @@ -22,6 +22,7 @@ #include "slic3r/plugin/PythonSession.hpp" #include "slic3r/plugin/host/PluginHostTools.hpp" +#include #include #include @@ -228,22 +229,52 @@ json python_api_reference() } } -json rank_python_api(const json& reference, const std::string& query) +json python_api_children(const json& reference, const std::string& within) { - const std::vector words = query_words(query); - std::vector, std::size_t>> scored; - for (std::size_t i = 0; i < reference.size(); ++i) { - const json& e = reference[i]; - const std::pair score = match_score(words, e["name"].get(), - e["signature"].get() + '\n' + e["doc"].get()); - if (score.first > 0) - scored.emplace_back(score, i); + const auto is_scope = [&within](const json& e) { + return e["name"] == within && (e["kind"] == "module" || e["kind"] == "class"); + }; + if (std::none_of(reference.begin(), reference.end(), is_scope)) { + json modules = json::array(); + std::string names; + for (const json& e : reference) + if (e["kind"] == "module") { + modules.push_back(e["name"]); + names += (names.empty() ? "" : ", ") + e["name"].get(); + } + throw ToolFailure(within + " is no module or class of the orca package; its modules are " + names, + {{"code", "invalid_argument"}, {"modules", std::move(modules)}}); } - std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); - json out = json::array(); - for (const auto& [score, i] : scored) - out.push_back(reference[i]); - return out; + // An entry is directly inside `within` when its name is `within`, a dot and one more part. + const std::string prefix = within + '.'; + json items = json::array(); + for (const json& e : reference) { + const std::string& name = e["name"].get_ref(); + if (boost::algorithm::starts_with(name, prefix) && name.find('.', prefix.size()) == std::string::npos) + items.push_back({{"name", name}, {"kind", e["kind"]}, {"signature", e["signature"]}, + {"summary", first_sentence(e["doc"].get())}}); + } + return items; +} + +json python_api_entry(const json& reference, const std::string& name) +{ + std::vector> scored; // {distance, index}, the reference's order among equals + for (std::size_t i = 0; i < reference.size(); ++i) { + const std::string& candidate = reference[i]["name"].get_ref(); + if (candidate == name) + return reference[i]; + scored.emplace_back(edit_distance(name, candidate), i); + } + std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + json closest = json::array(); + std::string names; + for (std::size_t i = 0; i < scored.size() && closest.size() < 3; ++i) { + closest.push_back(reference[scored[i].second]["name"]); + names += (names.empty() ? "" : ", ") + closest.back().get(); + } + throw ToolFailure("No entry " + name + " in the orca package; the closest are " + names, + {{"code", "invalid_argument"}, {"did_you_mean", std::move(closest)}}); } bool python_has_numpy() @@ -341,10 +372,10 @@ void register_python_tools(CommandCatalog& catalog) NativeCommand run = mutate_tool( "script_run", L("Run a Python script"), "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin " - "API (script_search_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset " + "API (script_list_api lists it): read objects, meshes and settings, compute, use orca.host.ui and the preset " "API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args). Mesh and " "matrix arrays need numpy, which " - "script_search_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker " + "script_list_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker " "thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon " "threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` " "to a JSON value to return it; print() output comes back as output. Reply: {status: finished | raised | cancelled | " @@ -417,35 +448,45 @@ void register_python_tools(CommandCatalog& catalog) run.open_world = true; catalog.add(run); + // Both read the package as Python runs it now, holding its runtime for the read as script_run does. + const auto while_python_runs = [](const auto& read) { + if (!PythonInterpreter::instance().is_initialized()) + throw ToolFailure("Python is not available in this OrcaSlicer"); + PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); + if (!lease) + throw ToolFailure("Python is shutting down"); + return read(); + }; catalog.add(inspect_tool( - "script_search_api", L("Search the Python API"), - "Search orca, the Python API of script_run scripts and plugins, in the running build: orca.host (the project's " - "model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools " - "calling these tools) and the classes, events and pages plugins build on. Each entry has its kind, signature (a " - "class's constructors) and documentation. A query ranks them, best match first; without one, the whole package is " - "listed with each entry's first sentence. Page with offset. numpy says whether numpy is installed, which mesh and " - "matrix arrays need.", - object_schema({{"query", prop("string", "A few words, such as \"mesh normals\" or \"preset value\".")}, + "script_list_api", L("List the Python API"), + "List orca, the Python API of script_run scripts and plugins, in the running build, one module or class at a time: " + "orca.host (the project's model and meshes, presets and their editors, slicing data, orca.host.ui windows and " + "dialogs, orca.host.tools calling these tools) and the classes, events and pages plugins build on. It lists what is " + "directly inside within, a module or a class (default orca): each entry's name, kind, signature (a class's " + "constructors) and the first sentence of its documentation. A module or class it lists is listed with within set " + "to its name, and script_describe_api {name} gives an entry's whole documentation. Page with offset. numpy says " + "whether numpy is installed, which mesh and matrix arrays need.", + object_schema({{"within", {{"type", "string"}, {"default", kPythonApiRoot}, + {"description", "A module's or class's dotted name, e.g. \"orca.host\" or " + "\"orca.host.TriangleMesh\"."}}}, {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many (default 20)."}}}, {"offset", {{"type", "integer"}, {"minimum", 0}}}}), - [](const json& args, ToolContext&) { - if (!PythonInterpreter::instance().is_initialized()) - throw ToolFailure("Python is not available in this OrcaSlicer"); - PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); - if (!lease) - throw ToolFailure("Python is shutting down"); - const json reference = python_api_reference(); - const std::string query = arg_string(args, "query"); - json items = json::array(); - if (query.empty()) { - for (const json& e : reference) - items.push_back({{"name", e["name"]}, {"kind", e["kind"]}, {"signature", e["signature"]}, - {"summary", first_sentence(e["doc"].get())}}); - } else - items = rank_python_api(reference, query); - json out = page(items, args, 20); - out["numpy"] = python_has_numpy(); - return ToolResult::ok(std::move(out)); + [while_python_runs](const json& args, ToolContext&) { + return ToolResult::ok(while_python_runs([&args] { + json out = page(python_api_children(python_api_reference(), arg_string(args, "within", kPythonApiRoot)), args, 20); + out["numpy"] = python_has_numpy(); + return out; + })); + })); + catalog.add(inspect_tool( + "script_describe_api", L("Describe a Python API entry"), + "Read one entry of orca, the Python API of script_run scripts and plugins, by its dotted name as script_list_api " + "lists it (orca.host.TriangleMesh.face_normals): its kind, its signature (a class's constructors) and its whole " + "documentation. A name no entry has is refused with the closest names.", + object_schema({{"name", prop("string", "An entry's dotted name, as script_list_api lists it.")}}, {"name"}), + [while_python_runs](const json& args, ToolContext&) { + return ToolResult::ok( + while_python_runs([&args] { return python_api_entry(python_api_reference(), arg_string(args, "name")); })); })); // The Run Script panel's menu item, which has no argument form. diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index ec31787a94..56d600d1d5 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -7905,7 +7905,7 @@ }, { "completion": "immediate", - "description": "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin API (script_search_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args). Mesh and matrix arrays need numpy, which script_search_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` to a JSON value to return it; print() output comes back as output. Reply: {status: finished | raised | cancelled | timed_out, result, output, traceback?, message?}; a script that raised changed what it changed before. The code's own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises PermissionError, unless a person has let Python scripts run unrestricted in Preferences (app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while the run lasts; the tools it calls work as they do for you. Recorded by replay_export as one step with its code, which a replay runs again against the project as it is then.", + "description": "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin API (script_list_api lists it): read objects, meshes and settings, compute, use orca.host.ui and the preset API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args). Mesh and matrix arrays need numpy, which script_list_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` to a JSON value to return it; print() output comes back as output. Reply: {status: finished | raised | cancelled | timed_out, result, output, traceback?, message?}; a script that raised changed what it changed before. The code's own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises PermissionError, unless a person has let Python scripts run unrestricted in Preferences (app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while the run lasts; the tools it calls work as they do for you. Recorded by replay_export as one step with its code, which a replay runs again against the project as it is then.", "destructive": false, "group": "Recordings, replays and scripts", "guard": "mutate", @@ -7947,7 +7947,7 @@ }, { "completion": "immediate", - "description": "Search orca, the Python API of script_run scripts and plugins, in the running build: orca.host (the project's model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools calling these tools) and the classes, events and pages plugins build on. Each entry has its kind, signature (a class's constructors) and documentation. A query ranks them, best match first; without one, the whole package is listed with each entry's first sentence. Page with offset. numpy says whether numpy is installed, which mesh and matrix arrays need.", + "description": "List orca, the Python API of script_run scripts and plugins, in the running build, one module or class at a time: orca.host (the project's model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools calling these tools) and the classes, events and pages plugins build on. It lists what is directly inside within, a module or a class (default orca): each entry's name, kind, signature (a class's constructors) and the first sentence of its documentation. A module or class it lists is listed with within set to its name, and script_describe_api {name} gives an entry's whole documentation. Page with offset. numpy says whether numpy is installed, which mesh and matrix arrays need.", "destructive": false, "group": "Recordings, replays and scripts", "guard": "inspect", @@ -7966,19 +7966,48 @@ "minimum": 0, "type": "integer" }, - "query": { - "description": "A few words, such as \"mesh normals\" or \"preset value\".", + "within": { + "default": "orca", + "description": "A module's or class's dotted name, e.g. \"orca.host\" or \"orca.host.TriangleMesh\".", "type": "string" } }, "type": "object" }, - "key": "script_search_api", + "key": "script_list_api", "listed": true, "open_world": false, "operations": [], "read_only": true, - "title": "Search the Python API" + "title": "List the Python API" + }, + { + "completion": "immediate", + "description": "Read one entry of orca, the Python API of script_run scripts and plugins, by its dotted name as script_list_api lists it (orca.host.TriangleMesh.face_normals): its kind, its signature (a class's constructors) and its whole documentation. A name no entry has is refused with the closest names.", + "destructive": false, + "group": "Recordings, replays and scripts", + "guard": "inspect", + "has_own_action": false, + "idempotent": true, + "input_schema": { + "additionalProperties": false, + "properties": { + "name": { + "description": "An entry's dotted name, as script_list_api lists it.", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "key": "script_describe_api", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "Describe a Python API entry" }, { "actions": [ diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index 8f3752cc6a..10ddf6c234 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -144,7 +144,7 @@ std::string first_difference(const std::string& actual, const std::string& expec } // The design's command set outside the Design tab, heading by heading in the order tools/list gives them, Driving the -// GUI last, after the Design tab's commands: the 131 commands of the catalog, its typed tools, the commands made from +// GUI last, after the Design tab's commands: the 137 commands of the catalog, its typed tools, the commands made from // menu items, the seven Parts 4a to 4c add (Printable, Fix Model, Auto Drop, Clone, Reload from disk, Replace 3D file, // Add Mixed Filament), the three of Part 5a (the Printer Selection dialog's list, install and uninstall), the two of // Part 5b (the System Filaments dialog's install and uninstall), Part 5c's write of the Preferences dialog's preferences @@ -182,7 +182,7 @@ const std::vector>> kPlaces{ {"Plugins", {"plugin_list", "plugin_install_local", "plugin_enable", "plugin_reload", "plugin_uninstall", "plugin_refresh"}}, {"View and windows", {"view_set", "window_list", "window_set", "window_open"}}, {"Recordings, replays and scripts", - {"script_search_api", "window_screenshot", "recording_start", "recording_stop", "recording_encode", "replay_run", "replay_export", + {"script_list_api", "script_describe_api", "window_screenshot", "recording_start", "recording_stop", "recording_encode", "replay_run", "replay_export", "script_run", "window_save_screenshot", "script_toggle_panel"}}, {"Driving the GUI", {"widget_list", "widget_click", "widget_set_value", "keyboard_press", "mouse_gesture", "webview_run_javascript", "dialog_answer", @@ -456,8 +456,8 @@ 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, the four of the filament list (filament_list, filament_edit_mixed, filament_set_colour and - // filament_set_flushing) and tool_describe. - CHECK(commands == 136); + // filament_set_flushing), tool_describe and script_describe_api. + CHECK(commands == 137); // 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 == 136); + CHECK(commands == 137); // tool_list's group says which there are. const NativeCommand* list = NativeCommands::find("tool_list"); @@ -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_list lists 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, the filament list's four and tool_describe. - CHECK(listed.size() == 133); + // seven gizmo commands, the six printing commands, the filament list's four, tool_describe and script_describe_api. + CHECK(listed.size() == 134); // The listing of the other commands, the manual, the generic call and the app's state first; then each heading's // commands together, in the design's order, Driving the GUI last. @@ -554,7 +554,7 @@ TEST_CASE("only deleting a preset, uninstalling a plugin and stopping a print ar const std::set reads{"app_state", "app_wait", "app_log", "tool_list", "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_list", + "window_screenshot", "plate_slice_stats", "script_list_api", "script_describe_api", "action_list", "window_list", "widget_list", "printer_list_models", "plugin_list", "printer_status", "filament_list"}; // The commands made from menu items whose item reaches a printer, the cloud account or the network. diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 2ac82e0da3..efe964c826 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -556,8 +556,10 @@ TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") CHECK(catalog.find("tool_search") == nullptr); // The action search is action_list, a listing with no query, under no other name. CHECK(catalog.find("action_search") == nullptr); + // The Python API's search is script_list_api and script_describe_api, under no other name. + CHECK(catalog.find("script_search_api") == nullptr); - // Each of the 40 under its name, listed, the first sentence of its description pinned (the commands that sentence + // Each of the 39 under its name, listed, the first sentence of its description pinned (the commands that sentence // names under their names too). struct Renamed { @@ -620,12 +622,8 @@ TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") "and recording paths moved under ${out_dir}."}, {"run_script", "script_run", "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin API " - "(script_search_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset API, and call " + "(script_list_api lists it): read objects, meshes and settings, compute, use orca.host.ui and the preset API, and call " "these same tools, with their guards and undo, through orca.host.tools.call(name, args)."}, - {"search_python_api", "script_search_api", - "Search orca, the Python API of script_run scripts and plugins, in the running build: orca.host (the project's model and " - "meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools calling these tools) and " - "the classes, events and pages plugins build on."}, {"answer_dialog", "dialog_answer", "Press a button of the topmost modal dialog: yes, no, ok, cancel, close, apply, a button's " "label, or a numeric id."}, {"auto_answer_dialogs", "dialog_auto_answer", "Answer modal dialogs automatically when their title or message matches a rule's " @@ -670,7 +668,7 @@ TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") {"run_javascript", "webview_run_javascript", "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, " "dialogs, plugin windows)."}, }; - REQUIRE(std::size(renamed) == 40); + REQUIRE(std::size(renamed) == 39); for (const Renamed& r : renamed) { INFO(r.retired << " is " << r.name); CHECK(std::find(kRetiredTools.begin(), kRetiredTools.end(), r.retired) != kRetiredTools.end()); @@ -680,14 +678,15 @@ TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") CHECK(first_sentence(command->description) == r.first_sentence); } - // Outside the Design group 133 commands are listed: every one that runs from its arguments, all but the three menu + // Outside the Design group 134 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, the filament list's four and tool_describe). + // Part 5d's four, the seven gizmo commands, the six printing commands, the filament list's four, tool_describe and + // script_describe_api). std::size_t listed = 0; for (const NativeCommand& c : catalog.commands()) if (c.listed && c.group != Slic3r::GUI::kDesignGroup) ++listed; - CHECK(listed == 133); + CHECK(listed == 134); } TEST_CASE("opening a project and importing models are two commands", "[Mcp]") @@ -706,7 +705,7 @@ TEST_CASE("opening a project and importing models are two commands", "[Mcp]") CHECK_FALSE(import_->input_schema["properties"].contains("as")); } -TEST_CASE("script_search_api's reference covers the orca package with constructors and named instances", "[Mcp][Python]") +TEST_CASE("the Python API reference covers the orca package with constructors and named instances", "[Mcp][Python]") { (void) import_orca_module(); const json reference = python_api_reference(); @@ -754,8 +753,68 @@ TEST_CASE("script_search_api's reference covers the orca package with constructo REQUIRE(by_name.count("orca.register_operation") == 1); CHECK(by_name["orca.register_operation"]["signature"].get().find("schema: object = None, handler: object = None") != std::string::npos); +} - CHECK(rank_python_api(reference, "mesh normals")[0]["name"] == "orca.host.TriangleMesh.face_normals"); +TEST_CASE("script_list_api lists a module or class at a time and script_describe_api gives one entry", "[Mcp][Python]") +{ + (void) import_orca_module(); + const json reference = python_api_reference(); + const auto names_in = [&reference](const std::string& within) { + std::set names; + for (const json& item : python_api_children(reference, within)) + names.insert(item["name"].get()); + return names; + }; + // The details of the refusal `call` throws, or null when it throws none. + const auto refusal = [](const std::function& call) -> json { + try { + call(); + } catch (const ToolFailure& refused) { + return refused.details; + } + return nullptr; + }; + + // A class's methods and properties, each with its signature and the first sentence of its documentation. + const std::set mesh = names_in("orca.host.TriangleMesh"); + CHECK(mesh.count("orca.host.TriangleMesh.face_normals") == 1); + const json items = python_api_children(reference, "orca.host.TriangleMesh"); + const auto normals = std::find_if(items.begin(), items.end(), + [](const json& item) { return item["name"] == "orca.host.TriangleMesh.face_normals"; }); + REQUIRE(normals != items.end()); + const json entry = python_api_entry(reference, "orca.host.TriangleMesh.face_normals"); + CHECK(*normals == json{{"name", "orca.host.TriangleMesh.face_normals"}, {"kind", entry["kind"]}, {"signature", entry["signature"]}, + {"summary", first_sentence(entry["doc"].get())}}); + // Only what is directly inside: orca lists its modules and classes, not what they hold. + const std::set root = names_in(kPythonApiRoot); + CHECK(root.count("orca.host") == 1); + CHECK(root.count("orca.pages") == 1); + CHECK(root.count("orca.host.TriangleMesh") == 0); + CHECK(names_in("orca.host").count("orca.host.TriangleMesh") == 1); + // The listing a call without within gives is orca's. + const NativeCommand* list = NativeCommands::find("script_list_api"); + REQUIRE(list != nullptr); + CHECK(list->input_schema.at("properties").at("within").at("default") == json(kPythonApiRoot)); + + // A within that is no module or class, a function's name among them, is refused with the package's modules. + for (const std::string within : {"orca.nothing", "orca.register_operation"}) { + INFO(within); + const json refused = refusal([&] { (void) python_api_children(reference, within); }); + REQUIRE(refused.is_object()); + CHECK(refused.value("code", std::string()) == "invalid_argument"); + const json& modules = refused.at("modules"); + CHECK(std::find(modules.begin(), modules.end(), json("orca.host")) != modules.end()); + CHECK(std::find(modules.begin(), modules.end(), json("orca.host.TriangleMesh")) == modules.end()); + } + + // script_describe_api gives the whole entry, its documentation whole, and a name no entry has its three closest. + CHECK(entry["doc"].get().size() >= (*normals)["summary"].get().size()); + CHECK(entry.contains("doc")); + const json misspelt = refusal([&] { (void) python_api_entry(reference, "orca.host.TriangleMesh.face_normal"); }); + REQUIRE(misspelt.is_object()); + CHECK(misspelt.value("code", std::string()) == "invalid_argument"); + REQUIRE(misspelt.at("did_you_mean").size() == 3); + CHECK(misspelt.at("did_you_mean").front() == "orca.host.TriangleMesh.face_normals"); } TEST_CASE("no description starts with a bracketed tag", "[Mcp]") diff --git a/tests/slic3rutils/test_plugin_host_api.cpp b/tests/slic3rutils/test_plugin_host_api.cpp index bd481126b3..40b882a577 100644 --- a/tests/slic3rutils/test_plugin_host_api.cpp +++ b/tests/slic3rutils/test_plugin_host_api.cpp @@ -702,7 +702,7 @@ except tools.ToolError as error: REQUIRE_FALSE(close.empty()); CHECK(close.front() == "app_state"); - // script_search_api documents both, as it does every function of the package. + // script_describe_api documents both, as it does every function of the package. std::set documented; for (const nlohmann::json& entry : Slic3r::GUI::Mcp::python_api_reference()) if (entry["kind"] == "function" && !entry["doc"].get().empty()) @@ -713,7 +713,7 @@ except tools.ToolError as error: TEST_CASE("every public member of the orca package has documentation and named parameters", "[PluginHost][Python]") { - // script_search_api serves this documentation to agents writing scripts and plugins: a member without it, or + // script_list_api and script_describe_api serve this documentation to agents writing scripts and plugins: a member without it, or // with a parameter pybind11 names argN, is one they can only guess at. A constant's documentation is // the documentation that names it, and a class's goes on with what its constructors say; an enum's // constructor takes one of the values its documentation lists. diff --git a/tools/mcp/test-entries/commands.md b/tools/mcp/test-entries/commands.md index 1ef6a0918b..cf80e83184 100644 --- a/tools/mcp/test-entries/commands.md +++ b/tools/mcp/test-entries/commands.md @@ -232,9 +232,9 @@ An action is its command run with fixed arguments as a person's pick, and `actio **Strength:** Strong — each command's reply and the resulting `plugin_list`, files and window rows are compared exactly. ## `test_plugin_tools` -`test_plugin_tools.py` · Python, 31 checks +`test_plugin_tools.py` · Python, 33 checks -**Tests:** A plugin's side of the MCP tools, with `mcp_tools_fixture` side-loaded (enabled, 5 capabilities, thread permission) and `mcp_tools_broken`, whose `get_default_config` raises after it registered `measure`. Covers the fixture's `measure` operation through `tool_list`, `tool_describe` and `tool_call`, its five scripts, which `action_list` lists as its Speed Dial actions, calling tools from the Script worker and a thread, setting an auto-answer rule owned by the plugin, being refused `replay_export`, keeping a progress-dialog handle, and receiving NewProject events. Also covers `tool_list` and `tool_describe` on the menu items with no argument form, a group and the Design commands, unloading via the Plugins dialog (operation and rule withdrawn), and a `--run` launch without MCP where the rule script still runs. +**Tests:** A plugin's side of the MCP tools, with `mcp_tools_fixture` side-loaded (enabled, 5 capabilities, thread permission) and `mcp_tools_broken`, whose `get_default_config` raises after it registered `measure`. Covers the fixture's `measure` operation through `tool_list`, `tool_describe` and `tool_call`, its five scripts, which `action_list` lists as its Speed Dial actions, calling tools from the Script worker and a thread, setting an auto-answer rule owned by the plugin, being refused `replay_export`, keeping a progress-dialog handle, and receiving NewProject events. Also covers `tool_list` and `tool_describe` on the menu items with no argument form, a group and the Design commands, the Python API through `script_list_api` and `script_describe_api`, unloading via the Plugins dialog (operation and rule withdrawn), and a `--run` launch without MCP where the rule script still runs. **Starts from:** a data folder of its own, not a job's: a new temporary folder with the two plugins side-loaded into it before the first launch, `orca_mcp.py launch --cad` on a port nothing listens on, which seeds it with the default printer, the Generic Klipper Printer 0.4; no check reads a preset. Its plugins are the only ones there. The `--run` launch starts the binary on the same folder, after the first app has stopped (`orca_mcp.py stop` returns once it has exited) and the fixture's install state has been written enabled again. @@ -246,6 +246,7 @@ An action is its command run with fixed arguments as a person's pick, and `actio - Fixture scripts (outcome JSON read from the plugin's storage folder, waited for up to 60 s, since a script runs on its own after `action_run` has replied): `call` and `thread` == `{"ok": true, "result": true}`, `rule` == `{"ok": true, "result": "plugin"}` (both with MCP and under `--run`), `export` gives `ok` false with "agent's session", and a separate script's `handle.update(5)` returns true. - Progress dialog: "the plugin opens a progress dialog and keeps its handle": the `handle` script's outcome has `ok` true, and `window_list` lists a window titled `MCP tools fixture`, the title the script gives `create_progress_dialog`. - Menu items and groups: `tool_list` lists `settings_toggle_developer_mode` and `script_toggle_panel`, each with `does` equal to the `description` `tool_describe` gives it; `tool_describe {tool: "script_toggle_panel"}` gives `listed` false and no parameters; `tool_list {group: "objects"}` gives no items and a note naming tools/list; an unknown group is refused with code `invalid_argument`, naming "Design". +- Python API: `script_list_api {within: "orca.host.TriangleMesh"}` lists `orca.host.TriangleMesh.face_normals`, and `script_describe_api {name: "orca.host.TriangleMesh.face_normals"}` gives a non-empty `doc`. - Design commands: "the Design tab is on (launch --cad)" reads `app_state.design_tab` true, and then `tool_list {group: "design"}` lists `extrude` with heading "Solid". - A menu item's command: with Prepare shown, "tool_call runs a menu item's command" calls `script_toggle_panel` and waits up to 30 s for the 3D view's height in `widget_list` (its `name=OrcaSceneCanvas` line) to be less than before the call, as the Run Script panel docks under it; "and a second call hides it" waits up to 30 s for it to be greater than after the first call. - Events and journal: `new_projects.txt` gains exactly 1 line per `project_new` and per `new_project` action, each waited for up to 30 s. Before the `rule` script runs, the agent calls `dialog_auto_answer {rules: []}` itself (it clears only the rules MCP clients set). "a plugin's calls are not in the agent's journal": `replay_export`'s steps hold exactly one `dialog_auto_answer` step, the agent's, with `rules` `[]`; the plugin's call of the same tool is not there. diff --git a/tools/mcp/test_plugin_tools.py b/tools/mcp/test_plugin_tools.py index 5a16b2fb88..d3aef356d0 100644 --- a/tools/mcp/test_plugin_tools.py +++ b/tools/mcp/test_plugin_tools.py @@ -186,6 +186,10 @@ def main(): objects = orca.call("tool_list", group="objects") check("a group the tool list shows whole lists nothing, in any case, and says so", objects.get("items") == [] and "tools/list" in objects.get("note", ""), objects) + mesh = [i["name"] for i in orca.call("script_list_api", within="orca.host.TriangleMesh", limit=200)["items"]] + check("script_list_api lists a class's members", "orca.host.TriangleMesh.face_normals" in mesh, mesh) + normals = orca.call("script_describe_api", name="orca.host.TriangleMesh.face_normals") + check("script_describe_api gives an entry's documentation", bool(normals.get("doc")), normals) unknown = orca.call_raw("tool_list", {"group": "commandz"}) check("a group no command has is refused, naming the groups there are", unknown.get("isError") and '"code":"invalid_argument"' in unknown["content"][0]["text"] and