38using Object = Poco::JSON::Object;
39using Clock = std::chrono::steady_clock;
41std::string json(
const Poco::Dynamic::Var&
value) {
42 std::ostringstream
out;
43 Poco::JSON::Stringifier::stringify(
value,
out);
47std::string executablePath() {
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");
53 return std::filesystem::path(
buffer).string();
54#elif defined(__APPLE__)
56 _NSGetExecutablePath(
nullptr, &
size);
58 if (_NSGetExecutablePath(
buffer.data(), &
size) != 0)
throw std::runtime_error(
"cannot locate eve executable");
59 return std::filesystem::canonical(
buffer.c_str()).string();
61 return std::filesystem::read_symlink(
"/proc/self/exe").string();
66volatile std::sig_atomic_t workerPid = 0;
69void terminateSupervisor(
int signal) {
70 const auto pid =
static_cast<pid_t
>(workerPid);
73 while (::waitpid(pid,
nullptr, 0) < 0 && errno == EINTR) {
80class DeadlineExceeded :
public std::runtime_error {
82 DeadlineExceeded() : std::runtime_error(
"execution deadline exceeded") {}
87 Supervisor(std::string
root,
int timeoutMs)
88 : executable_(executablePath()), root_(std::move(
root)), timeout_(timeoutMs) {
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))) {
96 throw std::runtime_error(
"cannot configure MCP worker job");
109 while (std::getline(std::cin,
line)) {
110 if (
line.empty())
continue;
113 Poco::JSON::Parser parser;
114 request = parser.parse(
line).extract<Object::Ptr>();
116 throw std::runtime_error(
"invalid request");
117 }
catch (
const std::exception&) {
119 error->set(
"code", -32600);
120 error->set(
"message",
"Invalid Request");
123 response->set(
"id", Poco::Dynamic::Var());
125 std::cout << json(
response) << std::endl;
129 const std::string tool =
params ?
params->optValue<std::string>(
"name",
"") :
"";
130 if (tool ==
"eve_error_slice" && !lastDiagnostic_.empty()) {
135 if (!process_)
start();
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;
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();
148 }
catch (
const std::exception&
error) {
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);
170 void reply(
const Object::Ptr&
request,
const std::string&
message,
bool isError) {
171 Object::Ptr item =
new Object;
172 item->set(
"type",
"text");
174 Poco::JSON::Array::Ptr content =
new Poco::JSON::Array;
177 result->set(
"content", content);
178 result->set(
"isError", isError);
182 if (
request->getValue<std::string>(
"method") ==
"tools/call") {
186 error->set(
"code", -32000);
190 std::cout << json(
response) << std::endl;
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));
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);
204 throw std::runtime_error(
"cannot assign MCP worker to lifetime job");
207 workerPid =
static_cast<std::sig_atomic_t
>(process_->id());
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>();
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);
224 if (!process_)
return;
225 if (process_->tryWait() == -1) {
226 Poco::Process::kill(*process_);
227 const int exitCode = process_->wait();
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';
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);
248 if (!
request->has(
"id"))
return {};
250 while (std::getline(*reader_,
response)) {
252 Poco::JSON::Parser parser;
253 auto object = parser.parse(
response).extract<Object::Ptr>();
256 }
catch (
const std::exception&) {
257 std::cerr <<
"eve mcp: ignored malformed worker output\n";
260 throw std::runtime_error(
"worker disconnected");
262 if (task.wait_until(
deadline) != std::future_status::ready) {
265 throw DeadlineExceeded();
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_;
276 HANDLE job_ =
nullptr;
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);
289 Supervisor supervisor(std::filesystem::absolute(
root).
string(), timeoutMs);
291 }
catch (
const std::exception&
error) {
292 std::cerr <<
"eve mcp supervisor: " <<
error.what() << std::endl;
296 std::signal(SIGTERM, oldTerm);
297 std::signal(SIGINT, oldInt);
298 std::signal(SIGPIPE, oldPipe);
wgpu::PopErrorScopeStatus status