From 99018203de71481bc3c484d7857c8499173e1bf8 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Mon, 2 Nov 2026 16:05:13 +0800 Subject: [PATCH] Add Python scripts and plugin tools to the MCP server The MCP tools are listed in core, API and UI lanes. With Python scripts turned on in Preferences, agents and people can run Python against the open app; plugins holding the tools permission can call the tools, and plugins can offer operations of their own to agents. Calls can pin object and volume ids so a stale index is refused, and run_script takes a script as JSON text as well as an object. --- docs/HLSD/mcp-server.md | 156 +++++- localization/i18n/list.txt | 3 + src/slic3r/CMakeLists.txt | 11 + src/slic3r/GUI/GUI_App.cpp | 19 + src/slic3r/GUI/Mcp/JobRegistry.cpp | 75 ++- src/slic3r/GUI/Mcp/JobRegistry.hpp | 38 +- src/slic3r/GUI/Mcp/McpCore.cpp | 64 ++- src/slic3r/GUI/Mcp/McpCore.hpp | 9 +- src/slic3r/GUI/Mcp/McpJournal.cpp | 40 +- src/slic3r/GUI/Mcp/McpJournal.hpp | 5 + src/slic3r/GUI/Mcp/McpOptions.hpp | 5 + src/slic3r/GUI/Mcp/McpPluginCaller.cpp | 142 +++++ src/slic3r/GUI/Mcp/McpProtocol.cpp | 75 ++- src/slic3r/GUI/Mcp/McpScript.cpp | 58 +- src/slic3r/GUI/Mcp/McpScript.hpp | 3 + src/slic3r/GUI/Mcp/McpScriptSummary.cpp | 4 +- src/slic3r/GUI/Mcp/McpService.cpp | 232 +++++++- src/slic3r/GUI/Mcp/McpService.hpp | 36 +- src/slic3r/GUI/Mcp/McpTools.hpp | 12 + src/slic3r/GUI/Mcp/McpToolsApi.cpp | 154 +++++ src/slic3r/GUI/Mcp/McpToolsApp.cpp | 1 + src/slic3r/GUI/Mcp/McpToolsCommon.cpp | 24 + src/slic3r/GUI/Mcp/McpToolsConfig.cpp | 3 + src/slic3r/GUI/Mcp/McpToolsLayers.cpp | 3 + src/slic3r/GUI/Mcp/McpToolsPython.cpp | 219 ++++++++ src/slic3r/GUI/Mcp/McpToolsScene.cpp | 53 +- src/slic3r/GUI/Mcp/McpToolsScript.cpp | 11 +- src/slic3r/GUI/Mcp/McpTypes.hpp | 46 +- src/slic3r/GUI/Mcp/ModalTracker.cpp | 4 + src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp | 110 ++++ src/slic3r/GUI/Mcp/PythonScriptsDialog.hpp | 19 + src/slic3r/GUI/Preferences.cpp | 31 ++ src/slic3r/GUI/Preferences.hpp | 1 + src/slic3r/GUI/ScriptRunnerDialog.cpp | 144 ++++- src/slic3r/GUI/ScriptRunnerDialog.hpp | 6 + src/slic3r/plugin/PluginAuditManager.cpp | 107 ++++ src/slic3r/plugin/PluginAuditManager.hpp | 18 + src/slic3r/plugin/PluginFsUtils.cpp | 5 + src/slic3r/plugin/PluginFsUtils.hpp | 5 + src/slic3r/plugin/PluginManager.cpp | 25 + src/slic3r/plugin/PluginOperations.cpp | 139 +++++ src/slic3r/plugin/PluginOperations.hpp | 68 +++ src/slic3r/plugin/PythonPluginBridge.cpp | 103 +++- src/slic3r/plugin/PythonScriptRunner.cpp | 451 +++++++++++++++ src/slic3r/plugin/PythonScriptRunner.hpp | 66 +++ src/slic3r/plugin/host/PluginHost.cpp | 9 + src/slic3r/plugin/host/PluginHostApp.cpp | 1 + src/slic3r/plugin/host/PluginHostBindings.hpp | 8 + src/slic3r/plugin/host/PluginHostPresets.cpp | 7 + src/slic3r/plugin/host/PluginHostTools.cpp | 132 +++++ src/slic3r/plugin/host/PluginHostTools.hpp | 69 +++ src/slic3r/plugin/host/PluginHostUi.cpp | 15 + tests/slic3rutils/CMakeLists.txt | 2 + tests/slic3rutils/test_mcp_config.cpp | 12 + tests/slic3rutils/test_mcp_core.cpp | 199 +++++++ tests/slic3rutils/test_mcp_protocol.cpp | 72 +++ tests/slic3rutils/test_mcp_results.cpp | 34 ++ tests/slic3rutils/test_mcp_script.cpp | 80 +++ tests/slic3rutils/test_mcp_script_summary.cpp | 11 + tests/slic3rutils/test_mcp_tools.cpp | 92 +++ tests/slic3rutils/test_plugin_audit.cpp | 77 +++ tests/slic3rutils/test_plugin_host_api.cpp | 291 ++++++++++ tests/slic3rutils/test_plugin_operations.cpp | 95 ++++ .../slic3rutils/test_python_script_runner.cpp | 526 ++++++++++++++++++ tools/mcp/README.md | 20 + tools/mcp/test_plugin_tools.py | 211 +++++++ .../mcp_tools_broken/mcp_tools_broken.py | 37 ++ .../mcp_tools_fixture/mcp_tools_fixture.py | 123 ++++ 68 files changed, 4844 insertions(+), 82 deletions(-) create mode 100644 src/slic3r/GUI/Mcp/McpPluginCaller.cpp create mode 100644 src/slic3r/GUI/Mcp/McpToolsApi.cpp create mode 100644 src/slic3r/GUI/Mcp/McpToolsPython.cpp create mode 100644 src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp create mode 100644 src/slic3r/GUI/Mcp/PythonScriptsDialog.hpp create mode 100644 src/slic3r/plugin/PluginOperations.cpp create mode 100644 src/slic3r/plugin/PluginOperations.hpp create mode 100644 src/slic3r/plugin/PythonScriptRunner.cpp create mode 100644 src/slic3r/plugin/PythonScriptRunner.hpp create mode 100644 src/slic3r/plugin/host/PluginHostTools.cpp create mode 100644 src/slic3r/plugin/host/PluginHostTools.hpp create mode 100644 tests/slic3rutils/test_plugin_operations.cpp create mode 100644 tests/slic3rutils/test_python_script_runner.cpp create mode 100644 tools/mcp/test_plugin_tools.py create mode 100644 tools/mcp/tests/plugins/mcp_tools_broken/mcp_tools_broken.py create mode 100644 tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index d5be89cd56..63f8ec29be 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -394,8 +394,28 @@ the UI thread. | | `webview_eval` | run JavaScript in a web view (the topmost dialog's while a modal is open), with a page element as `el`, and return the result | | Scripts | `run_script` | run a script file or inline script, with results per step | | | `export_script` | write the session journal as a script that can be replayed; calls whose job is still running are left out and listed | +| | `run_python` | run Python code against `orca.host`, calling tools through `orca.host.tools`; needs the Python setting (see Python scripts); cancellable | +| | `python_api` | search `orca.host` in the running build: names, signatures and documentation | +| API | `api_describe` | look up any registered tool or plugin operation: its schema by name, matches by words, or every name | +| | `api_call` | call a registered tool or plugin operation by name; runs and is journaled as that tool's own call | | CAD | `cad_call` | a method of the Design tab: sketches, features, reads and measurements, feature and body edits, undo, commit to plate; `describe_tools` lists them (CAD builds, Design tab enabled) | +Each tool has a lane, the way it acts, set by `ToolRegistry::add()` from `tool_lane()`: core (the +session, recovery and Python), API (project data by index and name, JSON in and out) and UI (the GUI +itself). Every caller reaches every tool; the lane is a hint for the agent choosing one. It starts each +description (`[core]`, `[api]`, `[ui]`), orders `tools/list` (core, then API, then UI) and orders the +server instructions. The access label is `read_only`: the tool reads and writes nothing. + +The tools that take an object index (`set_settings` object and volume scopes, `transform`, `add_part`, +`set_layer_ranges`, `set_layer_height_profile`) also take an optional `object_id`, and where they take a +part index a `volume_id`; `select` takes `object_ids`, `instance_object_ids` and `volume_ids`, one per +entry of `objects`, `instances` and `volumes`: the `ObjectID` values `list_objects` reports as `id`, which `orca.host` shows +too. `check_expected_ids()` refuses the call before anything changes when the index names another object +or part now, so a script addresses what it read. Ids are allocated per process, so the journal leaves +them out of those tools' calls (`without_expected_ids()`), through `api_call` and inline `run_script` steps +too, and a replay addresses by index; a `run_python` step's code and `args`, and a plugin operation's own +arguments, are kept as written. + Each tool family registers itself from its own `McpTools*.cpp` through `register_*_tools()`. List tools take `limit` and `offset` and report `total` and `next_offset`. `McpPaths.hpp` requires absolute paths, since a relative one would resolve against `/log`, the GUI's working @@ -2212,9 +2232,13 @@ thread's progress and error events go to, so the row exists before any of them i A script is JSON with comments allowed. `run_script` runs a file or an inline script as a job whose steps call tools as its children (`ToolContext::call_child()`), so steps are not journaled and a -script's `wait {for: "idle"}` doesn't wait for the script. Every string is substituted recursively +script's `wait {for: "idle"}` doesn't wait for the script. An inline script is the script object or +its JSON text, comments included, so a caller holding a script file's text passes it as read; the +journal records the text as the object it parses to. Every string is substituted recursively with `${script_dir}`, `${out_dir}`, `${env:NAME}`, `${vars.NAME}` and `${jobs.NAME}`; a string that -is just one placeholder becomes the referenced JSON value. A step that returns a job is awaited, +is just one placeholder becomes the referenced JSON value. A JSON script's own `run_script` step +gives its nested script as an object: the outer run splices placeholders into a text script as plain +text, so a value holding a quote or a backslash, such as a Windows path, breaks its JSON. A step that returns a job is awaited, up to `timeout_s` (default 120), before its `expect` is checked; a wait that times out with a dialog open names the topmost one, since a step can't answer a dialog it opened. `"await": false` returns the job at once and stores it under `save_as`, so later steps can answer a dialog it opened and then @@ -2252,7 +2276,11 @@ GUI changes it. wx ignores `OnExit()`'s return value, so `GUI_Run()` returns ### Script runner dialog File › Run Script… and the Speed Dial command `open_script_runner` open `ScriptRunnerDialog`, where a -person opens or writes a script, reads its steps and runs it whole or one step at a time. It is a +person opens or writes a script, reads its steps and runs it whole or one step at a time. A `.py` file is a +Python script, shown and run as one step through `McpService::start_python_run()`: its printed output, its +result or its traceback show in that step. With the Python setting off it does not parse, so Run stays +off and the page says why. The editor holds UTF-8 text: a `.py` file is decoded as Python reads it and +saved back in the encoding it was read in, BOM included; text that encoding can't hold is not saved. It is a `WebViewHostDialog` page (`resources/web/dialog/ScriptRunner/`), modeless and one at a time (`MainFrame::show_script_runner()`). The page's editor starts from a commented draft and suggests the script's keys, tool names, a tool's arguments and their allowed values, and `${…}` placeholders; the @@ -2329,6 +2357,128 @@ call that acted with a modal open is preceded in the script by `wait {"for": "di be satisfied. Only the call's own job counts as its job: a `wait` that timed out names the job it waits on in its reply, and stays a plain step. +## Python scripts + +A Python script is a `.py` file or a code string that runs on the plugin interpreter against `orca.host`, +the plugin API, without being packaged as a plugin. A person runs one from the Run Script dialog or with +`--mcp-script file.py`; an agent sends one with `run_python {code, args, timeout_s}`; a plugin's code may +call `run_python` too. The code computes next to the data (meshes as numpy, settings, presets) and changes +the project only through the tools. + +**Entry contract.** `run_python_code()` (`plugin/PythonScriptRunner.cpp`) runs the code as a module body +on the calling thread, the MCP job that runs `run_python`, in a fresh namespace with `args` bound and +`orca` importable. The code is text, compiled as Python compiles any code string, so a coding line in it +changes nothing; a file's bytes are decoded first as Python reads a source file, by its BOM or its PEP 263 +declaration, else as UTF-8 (`decode_python_source()`), and `filename` (a `.py` file's path) names it in +tracebacks. It holds an interpreter lease and the GIL for the run. The value left in `result` is +read once when the body returns; one that is not JSON (a dict with string keys, a list, a string, a +finite number, a boolean or None, nested) makes the run `raised`, and `SystemExit` with code 0 or None +finishes it. What the run's own thread prints to stdout and stderr is captured, up to 256 KiB, by a +stream installed once over `sys.stdout` and `sys.stderr` that routes writes by thread; other threads +print through. The outcome is `finished`, `raised` (with the traceback), `cancelled` or `timed_out`, +reported in a successful result, as `run_script` reports a failed step. Everything that can run the +script's Python, its body and also a result's or an exception's own methods (iteration, `__str__`) and the +finalizers of what its namespace and traceback hold, runs inside the script's audit scope and under the +watcher; the capture functions the runner calls are the ones it installed, held from then on. A +finalizer that runs on past the budget or a cancel while the namespace is cleared makes the run +`timed_out` or `cancelled`, though Python swallows the interrupt it raises there. + +**Cancellation.** A watcher thread interrupts the run with `PyThreadState_SetAsyncExc` when `cancel +{job}` stops the job (`run_python` is `cancellable`) or the time budget (default 300 s) runs out, again +every second until the code ends; code blocked inside a C call stops once the call returns. A pending +interrupt is cleared before the thread runs anything else. + +**Identity.** A person's script runs under the audit identity `script`, an agent's under `mcp` +(`kScriptIdentityPerson`, `kScriptIdentityAgent`); `McpService::person_run()` tells them apart by the +run's lineage, since the dialog's and `--mcp-script`'s jobs are marked as a person's (`as_person()`). +Every audited access is allowed to these identities and logged under them (reads at debug level), apart +from the categorical denies every plugin has (`is_denied_path()`): nothing contains the code, and the +setting is the boundary. Threads the code starts keep the identity through the interpreter's thread +shim, but outlive the run. A run owns what its calls leave behind, as a JSON script does +(`begin_script_scope()`): auto-answer rules, a recording and a held press end with it. The identities are reserved: a plugin whose key equals one is refused before any of its code runs. A +plugin's `run_python` runs under the plugin's own identity and grants instead. + +**The setting.** One switch, `mcp_python_scripts`, off by default, lets both a person's scripts and an +agent's `run_python` run; with it off they are refused (a plugin's `run_python` needs none). It is +changed only in `PythonScriptsDialog`, opened from Preferences › AI features › Python scripts, which is +named `kHiddenFromAutomation`: the UI tools never see it and `ModalTracker` leaves it off the stack, so +no dialog tool or auto-answer rule reaches it. No tool writes the key. + +**The host surface and the bridge.** A script reads through `orca.host` as a plugin does. The functions +that change state outside the tools (the staged preset update, bundle reload, the 3MF copy, plugin UI, +plugin storage) call `require_plugin_caller()` and refuse a script identity; the test "every orca.host +function is classified" lists every function as script-callable or plugin-only, so a new binding is +plugin-only until someone classifies it. `orca.host.tools.call(name, args)` and `run_script(script, +vars)`, whose script is a dict or its JSON text (`plugin/host/PluginHostTools.cpp`), reach the tools through the `ToolBridge` bound to the calling +thread: a run binds one whose calls are `ToolContext::call_child()` of the `run_python` job, so each has +its tool's guards, admission and undo, and the GIL is released while it waits. An error result raises +`orca.host.tools.ToolError` with its data as `details`. A thread a script starts has no bridge and is +refused, and code with no audit identity at all is refused. + +**Journal and replay.** `run_python` is journaled as one step holding its code, kept when the code failed +partway; its tool calls are not journaled. In a JSON script a `run_python` step's `code` is never +substituted, and a step whose outcome is not `finished` fails. `python_api` searches the reference built +from the running build's `orca.host`. + +## Plugins and the tools + +A plugin's code calls the tools through `orca.host.tools` once it holds the `tools` permission +(`PluginPermissions::tools`), which it declares with `request_permissions(tools=True)`. The person answers +it at load in its own prompt (`request_tools_permission()`), apart from the plugin's other permissions, +and a refusal leaves the plugin loading without it. With the permission a plugin can do what an agent can: +work in the GUI, answer dialogs, replace the project, write presets and files; the prompt says so. + +A plugin's call waits for the UI thread, so it comes only from a thread nothing there waits for: a Script +worker, a Python thread one starts (the thread shim carries the mark) or MCP's own thread running a plugin +operation (`ScopedToolCallerThread`). A call from the UI thread, a slicing hook or another plugin callback +is refused before anything waits. `install_plugin_tool_caller()` routes a permitted plugin's calls. The UI +thread, which owns the service and runs the plugin's unload, admits each one: the plugin must still be +loaded and its scope not ended, and the service is started in its catalog-only mode when MCP is off; the +call then holds a lease the service's drain waits for. A caller that stops waiting because the app closes +marks its admission abandoned, so no lease is taken that nobody releases. The call runs as +`McpCore::call_plugin()`: a top-level job owned by the plugin +(`JobRegistry::owner()`), never journaled, whose children inherit the plugin +(`ToolContext::caller_plugin()`). The session tools are scoped to the plugin: `export_script` is refused, +and `cancel {job}` and `wait {for: "job"}` act only on its own jobs (`require_own_job()`). What its calls +leave behind (auto-answer rules, a recording, a held press) belongs to the plugin's scope +(`begin_plugin_scope()`), which ends when the plugin unloads. From the moment the plugin manager unloads +it, no call of the plugin starts, inline or as a job, nor a child of one of its jobs, a call admitted just +before included (`JobRegistry::unloaded()`, which asks the plugin manager itself, since the scope ends later +from the UI thread). A job is checked once it is registered and again on its thread before its handler, +so it is either refused or registered while the plugin was loaded, where the unload finds it. A running +call of the plugin reads as cancelled at once (`ToolContext::cancelled()`), so a handler that waits or +polls ends; one that does neither (a screenshot, a settings change) runs to its end, as a call does that +started just before the unload. Ending the scope then stops the +plugin's running jobs and blocks new ones (`JobRegistry::block_owner()`) until it loads again; one still +running that would leave something behind (a rule, a recording, a press) is refused. The wait for admission also ends +when the plugins shut down, which on macOS's end of session happens without the app closing. The handlers raise no audit events, +so each call is logged as `[MCP plugin] plugin=… tool=… outcome=… paths=[…]`; the record is best effort, +since plugin code may write the log folder. A plugin's window callbacks run without its audit identity, +so their calls are refused. + +**Plugin operations.** A plugin may offer operations to agents and scripts with +`orca.register_operation(name, description, schema, handler, changes)` while it loads. The person grants +each one in its own prompt (`request_operation_permission()`, saved in `PluginPermissions::operations`); +a refused one is not offered. Granted operations are staged and offered once the plugin's load has committed +(`PluginOperations::activate()`, in one step under the lock an unload's withdrawal takes); any exit of a +load that did not commit, an exception included, drops them, and they are withdrawn when the plugin +unloads. An operation is reached as +`plugin..` through `api_call`, `orca.host.tools.call` and script steps, and never +appears in `tools/list`: `ToolRegistry::set_dynamic()` resolves those names (`ToolRegistry::lookup()`). +It runs as a job, under the mutate guard and journaled when it changes something, under the inspect guard +otherwise; its handler runs under the plugin's identity and grants, and each call is logged with the +plugin and the caller. A call is refused once the plugin has unloaded, by the plugin manager's state, and +by `PluginOperations::invoke()` when the operation found is no longer the one offered (withdrawn, or +offered again by a new load). The call's job is the caller's, so an operation already running when its +plugin unloads runs to its end; its own tool calls are refused from then on. + +**`api_describe` and `api_call`.** `api_describe` gives the schema of any registered tool or operation, +searches them by words (each match with its schema), or lists every name; for `cad_call` it points to +`describe_tools`, which lists the Design tab's methods. `api_call {tool, args}` is dispatched before it runs +(`resolve_api_call()`, in the protocol, in child calls and in the plugin caller): the target's arguments +are normalized and validated, and the call runs as the target's own, with its guard, mode, budget and +journal flag, so the journal records the target. + ## stdio bridge `orca-slicer --mcp-stdio [--datadir DIR] [--mcp-port N]` serves clients that speak only stdio, diff --git a/localization/i18n/list.txt b/localization/i18n/list.txt index 7fbcf06cb6..32a03e0918 100644 --- a/localization/i18n/list.txt +++ b/localization/i18n/list.txt @@ -151,16 +151,19 @@ src/slic3r/GUI/ConnectPrinter.cpp src/slic3r/GUI/HMSPanel.cpp src/slic3r/GUI/MainFrame.cpp src/slic3r/GUI/Mcp/McpToolsActions.cpp +src/slic3r/GUI/Mcp/McpToolsApi.cpp src/slic3r/GUI/Mcp/McpToolsApp.cpp src/slic3r/GUI/Mcp/McpToolsCad.cpp src/slic3r/GUI/Mcp/McpToolsConfig.cpp src/slic3r/GUI/Mcp/McpToolsLayers.cpp src/slic3r/GUI/Mcp/McpToolsProject.cpp +src/slic3r/GUI/Mcp/McpToolsPython.cpp src/slic3r/GUI/Mcp/McpToolsRecord.cpp src/slic3r/GUI/Mcp/McpToolsScene.cpp src/slic3r/GUI/Mcp/McpToolsScript.cpp src/slic3r/GUI/Mcp/McpToolsUi.cpp src/slic3r/GUI/Mcp/McpToolsView.cpp +src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp src/slic3r/GUI/Mcp/RecordingSettings.cpp src/slic3r/GUI/RecordingDialog.cpp src/slic3r/GUI/RecordingIndicator.cpp diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 4f768f9fd3..786d2224cb 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -179,12 +179,15 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpTools.hpp GUI/Mcp/McpPaths.cpp GUI/Mcp/McpPaths.hpp + GUI/Mcp/McpPluginCaller.cpp GUI/Mcp/McpToolsActions.cpp + GUI/Mcp/McpToolsApi.cpp GUI/Mcp/McpToolsApp.cpp GUI/Mcp/McpToolsCommon.cpp GUI/Mcp/McpToolsConfig.cpp GUI/Mcp/McpToolsLayers.cpp GUI/Mcp/McpToolsProject.cpp + GUI/Mcp/McpToolsPython.cpp GUI/Mcp/McpToolsRecord.cpp GUI/Mcp/McpToolsScene.cpp GUI/Mcp/McpToolsScript.cpp @@ -193,6 +196,8 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/ScreenCapture.cpp GUI/Mcp/ScreenCapture.hpp GUI/Mcp/McpTypes.hpp + GUI/Mcp/PythonScriptsDialog.cpp + GUI/Mcp/PythonScriptsDialog.hpp GUI/Mcp/MkvWriter.cpp GUI/Mcp/MkvWriter.hpp GUI/Mcp/ModalTracker.cpp @@ -756,6 +761,10 @@ set(SLIC3R_GUI_SOURCES plugin/PythonPluginBridge.cpp plugin/PythonPluginBridge.hpp plugin/PythonPluginInterface.hpp + plugin/PluginOperations.cpp + plugin/PluginOperations.hpp + plugin/PythonScriptRunner.cpp + plugin/PythonScriptRunner.hpp plugin/PyPluginPackage.hpp plugin/PluginBindingUtils.hpp plugin/host/PluginHost.cpp @@ -768,6 +777,8 @@ set(SLIC3R_GUI_SOURCES plugin/host/PluginHostModel.cpp plugin/host/PluginHostPresets.cpp plugin/host/PluginHostSlicing.cpp + plugin/host/PluginHostTools.cpp + plugin/host/PluginHostTools.hpp plugin/host/PluginHostUi.cpp plugin/host/PluginHostUi.hpp plugin/host/PluginPages.cpp diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index dc86f30663..6674737bfd 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -257,6 +257,7 @@ #include "slic3r/GUI/HttpServer.hpp" #include "slic3r/GUI/Mcp/McpOptions.hpp" #include "slic3r/GUI/Mcp/McpService.hpp" +#include "slic3r/plugin/PluginOperations.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/ParamsDialog.hpp" #include "slic3r/GUI/ParamsPanel.hpp" @@ -3112,6 +3113,24 @@ void GUI_App::init_plugin_gui_wiring() }; plugin_mgr.subscribe_on_unload_callback(PluginHostUi::close_windows_for_plugin); + Mcp::install_plugin_tool_caller(); + // A plugin loaded again may make tool calls again. + plugin_mgr.subscribe_on_load_callback([](const std::string& plugin_key) { + if (wxTheApp != nullptr) + wxGetApp().CallAfter([plugin_key] { + if (Mcp::McpService* service = wxGetApp().mcp_service(); service != nullptr && service->started()) + service->plugin_loaded(plugin_key); + }); + }); + plugin_mgr.subscribe_on_unload_callback([](const std::string& plugin_key) { + PluginOperations::instance().remove_plugin(plugin_key); + // What the plugin's tool calls left behind (rules, a recording, a held press) ends with it. + if (wxTheApp != nullptr) + wxGetApp().CallAfter([plugin_key] { + if (Mcp::McpService* service = wxGetApp().mcp_service(); service != nullptr && service->started()) + service->end_plugin_scope(plugin_key); + }); + }); plugin_mgr.subscribe_on_load_callback([refresh_plugins_dialog](const std::string&) { refresh_plugins_dialog(); }); plugin_mgr.subscribe_on_unload_callback([refresh_plugins_dialog](const std::string&) { refresh_plugins_dialog(); }); plugin_mgr.subscribe_on_load_callback(NetworkAgentFactory::register_python_plugin); diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp index 2d9645e0ae..ad5eab70d1 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -14,7 +14,37 @@ namespace Slic3r { namespace GUI { namespace Mcp { -std::string JobRegistry::create(const std::string& tool, const std::string& parent) +bool JobRegistry::unloaded(const std::string& parent, const std::string& owner) const +{ + std::string plugin = owner; + { + std::lock_guard lock(m_mutex); + if (plugin.empty() && !parent.empty()) + if (const auto it = m_jobs.find(parent); it != m_jobs.end()) + plugin = it->second.owner; + if (plugin.empty()) + return false; + if (m_blocked_owners.count(plugin) != 0) + return true; + } + // The hook takes the plugin manager's lock, so it is asked without this registry's. + return m_owner_loaded && !m_owner_loaded(plugin); +} + +std::string JobRegistry::create(const std::string& tool, const std::string& parent, const std::string& owner) +{ + const std::string id = register_job(tool, parent, owner); + if (unloaded(id, {})) { + // Never started: nothing waits for it, and a stop the unload asked for it meanwhile goes with it. + std::lock_guard lock(m_mutex); + m_jobs.erase(id); + m_stop_requests.erase(id); + throw ToolFailure(kPluginUnloaded); + } + return id; +} + +std::string JobRegistry::register_job(const std::string& tool, const std::string& parent, const std::string& owner) { std::lock_guard lock(m_mutex); const std::size_t running = std::count_if(m_jobs.begin(), m_jobs.end(), [](const auto& kv) { return !kv.second.finished; }); @@ -24,16 +54,57 @@ std::string JobRegistry::create(const std::string& tool, const std::string& pare Job job; job.tool = tool; job.parent = parent; + job.owner = owner; job.created = std::chrono::steady_clock::now(); if (!parent.empty()) { job.ancestors.push_back(parent); - if (auto it = m_jobs.find(parent); it != m_jobs.end()) + if (auto it = m_jobs.find(parent); it != m_jobs.end()) { job.ancestors.insert(job.ancestors.end(), it->second.ancestors.begin(), it->second.ancestors.end()); + if (job.owner.empty()) + job.owner = it->second.owner; + } } + if (!job.owner.empty() && m_blocked_owners.count(job.owner) != 0) + throw ToolFailure(kPluginUnloaded); m_jobs.emplace(id, std::move(job)); return id; } +void JobRegistry::block_owner(const std::string& owner) +{ + std::lock_guard lock(m_mutex); + m_blocked_owners.insert(owner); +} + +void JobRegistry::unblock_owner(const std::string& owner) +{ + std::lock_guard lock(m_mutex); + m_blocked_owners.erase(owner); +} + +std::vector JobRegistry::running_owned_by(const std::string& owner) const +{ + std::lock_guard lock(m_mutex); + std::vector out; + for (const auto& [id, job] : m_jobs) + if (!job.finished && !owner.empty() && job.owner == owner) + out.push_back(id); + return out; +} + +void require_own_job(const ToolContext& ctx, const JobRegistry& jobs, const std::string& job, const char* what) +{ + if (!ctx.caller_plugin().empty() && jobs.owner(job) != ctx.caller_plugin()) + throw ToolFailure(std::string("A plugin ") + what + " only the jobs of its own calls"); +} + +std::string JobRegistry::owner(const std::string& id) const +{ + std::lock_guard lock(m_mutex); + const auto it = m_jobs.find(id); + return it == m_jobs.end() ? std::string() : it->second.owner; +} + void JobRegistry::finish(const std::string& id, ToolResult result) { { diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp index f47d039597..29eda6cd8a 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.hpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -15,10 +15,14 @@ #include #include #include +#include #include namespace Slic3r { namespace GUI { namespace Mcp { +// What a call of a plugin that has unloaded fails with. +inline constexpr char kPluginUnloaded[] = "The plugin that made this call has been unloaded"; + // Bookkeeping for mutate tool calls that run on their own threads. A call that outlives its reply // budget stays here until it finishes, so a later `wait {for:"job"}` can return its result; the // most recent finished jobs are kept for that purpose, and so is a finished job whose parent (a @@ -30,8 +34,28 @@ public: static constexpr std::size_t kKeepFinished = 64; static constexpr std::size_t kKeepFinishedMax = 1024; - // Registers a running job. Throws ToolFailure when kMaxRunning jobs are already running. - std::string create(const std::string& tool, const std::string& parent); + // Registers a running job. `owner` is the plugin whose call it is ("" for a client's or a script's); + // a child job takes its parent's. Throws ToolFailure when kMaxRunning jobs are already running, and + // kPluginUnloaded when its plugin is unloaded(), which is asked once the job is registered: a plugin + // found loaded then was loaded while the job was there for its unload to find, so every job of the + // plugin is either refused or one the unload finds running. + std::string create(const std::string& tool, const std::string& parent, const std::string& owner = {}); + // Whether the call's plugin (`owner`, else the owner of the job `parent`) is blocked or, by the liveness + // hook, no longer loaded. False for a call that is not a plugin's. + bool unloaded(const std::string& parent, const std::string& owner) const; + // Whether a plugin is loaded, asked on the calling thread without the registry's lock held. It is the + // plugin manager's own state, so it changes the moment the plugin unloads, while the block comes later + // from the UI thread. Set once, before any job is created. + void set_owner_liveness(std::function loaded) { m_owner_loaded = std::move(loaded); } + // The plugin that owns `id`, or "" for a client's or script's job, or one no longer known. + std::string owner(const std::string& id) const; + // The running jobs `owner` (a plugin) owns. + std::vector running_owned_by(const std::string& owner) const; + // While `owner` (an unloaded plugin) is blocked, create() refuses its jobs and its jobs' children. The + // block is checked as the job is registered, so a job registered just before it is among the jobs + // running_owned_by() returns, which the unload then stops. + void block_owner(const std::string& owner); + void unblock_owner(const std::string& owner); void finish(const std::string& id, ToolResult result); // The job's result once it has finished; nullopt when it is still running after `timeout` or @@ -67,10 +91,14 @@ public: void wake_all(); private: + // create() without the liveness check. + std::string register_job(const std::string& tool, const std::string& parent, const std::string& owner); + struct Job { std::string tool; std::string parent; + std::string owner; // The parent chain, nearest first, recorded at creation: a finished ancestor may be forgotten // while this job still runs, and the chain must still reach the root (a stop asked for it). std::vector ancestors; @@ -85,8 +113,14 @@ private: std::map m_jobs; std::deque m_finished_order; std::set m_stop_requests; + std::set m_blocked_owners; + std::function m_owner_loaded; uint64_t m_next = 1; bool m_woken = false; }; +// Refuses a plugin's call (ToolContext::caller_plugin()) about a job its own calls did not start: the +// session tools act only on a plugin's own jobs. `what` names the action, as in "waits for". +void require_own_job(const ToolContext& ctx, const JobRegistry& jobs, const std::string& job, const char* what); + }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index 01944ffe1b..94c5c30086 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -1,5 +1,6 @@ #include "McpCore.hpp" +#include "JobRegistry.hpp" #include "McpJournal.hpp" #include "McpTypes.hpp" #include "UiInvoker.hpp" @@ -43,12 +44,13 @@ std::string busy_message(const std::string& op) class CallContext final : public ToolContext { public: - CallContext(McpCore& core, const ToolDef& def, std::string job, std::string parent, Journal* journal, uint64_t journal_seq, - CallObserver* observer, uint64_t call) + CallContext(McpCore& core, const ToolDef& def, std::string job, std::string parent, std::string plugin, Journal* journal, + uint64_t journal_seq, CallObserver* observer, uint64_t call) : m_core(core) , m_def(def) , m_job(std::move(job)) , m_parent(std::move(parent)) + , m_plugin(std::move(plugin)) , m_journal(journal) , m_seq(journal_seq) , m_observer(observer) @@ -89,24 +91,31 @@ public: }); } const std::string& job_id() const override { return m_job; } + // A plugin's call reads as cancelled the moment the plugin unloads, before the unload's stop request comes; + // a handler that waits or polls then ends, one that does neither runs to its end. bool cancelled() const override { - return m_core.ui().is_shutdown() || m_core.jobs().stop_requested(m_job.empty() ? m_parent : m_job); + return m_core.ui().is_shutdown() || m_core.jobs().stop_requested(m_job.empty() ? m_parent : m_job) || + (!m_plugin.empty() && m_core.jobs().unloaded({}, m_plugin)); } ToolResult call_child(const std::string& tool, const nlohmann::json& raw_args) override { - const ToolDef* def = m_core.registry().find(tool); + std::shared_ptr def = m_core.registry().lookup(tool); if (def == nullptr) return ToolResult::error("Unknown tool: " + tool); nlohmann::json args = raw_args; normalize_arguments(def->input_schema, args); if (std::string err = validate_arguments(def->input_schema, args); !err.empty()) return ToolResult::error("Invalid arguments: " + err); + if (std::string err = resolve_api_call(m_core.registry(), def, args); !err.empty()) + return ToolResult::error(err); // An inline caller has no job of its own; its children are rooted at its parent. - return m_core.call_child(*def, args, m_job.empty() ? m_parent : m_job); + return m_core.call_child(*def, args, m_job.empty() ? m_parent : m_job, m_plugin); } + const std::string& caller_plugin() const override { return m_plugin; } + std::set lineage() const override { return m_core.jobs().lineage(m_job.empty() ? m_parent : m_job); @@ -146,6 +155,7 @@ private: const ToolDef& m_def; std::string m_job; std::string m_parent; + std::string m_plugin; Journal* m_journal; uint64_t m_seq; CallObserver* m_observer; @@ -198,21 +208,27 @@ void McpCore::leave() m_threads_cv.notify_all(); } -ToolResult McpCore::call(const ToolDef& def, const nlohmann::json& args) { return run(def, args, {}); } +ToolResult McpCore::call(const ToolDef& def, const nlohmann::json& args) { return run(def, args, {}, {}); } -ToolResult McpCore::call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job) +ToolResult McpCore::call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job, const std::string& plugin) { - return run(def, args, parent_job); + return run(def, args, parent_job, plugin); } -ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const std::string& parent) +ToolResult McpCore::call_plugin(const ToolDef& def, const nlohmann::json& args, const std::string& plugin_key) +{ + return run(def, args, {}, plugin_key); +} + +ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const std::string& parent, const std::string& plugin) { if (m_ui.is_shutdown() || !enter()) return ToolResult::error("OrcaSlicer is shutting down"); struct Leave { McpCore* core; ~Leave() { core->leave(); } } leave_on_return{this}; - // Only client calls are journaled; a script's own steps replay through the script. - const bool journal = m_journal != nullptr && parent.empty() && def.journal; + // Only client calls are journaled; a script's own steps replay through the script, and a plugin's calls + // are not the agent's. + const bool journal = m_journal != nullptr && parent.empty() && plugin.empty() && def.journal; const uint64_t seq = journal ? m_journal->begin(def.name, args, def.guard == GuardClass::Recover && !m_ui.open_dialogs().empty()) : 0; auto finish = [&](ToolResult r) { if (journal) @@ -220,9 +236,15 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st return r; }; + // A call of a plugin that has unloaded, or a child of one of its jobs, never runs. An inline call + // creates no job, so this is its last check before its handler; it is cancelled once the plugin + // unloads (CallContext::cancelled()). + if (m_jobs.unloaded(parent, plugin)) + return finish(ToolResult::error(kPluginUnloaded)); + const uint64_t call = m_next_call++; if (def.inline_call) { - CallContext ctx(*this, def, {}, parent, m_journal, seq, m_observer, call); + CallContext ctx(*this, def, {}, parent, plugin, m_journal, seq, m_observer, call); // Any inline call can wait for the UI thread, so each holds a blocking slot. if (!acquire_slot()) return finish(ToolResult::ok({{"status", "pending"}, {"note", "Too many calls are waiting right now; try again shortly."}})); @@ -241,7 +263,7 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st std::string job; try { - job = m_jobs.create(def.name, parent); + job = m_jobs.create(def.name, parent, plugin); } catch (const ToolFailure& f) { return finish(ToolResult::error(f.what())); } @@ -255,11 +277,17 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st // The job thread owns copies of what it needs; the core outlives it, as the owner destroys the // core only once drain() has seen every job thread leave. try { - std::thread([this, def, args, job, parent, seq, call]() { - CallContext ctx(*this, def, job, parent, m_journal, seq, m_observer, call); - notify(m_observer, [&](CallObserver& o) { o.call_started(call, def, args, parent); }); - ToolResult result = await_worker(job, def.name, invoke(def, args, ctx)); - notify(m_observer, [&](CallObserver& o) { o.call_ended(call, result); }); + std::thread([this, def, args, job, parent, plugin, seq, call]() { + CallContext ctx(*this, def, job, parent, plugin, m_journal, seq, m_observer, call); + ToolResult result; + // The plugin may have unloaded since the job was registered; its handler then never starts. + if (m_jobs.unloaded(job, {})) { + result = ToolResult::error(kPluginUnloaded); + } else { + notify(m_observer, [&](CallObserver& o) { o.call_started(call, def, args, parent); }); + result = await_worker(job, def.name, invoke(def, args, ctx)); + notify(m_observer, [&](CallObserver& o) { o.call_ended(call, result); }); + } // Before finish(): an export_script right after the wait that sees the result must know it. if (seq != 0) m_journal->job_ended(seq, result); diff --git a/src/slic3r/GUI/Mcp/McpCore.hpp b/src/slic3r/GUI/Mcp/McpCore.hpp index 5960a83370..e0f233fe12 100644 --- a/src/slic3r/GUI/Mcp/McpCore.hpp +++ b/src/slic3r/GUI/Mcp/McpCore.hpp @@ -78,7 +78,12 @@ public: ToolResult call(const ToolDef& def, const nlohmann::json& args) override; // A call made by a running job (a script step). The new job's parent is `parent_job`, so a // `wait {for:"idle"}` from that job does not wait for it, and the journal leaves it out. - ToolResult call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job); + ToolResult call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job, + const std::string& plugin = {}); + // A call a plugin's code makes through orca.host.tools: run as a client's call is, its job owned by + // `plugin_key` (JobRegistry::owner, ToolContext::caller_plugin), and never journaled, since the journal + // is the agent's session. + ToolResult call_plugin(const ToolDef& def, const nlohmann::json& args, const std::string& plugin_key); // Refuses new calls. The owner wakes UiInvoker and JobRegistry, which makes running calls return. void shutdown(); @@ -108,7 +113,7 @@ public: private: std::uint64_t dialog_of(const std::string& job) const; - ToolResult run(const ToolDef& def, const nlohmann::json& args, const std::string& parent); + ToolResult run(const ToolDef& def, const nlohmann::json& args, const std::string& parent, const std::string& plugin); // On `job`'s thread once its handler returned: when it holds the UI job worker, waits until the // worker is idle, cancelling the job after CoreTiming::worker_timeout, and then lets it go. The // result becomes a failure when the job was cancelled or timed out. diff --git a/src/slic3r/GUI/Mcp/McpJournal.cpp b/src/slic3r/GUI/Mcp/McpJournal.cpp index 3eb3faffa1..e55da4361a 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.cpp +++ b/src/slic3r/GUI/Mcp/McpJournal.cpp @@ -10,12 +10,48 @@ #include #include #include +#include #include #include #include namespace Slic3r { namespace GUI { namespace Mcp { +using nlohmann::json; + +json without_expected_ids(const std::string& tool, json args) +{ + // The tools that take expected ids; any other tool's arguments (a plugin operation's own fields among + // them) are recorded as given. + static const std::set takes_ids{"set_settings", "transform", "add_part", "set_layer_ranges", + "set_layer_height_profile", "select"}; + if (!args.is_object()) + return args; + if (tool == "api_call") { + if (args.contains("args") && args["args"].is_object()) + args["args"] = without_expected_ids(args.value("tool", std::string()), std::move(args["args"])); + return args; + } + if (tool == "run_script") { + // An inline script given as JSON text is recorded as the object it parses to, so its steps are + // stripped too. Text that doesn't parse stays as given: the call fails, and no replay keeps it. + if (args.contains("script") && args["script"].is_string()) { + json parsed = json::parse(args["script"].get(), nullptr, /*allow_exceptions=*/false, /*ignore_comments=*/true); + if (parsed.is_object()) + args["script"] = std::move(parsed); + } + if (args.contains("script") && args["script"].is_object() && args["script"].contains("steps") && args["script"]["steps"].is_array()) + for (json& step : args["script"]["steps"]) + if (step.is_object() && step.contains("args")) + step["args"] = without_expected_ids(step.value("tool", std::string()), std::move(step["args"])); + return args; + } + if (takes_ids.count(tool) != 0) + for (const char* key : {"object_id", "volume_id", "object_ids", "volume_ids", "instance_object_ids"}) + args.erase(key); + return args; +} + uint64_t Journal::begin(const std::string& tool, const nlohmann::json& args, bool answers_dialog) { std::lock_guard lock(m_mutex); @@ -26,7 +62,7 @@ uint64_t Journal::begin(const std::string& tool, const nlohmann::json& args, boo Entry e; e.seq = m_next++; e.tool = tool; - e.args = args; + e.args = without_expected_ids(tool, args); e.answers_dialog = answers_dialog; m_entries.push_back(std::move(e)); // A session kept open for days must not grow without bound; a script is exported from the @@ -45,7 +81,7 @@ void Journal::set_args(uint64_t seq, nlohmann::json args) std::lock_guard lock(m_mutex); for (Entry& e : m_entries) if (e.seq == seq) - e.args = std::move(args); + e.args = without_expected_ids(e.tool, std::move(args)); } void Journal::end(uint64_t seq, const ToolResult& result) diff --git a/src/slic3r/GUI/Mcp/McpJournal.hpp b/src/slic3r/GUI/Mcp/McpJournal.hpp index 8fec47b88f..6727bdbe5a 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.hpp +++ b/src/slic3r/GUI/Mcp/McpJournal.hpp @@ -26,6 +26,11 @@ namespace Slic3r { namespace GUI { namespace Mcp { // its reply or before it, and the answer depends on it. Such a job replays with `await:false`, and a // call that answered a dialog replays after a `wait {for:"dialog"}`, since the dialog may open later // than the job's replayed reply. Thread-safe. +// `args` of a `tool` call as the journal records them: expected object_id and volume_id are left out, +// as ids are allocated per process and a replay addresses by index. Inside a run_script's inline steps +// too; a run_python call's code and args stay as written, since a script reads the ids it uses. +nlohmann::json without_expected_ids(const std::string& tool, nlohmann::json args); + class Journal { public: diff --git a/src/slic3r/GUI/Mcp/McpOptions.hpp b/src/slic3r/GUI/Mcp/McpOptions.hpp index 03951840ac..d0fcbef4d0 100644 --- a/src/slic3r/GUI/Mcp/McpOptions.hpp +++ b/src/slic3r/GUI/Mcp/McpOptions.hpp @@ -7,6 +7,11 @@ namespace Slic3r { namespace GUI { namespace Mcp { // Default port of the MCP endpoint; 13618 is the OAuth callback server. inline constexpr int kDefaultPort = 13619; +// The app config key of the Python scripts setting: one switch, off unless true, that lets a person run +// .py scripts (the Run Script dialog, --mcp-script) and agents send run_python. Only the window +// show_python_scripts_dialog() opens writes it; no tool does. +inline constexpr char kPythonScriptsKey[] = "mcp_python_scripts"; + // MCP settings from the command line. Script paths are absolute: OrcaSlicer.cpp resolves them // against the original working directory before the GUI changes it. struct McpLaunchOptions diff --git a/src/slic3r/GUI/Mcp/McpPluginCaller.cpp b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp new file mode 100644 index 0000000000..a67dba506c --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp @@ -0,0 +1,142 @@ +// How a plugin's orca.host.tools calls reach the MCP tools. + +#include "McpService.hpp" +#include "McpTypes.hpp" + +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/plugin/PluginFsUtils.hpp" +#include "slic3r/plugin/PluginManager.hpp" +#include "slic3r/plugin/host/PluginHostTools.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +// The UI thread's answer to a plugin's call: the service with a lease the caller releases, or why not. +struct Admission +{ + std::mutex mutex; + std::condition_variable cv; + bool answered = false; + bool abandoned = false; // the caller stopped waiting: take no lease + McpService* service = nullptr; + std::string refusal; +}; + +// Admits a plugin's call on the UI thread, which owns the service and runs the plugin's unload: the plugin +// must still be loaded and its scope not ended, and the service is started in its catalog-only mode (no +// endpoint) when MCP is off, as the script runner dialog starts it. Returns the service with a lease taken, +// or throws. A caller that stops waiting because the app closes marks the admission abandoned, under the +// lock the UI thread answers it under, so no lease is taken that nobody releases. +McpService* admit_plugin_call(const std::string& plugin) +{ + auto admission = std::make_shared(); + wxGetApp().CallAfter([admission, plugin] { + std::lock_guard lock(admission->mutex); + if (admission->abandoned) + return; + admission->answered = true; + admission->cv.notify_all(); + if (wxGetApp().is_closing()) { + admission->refusal = "OrcaSlicer is closing"; + return; + } + if (!PluginManager::instance().is_plugin_loaded(plugin)) { + admission->refusal = "This plugin is not loaded"; + return; + } + if (wxGetApp().mcp_service() == nullptr || !wxGetApp().mcp_service()->started()) + wxGetApp().start_mcp_service(false); + McpService* service = wxGetApp().mcp_service(); + if (service == nullptr || !service->started() || !service->begin_plugin_scope(plugin) || !service->acquire_lease()) { + admission->refusal = "OrcaSlicer can't run the call now"; + return; + } + admission->service = service; + }); + std::unique_lock lock(admission->mutex); + while (!admission->cv.wait_for(lock, std::chrono::milliseconds(200), [&] { return admission->answered; })) + // The plugins shut down without the app closing at the end of a session on macOS, with the UI thread + // in PluginManager::shutdown(), which waits for this Script worker. + if (wxTheApp == nullptr || wxGetApp().is_closing() || PluginManager::instance().is_shutting_down()) { + // A closing app may never run the closure; a closure that runs after this takes nothing. + admission->abandoned = true; + throw std::runtime_error("OrcaSlicer is closing"); + } + if (admission->service == nullptr) + throw std::runtime_error(admission->refusal); + return admission->service; +} + +// The paths a call's arguments name, as the log records them: the values of the arguments whose name +// says path, dir or file. +std::string named_paths(const json& args) +{ + std::string out; + const auto add = [&out](const json& v) { + if (v.is_string()) + out += (out.empty() ? "" : ", ") + v.get(); + }; + for (const auto& [key, value] : args.items()) { + if (key.find("path") == std::string::npos && key.find("dir") == std::string::npos && key.find("file") == std::string::npos) + continue; + if (value.is_array()) + for (const json& v : value) + add(v); + else + add(value); + } + return out; +} + +} // namespace + +void install_plugin_tool_caller() +{ + set_plugin_tool_caller([](const std::string& plugin, const std::string& tool, const json& args) -> json { + PluginInstallState state; + if (!PluginManager::instance().get_install_state(plugin, state) || !state.permissions.tools) + throw std::runtime_error("This plugin has not been granted the tools permission; it asks for it with " + "request_permissions(tools=True)"); + McpService* service = admit_plugin_call(plugin); + struct Lease + { + McpService* service; + ~Lease() { service->release_lease(); } + } lease{service}; + std::shared_ptr def = service->registry().lookup(tool); + if (def == nullptr) + throw ToolCallError("Unknown tool: " + tool, {{"did_you_mean", service->registry().similar(tool)}}); + json arguments = args; + normalize_arguments(def->input_schema, arguments); + if (std::string err = validate_arguments(def->input_schema, arguments); !err.empty()) + throw ToolCallError("Invalid arguments: " + err, json()); + if (std::string err = resolve_api_call(service->registry(), def, arguments); !err.empty()) + throw ToolCallError(err, json()); + + const ToolResult r = service->core().call_plugin(*def, arguments, plugin); + // The handlers raise no audit events, so this line is the record of what a plugin did; it is best + // effort, since plugin code may write the log folder. + const std::string outcome = r.is_error ? "error: " + r.message : r.data.is_object() ? r.data.value("status", "ok") : "ok"; + BOOST_LOG_TRIVIAL(info) << "[MCP plugin] plugin=" << plugin << " tool=" << tool << " outcome=" << outcome << " paths=[" + << named_paths(arguments) << "]"; + if (r.is_error) + throw ToolCallError(r.message, r.data); + return r.data; + }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpProtocol.cpp b/src/slic3r/GUI/Mcp/McpProtocol.cpp index a095e24362..2e2beeade1 100644 --- a/src/slic3r/GUI/Mcp/McpProtocol.cpp +++ b/src/slic3r/GUI/Mcp/McpProtocol.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include #include @@ -241,8 +243,38 @@ void normalize_arguments(const json& schema, json& args) // ---- ToolRegistry ------------------------------------------------------------ +ToolLane tool_lane(const std::string& name) +{ + static const std::set core{"get_state", "wait", "cancel", "get_log", + "run_script", "export_script", "dialog_respond", "dialog_auto_answer", + "run_python", "python_api"}; + static const std::set ui{"ui_snapshot", "ui_click", "ui_input", "ui_key", "ui_mouse", + "gizmo_file", "webview_eval", "set_view", "screenshot", "start_recording", + "stop_recording", "encode_recording", "list_actions", "run_action", "select"}; + if (core.count(name) != 0) + return ToolLane::Core; + if (ui.count(name) != 0) + return ToolLane::Ui; + return ToolLane::Api; +} + +const char* lane_name(ToolLane lane) +{ + switch (lane) { + case ToolLane::Core: return "core"; + case ToolLane::Ui: return "ui"; + case ToolLane::Api: break; + } + return "api"; +} + void ToolRegistry::add(ToolDef def) { + def.lane = tool_lane(def.name); + const std::string tag = std::string("[") + lane_name(def.lane) + "] "; + // A def copied from the registry and added again already has its tag. + if (def.description.compare(0, tag.size(), tag) != 0) + def.description.insert(0, tag); auto it = std::find_if(m_tools.begin(), m_tools.end(), [&](const ToolDef& t) { return t.name == def.name; }); if (it != m_tools.end()) *it = std::move(def); @@ -256,6 +288,36 @@ const ToolDef* ToolRegistry::find(const std::string& name) const return it == m_tools.end() ? nullptr : &*it; } +std::shared_ptr ToolRegistry::lookup(const std::string& name) const +{ + if (const ToolDef* def = find(name)) + return std::shared_ptr(std::shared_ptr(), def); + return m_dynamic ? m_dynamic(name) : nullptr; +} + +std::string resolve_api_call(const ToolRegistry& registry, std::shared_ptr& def, json& args) +{ + if (!def || def->name != "api_call") + return {}; + const std::string target = args.value("tool", std::string()); + std::shared_ptr inner = registry.lookup(target); + if (!inner) { + std::string message = "Unknown tool: " + target; + if (const auto close = registry.similar(target); !close.empty()) + message += " (did you mean " + close.front() + "?)"; + return message; + } + if (inner->name == "api_call") + return "api_call calls another tool, not itself"; + json inner_args = args.contains("args") && args["args"].is_object() ? args["args"] : json::object(); + normalize_arguments(inner->input_schema, inner_args); + if (std::string err = validate_arguments(inner->input_schema, inner_args); !err.empty()) + return "Invalid arguments for " + target + ": " + err; + def = std::move(inner); + args = std::move(inner_args); + return {}; +} + std::vector ToolRegistry::similar(const std::string& name, std::size_t limit) const { std::vector> scored; @@ -335,17 +397,20 @@ json McpProtocol::result_to_json(const ToolResult& result) json McpProtocol::tools_list() const { + // Core first, then the API lane an agent should prefer, then the UI lane; registration order within each. json tools = json::array(); - for (const ToolDef& def : m_registry.tools()) - tools.push_back(tool_to_json(def)); + for (const ToolLane lane : {ToolLane::Core, ToolLane::Api, ToolLane::Ui}) + for (const ToolDef& def : m_registry.tools()) + if (def.lane == lane) + tools.push_back(tool_to_json(def)); return tools; } json McpProtocol::call_tool(const json& params, bool& unknown_tool, std::string& unknown_name) { unknown_tool = false; - const std::string name = params.value("name", ""); - const ToolDef* def = m_registry.find(name); + const std::string name = params.value("name", ""); + std::shared_ptr def = m_registry.lookup(name); if (def == nullptr) { unknown_tool = true; unknown_name = name; @@ -357,6 +422,8 @@ json McpProtocol::call_tool(const json& params, bool& unknown_tool, std::string& normalize_arguments(def->input_schema, args); if (std::string err = validate_arguments(def->input_schema, args); !err.empty()) return result_to_json(ToolResult::error("Invalid arguments: " + err)); + if (std::string err = resolve_api_call(m_registry, def, args); !err.empty()) + return result_to_json(ToolResult::error(err)); try { return result_to_json(m_caller.call(*def, args)); } catch (const ToolFailure& f) { diff --git a/src/slic3r/GUI/Mcp/McpScript.cpp b/src/slic3r/GUI/Mcp/McpScript.cpp index 0b67dc995e..543eadb2cd 100644 --- a/src/slic3r/GUI/Mcp/McpScript.cpp +++ b/src/slic3r/GUI/Mcp/McpScript.cpp @@ -196,6 +196,8 @@ std::optional check_matcher(const std::string& pointer, const json& } // namespace +std::string inline_script_text(const json& script) { return script.is_string() ? script.get() : script.dump(); } + std::optional