载入中...
搜索中...
未找到
McpSupervisor.cpp
浏览该文件的文档.
1#include "McpSupervisor.h"
2
3#if !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(EVENGINE_WEBGPU)
4#include <Poco/JSON/Array.h>
5#include <Poco/JSON/Object.h>
6#include <Poco/JSON/Parser.h>
7#include <Poco/JSON/Stringifier.h>
8#include <Poco/Pipe.h>
9#include <Poco/PipeStream.h>
10#include <Poco/Process.h>
11
12#include <algorithm>
13#include <cerrno>
14#include <chrono>
15#include <climits>
16#include <filesystem>
17#include <future>
18#include <iostream>
19#include <memory>
20#include <sstream>
21#include <stdexcept>
22
23#ifdef _WIN32
24#include <windows.h>
25#elif defined(__APPLE__)
26#include <mach-o/dyld.h>
27#include <sys/wait.h>
28#include <unistd.h>
29#include <csignal>
30#else
31#include <sys/wait.h>
32#include <unistd.h>
33#include <csignal>
34#endif
35
37namespace {
38using Object = Poco::JSON::Object;
39using Clock = std::chrono::steady_clock;
40
41std::string json(const Poco::Dynamic::Var& value) {
42 std::ostringstream out;
43 Poco::JSON::Stringifier::stringify(value, out);
44 return out.str();
45}
46
47std::string executablePath() {
48#ifdef _WIN32
49 std::wstring buffer(32768, L'\0');
50 const auto size = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
51 if (size == 0 || size >= buffer.size()) throw std::runtime_error("cannot locate eve executable");
52 buffer.resize(size);
53 return std::filesystem::path(buffer).string();
54#elif defined(__APPLE__)
55 uint32_t size = 0;
56 _NSGetExecutablePath(nullptr, &size);
57 std::string buffer(size, '\0');
58 if (_NSGetExecutablePath(buffer.data(), &size) != 0) throw std::runtime_error("cannot locate eve executable");
59 return std::filesystem::canonical(buffer.c_str()).string();
60#else
61 return std::filesystem::read_symlink("/proc/self/exe").string();
62#endif
63}
64
65#ifndef _WIN32
66volatile std::sig_atomic_t workerPid = 0;
67// Only async-signal-safe OS calls: do not leave an owned VM running when the
68// MCP client terminates its supervisor while stdin is blocked.
69void terminateSupervisor(int signal) {
70 const auto pid = static_cast<pid_t>(workerPid);
71 if (pid > 0) {
72 ::kill(pid, SIGKILL);
73 while (::waitpid(pid, nullptr, 0) < 0 && errno == EINTR) {
74 }
75 }
76 _exit(128 + signal);
77}
78#endif
79
80class DeadlineExceeded : public std::runtime_error {
81public:
82 DeadlineExceeded() : std::runtime_error("execution deadline exceeded") {}
83};
84
85class Supervisor {
86public:
87 Supervisor(std::string root, int timeoutMs)
88 : executable_(executablePath()), root_(std::move(root)), timeout_(timeoutMs) {
89#ifdef _WIN32
90 job_ = CreateJobObjectW(nullptr, nullptr);
91 if (!job_) throw std::runtime_error("cannot create MCP worker job");
92 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
93 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
94 if (!SetInformationJobObject(job_, JobObjectExtendedLimitInformation, &limits, sizeof(limits))) {
95 CloseHandle(job_);
96 throw std::runtime_error("cannot configure MCP worker job");
97 }
98#endif
99 }
100 ~Supervisor() {
101 stop();
102#ifdef _WIN32
103 CloseHandle(job_);
104#endif
105 }
106
107 void serve() {
108 std::string line;
109 while (std::getline(std::cin, line)) {
110 if (line.empty()) continue;
111 Object::Ptr request;
112 try {
113 Poco::JSON::Parser parser;
114 request = parser.parse(line).extract<Object::Ptr>();
115 if (!request || request->getValue<std::string>("jsonrpc") != "2.0" || !request->has("method"))
116 throw std::runtime_error("invalid request");
117 } catch (const std::exception&) {
118 Object::Ptr error = new Object;
119 error->set("code", -32600);
120 error->set("message", "Invalid Request");
121 Object::Ptr response = new Object;
122 response->set("jsonrpc", "2.0");
123 response->set("id", Poco::Dynamic::Var());
124 response->set("error", error);
125 std::cout << json(response) << std::endl;
126 continue;
127 }
128 auto params = request->getObject("params");
129 const std::string tool = params ? params->optValue<std::string>("name", "") : "";
130 if (tool == "eve_error_slice" && !lastDiagnostic_.empty()) {
131 if (request->has("id")) reply(request, lastDiagnostic_, false);
132 continue;
133 }
134 try {
135 if (!process_) start();
136 const std::string response = exchange(line, request);
137 if (!request->has("id")) continue;
138 if (request->getValue<std::string>("method") == "initialize") {
139 Poco::JSON::Parser parser;
140 if (parser.parse(response).extract<Object::Ptr>()->has("result")) initialization_ = line;
141 }
142 if (tool == "eve_run_script") {
143 Poco::JSON::Parser parser;
144 auto result = parser.parse(response).extract<Object::Ptr>()->getObject("result");
145 if (result && result->optValue<bool>("isError", false)) lastDiagnostic_.clear();
146 }
147 std::cout << response << std::endl;
148 } catch (const std::exception& error) {
149 // exchange has already joined its I/O task after killing the
150 // worker. Never label a mere client wait timeout as stopped.
151 stop();
152 Object::Ptr diagnostic = new Object;
153 diagnostic->set("schema", "eve.mcp.watchdog");
154 diagnostic->set("version", 1);
155 diagnostic->set("type",
156 dynamic_cast<const DeadlineExceeded*>(&error) ? "execution_timeout" : "host_failure");
157 diagnostic->set("origin", tool.empty() ? request->getValue<std::string>("method") : tool);
158 if (tool == "eve_run_script") diagnostic->set("source", "memory://mcp/snippet");
159 diagnostic->set("budget_ms", timeout_.count());
160 diagnostic->set("message", error.what());
161 diagnostic->set("vm_state", "terminated");
162 diagnostic->set("recovery", "next request starts a fresh host; in-memory state is lost");
163 lastDiagnostic_ = json(diagnostic);
164 if (request->has("id")) reply(request, lastDiagnostic_, true);
165 }
166 }
167 }
168
169private:
170 void reply(const Object::Ptr& request, const std::string& message, bool isError) {
171 Object::Ptr item = new Object;
172 item->set("type", "text");
173 item->set("text", message);
174 Poco::JSON::Array::Ptr content = new Poco::JSON::Array;
175 content->add(item);
176 Object::Ptr result = new Object;
177 result->set("content", content);
178 result->set("isError", isError);
179 Object::Ptr response = new Object;
180 response->set("jsonrpc", "2.0");
181 response->set("id", request->get("id"));
182 if (request->getValue<std::string>("method") == "tools/call") {
183 response->set("result", result);
184 } else {
185 Object::Ptr error = new Object;
186 error->set("code", -32000);
187 error->set("message", message);
188 response->set("error", error);
189 }
190 std::cout << json(response) << std::endl;
191 }
192
193 void start() {
194 input_ = std::make_unique<Poco::Pipe>();
195 output_ = std::make_unique<Poco::Pipe>();
196 process_ = std::make_unique<Poco::ProcessHandle>(Poco::Process::launch(
197 executable_, {"mcp", "--worker", "--root", root_}, input_.get(), output_.get(), nullptr));
198#ifdef _WIN32
199 HANDLE child = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, FALSE, process_->id());
200 const bool assigned = child && AssignProcessToJobObject(job_, child);
201 if (child) CloseHandle(child);
202 if (!assigned) {
203 stop();
204 throw std::runtime_error("cannot assign MCP worker to lifetime job");
205 }
206#else
207 workerPid = static_cast<std::sig_atomic_t>(process_->id());
208#endif
209 reader_ = std::make_unique<Poco::PipeInputStream>(*output_);
210 if (!initialization_.empty()) {
211 Poco::JSON::Parser parser;
212 auto request = parser.parse(initialization_).extract<Object::Ptr>();
213 const auto response = exchange(initialization_, request);
214 auto initialized = parser.parse(response).extract<Object::Ptr>();
215 if (initialized->has("error")) throw std::runtime_error("worker initialization failed");
216 Object::Ptr notification = new Object;
217 notification->set("jsonrpc", "2.0");
218 notification->set("method", "notifications/initialized");
219 exchange(json(notification), notification);
220 }
221 }
222
223 void stop() {
224 if (!process_) return;
225 if (process_->tryWait() == -1) {
226 Poco::Process::kill(*process_);
227 const int exitCode = process_->wait();
228 (void)exitCode; // Process is reaped; any exit status discards this VM.
229 }
230#ifndef _WIN32
231 workerPid = 0;
232#endif
233 process_.reset();
234 // exchange may still own the pipe/reader until its async task joins.
235 }
236
237 std::string exchange(const std::string& line, const Object::Ptr& request) {
238 const auto deadline = Clock::now() + timeout_;
239 auto task = std::async(std::launch::async, [this, line, request]() -> std::string {
240 const std::string wire = line + '\n';
241 std::size_t offset = 0;
242 while (offset < wire.size()) {
243 const int count = input_->writeBytes(
244 wire.data() + offset, static_cast<int>(std::min<std::size_t>(wire.size() - offset, INT_MAX)));
245 if (count <= 0) throw std::runtime_error("worker stdin closed");
246 offset += static_cast<std::size_t>(count);
247 }
248 if (!request->has("id")) return {};
249 std::string response;
250 while (std::getline(*reader_, response)) {
251 try {
252 Poco::JSON::Parser parser;
253 auto object = parser.parse(response).extract<Object::Ptr>();
254 if (object->has("id") && json(object->get("id")) == json(request->get("id"))) return response;
255 if (!object->has("id")) std::cout << response << std::endl;
256 } catch (const std::exception&) {
257 std::cerr << "eve mcp: ignored malformed worker output\n";
258 }
259 }
260 throw std::runtime_error("worker disconnected");
261 });
262 if (task.wait_until(deadline) != std::future_status::ready) {
263 stop();
264 task.wait();
265 throw DeadlineExceeded();
266 }
267 return task.get();
268 }
269
270 std::string executable_, root_, initialization_, lastDiagnostic_;
271 std::chrono::milliseconds timeout_;
272 std::unique_ptr<Poco::ProcessHandle> process_;
273 std::unique_ptr<Poco::Pipe> input_, output_;
274 std::unique_ptr<Poco::PipeInputStream> reader_;
275#ifdef _WIN32
276 HANDLE job_ = nullptr;
277#endif
278};
279} // namespace
280
281int runMcpSupervisor(const std::string& root, int timeoutMs) {
282#ifndef _WIN32
283 const auto oldTerm = std::signal(SIGTERM, terminateSupervisor);
284 const auto oldInt = std::signal(SIGINT, terminateSupervisor);
285 const auto oldPipe = std::signal(SIGPIPE, SIG_IGN);
286#endif
287 int status = 0;
288 try {
289 Supervisor supervisor(std::filesystem::absolute(root).string(), timeoutMs);
290 supervisor.serve();
291 } catch (const std::exception& error) {
292 std::cerr << "eve mcp supervisor: " << error.what() << std::endl;
293 status = 3;
294 }
295#ifndef _WIN32
296 std::signal(SIGTERM, oldTerm);
297 std::signal(SIGINT, oldInt);
298 std::signal(SIGPIPE, oldPipe);
299#endif
300 return status;
301}
302} // namespace eve::cmd::detail
303#endif
Duration start
int root
Definition AnimSmr.cpp:119
std::string message
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
size_t offset
std::chrono::steady_clock::time_point deadline
std::string response
Poco::JSON::Object::Ptr result
std::vector< RecipeParam > params
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
int wire
std::string error
Definition Package.cpp:174
Object::Ptr value
unsigned line
ScriptStructure out
Json object
float size
Definition TreeMesh.cpp:158
const AssetImportLimits & limits
int runMcpSupervisor(const std::string &root, int timeoutMs)
Run the desktop stdio MCP supervisor synchronously on the main thread. Owns a worker process and its ...