Files
OrcaSlicer/src/slic3r/GUI/Mcp/McpToolsApp.cpp
T
SoftFever fece418ae0 Make the automation runtime its own subsystem, with MCP as one front end
Everything that drives OrcaSlicer by command (the dispatch of the command
catalog, jobs, the journal, replays, Python scripts, recordings) lived
inside the MCP server's service class. So Action Replay, the Run Script
panel, a plugin's tool call, a person's recording and a run from the
command line each had to start "the MCP service", with all of its GUI
hooks, although none of them needs a server or an agent.

The automation runtime is now a subsystem of its own. It starts the first
time a front end asks for it and knows none of them. The MCP endpoint
(HTTP, the protocol, the token, the discovery file, the takeover of a port
another window holds) is one front end beside the others, opened and
closed without stopping what the others run. The widget inspector, menu
capture and ImGui item recording are turned on only by a front end that
drives the GUI, so a person's recording or long command does not carry
them.

The part of the runtime that needs no GUI is the library
libslic3r_automation, built without wxWidgets and tested by its own suite,
automation_tests. A wx dependency in it fails to build, and its tests no
longer link the GUI library or the embedded Python.

The command line has one option set for this: --run FILE runs a replay or
a Python script once the GUI is ready, with --outputdir for its files, and
--unrestricted-scripts and --cad turn their settings on for one run
without saving them. --mcp-run, --mcp-run-out and --mcp-token are gone;
the scripts setting is python_scripts_unrestricted and a session's output
folder is <datadir>/automation/out. get_app_state reports ready and
version at the top level, and its mcp block describes the endpoint only.

No change to slicing output.
2026-11-14 23:41:01 +08:00

352 lines
17 KiB
C++

