From b3dcf0ac7d8f66ed6cd919d7b0e2bee2dc10d574 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 26 Nov 2026 02:56:29 +0800 Subject: [PATCH] Ask before a plugin calls OrcaSlicer's tools Any plugin could call OrcaSlicer's tools through orca.host.tools without a permission, so it could change your project, run post-processing scripts and answer permission prompts. It now needs the OrcaSlicer tools permission or full access, which it can declare as it loads or is asked for the first time it calls, like its other permissions. The Plugins dialog's Permissions tab has a switch for it, and turning it off ends what the plugin's calls left in force. --- docs/HLSD/mcp-server.md | 12 +- docs/HLSD/mcp-tools.md | 7 +- docs/HLSD/plugin-permissions.md | 57 ++- resources/web/dialog/PluginsDialog/index.js | 17 +- .../web/dialog/PluginsDialog/index.test.js | 15 + src/slic3r/GUI/Mcp/AutomationRuntime.cpp | 102 ++++- src/slic3r/GUI/Mcp/AutomationRuntime.hpp | 29 +- src/slic3r/GUI/Mcp/JobRegistry.cpp | 25 +- src/slic3r/GUI/Mcp/JobRegistry.hpp | 15 + src/slic3r/GUI/Mcp/McpCore.cpp | 4 + src/slic3r/GUI/Mcp/McpPluginCaller.cpp | 24 +- src/slic3r/GUI/Mcp/McpPluginCaller.hpp | 3 +- src/slic3r/GUI/Mcp/McpRecorder.cpp | 6 + src/slic3r/GUI/Mcp/McpRecorder.hpp | 3 + src/slic3r/GUI/Mcp/Tools/GuiTools.cpp | 18 +- src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp | 2 + src/slic3r/GUI/PluginsDialog.cpp | 21 +- src/slic3r/plugin/PluginAuditManager.cpp | 64 ++- src/slic3r/plugin/PluginAuditManager.hpp | 11 + src/slic3r/plugin/PluginFsUtils.cpp | 4 + src/slic3r/plugin/PluginFsUtils.hpp | 6 + src/slic3r/plugin/PluginManager.cpp | 8 + src/slic3r/plugin/PluginManager.hpp | 6 + src/slic3r/plugin/PythonPluginBridge.cpp | 18 +- src/slic3r/plugin/host/PluginHostTools.cpp | 4 +- tests/automation/test_mcp_core.cpp | 69 ++++ tests/data/command_catalog.json | 2 +- tests/slic3rutils/test_mcp_core.cpp | 94 +++++ tests/slic3rutils/test_mcp_web.cpp | 20 + tests/slic3rutils/test_plugin_audit.cpp | 187 ++++++++- tests/slic3rutils/test_plugin_install.cpp | 143 ++++++- tools/mcp/TESTS.md | 5 +- tools/mcp/checks.py | 9 + tools/mcp/test-entries/commands.md | 24 +- tools/mcp/test_plugin_commands.py | 8 +- tools/mcp/test_plugin_tools.py | 389 +++++++++++++++--- .../mcp_tools_declaring.py | 41 ++ .../mcp_tools_fixture/mcp_tools_fixture.py | 29 +- .../mcp_tools_ungranted.py | 62 +++ 39 files changed, 1395 insertions(+), 168 deletions(-) create mode 100644 tools/mcp/tests/plugins/mcp_tools_declaring/mcp_tools_declaring.py create mode 100644 tools/mcp/tests/plugins/mcp_tools_ungranted/mcp_tools_ungranted.py diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index e5a247f946..d4a3597a50 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -465,11 +465,13 @@ stopped run ends. ## Plugins and the tools -A plugin's code calls the commands through `orca.host.tools` with no permission of its own: any loaded plugin can do -what an agent can. The tools run OrcaSlicer's own code, which the plugin audit doesn't judge, so a plugin's grants -bound its Python code and not what it asks the tools to do, and each call is logged with the plugin's key. A call -runs as a job owned by the plugin, never journaled, so the session tools are scoped to the plugin, and what its calls -leave behind ends when it unloads, from which moment its calls are refused. +A plugin's code calls the commands through `orca.host.tools` only with the tools permission or full access, asked for +at load or when it first calls, as its other permissions are ("Calling OrcaSlicer's tools" in +[plugin-permissions.md](plugin-permissions.md)). The tools run OrcaSlicer's own code, which the plugin audit doesn't +judge, so a plugin's other grants bound its Python code and not what it asks the tools to do, and each call is logged +with the plugin's key. A call runs as a job owned by the plugin, never journaled, so the session tools are scoped to the +plugin, and what its calls leave behind ends when it unloads or loses the permission, from which moment its calls are +refused; a call made before that leaves nothing behind for the client. A plugin may offer operations, `plugin..`, which `tool_list` lists and `tool_call`, scripts and replay steps run. They are a source of the command catalog, looked up after its own commands, and run as jobs under the diff --git a/docs/HLSD/mcp-tools.md b/docs/HLSD/mcp-tools.md index d5a82b09a8..895d73632c 100644 --- a/docs/HLSD/mcp-tools.md +++ b/docs/HLSD/mcp-tools.md @@ -299,9 +299,10 @@ with the same preference. `filament_sync_ams` refuses a printer of another model | `plugin_uninstall` | Remove a plugin for good, unsubscribing a cloud one | `plugin` | | `plugin_refresh` | Rescan the installed plugins and fetch the plugin hub's list again, then reply with the plugins | | -A plugin's code calls the commands through `orca.host.tools` as an agent does, scoped to the plugin: `replay_export` -is refused, `job_cancel` and `app_wait {for: "job"}` act only on its own jobs, and the rules, recordings and held -presses its calls leave end when it unloads, from which moment its calls are refused. An operation a plugin offers +A plugin's code calls the commands through `orca.host.tools` as an agent does, with the tools permission +([plugin-permissions.md](plugin-permissions.md)), scoped to the plugin: `replay_export` is refused, `job_cancel` and +`app_wait {for: "job"}` act only on its own jobs, and the rules, recordings and held presses its calls leave end when +it unloads or loses the permission, from which moment its calls are refused. An operation a plugin offers (`plugin..`, which `tool_list` lists and `tool_call` runs) runs as a job: as a change, refused behind a dialog and journaled, when the plugin declares that it changes something, else as a read. A call of an operation whose plugin has unloaded, or loaded again since, is refused. diff --git a/docs/HLSD/plugin-permissions.md b/docs/HLSD/plugin-permissions.md index 81d83fc659..ff7e6fa01f 100644 --- a/docs/HLSD/plugin-permissions.md +++ b/docs/HLSD/plugin-permissions.md @@ -33,6 +33,7 @@ Permissions are stored per plugin key. A plugin can hold: | `threading` | boolean | Permission to start a Python thread with `_thread.start_new_thread`. | | `events` | target list | Audited events that expose no target, keyed as `:`, for example `Socket:socket.__new__`. Matched verbatim. | | `full_access` | boolean | Turns off the permission decision for the plugin. See "Full access". | +| `tools` | boolean | Permission to call OrcaSlicer's tools through `orca.host.tools`. See "Calling OrcaSlicer's tools". | Create and delete grants are independent of read and read/write grants. An empty list grants no folders; an absolute folder path grants operations directly inside that folder, while a path @@ -201,6 +202,8 @@ GUI-thread caller is rejected when another prompt is active instead of blocking Denying the request aborts the load. A readable sidecar with `full_access` accepts the declaration without a prompt and without adding a grant. +`request_permissions(tools=True)` is one more bucket of that combined prompt, as `threading=True` is. + Network URLs passed to `request_permissions(network=...)` are normalized to `scheme://host` before prompting or storing, so one approval covers every path and port on that host and also authorizes raw sockets to it. A relative filesystem tree grant is @@ -212,7 +215,8 @@ sidecar show the absolute scope it covers. An event that is not covered by a saved grant or an implicit rule is either put to the user or denied. If the caller is on the wx main thread and no audit prompt is active, the modal runs inline. Otherwise, as on the Script workflow, the plugin-load worker, or the -slicing worker, the current event is denied and the prompt is queued for the GUI thread. +slicing worker, the current event is denied and the prompt is queued for the GUI thread. A +plugin's tool call without the tools grant takes the same path from its Script worker. `AuditPromptQueue` serializes runtime prompts, one-time recursive-delete consent, and load-time declarations, so at most one is shown at a time, including during a modal dialog's nested event loop. An event raised inside that loop is @@ -295,7 +299,7 @@ The following are denied before any allowed root or full-access check: Grants and install state live in `.install_state.json` in the plugin root. The `permissions` object stores `fs_read`, `fs_readwrite`, `fs_create`, `fs_delete`, `network_http`, -`network_socket`, `process`, `threading`, `events`, and `full_access`. It never stores a +`network_socket`, `process`, `threading`, `tools`, `events`, and `full_access`. It never stores a recursive-delete consent: that approval and any retry approval are in memory only, so accepting one does not widen the plugin's saved delete scope. The file is written by `write_install_state`, the single writer for the sidecar schema. In-process @@ -311,6 +315,7 @@ Reading is deliberately fail-closed: form. Reading never rewrites the file. - `full_access` is enabled only by an explicit JSON boolean. A missing key, a string, a number, or any other type reads as false. +- `tools` is granted only by a JSON `true`; a missing key or any other value reads as `false`. A sidecar that exists but cannot be read is never overwritten, because it may still hold grants and capability choices. The one exception is a plugin load: if the sidecar is a @@ -359,8 +364,8 @@ lowercase `scheme://host`, dropping port, path, query and fragment. Bare hosts, schemes, wildcards and URLs carrying userinfo are refused rather than guessed. Network entries cover every port, path and query on the host. -The dialog warns before enabling full access. Grants stored -while full access is on are inert and apply again when full access is off. Turning full access +The dialog warns before enabling full access. The OrcaSlicer tools switch is a yes/no switch like +Threading's. Grants stored while full access is on are inert and apply again when full access is off. Turning full access on does not delete the stored lists. A permission change affects subsequent audit decisions, not operations already authorized. @@ -369,6 +374,35 @@ On Linux and macOS, create and delete operations using a directory file descript against its resolved path. If that path cannot be resolved, the operation is denied, even with full access. +## Calling OrcaSlicer's tools + +`orca.host.tools` lets a plugin call every command a plugin caller has: an agent's commands, less the few +[mcp-tools.md](mcp-tools.md) refuses a plugin (`replay_export`) or limits to its own jobs. Through them it reaches +the project, presets and files, post-processing scripts (which run as programs), the window, and its dialogs, +permission requests included. A plugin holding it can therefore give itself any other permission, +which is why its prompt says so. `orca.host.tools.list()` and `describe()` only read the +catalog and need no permission, and operations a plugin offers with `orca.register_operation` stay +free; a Python script a person or an agent runs is not a plugin and is unaffected. + +The grant is `tools` true or full access, read from the sidecar on every call. A plugin's own call asks +for it as an undeclared audited event does, on the plugin's Script worker before the call is admitted +(`PluginAuditManager::request_tools_permission` in `admit_plugin_call`): without the grant the call is +refused and the prompt queued (see "Runtime prompts"), and a Yes is saved, so the plugin's next call +works. A sidecar that exists but cannot be read refuses the call without asking, as a declaration is refused, +since a Yes could not be saved there. The admission on the UI thread checks the grant again without asking +(`PluginManager::plugin_may_call_tools`), so a grant withdrawn in between cannot reopen the plugin's +scope, and every call a plugin owns, its script and replay runs' children included, is checked again +where the MCP core runs it (`JobRegistry::tools_refused` in `McpCore::run`). Each refuses with +`orca.host.tools.ToolError`, `details["code"] == "tools_not_allowed"`. + +When a Plugins-dialog edit leaves a plugin without the tools, `AutomationRuntime::plugin_tools_withdrawn` +asks its running calls to stop and ends its scope and its running runs' scopes, popping their +auto-answer rules, ending their recording and releasing their held presses, as an unload does, but +without blocking it, so a later grant works without a reload. A call that passed its check just before +is refused the moment it would leave such an effect behind: the plugin is marked withdrawn until a call +admitted under a new grant opens its scope again, and the places that publish a press or start a +recording check the scope is still open (`require_owner_scope`). + ## Full access Full access is a per-plugin boolean that turns off the permission decision. It does not @@ -376,7 +410,8 @@ remove the audit hook. For recognized events it is reached after the uncondition denied-path check, so the application configuration, the cloud user-secret file, certificates, configuration paths, and `.install_state.json` stay blocked from direct Python access. Everything else that the audit hook recognizes is allowed without a grant -or a prompt, and declared permissions are accepted without prompting. The read-only +or a prompt, and declared permissions are accepted without prompting. It also allows the plugin's +tool calls. The read-only `resources_dir()` root is a normal-mode restriction only: full access permits writes there when the operating system allows them. The denied `cert` keyword still blocks the bundled certificate. @@ -421,9 +456,10 @@ never treated as an opt-out. - **Host APIs are not audit events.** Calls into OrcaSlicer's Python host APIs, such as preset updates or UI actions, execute C++ host code and follow that API's contract. The audit hook judges the Python-level filesystem, network, process and thread events it is - given, not the host API's internal work. That includes `orca.host.tools`, through which any - plugin calls the MCP tools: it can write the files those tools write and answer dialogs, - permission prompts included. + given, not the host API's internal work. `orca.host.tools` is gated by the tools permission + instead (see "Calling OrcaSlicer's tools"), and once granted it reaches every command a plugin + caller has: the files those tools write, post-processing scripts, and dialogs, permission + prompts included. - **Denied paths are a direct-access block.** Path laundering through a symlink, hardlink, subprocess, or Windows 8.3 short name is outside the model. A tree grant is canonicalized for matching, but the deny check itself is base-name and component based. @@ -479,7 +515,10 @@ never treated as an opt-out. - `src/slic3r/plugin/PluginManager.hpp` / `.cpp` - `mutate_plugin_permissions`, `revoke_plugin_permissions`, `get_install_state`. - `src/slic3r/GUI/PluginsDialog.cpp` - permission editor payloads, native confirmations, - and the full-access request path. + the full-access request path, the tools switch and its withdrawal call. +- `src/slic3r/GUI/Mcp/McpPluginCaller.cpp`, `JobRegistry.hpp` / `.cpp`, `McpCore.cpp`, + `AutomationRuntime.hpp` / `.cpp` - the tools checks (`admit_plugin_call`, `tools_refused`), + `plugin_tools_withdrawn` and `require_owner_scope`. - `tests/slic3rutils/test_plugin_audit.cpp`, `tests/slic3rutils/test_plugin_install.cpp`, `tests/slic3rutils/test_plugin_lifecycle.cpp` - audit decision, sidecar, and permission mutation coverage. diff --git a/resources/web/dialog/PluginsDialog/index.js b/resources/web/dialog/PluginsDialog/index.js index 2c3efdc0d1..118fa51dc0 100644 --- a/resources/web/dialog/PluginsDialog/index.js +++ b/resources/web/dialog/PluginsDialog/index.js @@ -989,6 +989,9 @@ function PrunePermissionDraftBookkeeping(draft) { delete draft.additions[category]; } +// The permissions that are a yes/no switch rather than a list of targets. +const BOOLEAN_PERMISSIONS = new Set(["threading", "tools"]); + // A permission grant can arrive while the tab is open. Merge the latest stored list into the // rows on screen, but keep every unsaved value the user typed and let the draft win a conflict. // Edits are keyed by the original source value, so a grant that adds or reorders rows does not @@ -999,7 +1002,7 @@ function MergePermissionSource(draft, sourcePermissions) { const nextPending = {}; for (const [category, entries] of Object.entries(sourcePermissions || {})) { - if (category === "threading" && typeof entries === "boolean") { + if (BOOLEAN_PERMISSIONS.has(category) && typeof entries === "boolean") { nextValues[category] = entries; continue; } @@ -1108,6 +1111,7 @@ function RenderPermissions(plugin) { ["network_socket", "permissions_network_socket", "Network sockets"], ["process", "permissions_process", "Processes"], ["threading", "permissions_threading", "Threading"], + ["tools", "permissions_tools", "OrcaSlicer tools"], ["events", "permissions_events", "Events"] ]; const categoryGuidance = { @@ -1117,6 +1121,7 @@ function RenderPermissions(plugin) { network_socket: [null, "https://example.com"], process: [T("permissions_process_help", "Executable grants cover all arguments. CommandLine: entries cover only the exact command line."), T("permissions_process_placeholder", "Executable or command name")], threading: [T("permissions_threading_help_short", "Allow this plugin to create threads."), ""], + tools: [T("permissions_tools_help_short", "Allow this plugin to call OrcaSlicer's tools, as AI agents do: change your project, presets and files, run post-processing scripts, and answer dialogs, permission requests included."), ""], events: [T("permissions_events_help", "Enter a category and event separated by a colon, such as Socket:socket.__new__."), T("permissions_events_placeholder", "Socket:socket.__new__")] }; const placeholder = document.createElement("label"); @@ -1196,7 +1201,7 @@ function RenderPermissions(plugin) { { keys: ["fs_read", "fs_readwrite"], title: T("permissions_group_filesystem", "File system") }, { keys: ["network_http", "network_socket"], title: T("permissions_network_access_title", "Network access"), guidance: T("permissions_network_access_guidance", "Enter a full http:// or https:// URL; only its scheme and host are saved, so the grant covers every port, path, and query on that host. A network socket grant also accepts a bare host name or IP address, with or without a port, and covers every port on that host. Other schemes are not accepted. Grants in either list are checked for HTTP and socket access.") }, - { keys: ["process", "threading"], title: T("permissions_group_execution", "Execution") }, + { keys: ["process", "threading", "tools"], title: T("permissions_group_execution", "Execution") }, { keys: ["events"], title: T("permissions_group_events", "Audit events") } ]; const groupBodies = new Map(); @@ -1264,7 +1269,7 @@ function RenderPermissions(plugin) { description.appendChild(guidance); } const entries = draft.values[key]; - const available = key === "threading" ? typeof entries === "boolean" : Array.isArray(entries); + const available = BOOLEAN_PERMISSIONS.has(key) ? typeof entries === "boolean" : Array.isArray(entries); if (!available) { const unavailable = document.createElement("p"); unavailable.className = "permission-notice"; @@ -1274,16 +1279,16 @@ function RenderPermissions(plugin) { continue; } - const categoryEnabled = installed && (key === "threading" + const categoryEnabled = installed && (BOOLEAN_PERMISSIONS.has(key) ? typeof plugin.permissions?.[key] === "boolean" : Array.isArray(plugin.permissions?.[key])); - if (key === "threading") { + if (BOOLEAN_PERMISSIONS.has(key)) { const threadLabel = document.createElement("label"); threadLabel.className = "permission-thread-toggle"; const threadCheckbox = document.createElement("input"); threadCheckbox.type = "checkbox"; threadCheckbox.setAttribute("role", "switch"); - threadCheckbox.id = "permission-thread-toggle"; + threadCheckbox.id = `permission-${key}-toggle`; threadCheckbox.checked = entries; threadCheckbox.disabled = !categoryEnabled; threadCheckbox.setAttribute("aria-labelledby", heading.id); diff --git a/resources/web/dialog/PluginsDialog/index.test.js b/resources/web/dialog/PluginsDialog/index.test.js index f5b7051efc..284f214094 100644 --- a/resources/web/dialog/PluginsDialog/index.test.js +++ b/resources/web/dialog/PluginsDialog/index.test.js @@ -49,3 +49,18 @@ test("update control stays hidden when no update is available, even while loadin assert.equal(button.hidden, true); }); + +test("a permission source's boolean switches reach the draft with their values", () => { + const dialog = loadPluginDialog(); + const draft = { values: {}, edits: {}, additions: {} }; + + dialog.MergePermissionSource(draft, { threading: true, tools: false, full_access: false, fs_read: ["/a"] }); + + assert.equal(draft.values.threading, true); + assert.equal(draft.values.tools, false, "the OrcaSlicer tools switch shows its stored value"); + assert.deepEqual(Array.from(draft.values.fs_read), ["/a"]); + assert.equal(draft.values.full_access, undefined, "full access is its own control, not a permission row"); + + dialog.MergePermissionSource(draft, { threading: true, tools: true, fs_read: [] }); + assert.equal(draft.values.tools, true); +}); diff --git a/src/slic3r/GUI/Mcp/AutomationRuntime.cpp b/src/slic3r/GUI/Mcp/AutomationRuntime.cpp index 79640e1694..f2881853c3 100644 --- a/src/slic3r/GUI/Mcp/AutomationRuntime.cpp +++ b/src/slic3r/GUI/Mcp/AutomationRuntime.cpp @@ -104,6 +104,16 @@ WorkerHooks ui_job_worker_hooks() // The scope key of a plugin's calls, which no job id ("j") can equal. std::string plugin_scope_key(const std::string& plugin_key) { return "plugin:" + plugin_key; } +// The plugin whose scope `key` is, or "" for a run's. +std::string plugin_of_scope_key(const std::string& key) +{ + const std::string prefix = plugin_scope_key({}); + return key.compare(0, prefix.size(), prefix) == 0 ? key.substr(prefix.size()) : std::string(); +} + +// What a plugin's dialog_auto_answer call made before the plugin unloaded fails with. +constexpr char kRulesOfUnloadedPlugin[] = "The plugin that made this call has been unloaded; its rules were not applied"; + } // namespace void AutomationRuntimeDeleter::operator()(AutomationRuntime* runtime) const @@ -168,6 +178,8 @@ bool AutomationRuntime::start(std::string& err) }); // A plugin's calls are refused from the moment it unloads, before end_plugin_scope() comes. m_jobs.set_owner_liveness([](const std::string& plugin) { return PluginManager::instance().is_plugin_loaded(plugin); }); + // And refused while the plugin may not call the tools, read again for every call. + m_jobs.set_owner_permission([](const std::string& plugin) { return PluginManager::instance().plugin_may_call_tools(plugin); }); CoreTiming timing; timing.reply_budget_cap = reply_budget_cap_from(boost::nowide::getenv("ORCA_MCP_REPLY_BUDGET_MS")); if (timing.reply_budget_cap.count() > 0) @@ -343,6 +355,8 @@ AutoAnswerSet AutomationRuntime::set_auto_answer(std::vector rul const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); std::lock_guard lock(m_rules_mutex); const AutoAnswerSet set = [&]() -> AutoAnswerSet { + // Before any scope is looked for: a run the plugin started is the plugin's too. + refuse_gone_plugin(plugin, kRulesOfUnloadedPlugin); // The nearest running replay or script in the caller's job chain owns the rules. for (const std::string& job : ancestry) if (auto it = m_run_rule_layers.find(job); it != m_run_rule_layers.end()) { @@ -359,8 +373,8 @@ AutoAnswerSet AutomationRuntime::set_auto_answer(std::vector rul it->second.push_back(m_modals->push_rules(std::move(rules))); return {"plugin", it->second.back(), false}; } - if (m_unloaded_plugins.count(plugin) != 0) - throw ToolFailure("The plugin that made this call has been unloaded; its rules were not applied"); + // A call from before the plugin unloaded, as run_owner() refuses it: its rules are not the client's. + throw ToolFailure(kRulesOfUnloadedPlugin); } // A call that was running when the client scope closed must not bring its client's rules back. if (!m_client_scope_open) @@ -452,15 +466,13 @@ void AutomationRuntime::rule_answered(int layer, const std::string& title, const const std::string& button) { // Whose the layer is: a run's, a plugin's, else a client's. - std::string run, plugin; - const std::string prefix = plugin_scope_key({}); + std::string run, plugin; { std::lock_guard lock(m_rules_mutex); for (const auto& [owner, layers] : m_run_rule_layers) if (std::find(layers.begin(), layers.end(), layer) != layers.end()) { - if (owner.compare(0, prefix.size(), prefix) == 0) - plugin = owner.substr(prefix.size()); - else + plugin = plugin_of_scope_key(owner); + if (plugin.empty()) run = owner; break; } @@ -472,23 +484,35 @@ std::string AutomationRuntime::run_owner(const std::vector& ancestr { const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); std::lock_guard lock(m_rules_mutex); + // Before any scope is looked for: a run the plugin started is the plugin's too. A call of an unloaded plugin must + // not leave anything nothing would end. + refuse_gone_plugin(plugin, kPluginUnloaded); for (const std::string& job : ancestry) if (m_run_rule_layers.count(job) != 0) return job; - if (!plugin.empty() && m_run_rule_layers.count(plugin_scope_key(plugin)) != 0) + if (plugin.empty()) + return {}; + if (m_run_rule_layers.count(plugin_scope_key(plugin)) != 0) return plugin_scope_key(plugin); - // A call of an unloaded plugin must not leave anything nothing would end. - if (!plugin.empty() && m_unloaded_plugins.count(plugin) != 0) - throw ToolFailure("The plugin that made this call has been unloaded"); - return {}; + // Every call a plugin is admitted for opens its scope, so a call of the plugin's with none open was made before it + // unloaded (it may have loaded again since): it is not the client's. + throw ToolFailure(kPluginUnloaded); } bool AutomationRuntime::begin_plugin_scope(const std::string& plugin_key) { - std::lock_guard lock(m_rules_mutex); - if (m_unloaded_plugins.count(plugin_key) != 0) - return false; - m_run_rule_layers.emplace(plugin_scope_key(plugin_key), std::vector{}); + const std::string key = plugin_scope_key(plugin_key); + bool opened; + { + std::lock_guard lock(m_rules_mutex); + if (m_unloaded_plugins.count(plugin_key) != 0) + return false; + m_withdrawn_plugins.erase(plugin_key); + opened = m_run_rule_layers.try_emplace(key).second; + } + // The recorder remembers an ended scope, to refuse its late starts; a scope opened again records again. + if (opened && m_recorder) + m_recorder->owner_reopened(key); return true; } @@ -501,12 +525,54 @@ void AutomationRuntime::end_plugin_scope(const std::string& plugin_key) // No call of the plugin starts from now on, one it was admitted for included, and the ones running stop, // as a stopped replay's steps do. m_jobs.block_owner(plugin_key); - for (const std::string& job : m_jobs.running_owned_by(plugin_key)) + end_scopes_of(plugin_key); +} + +void AutomationRuntime::end_scopes_of(const std::string& plugin_key) +{ + const std::vector running = m_jobs.running_owned_by(plugin_key); + for (const std::string& job : running) m_jobs.request_stop(job); - // Not waited for: an unloading plugin's recording is closed by the recorder's own threads. + // A running replay's or script's rules, recording and presses end now, not when it unwinds; its own end then + // finds no scope. Not waited for: a recording is closed by the recorder's own threads. + for (const std::string& job : running) + end_run_scope(job, false); end_run_scope(plugin_scope_key(plugin_key), false); } +void AutomationRuntime::plugin_tools_withdrawn(const std::string& plugin_key) +{ + { + std::lock_guard lock(m_rules_mutex); + m_withdrawn_plugins.insert(plugin_key); + } + end_scopes_of(plugin_key); +} + +void AutomationRuntime::require_owner_scope(const std::string& owner) const +{ + if (owner.empty()) + return; + // The plugin whose scope it is, or whose run: a run's job carries the plugin that started it, if one did. Asked + // before the rules lock, as set_auto_answer() asks it. + const std::string scope_plugin = plugin_of_scope_key(owner); + const std::string plugin = scope_plugin.empty() ? m_jobs.owner(owner) : scope_plugin; + std::lock_guard lock(m_rules_mutex); + refuse_gone_plugin(plugin, kPluginUnloaded); + if (m_run_rule_layers.count(owner) == 0) + throw ToolFailure(scope_plugin.empty() ? "The replay or script that made this call has ended" : kPluginUnloaded); +} + +void AutomationRuntime::refuse_gone_plugin(const std::string& plugin, const char* unloaded) const +{ + if (plugin.empty()) + return; + if (m_withdrawn_plugins.count(plugin) != 0) + throw ToolFailure(kPluginToolsRefused, {{"code", kToolsNotAllowed}}); + if (m_unloaded_plugins.count(plugin) != 0) + throw ToolFailure(unloaded); +} + void AutomationRuntime::plugin_loaded(const std::string& plugin_key) { { diff --git a/src/slic3r/GUI/Mcp/AutomationRuntime.hpp b/src/slic3r/GUI/Mcp/AutomationRuntime.hpp index b153d70f2a..39dc1c3f85 100644 --- a/src/slic3r/GUI/Mcp/AutomationRuntime.hpp +++ b/src/slic3r/GUI/Mcp/AutomationRuntime.hpp @@ -174,7 +174,9 @@ public: // a slice or an export through the plater. UI thread. void cancel_operations_of(const std::string& job); // The job of the nearest running replay or script in `ancestry`, else the scope of the plugin whose call it is, - // or "" for a client's own call. Any thread. + // or "" for a client's own call. Throws ToolFailure for a plugin's call whose plugin lost the tools, unloaded, or + // has no scope open (the call was made before it unloaded), so nothing it leaves behind falls to the client. Any + // thread. std::string run_owner(const std::vector& ancestry) const; // Keeps the runtime from being destroyed while a caller outside the core uses it: a plugin's call holds // a lease from the moment the UI thread hands it the runtime until the call returns, and drain() waits @@ -185,11 +187,22 @@ public: // run's do, until the plugin unloads: begin is called before each of its calls (idempotent), end when // it unloads. Any thread. // begin returns false for a plugin whose scope ended (it unloaded) until plugin_loaded() is called for - // it again; end also stops the plugin's running calls, and a call of its that would leave something - // behind after that is refused (run_owner, set_auto_answer throw). + // it again; end also stops the plugin's running calls and ends the scopes of its running replays and scripts, + // and a call of its that would leave something behind after that is refused (run_owner, set_auto_answer and + // require_owner_scope throw). + // A begin that opens the scope afresh also lets a recording start under it again (McpRecorder::owner_reopened()). bool begin_plugin_scope(const std::string& plugin_key); void end_plugin_scope(const std::string& plugin_key); void plugin_loaded(const std::string& plugin_key); + // The plugin lost its permission to call the tools (the Plugins dialog's switch or full access turned off): its + // scopes end as at unload, but its calls are not blocked; the permission refuses them, and a call admitted before + // is refused where it would leave something behind, until begin_plugin_scope() opens the scope under a new grant. + // UI thread. + void plugin_tools_withdrawn(const std::string& plugin_key); + // Throws ToolFailure unless what `owner` (a run_owner() value) leaves behind may still be published: its scope is + // open and its plugin has neither lost the tools nor unloaded. A client's "" passes, as its own check covers it. + // Asked where a press or a recording is published, after the owner was found on the caller's thread. Any thread. + void require_owner_scope(const std::string& owner) const; // Calls a command on a thread the runtime owns, which stop() joins. False, with nothing started, when the // runtime is not started or is stopping, or when the system cannot start a thread. Any thread. @@ -208,6 +221,13 @@ private: // the runtime stops first. A thread follow() starts calls it. std::optional call_to_end(const NativeCommand& command, const nlohmann::json& args, bool person, const nlohmann::json& origin); + // Asks the plugin's running calls to stop and ends its scope with the scopes of its running replays and + // scripts, popping their rules, ending their recording and releasing their presses. For an unload and a + // withdrawal of the tools alike. + void end_scopes_of(const std::string& plugin_key); + // Under m_rules_mutex: throws for a call of `plugin` ("" for none) after it lost the tools, with kToolsNotAllowed, + // or unloaded, with the message `unloaded`. + void refuse_gone_plugin(const std::string& plugin, const char* unloaded) const; // An auto-answer rule of `layer` answered a dialog: the activity log lists it with the run, plugin or client whose // rule it was. UI thread. void rule_answered(int layer, const std::string& title, const std::string& message, const std::string& pattern, @@ -259,7 +279,8 @@ private: std::atomic m_generation{1}; std::vector> m_on_ready; // UI thread - std::set m_unloaded_plugins; // under m_rules_mutex + std::set m_unloaded_plugins; // under m_rules_mutex + std::set m_withdrawn_plugins; // under m_rules_mutex: lost the tools since their scope last opened // Last, so its threads, which use everything above, are gone first. FollowedThreads m_followed; }; diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp index 73a26b1a19..c99f390307 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -14,16 +14,22 @@ namespace Slic3r { namespace GUI { namespace Mcp { +std::string JobRegistry::call_owner(const std::string& parent, const std::string& owner) const +{ + if (!owner.empty() || parent.empty()) + return owner; + std::lock_guard lock(m_mutex); + const auto it = m_jobs.find(parent); + return it != m_jobs.end() ? it->second.owner : std::string(); +} + bool JobRegistry::unloaded(const std::string& parent, const std::string& owner) const { - std::string plugin = owner; + const std::string plugin = call_owner(parent, owner); + if (plugin.empty()) + return false; { 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; } @@ -31,6 +37,13 @@ bool JobRegistry::unloaded(const std::string& parent, const std::string& owner) return m_owner_loaded && !m_owner_loaded(plugin); } +bool JobRegistry::tools_refused(const std::string& parent, const std::string& owner) const +{ + const std::string plugin = call_owner(parent, owner); + // The hook reads the plugin's install state, so it is asked without this registry's lock. + return !plugin.empty() && m_owner_allowed && !m_owner_allowed(plugin); +} + std::string JobRegistry::create(const std::string& tool, const std::string& parent, const std::string& owner, bool person) { const std::string id = register_job(tool, parent, owner, person); diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp index 343e16bb03..54d6b1429c 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.hpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -22,6 +22,12 @@ 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"; +// What a call of a plugin without permission to call the tools fails with, with the code kToolsNotAllowed. +inline constexpr char kPluginToolsRefused[] = + "This plugin is not allowed to call OrcaSlicer's tools. A person allows them when OrcaSlicer asks, or on the " + "Permissions tab of the Plugins dialog; a plugin can also declare them as it loads with " + "orca.request_permissions(tools=True)."; +inline constexpr char kToolsNotAllowed[] = "tools_not_allowed"; // 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 `app_wait {for:"job"}` can return its result; the @@ -54,6 +60,12 @@ public: // 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); } + // Whether the call's plugin, found as unloaded() finds it, may not call the tools now, by the permission + // hook. False for a call that is not a plugin's, and with no hook set. + bool tools_refused(const std::string& parent, const std::string& owner) const; + // Whether a plugin may call the tools, asked on the calling thread without the registry's lock held, on every + // call, so a grant changed meanwhile applies to the next one. Set once, before any job is created. + void set_owner_permission(std::function allowed) { m_owner_allowed = std::move(allowed); } // The plugin that owns `id`, or "" for anyone else's job, or one no longer known. std::string owner(const std::string& id) const; // The running jobs `owner` (a plugin) owns. @@ -103,6 +115,8 @@ public: private: // create() without the liveness check. std::string register_job(const std::string& tool, const std::string& parent, const std::string& owner, bool person); + // The call's plugin: `owner`, else the owner of the job `parent`, else "". + std::string call_owner(const std::string& parent, const std::string& owner) const; struct Job { @@ -129,6 +143,7 @@ private: std::set m_stop_requests; std::set m_blocked_owners; std::function m_owner_loaded; + std::function m_owner_allowed; uint64_t m_next = 1; bool m_woken = false; }; diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index 6bce269ef9..5c2e1b7c2f 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -394,6 +394,10 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co // unloads (CallContext::cancelled()). if (m_jobs.unloaded(parent, plugin)) return finish(ToolResult::error(kPluginUnloaded)); + // Nor does one of a plugin without permission to call the tools, its script runs' children included: each + // call is checked here, so a permission withdrawn meanwhile refuses the next. + if (m_jobs.tools_refused(parent, plugin)) + return finish(ToolResult::error(kPluginToolsRefused, {{"code", kToolsNotAllowed}})); const uint64_t call = m_next_call++; if (def.inline_call) { diff --git a/src/slic3r/GUI/Mcp/McpPluginCaller.cpp b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp index fff834bcc6..f55fb86763 100644 --- a/src/slic3r/GUI/Mcp/McpPluginCaller.cpp +++ b/src/slic3r/GUI/Mcp/McpPluginCaller.cpp @@ -5,11 +5,13 @@ #include "McpArguments.hpp" #include "McpProtocol.hpp" #include "AutomationRuntime.hpp" +#include "JobRegistry.hpp" #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/plugin/PluginAuditManager.hpp" #include "slic3r/plugin/PluginManager.hpp" #include "slic3r/plugin/host/PluginHostTools.hpp" @@ -38,17 +40,25 @@ struct Admission std::condition_variable cv; bool answered = false; bool abandoned = false; // the caller stopped waiting: take no lease + bool no_tools = false; // the plugin may not call the tools: a ToolError, not an admission error AutomationRuntime* runtime = nullptr; std::string refusal; }; // Admits a plugin's call on the UI thread, which owns the runtime and runs the plugin's unload: the plugin -// must still be loaded and its scope not ended, and the runtime is started without its endpoint when MCP is -// off, with the GUI instruments on, as Action Replay starts it. Returns the runtime 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. +// must still be loaded, may call the tools, and its scope not ended, and the runtime is started without its +// endpoint when MCP is off, with the GUI instruments on, as Action Replay starts it. A plugin without the tools +// is refused before anything starts, with the core's own refusal for it (McpCore::run checks every call again). +// Returns the runtime 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. AutomationRuntime* admit_plugin_call(const std::string& plugin) { + // Asked here, on the plugin's Script worker, as an undeclared audited event on a worker is: without the grant + // the call is refused and the prompt queued, and a Yes lets the plugin's next call through. The UI thread checks + // the grant again below, without asking, in case it was withdrawn meanwhile. + if (!PluginAuditManager::instance().request_tools_permission(plugin)) + throw ToolCallError(kPluginToolsRefused, {{"code", kToolsNotAllowed}}); auto admission = std::make_shared(); wxGetApp().CallAfter([admission, plugin] { std::lock_guard lock(admission->mutex); @@ -64,6 +74,10 @@ AutomationRuntime* admit_plugin_call(const std::string& plugin) admission->refusal = "This plugin is not loaded"; return; } + if (!PluginManager::instance().plugin_may_call_tools(plugin)) { + admission->no_tools = true; + return; + } AutomationRuntime* runtime = wxGetApp().automation(); if (runtime == nullptr || !runtime->begin_plugin_scope(plugin) || !runtime->acquire_lease()) { admission->refusal = "OrcaSlicer can't run the call now"; @@ -82,6 +96,8 @@ AutomationRuntime* admit_plugin_call(const std::string& plugin) admission->abandoned = true; throw std::runtime_error("OrcaSlicer is closing"); } + if (admission->no_tools) + throw ToolCallError(kPluginToolsRefused, {{"code", kToolsNotAllowed}}); if (admission->runtime == nullptr) throw std::runtime_error(admission->refusal); return admission->runtime; diff --git a/src/slic3r/GUI/Mcp/McpPluginCaller.hpp b/src/slic3r/GUI/Mcp/McpPluginCaller.hpp index 920bf023a3..339761db5d 100644 --- a/src/slic3r/GUI/Mcp/McpPluginCaller.hpp +++ b/src/slic3r/GUI/Mcp/McpPluginCaller.hpp @@ -14,7 +14,8 @@ namespace Mcp { // Lets plugins call the tools through orca.host.tools: a call from a plugin's Script worker runs as // McpCore::call_plugin(), starting the automation runtime without the MCP endpoint when the server is off, and is -// logged. Called once by GUI_App as it sets up plugins. +// logged. A plugin without the tools permission or full access is refused before anything starts. Called once by +// GUI_App as it sets up plugins. void install_plugin_tool_caller(); // What a plugin's orca.host.tools.call(tool, args) runs: the command `tool` names in `catalog`, `args` normalized and diff --git a/src/slic3r/GUI/Mcp/McpRecorder.cpp b/src/slic3r/GUI/Mcp/McpRecorder.cpp index 64ae69c555..411e4d7e94 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.cpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.cpp @@ -698,6 +698,12 @@ void McpRecorder::owner_ended(const std::string& owner) m_ended_owners.insert(owner); } +void McpRecorder::owner_reopened(const std::string& owner) +{ + std::lock_guard lock(m_mutex); + m_ended_owners.erase(owner); +} + bool McpRecorder::owner_ended_in(const std::vector& ancestry) const { std::lock_guard lock(m_mutex); diff --git a/src/slic3r/GUI/Mcp/McpRecorder.hpp b/src/slic3r/GUI/Mcp/McpRecorder.hpp index 5a276a9c21..27296ac310 100644 --- a/src/slic3r/GUI/Mcp/McpRecorder.hpp +++ b/src/slic3r/GUI/Mcp/McpRecorder.hpp @@ -99,6 +99,9 @@ public: // Any thread. Notes that the run `owner` (a job) has ended, so a start of its that runs later is // refused; end_owned_by() notes it too. Call it before the run's scope goes away. void owner_ended(const std::string& owner); + // Any thread. The scope `owner` was opened again (a plugin's, after it loaded again or got the tools back): + // its starts are accepted again. + void owner_reopened(const std::string& owner); // Any thread. Whether a run in `ancestry` (a call's job chain) has ended: a call from it is no client's. bool owner_ended_in(const std::vector& ancestry) const; // Any thread. Ends the recording `owner` started ("" for a client's), and with `wait`, waits up to 30 s diff --git a/src/slic3r/GUI/Mcp/Tools/GuiTools.cpp b/src/slic3r/GUI/Mcp/Tools/GuiTools.cpp index 4b43979fe8..b5b14b60b4 100644 --- a/src/slic3r/GUI/Mcp/Tools/GuiTools.cpp +++ b/src/slic3r/GUI/Mcp/Tools/GuiTools.cpp @@ -755,6 +755,7 @@ struct DownPress { std::uint64_t id = 0; bool client = false; // a client's, not a run's + std::string owner; // the run_owner() it was held for }; // Runs `action` on a page element, waiting up to `timeout` for the page. @@ -770,6 +771,16 @@ WebActed web_act(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget& // A client's down sent after the endpoint closed would leave a press no one releases. if (down.client && !runtime.client_scope_open()) throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed"); + // So would a run's or a plugin's sent after its scope ended, whose release has already run (or is queued + // behind this, which releases only presses already sent). The unsent press goes off the record. + if (down.id != 0) { + try { + runtime.require_owner_scope(down.owner); + } catch (...) { + runtime.web_presses().drop(down.id); + throw; + } + } wxWebView* web = web_view_of(t.web); if (web == nullptr || !web->IsShownOnScreen()) throw ToolFailure("The page's web view is gone or hidden; call widget_list again"); @@ -1010,7 +1021,7 @@ ToolResult web_mouse(AutomationRuntime& runtime, ToolContext& ctx, const json& a a["press"] = pressed; WebActed acted; try { - acted = web_act(runtime, ctx, t, "mouse", a, timeout, {pressed, owner.empty()}); + acted = web_act(runtime, ctx, t, "mouse", a, timeout, {pressed, owner.empty(), owner}); } catch (...) { // A down refused before it was sent is released as one that was: its release only answers. if (pressed != 0) @@ -1421,6 +1432,8 @@ void register_gui_tools(CommandCatalog& catalog) // to release it. if (owner.empty() && !runtime.client_scope_open()) throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed"); + // Nor would a run's or a plugin's whose scope ended since its owner was found. + runtime.require_owner_scope(owner); // The canvases are in the main window, which takes no input while a dialog is open. guard_target(runtime, wxGetApp().mainframe); try { @@ -1686,7 +1699,8 @@ void register_gui_tools(CommandCatalog& catalog) "dialog_auto_answer", L("Answer dialogs automatically"), "Answer modal dialogs automatically when their title or message matches a rule's regex (case-insensitive). " "`app_state.auto_answer_rules` lists the rules in force. Called from a replay or script, the rules join those " - "it set before and last until it ends, and a plugin's likewise until it unloads; an MCP client's replace the " + "it set before and last until it ends, and a plugin's likewise until it unloads or loses its permission to call the " + "tools; an MCP client's replace the " "ones MCP clients set before and last until the MCP server stops, and an empty list clears them. Reply: scope (run, plugin or session), rules (uses counts " "a rule's answers) and `answered_open_dialog`. A native dialog " "returns the rule's button at once and never shows. A file or folder picker takes button ok with an absolute path " diff --git a/src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp b/src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp index fac53c3da3..da52997971 100644 --- a/src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp +++ b/src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp @@ -1063,6 +1063,8 @@ void register_recording_tools(CommandCatalog& catalog) // closed must not begin a recording nothing would end. if (o.owner.empty() && !runtime.client_scope_open()) throw ToolFailure("The MCP server was turned off; the recording was not started"); + // Nor a run's or a plugin's whose scope ended since: refused before start() opens the file. + runtime.require_owner_scope(o.owner); handed_over = true; // start() owns the reservation from here, success or not return runtime.recorder().start(o, owner); }); diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index dff4402b60..36c21bd0a7 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -6,6 +6,7 @@ #include "I18N.hpp" #include "MsgDialog.hpp" #include "OrcaCloudServiceAgent.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntime.hpp" #include "slic3r/plugin/PluginConfig.hpp" #include "slic3r/plugin/PluginFsUtils.hpp" #include "slic3r/plugin/PluginManager.hpp" @@ -186,6 +187,7 @@ nlohmann::json build_permissions_payload(const PluginPermissions& permissions) payload["threading"] = permissions.threading; payload["events"] = permissions.events; payload["full_access"] = permissions.full_access; + payload["tools"] = permissions.tools; return payload; } @@ -741,6 +743,9 @@ nlohmann::json PluginsDialog::localized_strings() const {"permissions_process_help", _u8L("Executable grants cover all arguments. CommandLine: entries cover only the exact command line.")}, {"permissions_process_placeholder", _u8L("Executable or command name")}, {"permissions_threading_help_short", _u8L("Allow this plugin to create threads.")}, + // TRN The name of a plugin permission: calling OrcaSlicer's tools, the commands AI agents call (MCP tools). + {"permissions_tools", _u8L("OrcaSlicer tools")}, + {"permissions_tools_help_short", _u8L("Allow this plugin to call OrcaSlicer's tools, as AI agents do: change your project, presets and files, run post-processing scripts, and answer dialogs, permission requests included.")}, {"permissions_events_help", _u8L("Enter a category and event separated by a colon, such as Socket:socket.__new__.")}, {"permissions_events_placeholder", _u8L("Socket:socket.__new__")}, {"permissions_full_access_label", _u8L("Full access")}, @@ -1001,8 +1006,8 @@ bool PluginsDialog::prompt_enable_full_access(const std::string& plugin_key) wxString::Format( _L("Enable full access for \"%s\"?\n\n" "Full access turns off permission auditing for this plugin: its file system, network, " - "process, thread and event permissions are no longer checked. The plugin can read and " - "write most files your user account can access, including startup scripts, SSH keys " + "process, thread, event and OrcaSlicer tools permissions are no longer checked. The plugin " + "can read and write most files your user account can access, including startup scripts, SSH keys " "and a writable OrcaSlicer installation. Modifying startup or application files can " "let code run outside these checks. Direct Python access to OrcaSlicer's " "configuration, secret, certificate and install-state paths stays blocked, but " @@ -1070,7 +1075,7 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload) bucket = PluginPermissionCategory::Events; entries = &stored.permissions.events; } - if (category == "full_access" || category == "threading") { + if (category == "full_access" || category == "threading" || category == "tools") { if (operation != "set" || !payload.contains("value") || !payload.at("value").is_boolean()) { invalid(); return; @@ -1082,6 +1087,8 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload) return; } mutation.full_access = enabled; + } else if (category == "tools") { + mutation.tools = enabled; } else { mutation.threading = enabled; } @@ -1187,11 +1194,17 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload) } } - if (!PluginManager::instance().mutate_plugin_permissions(plugin_key, mutation)) { + PluginPermissions applied; + if (!PluginManager::instance().mutate_plugin_permissions(plugin_key, mutation, &applied)) { show_status(_L("Failed to save permissions."), "error"); finish(false); return; } + // An edit that leaves the plugin without the tools ends what its calls left in force (auto-answer rules, a + // recording, held presses) and stops its running calls. On the UI thread, as the calls publish those. + if ((mutation.tools || mutation.full_access) && !applied.allows_tools()) + if (Mcp::AutomationRuntime* runtime = wxGetApp().automation_if_started()) + runtime->plugin_tools_withdrawn(plugin_key); finish(true); show_status(wxString::Format(_L("Permissions saved for \"%s\"."), plugin_name), "success"); } diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index 6a058e5245..da781aa35e 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -396,6 +396,7 @@ static const char* category_name(AuditEventCategory category) case AuditEventCategory::ProcessCreate: return "ProcessCreate"; case AuditEventCategory::ProcessReplace: return "ProcessReplace"; case AuditEventCategory::Threading: return "Threading"; + case AuditEventCategory::Tools: return "Tools"; case AuditEventCategory::None: break; } return "None"; @@ -2017,6 +2018,16 @@ std::vector* permission_list_for(AuditEventCategory category, bool } } +// The saved flag that grants a yes/no category, or null for a category granted by target. +bool* boolean_permission_for(AuditEventCategory category, PluginPermissions& permissions) +{ + switch (category) { + case AuditEventCategory::Threading: return &permissions.threading; + case AuditEventCategory::Tools: return &permissions.tools; + default: return nullptr; + } +} + // An event with no target is granted by its effective category and name, e.g. "FsRead:open" // for a read of a file descriptor, which does not grant a write of one ("FsReadWrite:open"). std::string event_grant_key(AuditEventCategory category, const std::string& event_name) @@ -2605,8 +2616,8 @@ bool persist_permission(const std::string& plugin_key, AuditEventCategory catego return write_install_state(root, state); } -// Threading is a boolean grant, so it has no target list to append to. -bool persist_threading_grant(const std::string& plugin_key) +// Threading and the tools are boolean grants, so they have no target list to append to. +bool persist_boolean_grant(const std::string& plugin_key, AuditEventCategory category) { std::lock_guard state_lock(install_state_mutex()); @@ -2619,8 +2630,11 @@ bool persist_threading_grant(const std::string& plugin_key) // Same rule as persist_permission: seed a missing sidecar, never replace an unreadable one. if (read_install_state_status(root, state) == InstallStateReadStatus::Unreadable) return false; + bool* granted = boolean_permission_for(category, state.permissions); + if (!granted) + return false; seed_install_metadata(descriptor, state); - state.permissions.threading = true; + *granted = true; return write_install_state(root, state); } @@ -2823,6 +2837,14 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name, plugin_name, target_list); case AuditEventCategory::Threading: return wxString::Format(_L("Plugin \"%s\" is requesting permission to create a thread."), plugin_name); + case AuditEventCategory::Tools: + // TRN %s is the plugin's name. "OrcaSlicer's tools" are the commands AI agents call (MCP tools). + return wxString::Format(_L("Plugin \"%s\" asks to call OrcaSlicer's tools, as AI agents do. With them it can change your " + "project, presets and files, run post-processing scripts and other programs, work in " + "OrcaSlicer's window while you use it, and answer dialogs, permission requests included, " + "so it can also give itself any other permission.\n\n" + "Allow it only for a plugin you trust."), + plugin_name); case AuditEventCategory::ProcessReplace: return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s\n\n" "Approval covers any arguments. Approving a shell allows it to run any command."), plugin_name, target_list); @@ -3158,8 +3180,8 @@ bool request_recursive_delete_consent(const std::string& plugin_key, const std:: bool persist_grant(const std::string& plugin_key, AuditEventCategory category, bool by_event, const std::vector& keys) { bool persisted = false; - if (category == AuditEventCategory::Threading) { - persisted = persist_threading_grant(plugin_key); + if (category == AuditEventCategory::Threading || category == AuditEventCategory::Tools) { + persisted = persist_boolean_grant(plugin_key, category); } else { for (const auto& key : keys) { if (persist_permission(plugin_key, category, by_event, key)) @@ -3201,8 +3223,8 @@ bool persist_declared_permissions(const std::string& plugin_key, const std::vect seed_install_metadata(descriptor, state); for (const AuditPromptBucket& bucket : buckets) { - if (bucket.category == AuditEventCategory::Threading) { - state.permissions.threading = true; + if (bool* granted = boolean_permission_for(bucket.category, state.permissions)) { + *granted = true; continue; } std::vector* permission_list = @@ -3422,6 +3444,7 @@ static const char* audit_category_name(AuditEventCategory category) case AuditEventCategory::ProcessCreate: return "ProcessCreate"; case AuditEventCategory::ProcessReplace: return "ProcessReplace"; case AuditEventCategory::Threading: return "Threading"; + case AuditEventCategory::Tools: return "Tools"; default: return "None"; } } @@ -4191,6 +4214,8 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons // sentinel gives the prompt a target even though thread creation exposes none. if (requested.threading && !state.permissions.threading) missing_buckets.push_back({AuditEventCategory::Threading, {kThreadPermissionTarget}}); + if (requested.tools && !state.permissions.tools) + missing_buckets.push_back({AuditEventCategory::Tools, {kToolsPermissionTarget}}); if (missing_buckets.empty()) return true; @@ -4308,6 +4333,31 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons return false; } +bool PluginAuditManager::request_tools_permission(const std::string& plugin_key) +{ + PluginDescriptor descriptor; + if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) + return false; + + PluginInstallState state; + InstallStateReadStatus state_status; + { + std::lock_guard state_lock(install_state_mutex()); + state_status = read_install_state_status(boost::filesystem::path(descriptor.plugin_root), state); + } + if (state_status == InstallStateReadStatus::Unreadable) + return false; + if (state.permissions.allows_tools()) + return true; + + // As decide_audited_event asks for an event no grant covers, and saves an inline or seam Yes; a + // queued prompt's Yes is saved by the drain. + const std::vector keys{kToolsPermissionTarget}; + return PluginAuditDetail::request_permission(AuditEventCategory::Tools, plugin_key, descriptor.name, kToolsPermissionTarget, + /*by_event=*/false, keys) && + PluginAuditDetail::persist_grant(plugin_key, AuditEventCategory::Tools, /*by_event=*/false, keys); +} + bool PluginAuditManager::is_create_delete_tree_grant(const std::string& target) { boost::filesystem::path root; diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index d868893422..0a4ec8813d 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -27,6 +27,8 @@ struct PluginPermissions; // target. Legacy sidecars also stored it as the sole entry of their threading target list; the // reader maps that form onto the boolean permission. inline constexpr const char* kThreadPermissionTarget = "thread"; +// The tools grant has no target either; its declaration and its prompt at a call name this one. +inline constexpr const char* kToolsPermissionTarget = "orca.host.tools.call"; // The audit identities of a Python script a person (the Run Script panel, --run) or an agent // (script_run) starts. A script is judged as a plugin is, but has no install state to hold a grant: what @@ -70,6 +72,9 @@ enum class AuditEventCategory { ProcessCreate, ProcessReplace, Threading, + // Calling OrcaSlicer's tools through orca.host.tools (PluginPermissions::tools). No audit event + // maps to it: a declaration asks for it, and request_tools_permission() at a call. + Tools, }; // Returns true if candidate resolves to a path inside allowed_root. @@ -226,6 +231,12 @@ public: // any folder below it. bool request_permissions(const std::string& plugin_key, const PluginPermissions& requested); + // Whether the plugin may call OrcaSlicer's tools now. Without the grant (PluginPermissions::tools + // or full access) it is asked as an undeclared audited event is: called off the GUI thread, as a + // plugin's tool call is, the call is refused and the prompt queued, and a Yes is saved so the + // plugin's next call works. A sidecar that cannot be read is never asked or replaced. + bool request_tools_permission(const std::string& plugin_key); + // Ask the user to grant network access to the given http(s) URLs. Each URL is reduced to its // scheme and host before prompting and persisting, so one approval covers every path, query // and port on that host. The grant is recorded as an HTTP grant; network_permission_matches diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index dea29d3e82..d2521d5ed0 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -1116,6 +1116,9 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path& // key, a "true" string, a number or any other type leaves it off. if (permissions.contains("full_access") && permissions["full_access"].is_boolean()) parsed.permissions.full_access = permissions["full_access"].get(); + // As full_access: only a JSON boolean counts. + if (permissions.contains("tools") && permissions["tools"].is_boolean()) + parsed.permissions.tools = permissions["tools"].get(); } if (state.contains("enabled") && state["enabled"].is_boolean()) @@ -1278,6 +1281,7 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin {"threading", state.permissions.threading}, {"events", state.permissions.events}, {"full_access", state.permissions.full_access}, + {"tools", state.permissions.tools}, }; nlohmann::json capabilities = nlohmann::json::array(); diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index 40a03de7f6..cbe505859b 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -56,6 +56,12 @@ struct PluginPermissions // the cloud refresh token), which stay blocked. Stored as a JSON boolean; a missing or // non-boolean value reads as false. This is a Python audit-hook policy, not an OS sandbox. bool full_access = false; + // Calling OrcaSlicer's tools through orca.host.tools is a yes/no grant, with the reach of an AI + // agent's calls, dialogs and permission requests included. Stored as a JSON boolean; a missing + // or non-boolean value reads as false. + bool tools = false; + + bool allows_tools() const { return tools || full_access; } }; struct PluginInstallState { diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index 9326310032..fc48e8aedc 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -721,6 +721,12 @@ bool PluginManager::get_install_state(const std::string& plugin_key, PluginInsta return true; } +bool PluginManager::plugin_may_call_tools(const std::string& plugin_key) +{ + PluginInstallState state; + return get_install_state(plugin_key, state) && state.permissions.allows_tools(); +} + // ── Lifecycle ─────────────────────────────────────────────────────────────────────────────── bool PluginManager::is_plugin_loaded(const std::string& plugin_key) const @@ -1457,6 +1463,8 @@ bool PluginManager::mutate_plugin_permissions(const std::string& plugin_key, con state.permissions.threading = *mutation.threading; if (mutation.full_access) state.permissions.full_access = *mutation.full_access; + if (mutation.tools) + state.permissions.tools = *mutation.tools; if (!write_install_state(root, state)) { BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to write install state for " << plugin_key; diff --git a/src/slic3r/plugin/PluginManager.hpp b/src/slic3r/plugin/PluginManager.hpp index 5775f5021e..b4b4e65325 100644 --- a/src/slic3r/plugin/PluginManager.hpp +++ b/src/slic3r/plugin/PluginManager.hpp @@ -140,6 +140,7 @@ struct PluginPermissionMutation std::vector remove; std::optional threading; std::optional full_access; + std::optional tools; }; class PluginManager @@ -216,6 +217,11 @@ public: // Must not be called while already holding install_state_mutex(); the lock is not recursive. bool get_install_state(const std::string& plugin_key, PluginInstallState& install_state); + // Whether the plugin may call OrcaSlicer's tools now: its sidecar reads and grants the tools + // (PluginPermissions::tools true) or full access. Read on every call, so a grant changed in the + // Plugins dialog applies to the next check. Same locking rule as get_install_state(). + bool plugin_may_call_tools(const std::string& plugin_key); + // Applies a granular edit to the plugin's latest sidecar contents in one locked read-modify- // write. Only the named entries and engaged boolean grants change; every other stored grant, // including one another writer added after the caller last read the state, is preserved. diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index 07d03ac741..011dd1639a 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -204,7 +204,8 @@ std::vector PythonPluginBridge::finalize_plugin_capture(cons !requested_permissions.fs_read.empty() || !requested_permissions.fs_readwrite.empty() || !requested_permissions.fs_create.empty() || !requested_permissions.fs_delete.empty() || !requested_permissions.network_http.empty() || !requested_permissions.network_socket.empty() || - !requested_permissions.process.empty() || requested_permissions.threading; + !requested_permissions.process.empty() || requested_permissions.threading || + requested_permissions.tools; if (has_permission_request) { bool granted = false; { @@ -757,7 +758,8 @@ after schema, or as handler= on its own. changes=False marks an operation that o bool threading, const std::vector& network, const std::vector& fs_create, - const std::vector& fs_delete) { + const std::vector& fs_delete, + bool tools) { if (g_active_plugin_key.empty()) throw py::value_error("request_permissions() called outside plugin discovery context"); @@ -834,6 +836,8 @@ after schema, or as handler= on its own. changes=False marks an operation that o if (threading && !requested.threading) requested.threading = true; + if (tools) + requested.tools = true; }, py::arg("fs_read") = std::vector{}, py::arg("fs_readwrite") = std::vector{}, @@ -844,6 +848,8 @@ after schema, or as handler= on its own. changes=False marks an operation that o py::arg("network") = std::vector{}, py::arg("fs_create") = std::vector{}, py::arg("fs_delete") = std::vector{}, + // Last, so a call that passes the earlier arguments by position keeps its meaning. + py::arg("tools") = false, R"pbdoc(Request permissions while OrcaSlicer loads your module. Each bucket takes the target strings the plugin expects the corresponding audit event to @@ -889,7 +895,13 @@ wildcard covers them. `network` also lists http(s) URLs, but each is reduced to its scheme and host, so one grant covers every path, query and port on that host and also authorizes raw socket events for it. The host presents one request to the user after register_capabilities() returns and before any capability -instance is created. Denying the request aborts the plugin load.)pbdoc"); +instance is created. Denying the request aborts the plugin load. + +tools=True asks to call OrcaSlicer's tools through orca.host.tools, as an AI agent calls them: change +the project, presets and files, work in the window and answer its dialogs, permission requests +included. A plugin that calls the tools without this grant is asked at that call (unless its +install state exists but cannot be read), which raises orca.host.tools.ToolError with +details["code"] == "tools_not_allowed"; a Yes lets its next call through.)pbdoc"); m.def("plugin", [](py::object cls) { if (g_active_plugin_key.empty()) diff --git a/src/slic3r/plugin/host/PluginHostTools.cpp b/src/slic3r/plugin/host/PluginHostTools.cpp index dc58b920e7..2e18e08461 100644 --- a/src/slic3r/plugin/host/PluginHostTools.cpp +++ b/src/slic3r/plugin/host/PluginHostTools.cpp @@ -162,7 +162,9 @@ void register_tools(py::module_& host) "with call(\"app_wait\", {\"for\": \"job\", \"job\": ...}). An error result raises ToolError, whose details " "hold the result's data. A person's or an agent's script calls tools from its own code and from the threads and " "pool tasks it starts, while its run lasts, but not from its window callbacks; a plugin calls from a " - "Script worker, never the UI thread."); + "Script worker, never the UI thread, and only with the tools permission or full access: without it a call " + "raises ToolError with details[\"code\"] == \"tools_not_allowed\" and asks the person, unless the plugin's " + "install state exists but cannot be read, and a Yes lets the plugin's next call through."); // Static, as pybind keeps a docstring by its pointer; it names the format version this build reads. static const std::string run_replay_doc = std::string("Run a replay ({\"orca_replay_version\": \"") + GUI::Mcp::REPLAY_VERSION + diff --git a/tests/automation/test_mcp_core.cpp b/tests/automation/test_mcp_core.cpp index 14d23f3f5d..35fc104261 100644 --- a/tests/automation/test_mcp_core.cpp +++ b/tests/automation/test_mcp_core.cpp @@ -1831,6 +1831,75 @@ TEST_CASE("a plugin's calls are refused once it unloads, before the block comes, CHECK(looks == 3); } +TEST_CASE("a plugin's calls and its jobs' child calls are refused while it may not call the tools", "[Mcp]") +{ + // What the handlers use, declared before the harness, so it outlives the core's threads, which the harness's + // destructor shuts down: also when the case fails while the job still runs. + std::atomic allowed{true}; + std::atomic started{false}; + std::atomic release{false}; + std::atomic ran{0}; + std::atomic handled{false}; // set once the handler has written both children's results + ToolResult inline_child; + ToolResult job_child; + Harness h; + // The plugin's install state, read for every call; the Plugins dialog's switch changes it. + h.jobs.set_owner_permission([&](const std::string& plugin) { return plugin != "measure" || allowed; }); + NativeCommand look = tool("look", GuardClass::Inspect, [&](const json&, ToolContext&) { ++ran; return ToolResult::ok(); }); + look.inline_call = true; + h.registry.add(look); + h.registry.add(tool("make", GuardClass::Mutate, [&](const json&, ToolContext&) { ++ran; return ToolResult::ok(); })); + h.registry.add(tool("slow", GuardClass::Mutate, [&](const json&, ToolContext& ctx) { + started = true; + while (!release) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + inline_child = ctx.call_child("look", json::object()); + job_child = ctx.call_child("make", json::object()); + handled = true; + return ToolResult::ok(); + })); + h.timing.soft_budget = std::chrono::milliseconds(10000); + h.start(); + // A job of the plugin, as a script it ran, whose handler calls on after the permission is withdrawn. + std::thread running([&] { h.core->call_plugin(*h.registry.find("slow"), json::object(), "measure"); }); + for (int i = 0; i < 2000 && !started; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + // Read once: a handler starting late must not pass the check below after its thread was joined here. + const bool handler_started = started; + if (!handler_started) { // the granted call was refused, or never reached its handler: end it before failing + release = true; + running.join(); + } + REQUIRE(handler_started); + + allowed = false; + const ToolResult inline_call = h.core->call_plugin(*h.registry.find("look"), json::object(), "measure"); + CHECK(inline_call.is_error); + CHECK(inline_call.message.find("not allowed to call OrcaSlicer's tools") != std::string::npos); + CHECK(inline_call.data.value("code", "") == "tools_not_allowed"); + const ToolResult job_call = h.core->call_plugin(*h.registry.find("make"), json::object(), "measure"); + CHECK(job_call.is_error); + CHECK(job_call.data.value("code", "") == "tools_not_allowed"); + release = true; + running.join(); + // The call may have answered "running" before its handler ended: its results are read once the handler wrote them. + for (int i = 0; i < 2000 && !handled; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + REQUIRE(handled); + CHECK(inline_child.is_error); + CHECK(inline_child.data.value("code", "") == "tools_not_allowed"); + CHECK(job_child.is_error); + CHECK(job_child.data.value("code", "") == "tools_not_allowed"); + CHECK(ran == 0); + + // Another plugin's calls and a client's still run, and the plugin's do once it may call the tools again. + CHECK_FALSE(h.core->call_plugin(*h.registry.find("look"), json::object(), "other").is_error); + CHECK_FALSE(h.call("look").is_error); + allowed = true; + CHECK_FALSE(h.core->call_plugin(*h.registry.find("look"), json::object(), "measure").is_error); + CHECK(ran == 3); +} + TEST_CASE("a plugin's job never starts once the plugin unloads, as it registers or right before its handler", "[Mcp]") { // The liveness hook is asked as the call comes in, once its job is registered, and on the job's thread right diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index b926e9adfc..cb90559a49 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -19863,7 +19863,7 @@ }, { "completion": "immediate", - "description": "Answer modal dialogs automatically when their title or message matches a rule's regex (case-insensitive). `app_state.auto_answer_rules` lists the rules in force. Called from a replay or script, the rules join those it set before and last until it ends, and a plugin's likewise until it unloads; an MCP client's replace the ones MCP clients set before and last until the MCP server stops, and an empty list clears them. Reply: scope (run, plugin or session), rules (uses counts a rule's answers) and `answered_open_dialog`. A native dialog returns the rule's button at once and never shows. A file or folder picker takes button ok with an absolute path and returns it without showing; without a path a picker can only be cancelled, and a multi-select picker takes no path. A wx dialog is answered as `dialog_answer` does. A matching dialog already open is answered too (`answered_open_dialog`), so a prompt that shows around the same time, such as the restore prompt after startup, is caught either way. A web dialog is matched by its title: a button that names one of its shown wx buttons (by label, standard name or id) is pressed as for a wx dialog, any other on its page once it shows there, for up to 10 s after the page loads; past that, cancel and close end the dialog and any other button gives up.", + "description": "Answer modal dialogs automatically when their title or message matches a rule's regex (case-insensitive). `app_state.auto_answer_rules` lists the rules in force. Called from a replay or script, the rules join those it set before and last until it ends, and a plugin's likewise until it unloads or loses its permission to call the tools; an MCP client's replace the ones MCP clients set before and last until the MCP server stops, and an empty list clears them. Reply: scope (run, plugin or session), rules (uses counts a rule's answers) and `answered_open_dialog`. A native dialog returns the rule's button at once and never shows. A file or folder picker takes button ok with an absolute path and returns it without showing; without a path a picker can only be cancelled, and a multi-select picker takes no path. A wx dialog is answered as `dialog_answer` does. A matching dialog already open is answered too (`answered_open_dialog`), so a prompt that shows around the same time, such as the restore prompt after startup, is caught either way. A web dialog is matched by its title: a button that names one of its shown wx buttons (by label, standard name or id) is pressed as for a wx dialog, any other on its page once it shows there, for up to 10 s after the page loads; past that, cancel and close end the dialog and any other button gives up.", "destructive": false, "group": "Driving the GUI", "guard": "recover", diff --git a/tests/slic3rutils/test_mcp_core.cpp b/tests/slic3rutils/test_mcp_core.cpp index 75af83ddb4..d99b651a8e 100644 --- a/tests/slic3rutils/test_mcp_core.cpp +++ b/tests/slic3rutils/test_mcp_core.cpp @@ -7,8 +7,10 @@ #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/Mcp/AutomationRuntime.hpp" +#include "slic3r/GUI/Mcp/AutomationRuntimePtr.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" #include "slic3r/GUI/Mcp/McpPersonContext.hpp" +#include "slic3r/GUI/Mcp/ModalTracker.hpp" #include @@ -108,3 +110,95 @@ TEST_CASE("an action of fixed arguments is journaled with the arguments action_r // action_run refuses any other arguments for such an action, so the step holds the action's, which its replay runs. CHECK(steps[0]["args"] == json{{"id", "orca_command:k:orca"}, {"args", action_args}}); } + +namespace { + +// Whether `fn` throws a ToolFailure whose details' code is `code`. +template bool fails_with_code(Fn&& fn, const std::string& code) +{ + try { + fn(); + } catch (const ToolFailure& f) { + return f.details.is_object() && f.details.value("code", "") == code; + } + return false; +} + +} // namespace + +TEST_CASE("a withdrawn plugin's late calls leave nothing behind until it may call the tools again", "[Mcp]") +{ + // Built, not started: the scope bookkeeping needs no GUI, and the scope ends skip what was never started. + AutomationRuntimePtr runtime(new AutomationRuntime()); + const std::string job = runtime->jobs().create("x", {}, "p"); + const std::string child = runtime->jobs().create("script_run", job); + REQUIRE(runtime->begin_plugin_scope("p")); + runtime->begin_run_scope(child); + CHECK(runtime->run_owner({job}) == "plugin:p"); + CHECK(runtime->run_owner({child, job}) == child); + CHECK_NOTHROW(runtime->require_owner_scope("plugin:p")); + CHECK_NOTHROW(runtime->require_owner_scope(child)); + + runtime->plugin_tools_withdrawn("p"); + // A call that passed its check before the withdrawal leaves no rule, press or recording, nor does its script's. + CHECK(fails_with_code([&] { runtime->run_owner({job}); }, "tools_not_allowed")); + CHECK(fails_with_code([&] { runtime->run_owner({child, job}); }, "tools_not_allowed")); + CHECK(fails_with_code([&] { runtime->set_auto_answer({}, {job}); }, "tools_not_allowed")); + CHECK(fails_with_code([&] { runtime->require_owner_scope("plugin:p"); }, "tools_not_allowed")); + // The script's own scope ended with the withdrawal, so what it would publish is refused too, and for the reason. + CHECK(fails_with_code([&] { runtime->require_owner_scope(child); }, "tools_not_allowed")); + // Another plugin and a client are untouched. + const std::string other = runtime->jobs().create("x", {}, "q"); + REQUIRE(runtime->begin_plugin_scope("q")); + CHECK(runtime->run_owner({other}) == "plugin:q"); + CHECK(runtime->run_owner({}).empty()); + CHECK_NOTHROW(runtime->require_owner_scope("")); + + // A call admitted under a new grant opens the scope again. + REQUIRE(runtime->begin_plugin_scope("p")); + CHECK(runtime->run_owner({job}) == "plugin:p"); + CHECK_NOTHROW(runtime->require_owner_scope("plugin:p")); + // The script's scope stays ended: the withdrawal closed it, not only the plugin's mark. + CHECK_THROWS_WITH(runtime->require_owner_scope(child), "The replay or script that made this call has ended"); +} + +TEST_CASE("an unloaded plugin's late press, recording or rule is refused, its scripts' too", "[Mcp]") +{ + AutomationRuntimePtr runtime(new AutomationRuntime()); + const std::string job = runtime->jobs().create("x", {}, "q"); + const std::string child = runtime->jobs().create("script_run", job); + REQUIRE(runtime->begin_plugin_scope("q")); + runtime->begin_run_scope(child); + CHECK_NOTHROW(runtime->require_owner_scope("plugin:q")); + CHECK_NOTHROW(runtime->require_owner_scope(child)); + + runtime->end_plugin_scope("q"); + const char* unloaded = "The plugin that made this call has been unloaded"; + CHECK_THROWS_WITH(runtime->require_owner_scope("plugin:q"), unloaded); + // Its script's scope ended with the unload: nothing the script would leave behind is published. + CHECK_THROWS_WITH(runtime->require_owner_scope(child), unloaded); + CHECK_THROWS_AS(runtime->run_owner({child, job}), ToolFailure); + CHECK_THROWS_AS(runtime->set_auto_answer({}, {child, job}), ToolFailure); + CHECK_FALSE(runtime->begin_plugin_scope("q")); + + // Loaded again, but before any call of the plugin is admitted: a call from before the unload still finds no scope + // of the plugin's, and is refused rather than taken for the client's. + runtime->plugin_loaded("q"); + CHECK_THROWS_WITH(runtime->run_owner({job}), unloaded); + CHECK_THROWS_AS(runtime->set_auto_answer({}, {job}), ToolFailure); + // Once a call is admitted the plugin's scope opens again, and the script's stays ended: the unload closed it, not + // only the plugin's mark. + REQUIRE(runtime->begin_plugin_scope("q")); + CHECK(runtime->run_owner({job}) == "plugin:q"); + CHECK_THROWS_WITH(runtime->require_owner_scope(child), "The replay or script that made this call has ended"); +} + +TEST_CASE("a run of no plugin is refused where it publishes once it has ended", "[Mcp]") +{ + AutomationRuntimePtr runtime(new AutomationRuntime()); + const std::string run = runtime->jobs().create("replay_run", {}); + runtime->begin_run_scope(run); + CHECK_NOTHROW(runtime->require_owner_scope(run)); + runtime->end_run_scope(run, false); + CHECK_THROWS_WITH(runtime->require_owner_scope(run), "The replay or script that made this call has ended"); +} diff --git a/tests/slic3rutils/test_mcp_web.cpp b/tests/slic3rutils/test_mcp_web.cpp index a8c640163c..cec4bd3693 100644 --- a/tests/slic3rutils/test_mcp_web.cpp +++ b/tests/slic3rutils/test_mcp_web.cpp @@ -493,6 +493,26 @@ TEST_CASE("a press is released only once its down came back, and a confirmed rel CHECK(kept[0].id == other); } +TEST_CASE("a press dropped before its down was sent leaves no record and no later effect", "[Mcp]") +{ + // A down refused at its send because its run's or plugin's scope ended goes off the record unsent. + WebPresses presses; + const PressAgent a{1, "d", ""}, b{2, "d", ""}; + const auto refused = presses.hold(a, "plugin:p"); + const auto neighbour = presses.hold(b, "plugin:p"); + presses.drop(refused); + presses.sent(refused); // the gesture's own clean-up after the refusal + presses.sent(neighbour); + const std::string owner = "plugin:p"; + const auto owned = presses.owned(&owner); + REQUIRE(owned.size() == 1); + CHECK(owned[0].id == neighbour); + CHECK(presses.of(a).empty()); + const auto releasable = presses.releasable(std::nullopt); + REQUIRE(releasable.size() == 1); + CHECK(releasable[0].id == neighbour); +} + TEST_CASE("a run's presses are told from a client's for the cleanup when either ends", "[Mcp]") { WebPresses presses; diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index ab29914f32..478e9676fe 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include "libslic3r_version.h" @@ -3363,6 +3364,169 @@ TEST_CASE("A threading permission request is prompted once and saved as a boolea CHECK_FALSE(prompted_again); } +TEST_CASE("A tools declaration is not asked with the tools grant or full access", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + + const bool full_access = GENERATE(false, true); + PluginPermissions granted; + granted.tools = !full_access; + granted.full_access = full_access; + harness.save_permissions(PLUGIN, granted); + const fs::path sidecar = harness.data.plugins_dir() / PLUGIN / INSTALL_STATE_FILE; + const std::string before = read_text_file(sidecar); + + PluginPermissions requested; + requested.tools = true; + bool asked = false; + PluginAuditManager::set_permission_message_prompt_for_testing([&](const std::string&) { + asked = true; + return false; + }); + CHECK(PluginAuditManager::instance().request_permissions(PLUGIN, requested)); + PluginAuditManager::set_permission_message_prompt_for_testing(nullptr); + CHECK_FALSE(asked); + // Nothing is written: the stored grant, or full access, already covers the declaration. + CHECK(read_text_file(sidecar) == before); +} + +TEST_CASE("A plugin may call the tools only with the tools grant or full access", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + PluginManager& manager = PluginManager::instance(); + + PluginPermissions permissions; + harness.save_permissions(PLUGIN, permissions); + CHECK_FALSE(manager.plugin_may_call_tools(PLUGIN)); + + permissions.tools = true; + harness.save_permissions(PLUGIN, permissions); + CHECK(manager.plugin_may_call_tools(PLUGIN)); + + // Full access allows them whatever the tools grant says. + permissions.full_access = true; + permissions.tools = false; + harness.save_permissions(PLUGIN, permissions); + CHECK(manager.plugin_may_call_tools(PLUGIN)); + + // A sidecar that does not read, or is gone, grants nothing, though it held full access. + const fs::path sidecar = harness.data.plugins_dir() / PLUGIN / INSTALL_STATE_FILE; + { + std::ofstream out(sidecar.string(), std::ios::binary | std::ios::trunc); + out << "{ \"permissions\": {"; + } + CHECK_FALSE(manager.plugin_may_call_tools(PLUGIN)); + boost::system::error_code ec; + fs::remove(sidecar, ec); + REQUIRE_FALSE(ec); + CHECK_FALSE(manager.plugin_may_call_tools(PLUGIN)); + CHECK_FALSE(manager.plugin_may_call_tools("NoSuchPlugin")); +} + +// request_tools_permission() is asked here through the runtime prompt seam, which answers before +// the prompt queue. A plugin's real call runs on a Script worker, where the prompt is queued and the +// call refused instead; that path needs a running app and is covered by the MCP sweep. +TEST_CASE("A tools call with the tools grant or full access is allowed without asking", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + + const bool full_access = GENERATE(false, true); + PluginPermissions granted; + granted.tools = !full_access; + granted.full_access = full_access; + harness.save_permissions(PLUGIN, granted); + + CHECK(PluginAuditManager::instance().request_tools_permission(PLUGIN)); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A tools call with an unreadable sidecar is refused without asking", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + harness.approve = [](const Prompt&) { return true; }; + + const fs::path sidecar = harness.data.plugins_dir() / PLUGIN / INSTALL_STATE_FILE; + const std::string malformed = "{ \"permissions\": {"; + { + std::ofstream out(sidecar.string(), std::ios::binary | std::ios::trunc); + out << malformed; + } + + // Its grants cannot be read, so a Yes could not be saved without replacing them: fail closed. + CHECK_FALSE(PluginAuditManager::instance().request_tools_permission(PLUGIN)); + CHECK(describe(harness.prompts).empty()); + CHECK(read_text_file(sidecar) == malformed); + + // A plugin that was never discovered has nowhere to keep the grant either. + CHECK_FALSE(PluginAuditManager::instance().request_tools_permission("NoSuchPlugin")); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A tools call without the grant asks each time and stores only a Yes", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + PluginAuditManager& mgr = PluginAuditManager::instance(); + const fs::path sidecar = harness.data.plugins_dir() / PLUGIN / INSTALL_STATE_FILE; + const std::string before = read_text_file(sidecar); + + // No refuses the call and is not remembered: the next call asks again. + harness.approve = [](const Prompt&) { return false; }; + CHECK_FALSE(mgr.request_tools_permission(PLUGIN)); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "orca.host.tools.call"); + CHECK(harness.prompts.front().targets == std::vector{"orca.host.tools.call"}); + CHECK(read_text_file(sidecar) == before); + + CHECK_FALSE(mgr.request_tools_permission(PLUGIN)); + CHECK(harness.prompts.size() == 2); + CHECK(read_text_file(sidecar) == before); + + // Yes allows the call and is stored as the boolean grant, so the next call is not asked. + harness.approve = [](const Prompt&) { return true; }; + CHECK(mgr.request_tools_permission(PLUGIN)); + CHECK(harness.prompts.size() == 3); + CHECK(harness.saved_permissions(PLUGIN).tools); + CHECK(mgr.request_tools_permission(PLUGIN)); + CHECK(harness.prompts.size() == 3); +} + +TEST_CASE("A tools call with no sidecar asks and a Yes creates one", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + + // A discovered plugin that has not been given a sidecar is asked, as for its other permissions. + const fs::path sidecar = harness.data.plugins_dir() / PLUGIN / INSTALL_STATE_FILE; + boost::system::error_code ec; + fs::remove(sidecar, ec); + REQUIRE_FALSE(ec); + + const bool answer = GENERATE(true, false); + harness.approve = [answer](const Prompt&) { return answer; }; + CHECK(PluginAuditManager::instance().request_tools_permission(PLUGIN) == answer); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "orca.host.tools.call"); + CHECK(fs::exists(sidecar) == answer); + CHECK(harness.saved_permissions(PLUGIN).tools == answer); +} + TEST_CASE("A permission request creates a sidecar for a discovered plugin that has none", "[audit]") { AuditHarness harness; @@ -3797,11 +3961,12 @@ TEST_CASE("A permission mutation changes boolean grants only when asked", "[audi PluginManager& manager = PluginManager::instance(); - // A mutation that names no booleans leaves both flags alone. + // A mutation that names no booleans leaves every flag alone. PluginPermissions applied; REQUIRE(manager.mutate_plugin_permissions(PLUGIN, PluginPermissionMutation{}, &applied)); CHECK_FALSE(applied.threading); CHECK(applied.full_access); + CHECK_FALSE(applied.tools); CHECK(applied.fs_read == std::vector{"/kept"}); PluginPermissionMutation booleans; @@ -3816,6 +3981,26 @@ TEST_CASE("A permission mutation changes boolean grants only when asked", "[audi CHECK(stored.threading); CHECK_FALSE(stored.full_access); CHECK(stored.fs_read == std::vector{"/kept"}); + + // The tools grant is set and cleared on its own, and the other grants stay. + PluginPermissionMutation tools_on; + tools_on.tools = true; + REQUIRE(manager.mutate_plugin_permissions(PLUGIN, tools_on, &applied)); + CHECK(applied.tools); + const PluginPermissions tools_granted = harness.saved_permissions(PLUGIN); + CHECK(tools_granted.tools); + CHECK(tools_granted.threading); + CHECK_FALSE(tools_granted.full_access); + CHECK(tools_granted.fs_read == std::vector{"/kept"}); + + PluginPermissionMutation tools_off; + tools_off.tools = false; + REQUIRE(manager.mutate_plugin_permissions(PLUGIN, tools_off, &applied)); + const PluginPermissions after_tools = harness.saved_permissions(PLUGIN); + CHECK_FALSE(after_tools.tools); + CHECK(after_tools.threading); + CHECK_FALSE(after_tools.full_access); + CHECK(after_tools.fs_read == std::vector{"/kept"}); } TEST_CASE("A permission mutation fails closed for a plugin it cannot update", "[audit]") diff --git a/tests/slic3rutils/test_plugin_install.cpp b/tests/slic3rutils/test_plugin_install.cpp index 9bfa770712..7422ea74a7 100644 --- a/tests/slic3rutils/test_plugin_install.cpp +++ b/tests/slic3rutils/test_plugin_install.cpp @@ -148,13 +148,15 @@ class FailingPackage(orca.base): raise RuntimeError("registration rejected by the plugin") )PY"; -// A plugin that declares one read permission while it registers its one capability, so its load -// goes through the combined permission prompt. -const char* const DECLARING_PLUGIN_SOURCE = R"PY(# /// script +// A plugin named `name` that declares `permissions`, the arguments of orca.request_permissions(), +// while it registers its one capability, so its load goes through the permission prompts. +std::string declaring_plugin_source(const std::string& name, const std::string& permissions) +{ + return R"PY(# /// script # requires-python = ">=3.12" # # [tool.orcaslicer.plugin] -# name = "Declaring Plugin" +# name = ")PY" + name + R"PY(" # type = "script" # version = "1.0" # /// @@ -170,9 +172,40 @@ class Echo(orca.script.ScriptPluginCapabilityBase): @orca.plugin class DeclaringPackage(orca.base): def register_capabilities(self): - orca.request_permissions(fs_read=["/declared/read"]) + orca.request_permissions()PY" + permissions + R"PY() orca.register_capability(Echo) )PY"; +} + +// What a plugin load with its permission prompts recorded produced. +struct PromptedLoad +{ + bool loaded = false; + std::string error; + std::vector prompts; +}; + +// Loads `plugin_key` and answers each permission prompt with `answer`. The prompts run on the load +// worker, so they are recorded there for the caller to assert on once the load is done. +PromptedLoad load_answering_prompts(const std::string& plugin_key, bool answer) +{ + PromptedLoad result; + PluginAuditManager::set_permission_message_prompt_for_testing([&result, answer](const std::string& message) { + result.prompts.push_back(message); + return answer; + }); + PluginManager& manager = PluginManager::instance(); + manager.load_plugin(plugin_key, /*skip_deps=*/true); + result.loaded = manager.wait_for_plugin_load(plugin_key, std::chrono::seconds(120), result.error); + // A load that timed out still runs and may prompt: it ends before the prompt and `result` go. + if (!result.loaded && manager.is_plugin_load_in_progress(plugin_key)) { + manager.cancel_plugin_load(plugin_key); + std::string ignored; + manager.wait_for_plugin_load(plugin_key, std::chrono::milliseconds::max(), ignored); + } + PluginAuditManager::set_permission_message_prompt_for_testing(nullptr); + return result; +} } // namespace @@ -347,6 +380,7 @@ TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's ins state.permissions.network_socket = {"192.168.45.6:443"}; state.permissions.process = {"/usr/bin/curl"}; state.permissions.threading = true; + state.permissions.tools = true; REQUIRE(write_install_state(plugin_dir, state)); // Permission data is persisted in the same sidecar as the installation metadata. @@ -360,6 +394,7 @@ TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's ins CHECK(persisted.permissions.network_socket == state.permissions.network_socket); CHECK(persisted.permissions.process == state.permissions.process); CHECK(persisted.permissions.threading == state.permissions.threading); + CHECK(persisted.permissions.tools == state.permissions.tools); // Reading the sidecar back onto a freshly-scanned descriptor (whose header version is still // 1.0.0) must surface the cloud-installed 1.2.0. This is what lets update_cloud_metadata compare @@ -556,35 +591,59 @@ TEST_CASE("a plugin that declares permissions loads over an unparsable install-s ScopedDataDir data_dir_guard("declaring-over-unparsable"); const fs::path plugin_dir = data_dir_guard.plugins_dir() / "Declaring_Plugin"; - write_py_file(plugin_dir, "Declaring_Plugin.py", DECLARING_PLUGIN_SOURCE); + write_py_file(plugin_dir, "Declaring_Plugin.py", + declaring_plugin_source("Declaring Plugin", R"(fs_read=["/declared/read"])")); - PluginManager& manager = PluginManager::instance(); - manager.discover_plugins(/*async=*/false, /*clear=*/true); + PluginManager::instance().discover_plugins(/*async=*/false, /*clear=*/true); const std::string malformed = "{ \"enabled\": tru"; write_raw_sidecar_text(plugin_dir, malformed); - // The prompt runs on the load worker: record it there and assert once the load is done. - std::vector prompts; - PluginAuditManager::set_permission_message_prompt_for_testing([&prompts](const std::string& message) { - prompts.push_back(message); - return true; - }); - std::string error; - manager.load_plugin("Declaring_Plugin", /*skip_deps=*/true); - const bool loaded = manager.wait_for_plugin_load("Declaring_Plugin", std::chrono::seconds(120), error); - PluginAuditManager::set_permission_message_prompt_for_testing(nullptr); + const PromptedLoad load = load_answering_prompts("Declaring_Plugin", true); // The declaration is put to the user again and the approval is saved in a fresh sidecar. - INFO(error); - CHECK(loaded); - CHECK(prompts.size() == 1); + INFO(load.error); + CHECK(load.loaded); + CHECK(load.prompts.size() == 1); PluginInstallState stored; REQUIRE(read_install_state(plugin_dir, stored)); CHECK(stored.permissions.fs_read == std::vector{"/declared/read"}); CHECK(read_sidecar_text(plugin_dir, ".install_state.json.corrupt") == malformed); } +TEST_CASE("a plugin that declares the tools is asked for them in its one permission prompt", "[PluginInstall][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const bool answer = GENERATE(true, false); + ScopedDataDir data_dir_guard("tools-declaring"); + const fs::path plugin_dir = data_dir_guard.plugins_dir() / "Tools_Declaring_Plugin"; + write_py_file(plugin_dir, "Tools_Declaring_Plugin.py", + declaring_plugin_source("Tools Declaring Plugin", R"(fs_read=["/declared/read"], tools=True)")); + write_raw_install_state(plugin_dir, {{"installed_from", "local"}, {"permissions", nlohmann::json::object()}}); + + PluginManager::instance().discover_plugins(/*async=*/false, /*clear=*/true); + + const PromptedLoad load = load_answering_prompts("Tools_Declaring_Plugin", answer); + + // One prompt names both declarations and says how far the tools reach. Yes loads the plugin and + // stores both grants; No, as for any declaration, fails the load and stores neither. + INFO(load.error); + REQUIRE(load.prompts.size() == 1); + CHECK_THAT(load.prompts[0], Catch::Matchers::ContainsSubstring("/declared/read")); + CHECK_THAT(load.prompts[0], Catch::Matchers::ContainsSubstring("OrcaSlicer's tools")); + CHECK_THAT(load.prompts[0], Catch::Matchers::ContainsSubstring("permission requests included")); + CHECK(load.loaded == answer); + PluginInstallState stored; + REQUIRE(read_install_state(plugin_dir, stored)); + CHECK(stored.permissions.tools == answer); + const std::vector expected_fs_read = answer ? std::vector{"/declared/read"} + : std::vector{}; + CHECK(stored.permissions.fs_read == expected_fs_read); +} + TEST_CASE("a plugin load leaves a sidecar path that is not a file in place", "[PluginInstall][Python]") { ScopedPluginManager plugin_system; @@ -769,6 +828,48 @@ TEST_CASE("install-state writes threading as a boolean and reads it back", "[Plu CHECK_FALSE(read_back.permissions.threading); } +TEST_CASE("install-state reads the tools grant only from a JSON true and always writes it", "[PluginInstall]") +{ + ScopedDataDir data_dir_guard("tools-permission"); + const fs::path plugin_dir = data_dir_guard.dir / "plugin"; + + const auto read_tools = [&plugin_dir]() { + PluginInstallState state; + REQUIRE(read_install_state(plugin_dir, state)); + return state.permissions.tools; + }; + + write_raw_install_state(plugin_dir, {{"permissions", {{"tools", true}}}}); + CHECK(read_tools()); + write_raw_install_state(plugin_dir, {{"permissions", {{"tools", false}}}}); + CHECK_FALSE(read_tools()); + write_raw_install_state(plugin_dir, {{"permissions", nlohmann::json::object()}}); + CHECK_FALSE(read_tools()); + for (const nlohmann::json& value : std::vector{"true", 1, nlohmann::json::array(), nullptr}) { + write_raw_install_state(plugin_dir, {{"permissions", {{"tools", value}}}}); + CHECK_FALSE(read_tools()); + } + + // Written as a boolean whatever its value, as threading is. + const auto written_permissions = [&plugin_dir](const PluginInstallState& state) { + REQUIRE(write_install_state(plugin_dir, state)); + return nlohmann::json::parse(read_sidecar_text(plugin_dir))["permissions"]; + }; + PluginInstallState state; + const nlohmann::json not_granted = written_permissions(state); + REQUIRE(not_granted.contains("tools")); + CHECK(not_granted["tools"].is_boolean()); + CHECK(not_granted["tools"] == false); + CHECK_FALSE(read_tools()); + + state.permissions.tools = true; + const nlohmann::json granted = written_permissions(state); + REQUIRE(granted.contains("tools")); + CHECK(granted["tools"].is_boolean()); + CHECK(granted["tools"] == true); + CHECK(read_tools()); +} + TEST_CASE("reading a legacy threading value does not rewrite the sidecar and a normal write migrates it", "[PluginInstall]") { diff --git a/tools/mcp/TESTS.md b/tools/mcp/TESTS.md index b109ed9f19..4719065c7c 100644 --- a/tools/mcp/TESTS.md +++ b/tools/mcp/TESTS.md @@ -303,5 +303,6 @@ something wrong passes. **A few steps still trust a fixed time, where no tool shows the state to wait for.** `test_runtime_calls` gives its 32 half-sent connections 1 s and the Run Script panel's page 1 s, since no tool sees either; it cancels a slice as soon as `app_state` lists its job, inside the slice's half-second wait, a race a slow machine fails rather than -passes. `test_plugin_tools`' `--run` replay waits 10 s for a dialog that never opens, so that the plugin script it -starts can record its outcome: a replay has no step that waits for a file. +passes. `test_plugin_tools`' `--run` replay waits up to 30 s for the ungranted plugin's permission prompt to open and 30 s +for it to close, so that the plugin scripts it starts can record their outcomes: a replay has no step that waits +for a file. diff --git a/tools/mcp/checks.py b/tools/mcp/checks.py index 3610110ed9..1f418e3b72 100644 --- a/tools/mcp/checks.py +++ b/tools/mcp/checks.py @@ -5,6 +5,7 @@ out of time, and readers that give the app's state in a fixed shape.""" import contextlib import json import os +import re import socket import subprocess import sys @@ -655,6 +656,14 @@ def dialogs(client): return [{"title": d.get("title"), "message": d.get("message")} for d in client.call("app_state").get("dialogs", [])] +def web_view(client, page): + """The ref widget_list gives the web view showing `page` (part of its URL, such as "PluginsDialog/index.html"), + or None while none is listed. The ref stays valid while the web view lives.""" + _, tree = client.call_with_text("widget_list", query=page) + view = re.search(r"\[(\w+)\] webview", "\n".join(tree)) + return view.group(1) if view else None + + def rule_uses(client, match): """How many times the auto-answer rule whose match is `match` has answered, from app_state; None when no rule has that match.""" diff --git a/tools/mcp/test-entries/commands.md b/tools/mcp/test-entries/commands.md index 6296f80374..f2d57f123f 100644 --- a/tools/mcp/test-entries/commands.md +++ b/tools/mcp/test-entries/commands.md @@ -234,15 +234,17 @@ An action is its command run with fixed arguments as a person's pick, and `actio ## `test_plugin_tools` `test_plugin_tools.py` · Python -**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. +**Tests:** A plugin's side of the MCP tools, with `mcp_tools_fixture` side-loaded (enabled, 6 capabilities, thread and tools permissions), `mcp_tools_ungranted`, which has no permissions, `mcp_tools_declaring`, which asks for the tools as it loads, 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 six 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. Covers the tools permission, which is asked for as the threading permission is: the fixture's calls need it; `mcp_tools_ungranted`'s call without it is refused and asks the person in the "Plugin permission request" prompt, whose No is not remembered and whose Yes lets its next call through, while its `list()`, `describe()` and its offered operation work without it, and full access alone lets it call; `mcp_tools_declaring`, switched on, asks for the tools in its load's "Plugin permissions" prompt, whose No fails the load and whose Yes stores the grant; and the Permissions tab's OrcaSlicer tools switch, with no confirmation either way, withdraws the grant, refusing the fixture's next call, which asks again, and ending its auto-answer rule, and gives it back, after which the fixture records again. 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 and the ungranted plugin's call is refused and asks, its prompt answered Yes by the replay's own auto-answer rule. -**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. +**Starts from:** a data folder of its own, not a job's: a new temporary folder with the four 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. + +The fixture's install state grants `threading` and `tools: true`; the fixture declares no permissions, so no load prompt comes up for it. Its sixth capability, "MCP tools fixture record", calls `recording_start {save_path: /fixture.mkv, overwrite: true, max_seconds: 1}` and, when the reply is a job envelope (`status` "running"), `app_wait {for: "job", job}`, and records that final result, so `ok` true means the recording started; the recording is `fixture.mkv`, or `fixture.mp4` where ffmpeg encodes it. `mcp_tools_declaring` is side-loaded disabled, with an install state that has no `permissions`, so it loads only when the test switches it on with `plugin_enable`, which loads it on a worker thread: its request waits in the prompt queue and the UI thread shows it (`drain_runtime_prompts()`). It asks for the tools with `orca.request_permissions(tools=True)` and for nothing else. Its one Script capability, "MCP tools declaring call", calls `app_state` and records to `out_declaring.json` in its storage folder `{ok, code, call}`: whether the call succeeded, a `ToolError`'s `details["code"]` or null, and `app_state`'s `ready` or the error text. `mcp_tools_ungranted` is side-loaded enabled with an install state that has no `permissions` and declares nothing. Its one Script capability, "MCP tools ungranted call", records to `out_ungranted.json` in its storage folder `{listed, described, ok, error_type, code, call}`: whether `orca.host.tools.list()` holds `app_state`, `orca.host.tools.describe("app_state")["key"]`, whether calling `app_state` succeeded, the exception's class name or null, a `ToolError`'s `details["code"]` or null, and `app_state`'s `ready` or the error text. It offers the operation `echo`, which returns its arguments and calls no tool. A call it makes without the grant is refused at once and queues its runtime prompt, titled "Plugin permission request", which the UI thread shows when the queue reaches it (`drain_runtime_prompts()`), so the prompt may open before or after the script records its outcome. **Leaves:** nothing in a job's data folder; its own folder is removed at the end. **Decides by:** Exits 1 when any check fails, or 1 at once if a launch fails. - Operation: `tool_list {group: "plugins"}` lists `plugin.mcp_tools_fixture.measure`; `tool_describe` of it has `group` "Plugins", `description` starting "Offered by a plugin.", a parameter named `a`, `listed` false and `access.open_world` true (plugin code reaches what its grants allow); `tool_call` result == `{"twice": 4}`; absent from `tools/list`; and within 30 s of the untick `tool_list {group: "plugins"}` no longer lists it and `tool_describe` of it is refused with code `invalid_argument` and text starting "Unknown tool: plugin.mcp_tools_fixture.measure". -- Speed Dial actions: within 30 s of the launch, `action_list {section: "MCP Tools Fixture"}` (the fixture's display name, which its script actions' section is) lists exactly the ids `plugin_script_action::mcp_tools_fixture` of its five capabilities. +- Speed Dial actions: within 30 s of the launch, `action_list {section: "MCP Tools Fixture"}` (the fixture's display name, which its script actions' section is) lists exactly the ids `plugin_script_action::mcp_tools_fixture` of its six capabilities. - 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". @@ -251,15 +253,25 @@ An action is its command run with fixed arguments as a person's pick, and `actio - 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. - The plugin whose load failed: "the plugin whose load failed is listed with its error" reads `plugin_list`'s row for `mcp_tools_broken` with an `error` holding "this fixture's load fails here on purpose" (a row's `error` is the plugin's own, `PluginOps`). "and offers none of its operations": `tool_describe {tool: "plugin.mcp_tools_broken.measure"}` is refused with code `invalid_argument` and text starting "Unknown tool: plugin.mcp_tools_broken.measure". -- Rule lifetime: the rule's match is in `auto_answer_rules` while the plugin is loaded and gone within 30 s of the untick. +- Ungranted plugin, three runs of its script, each after its `out_ungranted.json` is removed. In runs 1 and 2 the test waits for both the outcome file (up to 60 s) and the prompt: `app_wait {for: "dialog", timeout_s: 30}`, then a dialog titled "Plugin permission request" in `app_state.dialogs` (up to 30 s more). Run 1: the outcome has `listed` true, `described` "app_state", `ok` false, `error_type` "ToolError", `code` "tools_not_allowed" and `call` containing "not allowed to call OrcaSlicer's tools" and "request_permissions(tools=True)"; exactly one dialog titled "Plugin permission request" is open, its message containing "OrcaSlicer's tools"; `dialog_answer {button: "no", dialog: {title: "Plugin permission request"}}` is not refused, within 30 s no permission prompt is open (no dialog titled "Plugin permission request" or "Plugin permissions"), and the install state holds no `permissions.tools` true. Run 2: the same outcome and the same one prompt (a No is not remembered); the same `dialog_answer` with `button: "yes"`: within 30 s the install state holds `permissions.tools` true. Run 3: the outcome has `ok` true and `call` true, and `app_state.dialogs` is empty after it. The test then writes the install state back without permissions for the legs after; `tool_call {tool: "plugin.mcp_tools_ungranted.echo", args: {"a": 1}}` returns `{"a": 1}`, with no permission prompt open after it. +- Full access alone: the test rewrites the ungranted plugin's install state with `permissions: {full_access: true}` and no `tools`; its script then records `ok` true and `call` true, with no permission prompt open after it. The install state is written back without permissions. +- Load-time prompt, before the Plugins dialog is first opened (`plugin_enable` is refused while a modal dialog is open). Each leg calls `plugin_enable {plugin: "mcp_tools_declaring", enabled: true}`, then `app_wait {for: "dialog", timeout_s: 30}`, and `app_state.dialogs` holds exactly one dialog titled "Plugin permissions", its message containing "OrcaSlicer's tools"; `dialog_answer {dialog: {title: "Plugin permissions"}}` answers it and is not refused, the load's job is followed for up to 45 s (`app_wait {for: "job"}`) when the reply was a job envelope, and within 30 s no permission prompt is open. Leg 1, `button: "no"`: the load fails (the job's result is an error with code `not_loaded`, or `plugin_list`'s row for the plugin has `enabled` false and a `status` other than "Loading"), and the install state holds no `permissions.tools` true. Leg 2, after `plugin_enable` false, `button: "yes"`: the load ends without error, the install state holds `permissions.tools` true, and the plugin's script records `ok` true and `call` true, with no permission prompt open after it. +- Tools switch, after the `rule` script has set the fixture's rule, whose match the test reads in `app_state.auto_answer_rules`: `action_run orca_command:open_plugins:orca`; `widget_click` with `{css, within: "Plugins"}` on `div.plugin-row[data-plugin-key="mcp_tools_fixture"] span.plugin-name-text` (the row's name, which the page lists as an element) selects it, on `#permissionsTab` shows its Permissions tab, on `details.permission-group[data-group="process"] > summary` opens the Execution group. The switch is read with `webview_run_javascript` on the Plugins page's web view (found by `widget_list {query: "PluginsDialog/index.html"}`), giving `{checked, disabled}` of `#permission-tools-toggle`; the install state is read from the fixture's `.install_state.json`. Control first: `{checked: true, disabled: false}` and the install state holds `permissions.tools` true. Click 1, on `label.permission-thread-toggle:has(#permission-tools-toggle)` (the label class of every yes/no permission's switch): within 30 s the install state holds `false` and the switch reads `{checked: false, disabled: false}`, with no permission prompt open (`app_state.dialogs` lists the Plugins dialog itself, and no dialog titled "Plugin permissions" or "Plugin permission request"); within 30 s the rule's match is gone from `app_state.auto_answer_rules`; the `call` script records `ok` false with "not allowed to call OrcaSlicer's tools", and its prompt is waited for as in the ungranted leg (the `app_wait` returns at once while the Plugins dialog is open, so the title is what is waited for): exactly one dialog titled "Plugin permission request", its message containing "OrcaSlicer's tools"; `dialog_answer {button: "no", dialog: {title: "Plugin permission request"}}` is not refused, within 30 s no permission prompt is open, and the install state still holds `false`. Full access, with the switch off: a click on `label.permission-placeholder:has(#permissionFullAccess)` opens one dialog titled "Full access", waited for as the prompt is, its message (its whitespace collapsed, as the dialog wraps it) containing "OrcaSlicer tools"; `dialog_answer {button: "yes", dialog: {title: "Full access"}}` is not refused, within 30 s the confirmation is closed and the install state holds `full_access` true with `tools` still `false`; the `rule` script then records `{"ok": true, "result": "plugin"}`, the rule's match is in `auto_answer_rules`, and no permission prompt is open. A second click on the same label opens no dialog: within 30 s the install state holds `full_access` false and the tools switch reads `{checked: false, disabled: false}`, with neither the confirmation nor a permission prompt open; within 30 s the rule's match is gone; the `call` script records `ok` false with "not allowed to call OrcaSlicer's tools" and exactly one "Plugin permission request" prompt naming OrcaSlicer's tools opens, whose No is not refused and closes it within 30 s. Click 2, on the same label, opens no dialog: within 30 s the install state holds `true` and the switch reads `{checked: true, disabled: false}`, with no permission prompt open; the `call` script records `{"ok": true, "result": true}`, with no permission prompt open after it; `fixture.mkv` and `fixture.mp4` are removed, the `record` script records `ok` true with a final result whose `status` is not "running", and within 30 s one of them exists with a size above 0. Then the `rule` script runs again, so the unload that follows has a plugin rule to see end; the unload opens the dialog again with `action_run`, which raises the open one. +- Rule lifetime: the rule's match is in `auto_answer_rules` while the plugin is loaded and holds the tools permission, gone within 30 s of the switch turned off, set again under full access alone and gone within 30 s of full access turned off, and, set again once the switch is on, gone within 30 s of the untick. +- Without MCP: before the `--run` launch, the ungranted plugin's install state is written without permissions and `out_ungranted.json` is removed. The replay's steps are `dialog_auto_answer {rules: [{match: "^Plugin permission request", button: "yes"}]}`, `action_run` of the fixture's `rule` script and of `plugin_script_action:MCP tools ungranted call:mcp_tools_ungranted`, `app_wait {for: "dialog", timeout_s: 30}` and `app_wait {for: "no_dialog", timeout_s: 30}`. The waits keep the replay running while the prompt opens and the rule answers it, since the refused call queues the request and posts its drain before the script returns; the rule's scope is the replay's, so it ends with it. After the run, `out_ungranted.json` records `ok` false and `code` "tools_not_allowed", and the install state holds `permissions.tools` true. Only a Yes to the runtime prompt writes it, and with the MCP server off nothing but the replay's rule can answer, so the refusal and the queued prompt both happened without the endpoint. A prompt that came too late for the rule leaves the grant unsaved, so the leg fails rather than passing. **Not checked:** - The manual's fields past the operation's `group`, `description`, parameter `a` and `listed`, and past the menu item's `listed` and parameters: the unit tests read every command's manual. - The progress dialog's gauge: `handle.update(5)` returns true, but the gauge is not read. -- The `--run` launch's exit code is ignored, and only the rule script runs there. Its replay gives the script a fixed 10 s to record its outcome before the run ends, with an `app_wait` for a dialog that never opens: the script runs on its own after `action_run` replies (`PluginScriptAction::run()`), and a replay has no step that waits for a file. +- The `--run` launch's exit code is ignored, and only the rule and the ungranted scripts run there. A script runs on its own after `action_run` replies (`PluginScriptAction::run()`), and a replay has no step that waits for a file: the replay's two waits, which last until the prompt has been answered (up to 60 s), are what give the scripts time to record their outcomes before the run ends. +- The prompt a load on the UI thread shows at once (`request_permissions()`'s inline branch): `plugin_enable` loads on a worker thread, whose request goes through the queue. The prompts' text is read only for naming OrcaSlicer's tools, and their tip checkbox is left alone. +- A call made while the tools prompt is already open or waiting, which is refused without a second prompt (the queue's `Duplicate`): the prompt queue's unit tests cover that for every runtime prompt. +- A withdrawal landing between the worker's ask (`request_tools_permission()`) and the call's admission on the UI thread, which the admission's own check (`plugin_may_call_tools()`) refuses: the sweep cannot place a withdrawal there, and the admission needs a running app. No test covers that check, so removing it, or moving it after `begin_plugin_scope()`, fails nothing: an accepted gap, since a test would need a seam in production code that nothing else uses. +- The full-access confirmation's text past naming OrcaSlicer tools, and its No: the Tools switch leg answers it Yes, and the Full access alone leg writes the install state. +- A plugin-owned `script_run` across a revocation, a recording or held press ending at the switch-off (only the rule is read; the same scope end ends all three), and a late effect of a call in flight at the switch-off: the unit tests cover child calls of a plugin-owned job and drive the withdrawn guard and `require_owner_scope()` directly. No test reaches the three UI closures that call `require_owner_scope()` with the scope gone, since that needs the withdrawal to land between a call's job thread and its UI closure. - The Run Script panel's `.py` files: the panel is hidden from automation and opens its files through a file picker, so how it reads and saves them is left to the unit tests of `decode_python_source()` and `encode_python_source()`. -**Strength:** Partial — the fixture's operation, its listing and manual, script outcomes, events, journal, failed load and unload are each checked exactly, with a control for the journal's absence, but the `--run` launch's exit code is not read. +**Strength:** Partial — the fixture's operation, its listing and manual, script outcomes, events, journal, failed load, the tools permission's refusal and runtime prompt, load-time prompt, withdrawal and restore, and unload are each checked exactly, with controls for the journal's absence and the switch's starting state, but the `--run` launch's exit code is not read. ## `test_operation_routes` `test_operation_routes.py` · Python diff --git a/tools/mcp/test_plugin_commands.py b/tools/mcp/test_plugin_commands.py index cfc8d9404d..4d4f49cd9a 100644 --- a/tools/mcp/test_plugin_commands.py +++ b/tools/mcp/test_plugin_commands.py @@ -11,7 +11,6 @@ Run it as python tools/mcp/test_plugin_commands.py [--bin PATH] [--datadir PATH] """ import json import os -import re import shutil import sys import tempfile @@ -19,7 +18,7 @@ import time HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -from checks import Checks, launched, reached, refusal as error_of, speed_dial, until # noqa: E402 +from checks import Checks, launched, reached, refusal as error_of, speed_dial, until, web_view # noqa: E402 from orca_mcp import McpError # noqa: E402 TOKEN = "plugin-commands-test-token" @@ -71,11 +70,10 @@ def window_rows(orca): code = ("JSON.stringify(Array.from(document.querySelectorAll('.plugin-row')).map(function (r) {" " var box = r.querySelector('input.plugin-checkbox-input:not(.capability-checkbox-input)');" " return {key: r.dataset.pluginKey, enabled: !!(box && box.checked)}; }))") - _, tree = orca.call_with_text("widget_list", query="PluginsDialog/index.html") - view = re.search(r"\[(\w+)\] webview", "\n".join(tree)) + view = web_view(orca, "PluginsDialog/index.html") if view is None: return None - reply = orca.call("webview_run_javascript", code=code, target=view.group(1)) + reply = orca.call("webview_run_javascript", code=code, target=view) result = reply.get("result") return json.loads(result) if isinstance(result, str) else result diff --git a/tools/mcp/test_plugin_tools.py b/tools/mcp/test_plugin_tools.py index 7a420e9b4b..8598cb631a 100644 --- a/tools/mcp/test_plugin_tools.py +++ b/tools/mcp/test_plugin_tools.py @@ -2,11 +2,15 @@ Its design is the test_plugin_tools entry of tools/mcp/test-entries/commands.md. Launches OrcaSlicer on a fresh data folder with the Design tab on (--cad) and -tests/plugins/mcp_tools_fixture side-loaded, and tests/plugins/mcp_tools_broken, whose load fails after declaring an -operation: over MCP, then once without MCP, running a replay with --run, so the plugin's calls go to the -runtime started without its endpoint. The first launch also checks that the plugin is sent the NewProject event when -project_new or its Speed Dial action starts a project, and ends by unticking the fixture in the Plugins dialog, as a -person unloads it. +tests/plugins/mcp_tools_fixture side-loaded with the tools permission, tests/plugins/mcp_tools_ungranted without it, +tests/plugins/mcp_tools_declaring, which asks for it as it loads, and tests/plugins/mcp_tools_broken, whose load +fails after declaring an operation: over MCP, then once without MCP, +running a replay with --run, so the plugins' calls go to the runtime started without its endpoint. The first launch +also checks that the plugin is sent the NewProject event when project_new or its Speed Dial action starts a project, +answers the Plugin permission request prompt a call without the tools permission opens, No and then Yes, answers the +declaring plugin's load prompt, No and then Yes, turns the fixture's OrcaSlicer tools switch off and on again in the +Plugins dialog, with its Full access switch turned on and off between them, and ends by unticking the fixture there, as a person unloads it. Without MCP, the replay's own +auto-answer rule says Yes to the prompt the ungranted plugin's call opens. Run it as python tools/mcp/test_plugin_tools.py [--bin PATH]. """ import json @@ -18,14 +22,35 @@ import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -from checks import Checks, free_port, harness, reached, until # noqa: E402 -from orca_mcp import OrcaMcp, app_env, find_binary # noqa: E402 +from checks import Checks, dialogs, free_port, harness, reached, until, web_view # noqa: E402 +from orca_mcp import McpError, OrcaMcp, app_env, find_binary # noqa: E402 -FIXTURE = os.path.join(HERE, "tests", "plugins", "mcp_tools_fixture") PLUGIN = "mcp_tools_fixture" CAPABILITIES = ["MCP tools fixture call", "MCP tools fixture thread", "MCP tools fixture rule", "MCP tools fixture export", - "MCP tools fixture handle"] + "MCP tools fixture handle", "MCP tools fixture record"] BROKEN = "mcp_tools_broken" +UNGRANTED = "mcp_tools_ungranted" +UNGRANTED_CAPABILITY = "MCP tools ungranted call" +UNGRANTED_ACTION = f"plugin_script_action:{UNGRANTED_CAPABILITY}:{UNGRANTED}" +DECLARING = "mcp_tools_declaring" # asks for the tools as it loads +DECLARING_CAPABILITY = "MCP tools declaring call" +# Each side-loaded plugin's name and capabilities, as its install state lists them. +SIDE_LOADED = {PLUGIN: ("MCP Tools Fixture", CAPABILITIES), UNGRANTED: ("MCP Tools Ungranted", [UNGRANTED_CAPABILITY]), + DECLARING: ("MCP Tools Declaring", [DECLARING_CAPABILITY]), + BROKEN: ("MCP Tools Broken Fixture", ["MCP tools broken fixture"])} +REFUSED = "not allowed to call OrcaSlicer's tools" # the start of the refusal a plugin without the tools gets +# The titles of the prompt a call without the tools permission opens, and of the one a load's declaration opens. +RUNTIME_PROMPT = "Plugin permission request" +LOAD_PROMPT = "Plugin permissions" +TOOLS_NAMED = "OrcaSlicer's tools" # what both prompts' message says the plugin asks to call +# The fixture's OrcaSlicer tools switch on the Plugins dialog's Permissions tab, and the label a click lands on, which +# has the class of every yes/no permission's switch. +TOOLS_SWITCH = "permission-tools-toggle" +TOOLS_SWITCH_LABEL = f"label.permission-thread-toggle:has(#{TOOLS_SWITCH})" +# The Permissions tab's Full access switch, by the label a click lands on, and the title of the confirmation turning it +# on opens. +FULL_ACCESS_LABEL = "label.permission-placeholder:has(#permissionFullAccess)" +FULL_ACCESS_PROMPT = "Full access" # A script that finds the fixture's progress dialog among the loaded modules and moves its gauge. GRAB_HANDLE = """ import sys @@ -33,33 +58,59 @@ handle = next(m.HANDLE for m in list(sys.modules.values()) if getattr(m, "HANDLE result = handle.update(5) """ RULE = "MCP tools fixture never shown" # the match of the auto-answer rule the fixture's "rule" script sets +UNRECORDED = {"ok": None, "error": "the script recorded nothing"} # the outcome of a script that recorded none TOKEN = "plugin-tools-test-token" # The test's named checks; check() records one and prints it. t = Checks() check = t.check +def write_state(datadir, key, enabled=True, permissions=None): + """Writes the install state of the side-loaded plugin `key`: `enabled`, each of its capabilities on, and + `permissions` when given (none otherwise).""" + name, capabilities = SIDE_LOADED[key] + state = {"installed_from": "local", "installed_version": "1.0.0", "plugin_name": name, "enabled": enabled, + "capabilities": [{capability: True} for capability in capabilities]} + if permissions is not None: + state["permissions"] = permissions + with open(os.path.join(datadir, "orca_plugins", key, ".install_state.json"), "w", encoding="utf-8") as f: + json.dump(state, f, indent=2) + + +def side_load(datadir, key, enabled=True, permissions=None): + """Side-loads tests/plugins/ with the install state write_state() writes. Returns the plugin's storage folder, + where orca.host.plugin.storage() puts its files, and its scripts their outcomes.""" + dest = os.path.join(datadir, "orca_plugins", key) + os.makedirs(dest, exist_ok=True) + shutil.copy(os.path.join(HERE, "tests", "plugins", key, key + ".py"), dest) + write_state(datadir, key, enabled, permissions) + return os.path.join(datadir, "orca_plugins", "plugin_data", key) + + def install(datadir): - """Side-loads the fixture enabled, with its threads granted.""" - dest = os.path.join(datadir, "orca_plugins", PLUGIN) - os.makedirs(dest, exist_ok=True) - shutil.copy(os.path.join(FIXTURE, PLUGIN + ".py"), dest) - with open(os.path.join(dest, ".install_state.json"), "w", encoding="utf-8") as f: - json.dump({"installed_from": "local", "installed_version": "1.0.0", "plugin_name": "MCP Tools Fixture", "enabled": True, - "capabilities": [{name: True} for name in CAPABILITIES], - "permissions": {"threading": ["thread"]}}, f, indent=2) - # Where orca.host.plugin.storage() puts the plugin's files, and the scripts their outcomes. - return os.path.join(datadir, "orca_plugins", "plugin_data", PLUGIN) + """Side-loads the fixture enabled, with its threads and the tools granted; returns its storage folder.""" + return side_load(datadir, PLUGIN, permissions={"threading": ["thread"], "tools": True}) -def install_broken(datadir): - """Side-loads the plugin whose load fails.""" - dest = os.path.join(datadir, "orca_plugins", BROKEN) - os.makedirs(dest, exist_ok=True) - shutil.copy(os.path.join(HERE, "tests", "plugins", BROKEN, BROKEN + ".py"), dest) - with open(os.path.join(dest, ".install_state.json"), "w", encoding="utf-8") as f: - json.dump({"installed_from": "local", "installed_version": "1.0.0", "plugin_name": "MCP Tools Broken Fixture", "enabled": True, - "capabilities": [{"MCP tools broken fixture": True}]}, f, indent=2) +def read_json(path): + """What the JSON file at `path` holds, or None while it is missing or still being written.""" + try: + with open(path, encoding="utf-8") as f: + return json.load(f) + except (OSError, ValueError): + return None + + +def stored_permissions(datadir, key): + """The permissions the plugin `key`'s install state holds ({} while it has none), or None while it does not read.""" + state = read_json(os.path.join(datadir, "orca_plugins", key, ".install_state.json")) + return None if state is None else state.get("permissions", {}) + + +def tools_grant(datadir, key=PLUGIN): + """The tools permission the plugin `key`'s install state holds: True, False, or None while it holds none or does not + read.""" + return (stored_permissions(datadir, key) or {}).get("tools") def lines_of(path): @@ -80,24 +131,120 @@ def canvas_height(orca): return None -def run_plugin_script(orca, plugin_dir, name, capability): - """Runs one of the fixture's scripts and returns what it recorded in its storage folder.""" +def run_plugin_script(orca, plugin_dir, name, capability, plugin=PLUGIN): + """Runs one of a plugin's scripts and returns what it recorded in its storage folder (out_.json).""" out = os.path.join(plugin_dir, f"out_{name}.json") if os.path.exists(out): os.remove(out) - orca.call("action_run", id=f"plugin_script_action:{capability}:{PLUGIN}") - - def recorded(): - try: - with open(out, encoding="utf-8") as f: - return json.load(f) - except (OSError, ValueError): # not written yet, or still being written - return None - + orca.call("action_run", id=f"plugin_script_action:{capability}:{plugin}") try: - return until(recorded, f"the {name} script records its outcome", timeout_s=60) + return until(lambda: read_json(out), f"the {name} script records its outcome", timeout_s=60) except TimeoutError: - return {"ok": None, "error": "the script recorded nothing"} + return UNRECORDED + + +def tools_switch(orca, view): + """The OrcaSlicer tools switch on the Permissions tab of `view`, the Plugins dialog's page: {checked, disabled}, + or None.""" + if view is None: + return None + code = (f"JSON.stringify((function () {{ var b = document.getElementById('{TOOLS_SWITCH}');" + " return b ? {checked: b.checked, disabled: b.disabled} : null; })())") + result = orca.call("webview_run_javascript", code=code, target=view).get("result") + return json.loads(result) if isinstance(result, str) else result + + +def click_in_plugins(orca, css): + """Clicks the element `css` names on the Plugins dialog's page; the reply, which a dialog it opens may hold.""" + return orca.call_raw("widget_click", {"target": {"css": css, "within": "Plugins"}}) + + +def prompts_open(orca): + """Whether a permission prompt is open (the Plugins dialog itself may be listed).""" + return any(d["title"] in (RUNTIME_PROMPT, LOAD_PROMPT) for d in dialogs(orca)) + + +def prompt_messages(orca, title): + """The messages of the open dialogs titled `title`.""" + return [d.get("message") or "" for d in dialogs(orca) if d["title"] == title] + + +def await_prompt(orca, title): + """The messages of the dialogs titled `title` once one is open, waited for up to 30 s ([] when none opens). The + app_wait for a dialog returns at once while another dialog, such as the Plugins dialog, is open, so the title is then + waited for in app_state.dialogs.""" + orca.call_raw("app_wait", {"for": "dialog", "timeout_s": 30}) + reached(lambda: prompt_messages(orca, title), f"a dialog titled {title} opens") + return prompt_messages(orca, title) + + +def asks_once(messages): + """Whether `messages`, await_prompt()'s, are one prompt's, and it names OrcaSlicer's tools.""" + return len(messages) == 1 and TOOLS_NAMED in messages[0] + + +def answer(orca, title, button): + """Presses `button` on the dialog titled `title`, which must be the topmost; whether the press was not refused.""" + return not orca.call_raw("dialog_answer", {"button": button, "dialog": {"title": title}}).get("isError") + + +def run_and_prompt(orca, plugin_dir, name, capability, plugin): + """Runs a plugin's script whose call is refused for the tools permission, and waits for both what it records and the + Plugin permission request prompt the refused call queues: the queue may show the prompt before or after the script + writes its outcome. Returns the outcome and await_prompt()'s messages.""" + outcome = run_plugin_script(orca, plugin_dir, name, capability, plugin) + return outcome, await_prompt(orca, RUNTIME_PROMPT) + + +def refused_ungranted(outcome): + """Whether the ungranted plugin's script recorded what a call without the tools permission gets: the catalog read, + and the call refused as a ToolError whose text names the permission and how a plugin declares it.""" + return (outcome.get("listed") is True and outcome.get("described") == "app_state" and outcome.get("ok") is False and + outcome.get("error_type") == "ToolError" and outcome.get("code") == "tools_not_allowed" and + REFUSED in str(outcome.get("call")) and "request_permissions(tools=True)" in str(outcome.get("call"))) + + +def plugin_row(orca, key): + """The plugin `key`'s row in plugin_list, or None.""" + return next((r for r in orca.call("plugin_list")["plugins"] if r["key"] == key), None) + + +def load_declaring(orca, button): + """Switches the declaring plugin on and, once its load's prompt is up, answers it with `button`. Returns the prompt's + messages (await_prompt()'s), whether the answer was not refused, the load's end (its job's result, or the McpError + that ended the load or the 45 s wait for it), and whether no permission prompt is open after it.""" + try: + load = orca.call("plugin_enable", plugin=DECLARING, enabled=True) + except McpError as e: + load = e + asked = await_prompt(orca, LOAD_PROMPT) + answered = answer(orca, LOAD_PROMPT, button) + try: + load = orca.await_job(load, timeout=45) # an McpError is no job envelope, so it comes back as it is + except McpError as e: + load = e + settled = reached(lambda: not prompts_open(orca), "no permission prompt is open") + return asked, answered, load, settled + + +def load_ended(load): + """Whether load_declaring()'s end of the load is the load's end without error: no McpError, and no reply that the + load is still running or held by a dialog (one without a job id, which await_job() hands back as it is).""" + return not isinstance(load, McpError) and load.get("status") not in ("running", "blocked_by_dialog") + + +def load_failed(orca, load): + """Whether load_declaring()'s load ended in failure: its job's result is the error of a plugin that did not load, or + plugin_list shows the plugin neither loaded nor still loading.""" + row = plugin_row(orca, DECLARING) + unloaded = row is not None and not row.get("enabled") and row.get("status") != "Loading" + return (isinstance(load, McpError) and "not_loaded" in str(load)) or unloaded + + +def recording_written(plugin_dir): + """Whether the fixture's recording left a file: fixture.mkv, or the MP4 it is encoded to when ffmpeg is there.""" + return any(os.path.isfile(p) and os.path.getsize(p) > 0 + for p in (os.path.join(plugin_dir, "fixture.mkv"), os.path.join(plugin_dir, "fixture.mp4"))) def launch(env, datadir, extra): @@ -119,7 +266,9 @@ def main(): try: # --- Over MCP: the plugin's operation and its tool calls, beside a plugin whose load fails. --- plugin_dir = install(datadir) - install_broken(datadir) + ungranted_dir = side_load(datadir, UNGRANTED) + declaring_dir = side_load(datadir, DECLARING, enabled=False) # loaded only when the test switches it on + side_load(datadir, BROKEN) # The Design tab on, so that tool_list lists its commands. orca = launch(env, datadir, ["--cad", *extra]) operation_name = f"plugin.{PLUGIN}.measure" @@ -127,7 +276,7 @@ def main(): check("tool_list lists the plugin's operation", operation_name in listed_plugins(), listed_plugins()) scripts = {f"plugin_script_action:{capability}:{PLUGIN}" for capability in CAPABILITIES} fixture_actions = lambda: {a["id"] for a in orca.call("action_list", section="MCP Tools Fixture", limit=200)["items"]} - check("action_list lists the fixture's five scripts as its Speed Dial actions", + check("action_list lists the fixture's six scripts as its Speed Dial actions", reached(lambda: fixture_actions() == scripts, "the fixture's script actions are listed"), sorted(fixture_actions())) described = orca.call_raw("tool_describe", {"tool": operation_name}) operation = {} if described.get("isError") else json.loads(described["content"][0]["text"]) @@ -153,6 +302,53 @@ def main(): exported = run_plugin_script(orca, plugin_dir, "export", CAPABILITIES[3]) check("a plugin is refused replay_export", exported.get("ok") is False and "agent's session" in exported.get("error", ""), exported) + # --- A plugin without the tools permission: it reads the catalog and offers operations, but a call is refused and + # asks the person, in the Plugin permission request prompt. A No is not remembered; a Yes lets the next call through. + ungranted, asked = run_and_prompt(orca, ungranted_dir, "ungranted", UNGRANTED_CAPABILITY, UNGRANTED) + check("a plugin without the tools permission reads the catalog but is refused a call, as a ToolError", + refused_ungranted(ungranted), ungranted) + check("and is asked in the Plugin permission request prompt, which names OrcaSlicer's tools", asks_once(asked), + dialogs(orca)) + check("a No closes the prompt and stores no grant", + answer(orca, RUNTIME_PROMPT, "no") and reached(lambda: not prompts_open(orca), "the prompt closes") and + tools_grant(datadir, UNGRANTED) is not True, (stored_permissions(datadir, UNGRANTED), dialogs(orca))) + ungranted, asked = run_and_prompt(orca, ungranted_dir, "ungranted", UNGRANTED_CAPABILITY, UNGRANTED) + check("a No is not remembered: its next call is refused and asks again", + refused_ungranted(ungranted) and asks_once(asked), (ungranted, dialogs(orca))) + check("a Yes stores the grant", + answer(orca, RUNTIME_PROMPT, "yes") and + reached(lambda: tools_grant(datadir, UNGRANTED) is True, "the install state holds tools true"), + (stored_permissions(datadir, UNGRANTED), dialogs(orca))) + allowed = run_plugin_script(orca, ungranted_dir, "ungranted", UNGRANTED_CAPABILITY, UNGRANTED) + check("which lets its next call through", allowed.get("ok") is True and allowed.get("call") is True, allowed) + check("with no dialog open after it", not dialogs(orca), dialogs(orca)) + write_state(datadir, UNGRANTED) + echoed = orca.call_raw("tool_call", {"tool": f"plugin.{UNGRANTED}.echo", "args": {"a": 1}}) + check("the operation it offers runs without the grant, asking nothing", not echoed.get("isError") and + json.loads(echoed["content"][0]["text"]) == {"a": 1} and not prompts_open(orca), (echoed, dialogs(orca))) + write_state(datadir, UNGRANTED, permissions={"full_access": True}) + full = run_plugin_script(orca, ungranted_dir, "ungranted", UNGRANTED_CAPABILITY, UNGRANTED) + check("full access alone lets it call, asking nothing", full.get("ok") is True and full.get("call") is True and + not prompts_open(orca), (full, dialogs(orca))) + write_state(datadir, UNGRANTED) + + # --- The load prompt of a plugin that declares the tools, answered in its real dialog. Before the Plugins dialog + # is first opened: it is modal, and plugin_enable is refused while a modal dialog is open. --- + asked, answered, load, settled = load_declaring(orca, "no") + check("a plugin that declares the tools asks for them in its Plugin permissions prompt", asks_once(asked), + (asked, dialogs(orca))) + check("a No fails its load and stores no grant", + answered and settled and load_failed(orca, load) and tools_grant(datadir, DECLARING) is not True, + (load, plugin_row(orca, DECLARING), stored_permissions(datadir, DECLARING), dialogs(orca))) + orca.call("plugin_enable", plugin=DECLARING, enabled=False) + asked, answered, load, settled = load_declaring(orca, "yes") + check("switched on again, it asks again", asks_once(asked), (asked, dialogs(orca))) + check("and a Yes loads it and stores the grant", + answered and load_ended(load) and settled and tools_grant(datadir, DECLARING) is True, + (load, stored_permissions(datadir, DECLARING), dialogs(orca))) + allowed = run_plugin_script(orca, declaring_dir, "declaring", DECLARING_CAPABILITY, DECLARING) + check("which lets the plugin call the tools, asking nothing", + allowed.get("ok") is True and allowed.get("call") is True and not prompts_open(orca), (allowed, dialogs(orca))) # The menu items with no argument form, each with what it does as its manual's description says it. commands = {i["name"]: i for i in orca.call("tool_list")["items"]} for menu_item in ("settings_toggle_developer_mode", "script_toggle_panel"): @@ -201,7 +397,7 @@ def main(): answers = [s for s in journal if s["tool"] == "dialog_auto_answer"] check("a plugin's calls are not in the agent's journal", len(answers) == 1 and answers[0].get("args", {}).get("rules") == [], answers) - broken_row = next((r for r in orca.call("plugin_list")["plugins"] if r["key"] == BROKEN), None) + broken_row = plugin_row(orca, BROKEN) check("the plugin whose load failed is listed with its error", broken_row is not None and "this fixture's load fails here on purpose" in (broken_row.get("error") or ""), broken_row) broken = orca.call_raw("tool_describe", {"tool": f"plugin.{BROKEN}.measure"}) @@ -225,8 +421,83 @@ def main(): grab = orca.await_job(orca.call("script_run", code=GRAB_HANDLE)) check("a script that finds a plugin's handle can use its methods", grab.get("result") is True, grab) - # --- The plugin unloads, as a person unticks it in the Plugins dialog. --- + # --- The fixture's OrcaSlicer tools switch, turned off and on again on the Plugins dialog's Permissions tab. --- rules = lambda: json.dumps(orca.call("app_state").get("auto_answer_rules")) + check("the fixture's auto-answer rule is in force while it holds the tools", RULE in rules(), rules()) + orca.call("action_run", id="orca_command:open_plugins:orca") + # The row's name, which the page lists as an element (the row itself is not one); a click on it selects the row. + row = f'div.plugin-row[data-plugin-key="{PLUGIN}"] span.plugin-name-text' + check("the Plugins dialog selects the fixture's row", + reached(lambda: not click_in_plugins(orca, row).get("isError"), "the fixture's row is clicked")) + shown = click_in_plugins(orca, "#permissionsTab") + group = click_in_plugins(orca, 'details.permission-group[data-group="process"] > summary') + check("and shows its Permissions tab with the Execution group open", not shown.get("isError") and not group.get("isError"), + (shown, group)) + page = web_view(orca, "PluginsDialog/index.html") + on = {"checked": True, "disabled": False} + off = {"checked": False, "disabled": False} + check("the OrcaSlicer tools switch starts on, as the install state does", + reached(lambda: tools_switch(orca, page) == on, "the tools switch reads on") and tools_grant(datadir) is True, + (tools_switch(orca, page), tools_grant(datadir))) + clicked = click_in_plugins(orca, TOOLS_SWITCH_LABEL) + check("turning it off asks nothing and stores false", + not clicked.get("isError") and reached(lambda: tools_grant(datadir) is False, "the install state holds tools false") and + reached(lambda: tools_switch(orca, page) == off, "the switch reads off") and not prompts_open(orca), + (clicked, tools_grant(datadir), tools_switch(orca, page), dialogs(orca))) + check("and ends the fixture's auto-answer rule", reached(lambda: RULE not in rules(), "the fixture's rule ends"), rules()) + refused, asked = run_and_prompt(orca, plugin_dir, "call", CAPABILITIES[0], PLUGIN) + check("the fixture's next call is refused", refused.get("ok") is False and REFUSED in refused.get("error", ""), refused) + check("and asks in the Plugin permission request prompt, over the Plugins dialog", asks_once(asked), dialogs(orca)) + check("whose No stores nothing", + answer(orca, RUNTIME_PROMPT, "no") and reached(lambda: not prompts_open(orca), "the prompt closes") and + tools_grant(datadir) is False, (tools_grant(datadir), dialogs(orca))) + # Full access alone, with the switch off: it grants the tools, and turning it off withdraws them as the switch does. + full_access = lambda: (stored_permissions(datadir, PLUGIN) or {}).get("full_access") + confirming = lambda: any(d["title"] == FULL_ACCESS_PROMPT for d in dialogs(orca)) + clicked = click_in_plugins(orca, FULL_ACCESS_LABEL) + confirmation = await_prompt(orca, FULL_ACCESS_PROMPT) + check("turning full access on asks in its confirmation, which names the tools", + not clicked.get("isError") and len(confirmation) == 1 and + "OrcaSlicer tools" in " ".join(confirmation[0].split()), # the dialog wraps its message at any space + (clicked, confirmation)) + check("whose Yes stores full access, the tools grant still false", + answer(orca, FULL_ACCESS_PROMPT, "yes") and reached(lambda: not confirming(), "the confirmation closes") and + reached(lambda: full_access() is True, "the install state holds full access") and tools_grant(datadir) is False, + (stored_permissions(datadir, PLUGIN), dialogs(orca))) + rule = run_plugin_script(orca, plugin_dir, "rule", CAPABILITIES[2]) + check("which lets the fixture call the tools again and set its rule, asking nothing", + rule == {"ok": True, "result": "plugin"} and RULE in rules() and not prompts_open(orca), (rule, rules(), dialogs(orca))) + clicked = click_in_plugins(orca, FULL_ACCESS_LABEL) + check("turning full access off asks nothing and stores false, the tools switch usable again", + not clicked.get("isError") and reached(lambda: full_access() is False, "the install state holds full access false") and + reached(lambda: tools_switch(orca, page) == off, "the switch reads off") and not confirming() and + not prompts_open(orca), (clicked, stored_permissions(datadir, PLUGIN), tools_switch(orca, page), dialogs(orca))) + check("and, with the switch off too, ends the fixture's rule", reached(lambda: RULE not in rules(), "the fixture's rule ends"), + rules()) + refused, asked = run_and_prompt(orca, plugin_dir, "call", CAPABILITIES[0], PLUGIN) + check("and refuses its next call, asking again", + refused.get("ok") is False and REFUSED in refused.get("error", "") and asks_once(asked), (refused, dialogs(orca))) + check("whose No closes the prompt", + answer(orca, RUNTIME_PROMPT, "no") and reached(lambda: not prompts_open(orca), "the prompt closes"), dialogs(orca)) + clicked = click_in_plugins(orca, TOOLS_SWITCH_LABEL) + check("turning the switch on asks nothing and stores true", + not clicked.get("isError") and reached(lambda: tools_grant(datadir) is True, "the install state holds tools true") and + reached(lambda: tools_switch(orca, page) == on, "the switch reads on") and not prompts_open(orca), + (clicked, tools_grant(datadir), tools_switch(orca, page), dialogs(orca))) + allowed = run_plugin_script(orca, plugin_dir, "call", CAPABILITIES[0]) + check("the fixture calls the tools again, asking nothing", allowed == {"ok": True, "result": True} and + not prompts_open(orca), (allowed, dialogs(orca))) + for name in ("fixture.mkv", "fixture.mp4"): + if os.path.exists(os.path.join(plugin_dir, name)): + os.remove(os.path.join(plugin_dir, name)) + recorded = run_plugin_script(orca, plugin_dir, "record", CAPABILITIES[5]) + check("and starts a recording under its scope opened again", + recorded.get("ok") is True and (recorded.get("result") or {}).get("status") != "running" and + reached(lambda: recording_written(plugin_dir), "the fixture's recording is written"), recorded) + rule = run_plugin_script(orca, plugin_dir, "rule", CAPABILITIES[2]) + check("and sets its auto-answer rule again", rule == {"ok": True, "result": "plugin"}, rule) + + # --- The plugin unloads, as a person unticks it in the Plugins dialog. --- check("the auto-answer rule the plugin set lasts while it is loaded", RULE in rules(), rules()) orca.call("action_run", id="orca_command:open_plugins:orca") untick = orca.call_raw("widget_click", {"target": {"css": f'label.plugin-checkbox:has(input[data-plugin-key="{PLUGIN}"])', @@ -243,23 +514,33 @@ def main(): # stop returns once the app has exited, so that the --run launch below is the only app on the folder. harness(env, "stop") - # --- Without MCP: a launch replay runs the plugin's script, whose calls reach the runtime without its endpoint. --- + # --- Without MCP: a launch replay runs the plugins' scripts, whose calls reach the runtime without its endpoint. The + # ungranted plugin's refused call queues its prompt, which only the replay's own rule can answer, and the two waits + # keep the replay running while the prompt opens and is answered; the rule ends with the replay. --- install(datadir) # enabled again: unticking it saved it disabled + write_state(datadir, UNGRANTED) steps = os.path.join(datadir, "plugin_rule.json") with open(steps, "w", encoding="utf-8") as f: - json.dump({"orca_replay_version": "0.2.0", "name": "a plugin's rule without MCP", "steps": [ + json.dump({"orca_replay_version": "0.2.0", "name": "plugins' calls without MCP", "steps": [ + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": f"^{RUNTIME_PROMPT}", "button": "yes"}]}}, {"tool": "action_run", "args": {"id": f"plugin_script_action:{CAPABILITIES[2]}:{PLUGIN}"}}, - {"tool": "app_wait", "args": {"for": "dialog", "timeout_s": 10}}]}, f) + {"tool": "action_run", "args": {"id": UNGRANTED_ACTION}}, + {"tool": "app_wait", "args": {"for": "dialog", "timeout_s": 30}}, + {"tool": "app_wait", "args": {"for": "no_dialog", "timeout_s": 30}}]}, f) out = os.path.join(plugin_dir, "out_rule.json") - if os.path.exists(out): - os.remove(out) + ungranted_out = os.path.join(ungranted_dir, "out_ungranted.json") + for stale in (out, ungranted_out): + if os.path.exists(stale): + os.remove(stale) subprocess.run([binary, "--datadir", datadir, "--run", steps], env=env, timeout=600) - try: - with open(out, encoding="utf-8") as f: - offline = json.load(f) - except (OSError, ValueError) as e: - offline = {"ok": None, "error": str(e)} + offline = read_json(out) or UNRECORDED check("with MCP off, a plugin's auto-answer rule is the plugin's", offline == {"ok": True, "result": "plugin"}, offline) + offline_refused = read_json(ungranted_out) or UNRECORDED + check("and a plugin without the tools permission is refused", + offline_refused.get("ok") is False and offline_refused.get("code") == "tools_not_allowed", offline_refused) + # Only a Yes to the prompt writes the grant, and with the MCP server off only the replay's rule answers it. + check("and asked, in the prompt the replay's rule says Yes to", tools_grant(datadir, UNGRANTED) is True, + stored_permissions(datadir, UNGRANTED)) finally: if os.path.exists(os.path.join(datadir, "session.json")): harness(env, "stop") diff --git a/tools/mcp/tests/plugins/mcp_tools_declaring/mcp_tools_declaring.py b/tools/mcp/tests/plugins/mcp_tools_declaring/mcp_tools_declaring.py new file mode 100644 index 0000000000..660fba7ae6 --- /dev/null +++ b/tools/mcp/tests/plugins/mcp_tools_declaring/mcp_tools_declaring.py @@ -0,0 +1,41 @@ +# /// script +# requires-python = ">=3.12" +# +# [tool.orcaslicer.plugin] +# name = "MCP Tools Declaring" +# description = "Asks for the MCP tools as it loads, for tools/mcp/test_plugin_tools.py." +# author = "OrcaSlicer contributors" +# version = "1.0.0" +# /// +"""The plugin tools/mcp/test_plugin_tools.py loads to answer its load-time tools prompt. + +It asks for the tools as it registers, with orca.request_permissions(tools=True), and for nothing else. Its +script "MCP tools declaring call" calls app_state and writes what happened to out_declaring.json in the +plugin's storage folder: {"ok", "code", "call"}, the call's `ready` or the error text. +""" +import json +import os + +import orca + + +class CallTheTools(orca.script.ScriptPluginCapabilityBase): + def get_name(self): + return "MCP tools declaring call" + + def execute(self): + try: + out = {"ok": True, "code": None, "call": orca.host.tools.call("app_state").get("ready")} + except Exception as e: + details = getattr(e, "details", None) + out = {"ok": False, "code": details.get("code") if isinstance(details, dict) else None, "call": str(e)} + with open(os.path.join(orca.host.plugin.storage(), "out_declaring.json"), "w", encoding="utf-8") as f: + json.dump(out, f) + return orca.ExecutionResult.success("declaring") + + +@orca.plugin +class DeclaringPackage(orca.base): + def register_capabilities(self): + orca.request_permissions(tools=True) + orca.register_capability(CallTheTools) diff --git a/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py b/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py index 0a79706e94..4914b4b68a 100644 --- a/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py +++ b/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py @@ -13,10 +13,12 @@ Side-load it into a test data directory (test_plugin_tools.py does) and run its Each script writes what happened to out_.json in the plugin's storage folder, which the test reads back: {"ok": true, "result": ...} or {"ok": false, "error": "...", "details": ...}. "call" calls app_state, "thread" calls it from a thread the script starts, "rule" registers an auto-answer rule, "export" asks for -replay_export, which a plugin is refused, and "handle" opens a progress dialog and keeps its handle in -HANDLE, for a script to find and use. The plugin also offers the operation "measure", which doubles its -argument a, and its first capability adds a line to new_projects.txt in the storage folder for each -NewProject event it is sent. +replay_export, which a plugin is refused, "handle" opens a progress dialog and keeps its handle in +HANDLE, for a script to find and use, and "record" starts a one-second recording into fixture.mkv in the +storage folder and records the final result. The plugin also offers the operation "measure", which +doubles its argument a, and its first capability adds a line to new_projects.txt in the storage folder +for each NewProject event it is sent. It declares no permissions: the test seeds its grants, the tools +permission among them. """ import json import os @@ -111,6 +113,23 @@ class HoldHandle(orca.script.ScriptPluginCapabilityBase): return record("handle", create) +def start_recording(): + path = os.path.join(orca.host.plugin.storage(), "fixture.mkv") + reply = orca.host.tools.call("recording_start", {"save_path": path, "overwrite": True, "max_seconds": 1}) + # A start that outlives its reply budget comes back as a job: its final result says whether it started. + if reply.get("status") == "running": + reply = orca.host.tools.call("app_wait", {"for": "job", "job": reply["job"]}) + return reply + + +class Record(orca.script.ScriptPluginCapabilityBase): + def get_name(self): + return "MCP tools fixture record" + + def execute(self): + return record("record", start_recording) + + def measure(args): return {"twice": args.get("a", 0) * 2} @@ -120,5 +139,5 @@ class FixturePackage(orca.base): def register_capabilities(self): orca.register_operation("measure", "Doubles a.", {"type": "object", "properties": {"a": {"type": "number"}}}, measure, changes=False) - for capability in (CallTool, CallFromThread, SetRule, ExportReplay, HoldHandle): + for capability in (CallTool, CallFromThread, SetRule, ExportReplay, HoldHandle, Record): orca.register_capability(capability) diff --git a/tools/mcp/tests/plugins/mcp_tools_ungranted/mcp_tools_ungranted.py b/tools/mcp/tests/plugins/mcp_tools_ungranted/mcp_tools_ungranted.py new file mode 100644 index 0000000000..c4e4557ed9 --- /dev/null +++ b/tools/mcp/tests/plugins/mcp_tools_ungranted/mcp_tools_ungranted.py @@ -0,0 +1,62 @@ +# /// script +# requires-python = ">=3.12" +# +# [tool.orcaslicer.plugin] +# name = "MCP Tools Ungranted" +# description = "Calls the MCP tools without permission to, for tools/mcp/test_plugin_tools.py." +# author = "OrcaSlicer contributors" +# version = "1.0.0" +# /// +"""The plugin tools/mcp/test_plugin_tools.py side-loads without the tools permission. + +It declares no permissions. Its script "MCP tools ungranted call" reads the catalog through +orca.host.tools.list() and describe(), which need no permission, then calls app_state, which does, and +writes what happened to out_ungranted.json in the plugin's storage folder: {"listed", "described", "ok", +"error_type", "code", "call"}. It offers the operation "echo", which returns its arguments and calls no tool. +""" +import json +import os + +import orca + + +def outcome(): + out = {} + try: + out["listed"] = any(c["name"] == "app_state" for c in orca.host.tools.list()) + except Exception as e: + out["listed"] = f"{type(e).__name__}: {e}" + try: + out["described"] = orca.host.tools.describe("app_state").get("key") + except Exception as e: + out["described"] = f"{type(e).__name__}: {e}" + try: + out["call"] = orca.host.tools.call("app_state").get("ready") + out.update(ok=True, error_type=None, code=None) + except Exception as e: + details = getattr(e, "details", None) + out.update(ok=False, error_type=type(e).__name__, code=details.get("code") if isinstance(details, dict) else None, + call=str(e)) + with open(os.path.join(orca.host.plugin.storage(), "out_ungranted.json"), "w", encoding="utf-8") as f: + json.dump(out, f) + return orca.ExecutionResult.success("ungranted") + + +class CallWithoutPermission(orca.script.ScriptPluginCapabilityBase): + def get_name(self): + return "MCP tools ungranted call" + + def execute(self): + return outcome() + + +def echo(args): + return args + + +@orca.plugin +class UngrantedPackage(orca.base): + def register_capabilities(self): + orca.register_operation("echo", "Returns its arguments.", {"type": "object", "properties": {"a": {"type": "number"}}}, + echo, changes=False) + orca.register_capability(CallWithoutPermission)