diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 5df86e4f1e..b3e190f048 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -136,6 +136,23 @@ set(SLIC3R_GUI_SOURCES GUI/ActionRegistry.hpp GUI/NativeCommands.cpp GUI/NativeCommands.hpp + GUI/Mcp/JobRegistry.cpp + GUI/Mcp/JobRegistry.hpp + GUI/Mcp/McpCore.cpp + GUI/Mcp/McpCore.hpp + GUI/Mcp/McpHttpServer.cpp + GUI/Mcp/McpHttpServer.hpp + GUI/Mcp/McpJournal.cpp + GUI/Mcp/McpJournal.hpp + GUI/Mcp/McpOperations.cpp + GUI/Mcp/McpOperations.hpp + GUI/Mcp/McpProtocol.cpp + GUI/Mcp/McpProtocol.hpp + GUI/Mcp/McpScript.cpp + GUI/Mcp/McpScript.hpp + GUI/Mcp/McpTypes.hpp + GUI/Mcp/UiInvoker.cpp + GUI/Mcp/UiInvoker.hpp GUI/PluginsConfigDialog.cpp GUI/PluginsConfigDialog.hpp GUI/ProcessRunner.cpp diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp new file mode 100644 index 0000000000..e09c6c1872 --- /dev/null +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -0,0 +1,111 @@ +#include "JobRegistry.hpp" + +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +std::string JobRegistry::create(const std::string& tool, const std::string& parent) +{ + std::lock_guard lock(m_mutex); + const std::size_t running = std::count_if(m_jobs.begin(), m_jobs.end(), [](const auto& kv) { return !kv.second.finished; }); + if (running >= kMaxRunning) + throw ToolFailure("Too many running jobs; wait for some to finish (see get_state.jobs)"); + std::string id = "j" + std::to_string(m_next++); + Job job; + job.tool = tool; + job.parent = parent; + job.created = std::chrono::steady_clock::now(); + m_jobs.emplace(id, std::move(job)); + return id; +} + +void JobRegistry::finish(const std::string& id, ToolResult result) +{ + { + std::lock_guard lock(m_mutex); + auto it = m_jobs.find(id); + if (it == m_jobs.end() || it->second.finished) + return; + it->second.finished = true; + it->second.result = std::move(result); + m_finished_order.push_back(id); + while (m_finished_order.size() > kKeepFinished) { + m_jobs.erase(m_finished_order.front()); + m_finished_order.pop_front(); + } + } + m_cv.notify_all(); +} + +std::optional JobRegistry::wait(const std::string& id, std::chrono::milliseconds timeout) +{ + std::unique_lock lock(m_mutex); + if (m_jobs.find(id) == m_jobs.end()) + throw ToolFailure("Unknown job " + id + " (finished jobs are kept only for the last " + std::to_string(kKeepFinished) + ")"); + m_cv.wait_for(lock, timeout, [&] { + auto it = m_jobs.find(id); + return m_woken || it == m_jobs.end() || it->second.finished; + }); + auto it = m_jobs.find(id); + if (it == m_jobs.end() || !it->second.finished) + return std::nullopt; + return it->second.result; +} + +std::set JobRegistry::lineage(const std::string& id) const +{ + std::lock_guard lock(m_mutex); + std::set out; + std::string cur = id; + while (!cur.empty() && out.insert(cur).second) { + auto it = m_jobs.find(cur); + cur = it == m_jobs.end() ? std::string() : it->second.parent; + } + return out; +} + +bool JobRegistry::any_running_except(const std::set& excluded) const +{ + std::lock_guard lock(m_mutex); + return std::any_of(m_jobs.begin(), m_jobs.end(), + [&](const auto& kv) { return !kv.second.finished && excluded.count(kv.first) == 0; }); +} + +std::vector JobRegistry::running_of(const std::set& tools, const std::set& excluded) const +{ + std::lock_guard lock(m_mutex); + std::vector out; + for (const auto& [id, job] : m_jobs) + if (!job.finished && tools.count(job.tool) != 0 && excluded.count(id) == 0) + out.push_back(id); + return out; +} + +nlohmann::json JobRegistry::list() const +{ + std::lock_guard lock(m_mutex); + const auto now = std::chrono::steady_clock::now(); + nlohmann::json out = nlohmann::json::array(); + for (const auto& [id, job] : m_jobs) { + nlohmann::json j{{"id", id}, + {"tool", job.tool}, + {"state", job.finished ? (job.result.is_error ? "failed" : "done") : "running"}, + {"age_ms", std::chrono::duration_cast(now - job.created).count()}}; + if (!job.parent.empty()) + j["parent"] = job.parent; + out.push_back(std::move(j)); + } + return out; +} + +void JobRegistry::wake_all() +{ + { + std::lock_guard lock(m_mutex); + m_woken = true; + } + m_cv.notify_all(); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp new file mode 100644 index 0000000000..56744fc045 --- /dev/null +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -0,0 +1,69 @@ +#pragma once + +#include "McpTypes.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// Bookkeeping for mutate tool calls that run on their own threads. A call that outlives its reply +// budget stays here until it finishes, so a later `wait {for:"job"}` can return its result; the +// most recent finished jobs are kept for that purpose. Thread-safe. +class JobRegistry +{ +public: + static constexpr std::size_t kMaxRunning = 64; + static constexpr std::size_t kKeepFinished = 64; + + // Registers a running job. Throws ToolFailure when kMaxRunning jobs are already running. + std::string create(const std::string& tool, const std::string& parent); + void finish(const std::string& id, ToolResult result); + + // The job's result once it has finished; nullopt when it is still running after `timeout` or + // the registry was woken for shutdown. Throws ToolFailure for an unknown id. + std::optional wait(const std::string& id, std::chrono::milliseconds timeout); + + // `id` followed by its parent chain. + std::set lineage(const std::string& id) const; + // True when a running job exists that is not in `excluded`. + bool any_running_except(const std::set& excluded) const; + // Running jobs of the given tools that are not in `excluded`, for operation admission. + std::vector running_of(const std::set& tools, const std::set& excluded) const; + + // [{id, tool, parent, state, age_ms}] for get_state. + nlohmann::json list() const; + + // Wakes every waiter; later waits return nullopt immediately. + void wake_all(); + +private: + struct Job + { + std::string tool; + std::string parent; + bool finished = false; + ToolResult result; + std::chrono::steady_clock::time_point created; + }; + + mutable std::mutex m_mutex; + std::condition_variable m_cv; + std::map m_jobs; + std::deque m_finished_order; + uint64_t m_next = 1; + bool m_woken = false; +}; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp new file mode 100644 index 0000000000..1fd5db4b6c --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -0,0 +1,201 @@ +#include "McpCore.hpp" + +#include "McpJournal.hpp" + +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace { + +class CallContext final : public ToolContext +{ +public: + CallContext(McpCore& core, const ToolDef& def, std::string job, std::string parent, Journal* journal, uint64_t journal_seq) + : m_core(core), m_def(def), m_job(std::move(job)), m_parent(std::move(parent)), m_journal(journal), m_seq(journal_seq) + {} + + nlohmann::json run_ui(const std::function& fn) override { return m_core.ui().run(m_def.guard, m_def.name, fn); } + const std::string& job_id() const override { return m_job; } + bool cancelled() const override { return m_core.ui().is_shutdown(); } + + ToolResult call_child(const std::string& tool, const nlohmann::json& args) override + { + const ToolDef* def = m_core.registry().find(tool); + if (def == nullptr) + return ToolResult::error("Unknown tool: " + tool); + if (std::string err = validate_arguments(def->input_schema, args); !err.empty()) + return ToolResult::error("Invalid arguments: " + err); + // An inline caller has no job of its own; its children are rooted at its parent. + return m_core.call_child(*def, args, m_job.empty() ? m_parent : m_job); + } + + std::set lineage() const override + { + return m_core.jobs().lineage(m_job.empty() ? m_parent : m_job); + } + + void set_journal_args(nlohmann::json args) override + { + if (m_journal != nullptr && m_seq != 0) + m_journal->set_args(m_seq, std::move(args)); + } + +private: + McpCore& m_core; + const ToolDef& m_def; + std::string m_job; + std::string m_parent; + Journal* m_journal; + uint64_t m_seq; +}; + +ToolResult invoke(const ToolDef& def, const nlohmann::json& args, ToolContext& ctx) +{ + try { + return def.handler(args, ctx); + } catch (const ToolFailure& f) { + return ToolResult::error(f.what(), f.details); + } catch (const std::exception& e) { + return ToolResult::error(std::string("Internal error: ") + e.what()); + } catch (...) { + return ToolResult::error("Internal error"); + } +} + +} // namespace + +McpCore::McpCore(const ToolRegistry& registry, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing) + : m_registry(registry), m_ui(ui), m_jobs(jobs), m_journal(journal), m_timing(timing) +{} + +McpCore::~McpCore() { shutdown(); } + +ToolResult McpCore::call(const ToolDef& def, const nlohmann::json& args) { return run(def, args, {}); } + +ToolResult McpCore::call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job) +{ + return run(def, args, parent_job); +} + +ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const std::string& parent) +{ + if (m_ui.is_shutdown()) + return ToolResult::error("OrcaSlicer is shutting down"); + + // Only client calls are journaled; a script's own steps replay through the script. + const bool journal = m_journal != nullptr && parent.empty() && def.journal; + const uint64_t seq = journal ? m_journal->begin(def.name, args) : 0; + auto finish = [&](ToolResult r) { + if (journal) + m_journal->end(seq, r); + return r; + }; + + if (def.inline_call) { + CallContext ctx(*this, def, {}, parent, m_journal, seq); + // Any inline call can wait for the UI thread, so each holds a blocking slot. + if (!acquire_slot()) + return finish(ToolResult::ok({{"status", "pending"}, {"note", "Too many calls are waiting right now; try again shortly."}})); + ToolResult r = invoke(def, args, ctx); + release_slot(); + return finish(std::move(r)); + } + + // Operation admission: an MCP slice/export holds the project until it finishes; only recovery + // input and the tools that may run during an operation (cancel) get through. + if (def.guard == GuardClass::Mutate && !def.allowed_during_operation) + if (const auto busy = m_jobs.running_of(m_operation_tools, {}); !busy.empty()) + return finish(ToolResult::error("Busy: job " + busy.front() + + " (a slice or export) is running; wait for it or cancel it before changing the project", + {{"job", busy.front()}})); + + std::string job; + try { + job = m_jobs.create(def.name, parent); + } catch (const ToolFailure& f) { + return finish(ToolResult::error(f.what())); + } + + { + std::lock_guard lock(m_threads_mutex); + if (m_stopping) + return finish(ToolResult::error("OrcaSlicer is shutting down")); + ++m_threads; + } + // The job thread owns copies of what it needs; the core itself outlives it (shutdown() waits). + std::thread([this, def, args, job, parent, seq]() { + CallContext ctx(*this, def, job, parent, m_journal, seq); + ToolResult result = invoke(def, args, ctx); + m_jobs.finish(job, std::move(result)); + { + std::lock_guard lock(m_threads_mutex); + --m_threads; + } + m_threads_cv.notify_all(); + }).detach(); + + auto envelope = [&](const char* status, nlohmann::json extra) { + nlohmann::json out{{"status", status}, {"job", job}, {"tool", def.name}}; + out.update(extra); + return ToolResult::ok(std::move(out)); + }; + const std::string running_note = "The call is still running and will finish on its own; do not retry it. " + "Use wait {for:\"job\", job:\"" + job + "\"} for its result."; + if (!acquire_slot()) + return finish(envelope("running", {{"note", running_note}})); + struct SlotGuard { McpCore* core; ~SlotGuard() { core->release_slot(); } } slot_guard{this}; + + const auto start = std::chrono::steady_clock::now(); + const auto deadline = start + std::chrono::milliseconds(def.budget_ms); + auto next_probe = start + m_timing.soft_budget; + for (;;) { + const auto now = std::chrono::steady_clock::now(); + const auto stop = std::min(deadline, next_probe); + if (auto r = m_jobs.wait(job, std::chrono::duration_cast(stop > now ? stop - now : std::chrono::milliseconds(0)))) + return finish(std::move(*r)); + if (m_ui.is_shutdown()) + return finish(ToolResult::error("OrcaSlicer is shutting down")); + if (std::chrono::steady_clock::now() >= deadline) + break; + // Past the soft budget: if a modal dialog is open, the job is almost certainly waiting on it. + if (auto p = m_ui.probe(m_timing.probe_timeout); p && p->guards.modal) { + // A dialog can close between the probe and here; a finished job wins. + if (auto r = m_jobs.wait(job, std::chrono::milliseconds(0))) + return finish(std::move(*r)); + return finish(envelope("blocked_by_dialog", + {{"dialogs", p->guards.dialogs}, + {"note", "The call is waiting on a dialog and continues after it closes; do not retry it. " + "Answer the dialog (ui_snapshot, dialog_respond), then wait {for:\"job\", job:\"" + job + "\"}."}})); + } + next_probe = std::chrono::steady_clock::now() + m_timing.soft_budget; + } + return finish(envelope("running", {{"note", running_note}})); +} + +bool McpCore::acquire_slot() +{ + std::lock_guard lock(m_slots_mutex); + if (m_slots_used >= m_timing.blocking_slots) + return false; + ++m_slots_used; + return true; +} + +void McpCore::release_slot() +{ + std::lock_guard lock(m_slots_mutex); + --m_slots_used; +} + +void McpCore::shutdown() +{ + std::unique_lock lock(m_threads_mutex); + m_stopping = true; + m_threads_cv.wait_for(lock, m_timing.join_timeout, [this] { return m_threads == 0; }); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpCore.hpp b/src/slic3r/GUI/Mcp/McpCore.hpp new file mode 100644 index 0000000000..0503fc6303 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpCore.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include "JobRegistry.hpp" +#include "McpTypes.hpp" +#include "UiInvoker.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +class Journal; + +struct CoreTiming +{ + std::chrono::milliseconds soft_budget{1500}; // before probing for a blocking dialog + std::chrono::milliseconds probe_timeout{1000}; + std::chrono::milliseconds join_timeout{5000}; // for job threads at shutdown + int blocking_slots = 32; +}; + +// Executes tool calls for the protocol layer and for scripts: observation tools inline on the +// calling thread, everything else as a job on a thread of its own, with the reply budget, the +// blocked-by-dialog probe, blocking slots, operation admission and the session journal. Independent +// of wx so the threading contract is unit-testable with a hand-driven UiDispatcher. +class McpCore : public ToolCaller +{ +public: + McpCore(const ToolRegistry& registry, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing = {}); + ~McpCore() override; + + // A call from a client. Mutate tools become top-level jobs. + ToolResult call(const ToolDef& def, const nlohmann::json& args) override; + // A call made by a running job (a script step); the new job's parent is `parent_job`, which + // exempts it from operation admission against its own ancestors. + ToolResult call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job); + + // Tools whose jobs hold the operation lock (slice, export): while one runs, other mutate calls + // outside its job tree are refused. + void set_operation_tools(std::set tools) { m_operation_tools = std::move(tools); } + + // Wakes all waiters (UiInvoker and JobRegistry must be woken by the owner first or after) and + // waits, bounded, for job threads to return. + void shutdown(); + + const ToolRegistry& registry() const { return m_registry; } + UiInvoker& ui() { return m_ui; } + JobRegistry& jobs() { return m_jobs; } + +private: + ToolResult run(const ToolDef& def, const nlohmann::json& args, const std::string& parent); + + const ToolRegistry& m_registry; + UiInvoker& m_ui; + JobRegistry& m_jobs; + Journal* m_journal; + CoreTiming m_timing; + std::set m_operation_tools; + + // Requests that may block (a job within its reply budget, or wait) hold a slot, so the number of + // blocked request threads stays below the connection limit and recovery calls always get through. + bool acquire_slot(); + void release_slot(); + std::mutex m_slots_mutex; + int m_slots_used = 0; + + std::mutex m_threads_mutex; + std::condition_variable m_threads_cv; + int m_threads = 0; + bool m_stopping = false; +}; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpHttpServer.cpp b/src/slic3r/GUI/Mcp/McpHttpServer.cpp new file mode 100644 index 0000000000..c58a2f3762 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpHttpServer.cpp @@ -0,0 +1,377 @@ +#include "McpHttpServer.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +namespace net = boost::asio; +namespace beast = boost::beast; +namespace http = boost::beast::http; +using tcp = net::ip::tcp; + +namespace { + +std::string lower(std::string s) +{ + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return s; +} + +std::string trim(const std::string& s) +{ + const auto b = s.find_first_not_of(" \t"); + if (b == std::string::npos) + return {}; + return s.substr(b, s.find_last_not_of(" \t") - b + 1); +} + +// "http://localhost:3000" or "https://127.0.0.1" — any port, loopback host names only. +bool is_loopback_origin(const std::string& origin) +{ + const std::string o = lower(origin); + for (const char* scheme : {"http://", "https://"}) { + const std::string s(scheme); + if (o.compare(0, s.size(), s) != 0) + continue; + std::string rest = o.substr(s.size()); + const auto colon = rest.find(':'); + const std::string host = rest.substr(0, colon); + if (host != "localhost" && host != "127.0.0.1") + return false; + if (colon == std::string::npos) + return true; + const std::string port = rest.substr(colon + 1); + return !port.empty() && port.size() <= 5 && std::all_of(port.begin(), port.end(), [](char c) { return c >= '0' && c <= '9'; }); + } + return false; +} + +bool constant_time_equal(const std::string& a, const std::string& b) +{ + unsigned char diff = a.size() == b.size() ? 0 : 1; + const std::size_t n = std::max(a.size(), b.size()); + for (std::size_t i = 0; i < n; ++i) + diff |= (unsigned char) ((i < a.size() ? a[i] : 0) ^ (i < b.size() ? b[i] : 0)); + return diff == 0; +} + +std::string error_json(const std::string& message) +{ + return nlohmann::json{{"jsonrpc", "2.0"}, {"error", {{"code", -32600}, {"message", message}}}}.dump(); +} + +} // namespace + +HttpCheck validate_request(const HttpRequestView& r, uint16_t port, const std::string& token, std::size_t max_body) +{ + const std::string path = r.target.substr(0, r.target.find('?')); + if (path != "/mcp") + return {404, "Not found"}; + if (r.method != "POST") + return {405, "Only POST is supported on this endpoint"}; + + const std::string host = lower(trim(r.host)); + const std::string p = std::to_string(port); + if (host != "127.0.0.1:" + p && host != "localhost:" + p) + return {403, "Host header must name this loopback endpoint"}; + if (!r.origin.empty() && !is_loopback_origin(trim(r.origin))) + return {403, "Origin not allowed"}; + + const std::string auth = trim(r.authorization); + if (auth.size() < 7 || lower(auth.substr(0, 7)) != "bearer " || !constant_time_equal(trim(auth.substr(7)), token)) + return {401, "Missing or invalid bearer token"}; + + const std::string type = lower(trim(r.content_type.substr(0, r.content_type.find(';')))); + if (type != "application/json") + return {415, "Content-Type must be application/json"}; + if (r.body_size > max_body) + return {413, "Request body too large"}; + return {}; +} + +// ---- implementation --------------------------------------------------------------------------- + +struct McpHttpServer::Impl : std::enable_shared_from_this +{ + struct Session; + + std::string token; + Handler handler; + HttpLimits limits; + + net::io_context ioc{1}; + tcp::acceptor acceptor{ioc}; + std::thread io_thread; + uint16_t bound_port = 0; + std::atomic running{false}; + + // Live sessions, touched only on the I/O thread. + std::set> sessions; + + // Handler threads, one per in-flight request. + std::mutex requests_mutex; + std::condition_variable requests_cv; + int active_requests = 0; + bool accepting_requests = true; + + Impl(std::string t, Handler h, HttpLimits l) : token(std::move(t)), handler(std::move(h)), limits(l) {} + + // Runs `job` on a new detached thread that keeps this object alive until it returns. + void run_request(std::function job) + { + { + std::lock_guard lock(requests_mutex); + if (!accepting_requests) + return; + ++active_requests; + } + std::thread([self = shared_from_this(), job = std::move(job)] { + job(); + { + std::lock_guard lock(self->requests_mutex); + --self->active_requests; + } + self->requests_cv.notify_all(); + }).detach(); + } + + void do_accept(); +}; + +struct McpHttpServer::Impl::Session : std::enable_shared_from_this +{ + Impl* server; // outlives every session (see stop()) + beast::tcp_stream stream; + beast::flat_buffer buffer; + std::unique_ptr> parser; + http::response response; + bool first = true; + bool in_flight = false; // a request is being handled or answered + std::chrono::steady_clock::time_point idle_since = std::chrono::steady_clock::now(); + + Session(Impl* s, tcp::socket&& socket) : server(s), stream(std::move(socket)) {} + + void start() { do_read(); } + + void do_read() + { + in_flight = false; + idle_since = std::chrono::steady_clock::now(); + parser = std::make_unique>(); + parser->body_limit(server->limits.max_body); + parser->header_limit(64 * 1024); + stream.expires_after(first ? server->limits.read_timeout : server->limits.idle_timeout); + first = false; + http::async_read(stream, buffer, *parser, + [self = shared_from_this()](beast::error_code ec, std::size_t) { self->on_read(ec); }); + } + + void on_read(beast::error_code ec) + { + in_flight = true; + if (ec == http::error::body_limit) { + reply(413, error_json("Request body too large"), false); + return; + } + if (ec) { + close(); + return; + } + const auto& req = parser->get(); + HttpRequestView view; + view.method = std::string(req.method_string()); + view.target = std::string(req.target()); + view.host = std::string(req[http::field::host]); + view.origin = std::string(req[http::field::origin]); + view.content_type = std::string(req[http::field::content_type]); + view.authorization = std::string(req[http::field::authorization]); + view.body_size = req.body().size(); + + const HttpCheck check = validate_request(view, server->bound_port, server->token, server->limits.max_body); + if (check.status != 0) { + reply(check.status, error_json(check.message), req.keep_alive()); + return; + } + + PostRequest post; + post.body = req.body(); + post.protocol_version = std::string(req["MCP-Protocol-Version"]); + post.method_header = std::string(req["Mcp-Method"]); + post.name_header = std::string(req["Mcp-Name"]); + const bool keep_alive = req.keep_alive(); + + // A handler can block for a tool's whole reply budget; nothing may time the socket out + // meanwhile. + stream.expires_never(); + server->run_request([self = shared_from_this(), post = std::move(post), keep_alive]() { + PostReply out; + try { + out = self->server->handler(post); + } catch (const std::exception& e) { + out = {500, error_json(e.what())}; + } + net::post(self->stream.get_executor(), [self, out = std::move(out), keep_alive]() mutable { + self->reply(out.status, std::move(out.body), keep_alive); + }); + }); + } + + void reply(int status, std::string body, bool keep_alive) + { + response = {}; + response.version(11); + response.result(http::status(status)); + response.set(http::field::server, "OrcaSlicer-MCP"); + response.set(http::field::cache_control, "no-store"); + if (status == 405) + response.set(http::field::allow, "POST"); + if (status == 401) + response.set(http::field::www_authenticate, "Bearer"); + if (!body.empty()) + response.set(http::field::content_type, "application/json"); + response.body() = std::move(body); + response.keep_alive(keep_alive && status < 500 && status != 413); + response.prepare_payload(); + stream.expires_after(server->limits.write_timeout); + http::async_write(stream, response, [self = shared_from_this()](beast::error_code ec, std::size_t) { + if (ec || !self->response.keep_alive()) { + self->close(); + return; + } + self->do_read(); + }); + } + + void close() + { + beast::error_code ignored; + stream.socket().shutdown(tcp::socket::shutdown_both, ignored); + stream.close(); + server->sessions.erase(shared_from_this()); + } +}; + +void McpHttpServer::Impl::do_accept() +{ + acceptor.async_accept(net::make_strand(ioc), [self = this](beast::error_code ec, tcp::socket socket) { + if (!self->acceptor.is_open()) + return; + if (!ec) { + // At the cap, make room by closing the connection that has waited longest on its client + // (idle between requests, or still sending one); a dispatched request is never cut off. + if (int(self->sessions.size()) >= self->limits.max_connections) { + std::shared_ptr oldest; + for (const auto& s : self->sessions) + if (!s->in_flight && (!oldest || s->idle_since < oldest->idle_since)) + oldest = s; + if (oldest) + oldest->close(); + } + // With nothing evictable (every connection has a dispatched, authenticated request) the + // overflow reserve absorbs the short moments until one of them returns. + if (int(self->sessions.size()) >= self->limits.max_connections + self->limits.overflow_reserve) { + beast::error_code ignored; + socket.shutdown(tcp::socket::shutdown_both, ignored); + socket.close(ignored); + } else { + // Only the I/O thread runs this io_context, so the session set needs no lock. + auto session = std::make_shared(self, std::move(socket)); + self->sessions.insert(session); + session->start(); + } + } + self->do_accept(); + }); +} + +McpHttpServer::McpHttpServer(std::string token, Handler handler, HttpLimits limits) + : m_impl(std::make_shared(std::move(token), std::move(handler), limits)) +{} + +McpHttpServer::~McpHttpServer() { stop(); } + +bool McpHttpServer::start(uint16_t port, std::string& error) +{ + if (m_impl->running) + return true; + try { + const tcp::endpoint endpoint(net::ip::address_v4::loopback(), port); + m_impl->acceptor.open(endpoint.protocol()); + // Not reuse_address: a second instance on the same port must fail instead of sharing it. + m_impl->acceptor.bind(endpoint); + m_impl->acceptor.listen(net::socket_base::max_listen_connections); + m_impl->bound_port = m_impl->acceptor.local_endpoint().port(); + } catch (const std::exception& e) { + error = e.what(); + beast::error_code ignored; + m_impl->acceptor.close(ignored); + return false; + } + m_impl->running = true; + m_impl->do_accept(); + m_impl->io_thread = std::thread([impl = m_impl.get()] { impl->ioc.run(); }); + return true; +} + +void McpHttpServer::stop() +{ + if (!m_impl || !m_impl->running.exchange(false)) + return; + // Handlers return once the owner has woken them; give them a bounded time to do so. A handler + // that has not returned holds a reference to the internals, so nothing it touches is freed. + { + std::unique_lock lock(m_impl->requests_mutex); + m_impl->accepting_requests = false; + m_impl->requests_cv.wait_for(lock, m_impl->limits.stop_timeout, [this] { return m_impl->active_requests == 0; }); + } + + m_impl->ioc.stop(); + if (m_impl->io_thread.joinable()) + m_impl->io_thread.join(); + // No thread runs the context any more, so the sockets can be closed from here. Pending + // handlers that still hold sessions are destroyed with the io_context. + beast::error_code ignored; + m_impl->acceptor.close(ignored); + for (const auto& s : m_impl->sessions) { + s->stream.socket().shutdown(tcp::socket::shutdown_both, ignored); + s->stream.socket().close(ignored); + } + m_impl->sessions.clear(); +} + +bool McpHttpServer::running() const { return m_impl && m_impl->running; } + +uint16_t McpHttpServer::port() const { return m_impl ? m_impl->bound_port : 0; } + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpHttpServer.hpp b/src/slic3r/GUI/Mcp/McpHttpServer.hpp new file mode 100644 index 0000000000..27b8b94a2c --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpHttpServer.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include "McpProtocol.hpp" + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// The parts of an HTTP request the endpoint rules look at. Header values are empty when absent. +struct HttpRequestView +{ + std::string method; + std::string target; + std::string host; + std::string origin; + std::string content_type; + std::string authorization; + std::size_t body_size = 0; +}; + +// Status 0 accepts the request; anything else is the HTTP status to reply with. +struct HttpCheck +{ + int status = 0; + std::string message; +}; + +// Endpoint rules applied before any JSON is parsed: only POST /mcp, Host must name this loopback +// port (DNS rebinding), a browser Origin must be loopback, the body must be JSON, and the bearer +// token must match. +HttpCheck validate_request(const HttpRequestView& request, uint16_t port, const std::string& token, std::size_t max_body); + +struct HttpLimits +{ + std::chrono::milliseconds read_timeout{30000}; // to receive a complete request + std::chrono::milliseconds idle_timeout{120000}; // between keep-alive requests + std::chrono::milliseconds write_timeout{30000}; + std::chrono::milliseconds stop_timeout{5000}; // for request threads to return + std::size_t max_body = 8u << 20; + int max_connections = 64; + int overflow_reserve = 8; // used only when no connection can be evicted +}; + +// Loopback HTTP/1.1 server for the MCP endpoint. One I/O thread runs every socket asynchronously +// with deadlines. Each complete request is handled on a thread of its own, because a handler may +// block for a tool's whole reply budget; a connection carries one request at a time, so handler +// threads never outnumber connections and a blocked handler cannot delay another connection. +class McpHttpServer +{ +public: + using Handler = std::function; + + McpHttpServer(std::string token, Handler handler, HttpLimits limits = {}); + ~McpHttpServer(); + McpHttpServer(const McpHttpServer&) = delete; + McpHttpServer& operator=(const McpHttpServer&) = delete; + + // Binds 127.0.0.1:port (0 picks a free port) and starts serving. + bool start(uint16_t port, std::string& error); + // Stops accepting, waits (up to stop_timeout) for running handlers, then closes every connection. + // The owner makes handlers return first (see UiInvoker::shutdown); a handler that still has not + // returned keeps the server's internals alive until it does. + void stop(); + bool running() const; + uint16_t port() const; + +private: + struct Impl; + std::shared_ptr m_impl; +}; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpJournal.cpp b/src/slic3r/GUI/Mcp/McpJournal.cpp new file mode 100644 index 0000000000..34d26f8f83 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpJournal.cpp @@ -0,0 +1,78 @@ +#include "McpJournal.hpp" + +#include + +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +uint64_t Journal::begin(const std::string& tool, const nlohmann::json& args) +{ + std::lock_guard lock(m_mutex); + Entry e; + e.seq = m_next++; + e.tool = tool; + e.args = args; + m_entries.push_back(std::move(e)); + return m_entries.back().seq; +} + +void Journal::set_args(uint64_t seq, nlohmann::json args) +{ + std::lock_guard lock(m_mutex); + for (Entry& e : m_entries) + if (e.seq == seq) + e.args = std::move(args); +} + +void Journal::end(uint64_t seq, const ToolResult& result) +{ + std::lock_guard lock(m_mutex); + for (Entry& e : m_entries) + if (e.seq == seq) { + e.finished = true; + e.failed = result.is_error; + if (!result.is_error && result.data.is_object() && result.data.contains("job") && result.data.contains("status")) + e.job = result.data["job"].get(); + } +} + +void Journal::clear() +{ + std::lock_guard lock(m_mutex); + m_entries.clear(); +} + +nlohmann::json Journal::to_script(const std::string& name) const +{ + std::lock_guard lock(m_mutex); + nlohmann::json steps = nlohmann::json::array(); + std::map job_names; // live job id -> script name + for (const Entry& e : m_entries) { + if (e.failed) + continue; + nlohmann::json step{{"tool", e.tool}, {"args", e.args}}; + if (e.tool == "wait" && e.args.value("for", "") == "job") { + auto it = job_names.find(e.args.value("job", "")); + if (it == job_names.end()) + continue; // waits on a job the journal did not see start + step["args"]["job"] = "${jobs." + it->second + "}"; + } + if (e.tool == "screenshot" && e.args.contains("save_path") && e.args["save_path"].is_string()) { + const std::string file = boost::filesystem::path(e.args["save_path"].get()).filename().string(); + step["args"]["save_path"] = "${out_dir}/" + file; + } + if (!e.job.empty()) { + const std::string job_name = "job" + std::to_string(job_names.size() + 1); + job_names[e.job] = job_name; + step["await"] = false; + step["save_as"] = job_name; + } + steps.push_back(std::move(step)); + } + return {{"orca_script", 1}, {"name", name}, {"steps", std::move(steps)}}; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpJournal.hpp b/src/slic3r/GUI/Mcp/McpJournal.hpp new file mode 100644 index 0000000000..d47ac68094 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpJournal.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include "McpTypes.hpp" + +#include + +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// The session's client calls, in the order they were made, for export_script. A call that returned +// a job envelope is replayed with `await:false` and a name its later `wait` refers to, so a step +// that opened a dialog can be followed by the steps that answered it. Thread-safe. +class Journal +{ +public: + // Starts an entry; returns its sequence number. Calls made by scripts are not recorded. + uint64_t begin(const std::string& tool, const nlohmann::json& args); + void set_args(uint64_t seq, nlohmann::json args); + void end(uint64_t seq, const ToolResult& result); + void clear(); + + // {"orca_script":1, "name":..., "steps":[...]} with job names substituted and screenshot paths + // rewritten to ${out_dir}/. + nlohmann::json to_script(const std::string& name) const; + +private: + struct Entry + { + uint64_t seq = 0; + std::string tool; + nlohmann::json args; + bool finished = false; + bool failed = false; + std::string job; // set when the reply was a job envelope + }; + + mutable std::mutex m_mutex; + std::vector m_entries; + uint64_t m_next = 1; +}; + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpOperations.cpp b/src/slic3r/GUI/Mcp/McpOperations.cpp new file mode 100644 index 0000000000..ec9c199076 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpOperations.cpp @@ -0,0 +1,96 @@ +#include "McpOperations.hpp" + +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +const char* to_string(PlateOutcome outcome) +{ + switch (outcome) { + case PlateOutcome::Ok: return "ok"; + case PlateOutcome::Error: return "error"; + case PlateOutcome::Cancelled: return "cancelled"; + case PlateOutcome::Empty: return "empty"; + case PlateOutcome::Skipped: return "skipped"; + } + return "skipped"; +} + +const char* to_string(ExportStatus status) +{ + switch (status) { + case ExportStatus::Rejected: return "rejected"; + case ExportStatus::Pending: return "pending"; + case ExportStatus::Ok: return "ok"; + case ExportStatus::Failed: return "failed"; + case ExportStatus::Cancelled: return "cancelled"; + case ExportStatus::Superseded: return "superseded"; + } + return "failed"; +} + +std::vector classify_plates(const std::vector& requested, const std::vector& plates, bool cancelled) +{ + std::vector out; + out.reserve(requested.size()); + for (int index : requested) { + auto it = std::find_if(plates.begin(), plates.end(), [index](const PlateObservation& p) { return p.index == index; }); + if (it == plates.end()) + out.push_back(PlateOutcome::Skipped); // the plate no longer exists + else if (it->empty) + out.push_back(PlateOutcome::Empty); + else if (it->valid) + out.push_back(PlateOutcome::Ok); + else if (it->error) + out.push_back(PlateOutcome::Error); + else + out.push_back(cancelled ? PlateOutcome::Cancelled : PlateOutcome::Skipped); + } + return out; +} + +TicketStatus slice_status(const SliceTicketState& ticket, const SliceObservation& obs, std::chrono::steady_clock::time_point now) +{ + if (obs.slicing_any) + return TicketStatus::Pending; + if (!ticket.seen_running && obs.runs_since_start.empty() && now - ticket.started < kSliceStartGrace) + return TicketStatus::Pending; + bool any_run = false; + for (const SliceRunRecord& run : obs.runs_since_start) { + if (run.seq <= ticket.run_seq_before) + continue; + if (!run.finished) + return TicketStatus::Pending; + any_run = true; + if (run.request_seq_at_finish != ticket.request_seq_mine || run.revision_at_finish != ticket.revision_at_start) + return TicketStatus::Superseded; + } + if (!any_run && (obs.request_seq != ticket.request_seq_mine || obs.current_revision != ticket.revision_at_start)) + return TicketStatus::Superseded; + return TicketStatus::Done; +} + +bool slice_cancelled(const SliceTicketState& ticket, const SliceObservation& obs) +{ + for (const SliceRunRecord& run : obs.runs_since_start) + if (run.seq > ticket.run_seq_before && run.cancelled) + return true; + return false; +} + +ExportStatus export_status(uint64_t seq_before, uint64_t seq_after, const std::optional& record, uint64_t revision_at_start) +{ + if (seq_after == seq_before) + return ExportStatus::Rejected; + if (!record || !record->finished) + return ExportStatus::Pending; + if (record->cancelled) + return ExportStatus::Cancelled; + if (!record->ok) + return ExportStatus::Failed; + if (record->revision_at_finish != revision_at_start) + return ExportStatus::Superseded; + return ExportStatus::Ok; +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpOperations.hpp b/src/slic3r/GUI/Mcp/McpOperations.hpp new file mode 100644 index 0000000000..e6439fb40f --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpOperations.hpp @@ -0,0 +1,96 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// The decision logic of the slice and export operations, kept free of wx and Plater so it can be +// unit-tested: the tools observe Plater on the UI thread and feed the observations in here. + +enum class PlateOutcome { Ok, Error, Cancelled, Empty, Skipped }; + +struct PlateObservation +{ + int index = 0; + bool valid = false; // a current slice result exists + bool error = false; // the last process run on this plate failed + bool empty = false; // no printable object on the plate +}; + +const char* to_string(PlateOutcome outcome); + +// Per-plate outcome once the operation is terminal. `cancelled` is true when the process reported a +// cancellation during the operation: plates that are neither valid nor failed are then Cancelled +// instead of Skipped. +std::vector classify_plates(const std::vector& requested, const std::vector& plates, + bool cancelled); + +struct SliceRunRecord +{ + uint64_t seq = 0; + bool finished = false; + bool cancelled = false; + std::string error; + uint64_t revision_at_finish = 0; + uint64_t request_seq_at_finish = 0; +}; + +struct SliceTicketState +{ + uint64_t request_seq_mine = 0; // Plater's request sequence right after our request + uint64_t run_seq_before = 0; // Plater's run sequence before our request + uint64_t revision_at_start = 0; + bool seen_running = false; + std::chrono::steady_clock::time_point started; +}; + +// What the tool observed on the UI thread at one poll. +struct SliceObservation +{ + bool slicing_any = false; + uint64_t request_seq = 0; + uint64_t current_revision = 0; + std::vector runs_since_start; // runs numbered after run_seq_before +}; + +enum class TicketStatus { Pending, Done, Superseded }; + +// How long a slice that never visibly started may stay pending before it counts as finished (all +// requested plates were already valid or empty, so no run was needed). +inline constexpr std::chrono::milliseconds kSliceStartGrace{1500}; + +// Terminal once slicing was seen running (or the grace period passed with nothing running) and +// nothing is slicing any more. Superseded when another slice was requested, or the project changed, +// while the operation ran - judged from snapshots only: the request sequence and revision each of +// its own runs recorded at its finish, or, with no run, the observation at the terminal poll itself. +// Only the operation's own runs are consulted, never an earlier completion. The caller freezes the +// first terminal status it gets. +TicketStatus slice_status(const SliceTicketState& ticket, const SliceObservation& obs, std::chrono::steady_clock::time_point now); + +// True when one of the operation's own runs reported cancellation. +bool slice_cancelled(const SliceTicketState& ticket, const SliceObservation& obs); + +struct ExportRecord +{ + uint64_t seq = 0; + std::string path; + bool finished = false; + bool ok = false; + bool cancelled = false; + std::string error; + uint64_t revision_at_finish = 0; +}; + +enum class ExportStatus { Rejected, Pending, Ok, Failed, Cancelled, Superseded }; + +const char* to_string(ExportStatus status); + +// `seq_before`/`seq_after` are Plater's export sequence around the call that should have started the +// export; an unchanged sequence means it never started. `record` is the record of `seq_after`. +ExportStatus export_status(uint64_t seq_before, uint64_t seq_after, const std::optional& record, uint64_t revision_at_start); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpProtocol.cpp b/src/slic3r/GUI/Mcp/McpProtocol.cpp new file mode 100644 index 0000000000..fa84b7559c --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpProtocol.cpp @@ -0,0 +1,411 @@ +#include "McpProtocol.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +constexpr int kParseError = -32700; +constexpr int kInvalidRequest = -32600; +constexpr int kMethodNotFound = -32601; +constexpr int kInvalidParams = -32602; +constexpr int kInternalError = -32603; +constexpr int kHeaderMismatch = -32020; +constexpr int kUnsupportedProto = -32022; + +constexpr const char* kMetaVersion = "io.modelcontextprotocol/protocolVersion"; +constexpr const char* kMetaServer = "io.modelcontextprotocol/serverInfo"; +// How long a modern client may cache the tool list and discovery result. The catalog is fixed for +// the life of the process, so the value only bounds how long a stale client survives a restart into +// a different build. +constexpr int kListTtlMs = 300000; + +json error_body(const json& id, int code, const std::string& message, json data = json()) +{ + json err{{"code", code}, {"message", message}}; + if (!data.is_null()) + err["data"] = std::move(data); + return {{"jsonrpc", "2.0"}, {"id", id}, {"error", std::move(err)}}; +} + +PostReply reply(int status, const json& body) { return {status, body.dump()}; } + +PostReply result_reply(const json& id, json result) { return reply(200, {{"jsonrpc", "2.0"}, {"id", id}, {"result", std::move(result)}}); } + +json supported_versions() +{ + json v = json::array({kModernVersion}); + for (const std::string& legacy : legacy_versions()) + v.push_back(legacy); + return v; +} + +int base64_value(char c) +{ + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return -1; +} + +// Levenshtein distance, for "did you mean" suggestions on short identifiers. +std::size_t edit_distance(const std::string& a, const std::string& b) +{ + std::vector row(b.size() + 1); + for (std::size_t j = 0; j <= b.size(); ++j) + row[j] = j; + for (std::size_t i = 1; i <= a.size(); ++i) { + std::size_t diag = row[0]; + row[0] = i; + for (std::size_t j = 1; j <= b.size(); ++j) { + const std::size_t up = row[j]; + row[j] = std::min({row[j] + 1, row[j - 1] + 1, diag + (a[i - 1] == b[j - 1] ? 0 : 1)}); + diag = up; + } + } + return row[b.size()]; +} + +std::string json_type_name(const json& v) +{ + if (v.is_boolean()) return "boolean"; + if (v.is_number_integer() || v.is_number_unsigned()) return "integer"; + if (v.is_number()) return "number"; + if (v.is_string()) return "string"; + if (v.is_array()) return "array"; + if (v.is_object()) return "object"; + return "null"; +} + +bool type_matches(const json& value, const json& type) +{ + if (type.is_array()) + return std::any_of(type.begin(), type.end(), [&](const json& t) { return type_matches(value, t); }); + if (!type.is_string()) + return true; + const std::string t = type.get(); + if (t == "number") + return value.is_number(); + if (t == "integer") + return value.is_number_integer() || value.is_number_unsigned() || + (value.is_number_float() && value.get() == double(int64_t(value.get()))); + return json_type_name(value) == t; +} + +std::string validate_value(const json& schema, const json& value, const std::string& path) +{ + if (!schema.is_object()) + return {}; + if (auto it = schema.find("type"); it != schema.end() && !type_matches(value, *it)) + return path + " must be of type " + (it->is_string() ? it->get() : it->dump()) + ", got " + json_type_name(value); + if (auto it = schema.find("enum"); it != schema.end() && it->is_array() && + std::find(it->begin(), it->end(), value) == it->end()) + return path + " must be one of " + it->dump(); + if (value.is_number()) { + if (auto it = schema.find("minimum"); it != schema.end() && value.get() < it->get()) + return path + " must be >= " + it->dump(); + if (auto it = schema.find("maximum"); it != schema.end() && value.get() > it->get()) + return path + " must be <= " + it->dump(); + } + if (value.is_array()) { + if (auto it = schema.find("items"); it != schema.end()) + for (std::size_t i = 0; i < value.size(); ++i) + if (std::string err = validate_value(*it, value[i], path + "[" + std::to_string(i) + "]"); !err.empty()) + return err; + } + if (value.is_object() && schema.contains("properties")) { + const json& props = schema["properties"]; + if (auto it = schema.find("required"); it != schema.end() && it->is_array()) + for (const json& key : *it) + if (key.is_string() && !value.contains(key.get())) + return (path.empty() ? std::string() : path + ".") + key.get() + " is required"; + const bool closed = schema.value("additionalProperties", true) == false; + for (auto it = value.begin(); it != value.end(); ++it) { + const std::string child = path.empty() ? it.key() : path + "." + it.key(); + if (auto p = props.find(it.key()); p != props.end()) { + if (std::string err = validate_value(*p, it.value(), child); !err.empty()) + return err; + } else if (closed) { + std::vector names; + for (auto k = props.begin(); k != props.end(); ++k) + names.push_back(k.key()); + return "unknown argument " + child + " (accepted: " + json(names).dump() + ")"; + } + } + } + return {}; +} + +} // namespace + +// ---- ToolRegistry ------------------------------------------------------------ + +void ToolRegistry::add(ToolDef def) +{ + auto it = std::find_if(m_tools.begin(), m_tools.end(), [&](const ToolDef& t) { return t.name == def.name; }); + if (it != m_tools.end()) + *it = std::move(def); + else + m_tools.push_back(std::move(def)); +} + +const ToolDef* ToolRegistry::find(const std::string& name) const +{ + auto it = std::find_if(m_tools.begin(), m_tools.end(), [&](const ToolDef& t) { return t.name == name; }); + return it == m_tools.end() ? nullptr : &*it; +} + +std::vector ToolRegistry::similar(const std::string& name, std::size_t limit) const +{ + std::vector> scored; + for (const ToolDef& t : m_tools) + scored.emplace_back(t.name.find(name) != std::string::npos ? 0 : edit_distance(name, t.name), t.name); + std::sort(scored.begin(), scored.end()); + std::vector out; + for (const auto& [score, n] : scored) + if (out.size() < limit && score <= std::max(3, name.size() / 2)) + out.push_back(n); + return out; +} + +std::string validate_arguments(const json& schema, const json& args) { return validate_value(schema, args, ""); } + +std::string decode_header_value(const std::string& value) +{ + static const std::string prefix = "=?base64?", suffix = "?="; + if (value.size() < prefix.size() + suffix.size() || value.compare(0, prefix.size(), prefix) != 0 || + value.compare(value.size() - suffix.size(), suffix.size(), suffix) != 0) + return value; + std::string out; + uint32_t acc = 0; + int bits = 0; + for (std::size_t i = prefix.size(); i < value.size() - suffix.size(); ++i) { + const int v = base64_value(value[i]); + if (v < 0) + continue; // padding + acc = (acc << 6) | uint32_t(v); + bits += 6; + if (bits >= 8) { + bits -= 8; + out.push_back(char((acc >> bits) & 0xFF)); + } + } + return out; +} + +// ---- McpProtocol -------------------------------------------------------------- + +McpProtocol::McpProtocol(const ToolRegistry& registry, ToolCaller& caller, ServerInfo info) + : m_registry(registry), m_caller(caller), m_info(std::move(info)) +{} + +json McpProtocol::tool_to_json(const ToolDef& def) +{ + json t{{"name", def.name}, {"description", def.description}, {"inputSchema", def.input_schema}}; + if (!def.title.empty()) + t["title"] = def.title; + t["annotations"] = {{"readOnlyHint", def.read_only}, + {"destructiveHint", def.destructive}, + {"idempotentHint", def.idempotent}, + {"openWorldHint", false}}; + if (!def.title.empty()) + t["annotations"]["title"] = def.title; + return t; +} + +json McpProtocol::result_to_json(const ToolResult& result) +{ + json content = json::array(); + if (result.is_error) { + std::string text = result.message; + if (!result.data.is_null() && !(result.data.is_object() && result.data.empty())) + text += "\n" + result.data.dump(); + content.push_back({{"type", "text"}, {"text", text}}); + } else { + content.push_back({{"type", "text"}, {"text", result.data.dump()}}); + } + for (const json& block : result.content) + content.push_back(block); + json out{{"content", std::move(content)}}; + if (result.is_error) + out["isError"] = true; + return out; +} + +json McpProtocol::tools_list() const +{ + json tools = json::array(); + for (const ToolDef& def : m_registry.tools()) + tools.push_back(tool_to_json(def)); + return tools; +} + +json McpProtocol::call_tool(const json& params, bool& unknown_tool, std::string& unknown_name) +{ + unknown_tool = false; + const std::string name = params.value("name", ""); + const ToolDef* def = m_registry.find(name); + if (def == nullptr) { + unknown_tool = true; + unknown_name = name; + return json(); + } + json args = params.contains("arguments") && !params["arguments"].is_null() ? params["arguments"] : json::object(); + if (!args.is_object()) + return result_to_json(ToolResult::error("arguments must be an object")); + if (std::string err = validate_arguments(def->input_schema, args); !err.empty()) + return result_to_json(ToolResult::error("Invalid arguments: " + err)); + try { + return result_to_json(m_caller.call(*def, args)); + } catch (const ToolFailure& f) { + return result_to_json(ToolResult::error(f.what(), f.details)); + } catch (const std::exception& e) { + return result_to_json(ToolResult::error(std::string("Internal error: ") + e.what())); + } +} + +PostReply McpProtocol::handle_post(const PostRequest& request) +{ + json msg = json::parse(request.body, nullptr, false); + if (msg.is_discarded()) + return reply(400, error_body(nullptr, kParseError, "Parse error")); + if (msg.is_array()) + return reply(400, error_body(nullptr, kInvalidRequest, "Batches are not supported")); + if (!msg.is_object() || msg.value("jsonrpc", "") != "2.0") + return reply(400, error_body(nullptr, kInvalidRequest, "Not a JSON-RPC 2.0 message")); + + // Responses (to requests this server never sends) and notifications are accepted silently. + if (!msg.contains("method") || !msg["method"].is_string()) + return msg.contains("result") || msg.contains("error") ? PostReply{202, {}} + : reply(400, error_body(nullptr, kInvalidRequest, "Missing method")); + if (!msg.contains("id")) + return {202, {}}; + + const json& id = msg["id"]; + if (!id.is_string() && !id.is_number_integer() && !id.is_number_unsigned()) + return reply(400, error_body(nullptr, kInvalidRequest, "id must be a string or an integer")); + + const std::string method = msg["method"].get(); + const json params = msg.contains("params") && msg["params"].is_object() ? msg["params"] : json::object(); + + try { + if (params.contains("_meta") && params["_meta"].is_object() && params["_meta"].contains(kMetaVersion)) { + const json& v = params["_meta"][kMetaVersion]; + return handle_modern(id, method, params, v.is_string() ? v.get() : v.dump(), request); + } + return handle_legacy(id, method, params, request); + } catch (const std::exception& e) { + return reply(500, error_body(id, kInternalError, e.what())); + } +} + +PostReply McpProtocol::handle_legacy(const json& id, const std::string& method, const json& params, const PostRequest& request) +{ + const auto& versions = legacy_versions(); + if (method != "initialize" && !request.protocol_version.empty() && + std::find(versions.begin(), versions.end(), request.protocol_version) == versions.end()) + return reply(400, error_body(id, kInvalidRequest, "Unsupported MCP-Protocol-Version: " + request.protocol_version, + {{"supported", versions}})); + + if (method == "initialize") { + const std::string requested = params.value("protocolVersion", ""); + const bool supported = std::find(versions.begin(), versions.end(), requested) != versions.end(); + json server_info{{"name", m_info.name}, {"title", m_info.title}, {"version", m_info.version}}; + return result_reply(id, {{"protocolVersion", supported ? requested : versions.front()}, + {"capabilities", {{"tools", {{"listChanged", false}}}}}, + {"serverInfo", std::move(server_info)}, + {"instructions", m_info.instructions}}); + } + if (method == "ping") + return result_reply(id, json::object()); + if (method == "tools/list") + return result_reply(id, {{"tools", tools_list()}}); + if (method == "tools/call") { + bool unknown = false; + std::string name; + json result = call_tool(params, unknown, name); + if (unknown) { + json data{{"name", name}}; + if (auto close = m_registry.similar(name); !close.empty()) + data["did_you_mean"] = close; + return reply(200, error_body(id, kInvalidParams, "Unknown tool: " + name, std::move(data))); + } + return result_reply(id, std::move(result)); + } + return reply(200, error_body(id, kMethodNotFound, "Method not found: " + method)); +} + +PostReply McpProtocol::handle_modern(const json& id, const std::string& method, const json& params, const std::string& version, + const PostRequest& request) +{ + if (version != kModernVersion) + return reply(400, error_body(id, kUnsupportedProto, "Unsupported protocol version", + {{"supported", supported_versions()}, {"requested", version}})); + if (request.protocol_version.empty()) + return reply(400, error_body(id, kHeaderMismatch, "Header mismatch: MCP-Protocol-Version header is required")); + if (request.protocol_version != version) + return reply(400, error_body(id, kHeaderMismatch, + "Header mismatch: MCP-Protocol-Version header value '" + request.protocol_version + + "' does not match body value '" + version + "'")); + if (request.method_header.empty()) + return reply(400, error_body(id, kHeaderMismatch, "Header mismatch: Mcp-Method header is required")); + if (request.method_header != method) + return reply(400, error_body(id, kHeaderMismatch, + "Header mismatch: Mcp-Method header value '" + request.method_header + + "' does not match body value '" + method + "'")); + if (method == "tools/call" || method == "prompts/get" || method == "resources/read") { + const std::string body_name = method == "resources/read" ? params.value("uri", "") : params.value("name", ""); + if (request.name_header.empty()) + return reply(400, error_body(id, kHeaderMismatch, "Header mismatch: Mcp-Name header is required")); + const std::string header_name = decode_header_value(request.name_header); + if (header_name != body_name) + return reply(400, error_body(id, kHeaderMismatch, + "Header mismatch: Mcp-Name header value '" + header_name + "' does not match body value '" + + body_name + "'")); + } + + auto complete = [](json result) { + result["resultType"] = "complete"; + return result; + }; + + if (method == "server/discover") { + json result{{"supportedVersions", supported_versions()}, + {"capabilities", {{"tools", json::object()}}}, + {"_meta", {{kMetaServer, {{"name", m_info.name}, {"title", m_info.title}, {"version", m_info.version}}}}}, + {"instructions", m_info.instructions}, + {"ttlMs", kListTtlMs}, + {"cacheScope", "public"}}; + return result_reply(id, complete(std::move(result))); + } + if (method == "ping") + return result_reply(id, complete(json::object())); + if (method == "tools/list") + return result_reply(id, complete({{"tools", tools_list()}, {"ttlMs", kListTtlMs}, {"cacheScope", "public"}})); + if (method == "tools/call") { + bool unknown = false; + std::string name; + json result = call_tool(params, unknown, name); + if (unknown) { + json data{{"name", name}}; + if (auto close = m_registry.similar(name); !close.empty()) + data["did_you_mean"] = close; + return reply(200, error_body(id, kInvalidParams, "Unknown tool: " + name, std::move(data))); + } + return result_reply(id, complete(std::move(result))); + } + return reply(404, error_body(id, kMethodNotFound, "Method not found: " + method)); +} + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpProtocol.hpp b/src/slic3r/GUI/Mcp/McpProtocol.hpp new file mode 100644 index 0000000000..91756e6b85 --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpProtocol.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include "McpTypes.hpp" + +#include + +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +// Revision served statelessly to requests that carry the per-request `_meta` version. +inline constexpr const char* kModernVersion = "2026-07-28"; +// Revisions negotiated through the `initialize` handshake, newest first. +inline const std::vector& legacy_versions() +{ + static const std::vector versions{"2025-11-25", "2025-06-18"}; + return versions; +} + +struct ServerInfo +{ + std::string name = "orcaslicer"; + std::string title = "OrcaSlicer"; + std::string version; + std::string instructions; +}; + +// One POSTed message and the transport headers the protocol checks. Header values are empty when +// the header was absent. +struct PostRequest +{ + std::string body; + std::string protocol_version; // MCP-Protocol-Version + std::string method_header; // Mcp-Method + std::string name_header; // Mcp-Name +}; + +// Body is empty for 202 Accepted. +struct PostReply +{ + int status = 200; + std::string body; +}; + +// The MCP protocol layer: JSON-RPC 2.0 framing and the MCP methods of both eras, independent of +// the HTTP transport and of wx. It never throws; every failure becomes a JSON-RPC error or an +// isError tool result. +class McpProtocol +{ +public: + McpProtocol(const ToolRegistry& registry, ToolCaller& caller, ServerInfo info); + + PostReply handle_post(const PostRequest& request); + + static nlohmann::json tool_to_json(const ToolDef& def); + static nlohmann::json result_to_json(const ToolResult& result); + +private: + PostReply handle_legacy(const nlohmann::json& id, const std::string& method, const nlohmann::json& params, + const PostRequest& request); + PostReply handle_modern(const nlohmann::json& id, const std::string& method, const nlohmann::json& params, + const std::string& version, const PostRequest& request); + nlohmann::json call_tool(const nlohmann::json& params, bool& unknown_tool, std::string& unknown_name); + nlohmann::json tools_list() const; + + const ToolRegistry& m_registry; + ToolCaller& m_caller; + ServerInfo m_info; +}; + +// Decodes the `=?base64?...?=` sentinel form of an Mcp-Name / Mcp-Param header value; plain values +// pass through unchanged. +std::string decode_header_value(const std::string& value); + +}}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpScript.cpp b/src/slic3r/GUI/Mcp/McpScript.cpp new file mode 100644 index 0000000000..2b9b72787b --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpScript.cpp @@ -0,0 +1,294 @@ +#include "McpScript.hpp" + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { namespace Mcp { + +using nlohmann::json; + +namespace { + +bool is_job_envelope(const ToolResult& r) +{ + if (r.is_error || !r.data.is_object() || !r.data.contains("job") || !r.data.contains("status")) + return false; + const std::string status = r.data.value("status", ""); + return status == "running" || status == "blocked_by_dialog"; +} + +// Resolves one placeholder body ("vars.model", "env:HOME", ...) to a JSON value. +std::optional resolve_placeholder(const std::string& key, const Script& script, const ScriptContext& ctx) +{ + if (key == "script_dir") + return json(ctx.script_dir.string()); + if (key == "out_dir") + return json(ctx.out_dir.string()); + if (key.rfind("env:", 0) == 0) { + const char* v = std::getenv(key.substr(4).c_str()); + return json(v ? std::string(v) : std::string()); + } + if (key.rfind("vars.", 0) == 0) { + auto it = script.vars.find(key.substr(5)); + if (it != script.vars.end()) + return std::optional(it.value()); + return std::nullopt; + } + if (key.rfind("jobs.", 0) == 0) { + auto it = ctx.jobs.find(key.substr(5)); + if (it != ctx.jobs.end()) + return std::optional(it.value()); + return std::nullopt; + } + return std::nullopt; +} + +json substitute_value(const json& value, const Script& script, const ScriptContext& ctx, std::string& err, int depth) +{ + if (depth > 8) { + err = "variable substitution nests too deeply"; + return value; + } + if (value.is_array() || value.is_object()) { + json out = value; + for (auto it = out.begin(); it != out.end(); ++it) + *it = substitute_value(*it, script, ctx, err, depth); + return out; + } + if (!value.is_string()) + return value; + static const std::regex placeholder(R"(\$\{([^}]+)\})"); + const std::string text = value.get(); + std::smatch whole; + if (std::regex_match(text, whole, placeholder)) { + auto v = resolve_placeholder(whole[1].str(), script, ctx); + if (!v) { + err = "unknown placeholder " + text; + return value; + } + // A var may itself contain placeholders (e.g. "${script_dir}/part.stl"). + return substitute_value(*v, script, ctx, err, depth + 1); + } + std::string out; + auto begin = std::sregex_iterator(text.begin(), text.end(), placeholder); + std::size_t last = 0; + for (auto it = begin; it != std::sregex_iterator(); ++it) { + out.append(text, last, std::size_t(it->position()) - last); + auto v = resolve_placeholder((*it)[1].str(), script, ctx); + if (!v) { + err = "unknown placeholder " + it->str(); + return value; + } + const json resolved = substitute_value(*v, script, ctx, err, depth + 1); + out += resolved.is_string() ? resolved.get() : resolved.dump(); + last = std::size_t(it->position() + it->length()); + } + out.append(text, last, std::string::npos); + return json(out); +} + +bool numeric(const json& v) { return v.is_number(); } + +std::optional check_matcher(const std::string& pointer, const json& actual, bool exists, const std::string& op, + const json& operand) +{ + auto fail = [&](const std::string& what) { + return std::optional(pointer + ": expected " + op + " " + operand.dump() + ", " + what); + }; + if (op == "exists") + return exists == operand.get() ? std::nullopt : fail(exists ? "but it exists" : "but it is missing"); + if (!exists) + return fail("but it is missing"); + const std::string got = "got " + actual.dump(); + if (op == "eq") + return actual == operand ? std::nullopt : fail(got); + if (op == "ne") + return actual != operand ? std::nullopt : fail(got); + if (op == "gt" || op == "ge" || op == "lt" || op == "le") { + if (!numeric(actual) || !numeric(operand)) + return fail(got + " (not a number)"); + const double a = actual.get(), b = operand.get(); + const bool ok = op == "gt" ? a > b : op == "ge" ? a >= b : op == "lt" ? a < b : a <= b; + return ok ? std::nullopt : fail(got); + } + if (op == "contains") { + bool ok = false; + if (actual.is_string() && operand.is_string()) + ok = actual.get().find(operand.get()) != std::string::npos; + else if (actual.is_array()) + ok = std::find(actual.begin(), actual.end(), operand) != actual.end(); + else if (actual.is_object() && operand.is_string()) + ok = actual.contains(operand.get()); + return ok ? std::nullopt : fail(got); + } + if (op == "regex") { + if (!actual.is_string() || !operand.is_string()) + return fail(got + " (not a string)"); + try { + return std::regex_search(actual.get(), std::regex(operand.get())) ? std::nullopt : fail(got); + } catch (const std::regex_error&) { + return fail("but the pattern is not a valid regular expression"); + } + } + if (op == "empty") { + const bool is_empty = actual.is_null() || ((actual.is_array() || actual.is_object() || actual.is_string()) && actual.empty()); + return is_empty == operand.get() ? std::nullopt : fail(got); + } + return std::optional(pointer + ": unknown matcher " + op); +} + +} // namespace + +std::optional