// get_app_state, wait and get_log: what an agent reads before and after acting.
#include "JobRegistry.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "McpEndpoint.hpp"
#include "McpPaths.hpp"
#include "McpRecorder.hpp"
#include "libslic3r/Config.hpp"
#include "AutomationRuntime.hpp"
#include "McpTools.hpp"
#include "ModalTracker.hpp"
#include "PythonScriptsDialog.hpp"
#include "ScreenCapture.hpp"
#include "UiInspector.hpp"
#include "WindowControl.hpp"
#include "slic3r/GUI/CommandTypes.hpp"
#include "slic3r/GUI/GCodeViewer.hpp"
#include "slic3r/GUI/GLCanvas3D.hpp"
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp"
#include "slic3r/GUI/Jobs/Worker.hpp"
#include "slic3r/GUI/MainFrame.hpp"
#include "slic3r/GUI/Notebook.hpp"
#include "slic3r/GUI/NotificationManager.hpp"
#include "slic3r/GUI/PartPlate.hpp"
#include "slic3r/GUI/Plater.hpp"
#include "slic3r/GUI/PrintHostDialogs.hpp"
#include "slic3r/plugin/PythonInterpreter.hpp"
#ifdef SLIC3R_CAD
#include "McpToolsCad.hpp"
#include "slic3r/GUI/NativeCommands.hpp"
#endif
#if defined(__WXGTK__)
#include "slic3r/GUI/LinuxDisplayBackend.hpp"
#endif
#include "libslic3r/Model.hpp"
#include "libslic3r/PresetBundle.hpp"
#include "libslic3r/Utils.hpp"
#include "libslic3r_version.h"
#include <boost/filesystem/path.hpp>
#include <boost/nowide/fstream.hpp>
#include <wx/defs.h>
#include <wx/display.h>
#include <wx/gdicmn.h>
#include <wx/glcanvas.h>
#include <wx/vector.h>
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <deque>
#include <string>
#include <set>
#include <thread>
#include <utility>
#include <vector>
namespace Slic3r { namespace GUI { namespace Mcp {
using nlohmann::json;
namespace {
const char* platform_name()
{
#if defined(_WIN32)
return "windows";
#elif defined(__APPLE__)
return "macos";
#else
return "linux";
#endif
}
const char* display_backend()
{
#if defined(_WIN32)
return "win32";
#elif defined(__APPLE__)
return "cocoa";
#elif defined(__WXGTK__)
switch (get_linux_display_backend()) {
case LinuxDisplayBackend::X11: return "x11";
case LinuxDisplayBackend::Wayland: return "wayland";
default: return "unknown";
}
#else
return "unknown";
#endif
}
const char* mode_name(ConfigOptionMode mode)
{
switch (mode) {
case comSimple: return "simple";
case comAdvanced: return "advanced";
case comExpert: return "expert";
case comDevelop: return "develop";
default: return "simple";
}
}
// The app as an agent sees it. UI thread.
json app_state(AutomationRuntime& runtime)
{
// A session that never opened the MCP endpoint has none.
const McpEndpoint* endpoint = wxGetApp().mcp_endpoint();
json state{{"version", SLIC3R_VERSION},
{"platform", platform_name()},
{"display_backend", display_backend()},
{"ready", runtime.ready()},
{"dialogs", runtime.modals().snapshot()},
{"closed_menus", runtime.inspector().closed_menus()},
{"auto_answer_rules", runtime.modals().rules_json()},
{"mcp", endpoint != nullptr ? endpoint->describe() : json{{"serving", false}}},
{"python",
{{"available", PythonInterpreter::instance().is_initialized()},
{"scripts_unrestricted", python_scripts_unrestricted(*wxGetApp().app_config)}}},
{"jobs", runtime.jobs().list()}};
if (json recording = runtime.recorder().state(); !recording.is_null())
state["recording"] = std::move(recording);
// Each display's work area, where set_window can place a window.
json displays = json::array();
for (unsigned i = 0; i < wxDisplay::GetCount(); ++i) {
const wxDisplay display(i);
json area = display_area(i);
area["scale"] = display.GetScaleFactor();
area["primary"] = display.IsPrimary();
displays.push_back(std::move(area));
}
state["displays"] = std::move(displays);
MainFrame* frame = wxGetApp().mainframe;
Plater* plater = wxGetApp().plater();
if (frame == nullptr || plater == nullptr)
return state;
// The size and state list_windows reports, and the place where the platform knows it.
const wxSize size = window_size(*frame);
const std::string frame_state = window_state(*frame);
state["window"] = {{"title", into_u8(frame->GetTitle())},
{"size", {size.x, size.y}},
{"maximized", frame_state == "maximized"},
{"minimized", frame_state == "minimized"},
{"shown", frame->IsShown()}};
if (window_positions_known()) {
const wxPoint pos = frame->GetScreenPosition();
state["window"]["position"] = {pos.x, pos.y};
}
if (Notebook* tabs = frame->m_tabpanel; tabs != nullptr && tabs->GetSelection() != wxNOT_FOUND)
state["tab"] = into_u8(tabs->GetPageName(size_t(tabs->GetSelection())));
// The page exists only when the CAD preference was on at startup.
#ifdef SLIC3R_CAD
state["design_tab"] = frame->m_design_page != nullptr;
if (json note = cad_note(NativeCommands::instance()); !note.is_null())
state["cad_note"] = std::move(note);
#else
state["design_tab"] = false;
#endif
state["mode"] = mode_name(wxGetApp().get_mode());
state["printer_technology"] = plater->printer_technology() == ptFFF ? "FFF" : "SLA";
state["project"] = {{"name", into_u8(plater->get_project_name())},
{"path", into_u8(plater->get_project_filename(".3mf"))},
{"dirty", plater->is_project_dirty()}};
PresetBundle& bundle = *wxGetApp().preset_bundle;
json filaments = json::array();
for (const std::string& name : bundle.filament_presets)
filaments.push_back(name);
state["presets"] = {{"printer", bundle.printers.get_selected_preset_name()},
{"process", bundle.prints.get_selected_preset_name()},
{"filaments", std::move(filaments)}};
PartPlateList& plates = plater->get_partplate_list();
state["plates"] = {{"count", plates.get_plate_count()}, {"current", plates.get_curr_plate_index()}};
// The current plate's toolpaths, as the Preview shows them; null without any, or while the Preview
// still holds another plate's.
GLCanvas3D* preview = plater->get_preview_canvas3D();
state["preview"] = preview != nullptr && viewer_holds(preview->get_gcode_viewer(), plates.get_curr_plate()->get_slice_result()) ?
preview_state(preview->get_gcode_viewer()) :
json();
if (!state["preview"].is_null())
state["preview"]["plate"] = plates.get_curr_plate_index();
// The camera of the 3D view shown, the Design view's on the Design tab, which swaps its camera into the
// plater's while it is shown.
if (GLCanvas3D* canvas = shown_canvas(); canvas != nullptr && canvas->get_wxglcanvas()->IsShownOnScreen())
state["camera"] = camera_state(plater->get_camera(), canvas->get_scale());
// The open gizmo, on the canvas shown first.
state["gizmo"] = nullptr;
std::vector<GLCanvas3D*> canvases = live_canvases();
std::stable_partition(canvases.begin(), canvases.end(), [&](GLCanvas3D* c) { return c == plater->get_current_canvas3D(); });
for (GLCanvas3D* c : canvases)
if (const auto type = c->get_gizmos_manager().get_current_type(); type != GLGizmosManager::Undefined) {
state["gizmo"] = {{"name", gizmo_name(type)}, {"canvas", canvas_name(c)}};
break;
}
state["objects"] = plater->model().objects.size();
state["slicing"] = plater->is_slicing_any();
// The selection select_objects acts on: the assemble view's while it is shown, else Prepare's.
GLCanvas3D* assemble = plater->get_assmeble_canvas3D();
GLCanvas3D* scene = assemble != nullptr && plater->get_current_canvas3D() == assemble ? assemble : plater->get_view3D_canvas3D();
state["selection"] = scene != nullptr ? selection_state(*scene) : json();
// The session's print host uploads, as the upload queue lists them; `id` is its ID column.
json uploads = json::array();
if (const PrintHostQueueDialog* queue = frame->printhost_queue_dlg())
for (size_t row = 0; row < queue->job_count(); ++row) {
const PrintHostQueueDialog::JobInfo job = queue->job_info(row);
json upload{{"id", row + 1}, {"state", job.state}, {"progress", job.progress}, {"host", job.host}, {"filename", job.filename}};
if (!job.error.empty())
upload["error"] = job.error;
uploads.push_back(std::move(upload));
}
state["uploads"] = std::move(uploads);
json notes = json::array();
for (const NotificationSummary& n : plater->get_notification_manager()->summaries())
notes.push_back({{"type", n.type}, {"level", n.level}, {"text", n.text}});
state["notifications"] = std::move(notes);
return state;
}
// Whether `condition` holds now. UI thread.
bool condition_holds(AutomationRuntime& runtime, const std::string& condition, const std::set<std::string>& own_jobs)
{
if (condition == "ready")
return runtime.ready();
if (condition == "dialog")
return runtime.modals().any_open();
if (condition == "no_dialog")
return !runtime.modals().any_open();
if (condition == "idle") {
if (runtime.modals().any_open() || runtime.jobs().any_running_except(own_jobs))
return false;
Plater* plater = wxGetApp().plater();
if (plater == nullptr)
return true;
if (plater->is_slicing_any() || !plater->get_ui_job_worker().is_idle())
return false;
// Gizmos working in the background (Simplify's calculation, a texture preview).
const auto canvases = live_canvases();
return std::none_of(canvases.begin(), canvases.end(), [](GLCanvas3D* c) { return c->get_gizmos_manager().is_busy(); });
}
throw ToolFailure("Unknown condition " + condition);
}
} // namespace
void register_app_tools(CommandCatalog& catalog)
{
catalog.add(inspect_tool(
"core", "get_app_state", L("Get app state"),
"Snapshot of OrcaSlicer. Call it first and whenever you are unsure what the app is doing. The app: version, platform "
"and display backend, whether it is ready, the main window, the displays (each one's work area x, y, width and "
"height, as set_window takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python "
"(available: Python runs "
"in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to "
"OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts or for one run "
"with --unrestricted-scripts), design_tab "
"(the Design tab is on, and call_tool runs its commands, search_tools' group Design) and, when they do not run, "
"cad_note, how a person turns the CAD feature on. The project: current tab and mode, printer technology, name, path and unsaved changes, "
"selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the "
"instances [[object, instance]] they are selected in and, when parts rather than whole instances are selected, "
"parts [[object, part]], in the indices select_objects takes; wipe_tower when a prime tower is selected; canvas is the 3D "
"view it belongs to), slicing state, "
"the Preview's view type, time mode and layer range (1-based, with their Z), and the camera of the 3D view shown "
"(camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as set_view replies with it). What "
"is going on: open modal "
"dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its "
"text and its controls row by row, fields [value], choices [value ▾], checkboxes [x] / [ ] / [-], radio and "
"selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled "
"control; menus closed unseen (a menu a call opened that no reply listed), auto_answer_dialogs rules in force, "
"notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running "
"recording.",
object_schema({}), [](const json&, ToolContext& ctx) {
AutomationRuntime& runtime = ctx.runtime();
return ToolResult::ok(ctx.run_ui([&runtime] { return app_state(runtime); }));
}));
NativeCommand wait = inspect_tool(
"core", "wait", L("Wait for a condition"),
"Block until a condition holds or timeout_s passes (max 50). for: \"ready\" (startup finished), \"idle\" (no dialog, "
"no running job, nothing slicing or arranging, no gizmo working in the background; a run_script run counts only "
"through the calls it makes), \"dialog\" / \"no_dialog\", or \"job\" with a job id an earlier call returned, whose "
"result is then the reply. On timeout the reply is {satisfied: false}: call it again.",
object_schema({{"for", enum_prop({"ready", "idle", "dialog", "no_dialog", "job"}, "What to wait for; default job when job "
"is given, else idle.")},
{"job", prop("string", "Job id, for \"job\".")},
{"timeout_s", {{"type", "number"}, {"minimum", 0}, {"maximum", 50}, {"description", "Default 30."}}}}),
[](const json& args, ToolContext& ctx) {
AutomationRuntime& runtime = ctx.runtime();
const std::string what = arg_string(args, "for", args.contains("job") ? "job" : "idle");
const auto timeout = std::chrono::milliseconds(int(arg_double(args, "timeout_s", 30) * 1000));
const auto start = std::chrono::steady_clock::now();
if (what == "job") {
const std::string job = arg_string(args, "job");
if (job.empty())
throw ToolFailure("job is required for \"job\"");
require_own_job(ctx, runtime.jobs(), job, "waits for");
if (auto r = runtime.jobs().wait(job, timeout, [&ctx] { return ctx.cancelled(); }))
return *r;
return ToolResult::ok({{"status", "running"}, {"job", job}, {"note", "Still running; wait again."}});
}
const std::set<std::string> own = ctx.lineage();
for (;;) {
const bool holds = ctx.run_ui([&] { return json(condition_holds(runtime, what, own)); }).get<bool>();
const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);
if (holds)
return ToolResult::ok({{"satisfied", true}, {"waited_ms", waited.count()}});
if (waited >= timeout || ctx.cancelled())
return ToolResult::ok({{"satisfied", false}, {"waited_ms", waited.count()}});
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
});
wait.journal = true; // a replay needs the same waits
catalog.add(wait);
catalog.add(inspect_tool(
"core", "get_log", L("Read the log"),
"The last lines of OrcaSlicer's current log file, optionally only those at or above a level.",
object_schema({{"lines", {{"type", "integer"}, {"minimum", 1}, {"maximum", 2000}, {"description", "Default 200."}}},
{"level", enum_prop({"trace", "debug", "info", "warning", "error", "fatal"}, "Minimum level.")}}),
[](const json& args, ToolContext&) {
const boost::filesystem::path file = get_log_file_name();
if (file.empty())
throw ToolFailure("No log file is open");
static const std::vector<std::string> levels{"trace", "debug", "info", "warning", "error", "fatal"};
const std::string min_level = arg_string(args, "level", "trace");
const auto min_it = std::find(levels.begin(), levels.end(), min_level);
const std::size_t lines = std::size_t(arg_int(args, "lines", 200));
flush_logs();
boost::nowide::ifstream in(path_to_utf8(file).c_str());
std::deque<std::string> tail;
std::string line;
while (std::getline(in, line)) {
bool keep = min_it == levels.begin();
for (auto it = min_it; !keep && it != levels.end(); ++it)
keep = line.find("[" + *it + "]") != std::string::npos;
if (!keep)
continue;
tail.push_back(line);
if (tail.size() > lines)
tail.pop_front();
}
return ToolResult::ok({{"file", path_to_utf8(file)}, {"lines", json(std::vector<std::string>(tail.begin(), tail.end()))}});
}));
}
}}} // namespace Slic3r::GUI::Mcp