载入中...
搜索中...
未找到
McpServer.cpp
浏览该文件的文档.
4
10
11#include "devtools/AiPanel.hpp"
13#include "devtools/Debugger.hpp"
14#include "devtools/DevTool.hpp"
17#include "devtools/McpArgs.hpp"
21#include "devtools/McpJson.hpp"
29#include "devtools/PlayHost.h"
32#include "devtools/Snapshot.hpp"
33
34#include "scripts.h"
35
36#include "common/AudioQuery.h"
38#include "common/Capability.h"
39#include "common/EditorHost.h"
40#include "common/Module.h"
42#include "common/PhysicsQuery.h"
44#include "common/ProcgenQuery.h"
46#include "common/SceneQuery.h"
48#include "common/ScriptError.h"
49#include "common/UIAutomation.h"
50
51#include <Poco/Dynamic/Var.h>
52#include <Poco/Exception.h>
53#include <Poco/JSON/Array.h>
54#include <Poco/JSON/Object.h>
55#include <Poco/JSON/Parser.h>
56#include <Poco/JSON/Stringifier.h>
57#include <Poco/Net/NetException.h>
58#include <Poco/Net/ServerSocket.h>
59#include <Poco/Net/SocketAddress.h>
60#include <Poco/Net/StreamSocket.h>
61#include <Poco/Timespan.h>
62
63#include <squirrel.h>
64#include <glm/glm.hpp>
65
66#include <cmath>
67#include <cstdio>
68#include <cstdlib>
69#include <filesystem>
70#include <fstream>
71#include <sstream>
72#include <vector>
73
74namespace eve::dev {
75namespace {
76
77std::string idToJson(const Poco::Dynamic::Var& id) {
78 if (id.isEmpty()) return "null";
79 try {
80 if (id.isInteger() || id.isNumeric()) return std::to_string(id.convert<Poco::Int64>());
81 } catch (...) {
82 }
83 try {
84 return std::string("\"") + mcpJsonEscape(id.convert<std::string>()) + "\"";
85 } catch (...) {
86 return "null";
87 }
88}
89
90std::string makeResult(const std::string& idJson, const std::string& resultJson) {
91 return std::string("{\"jsonrpc\":\"2.0\",\"id\":") + idJson + ",\"result\":" + resultJson + "}";
92}
93
94std::string makeError(const std::string& idJson, int code, const std::string& message) {
95 return std::string("{\"jsonrpc\":\"2.0\",\"id\":") + idJson + ",\"error\":{\"code\":" + std::to_string(code) +
96 ",\"message\":\"" + mcpJsonEscape(message) + "\"}}";
97}
98
99std::string pauseReasonName(PauseReason r) {
100 switch (r) {
101 case PauseReason::Breakpoint: return "breakpoint";
102 case PauseReason::Step: return "step";
103 case PauseReason::Exception: return "exception";
104 case PauseReason::Snapshot: return "snapshot";
105 case PauseReason::PauseKey: return "pause";
106 default: return "none";
107 }
108}
109
110std::string engineStatusJson(const McpServer& mcp) {
111 auto& dbg = Debugger::instance();
112 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
113 o->set("attached", mcpDevAttached());
114 o->set("paused", dbg.isPaused());
115 o->set("pauseReason", pauseReasonName(dbg.lastPauseReason()));
116 const auto& loc = dbg.pauseLocation();
117 o->set("source", loc.source);
118 o->set("line", loc.line);
119 o->set("function", loc.function);
120 o->set("mcpPort", mcp.port());
121 o->set("mcpConnected", mcp.hasClient());
122 switch (mcp.transport()) {
123 case McpServer::Transport::Stdio: o->set("transport", "stdio"); break;
124 case McpServer::Transport::Tcp: o->set("transport", "tcp"); break;
125 default: o->set("transport", "none"); break;
126 }
127 o->set("dapPort", DebugAdapter::instance().port());
128 o->set("gameRoot", mcp.gameRoot());
129 o->set("host", eve::cap::query<eve::IEditorHost>() ? eve::cap::query<eve::IEditorHost>()->status()
130 : std::string("unavailable"));
131 o->set("callgraphEvents", static_cast<int>(mcpCallgraphEvents()));
132 o->set("ai", AiPanel::instance().statusLine());
133 // The server dies with the process it serves; point the agent at the
134 // persistent log that outlives a crash.
135 o->set("crashLog", crashLogSummary());
136 o->set("scriptTools", scriptToolCount());
137 return mcpStringify(Poco::Dynamic::Var(o));
138}
139
140glm::vec3 argVec3(Poco::JSON::Object::Ptr args, const char* key, const glm::vec3& def = {}) {
141 if (!args || !args->has(key)) return def;
142 try {
143 auto arr = args->getArray(key);
144 if (arr && arr->size() >= 3) {
145 return glm::vec3(static_cast<float>(arr->get(0).convert<double>()),
146 static_cast<float>(arr->get(1).convert<double>()),
147 static_cast<float>(arr->get(2).convert<double>()));
148 }
149 } catch (...) {
150 }
151 return def;
152}
153
154Poco::JSON::Array::Ptr vec3ToArray(const glm::vec3& v) {
155 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
156 arr->add(v.x);
157 arr->add(v.y);
158 arr->add(v.z);
159 return arr;
160}
161
162// ============================= Scene Director (AI scene-authoring) =============
163// Thin C++ dispatchers over the Squirrel `scene_director` kit live in
164// McpSceneDirector.*; Agents build / inspect scenes through eve_scene_* tools.
165
166std::string renderStatusText(eve::IRenderCapture* cap) {
167 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
168 if (!cap) {
169 o->set("error", "Graphics module not available");
170 return mcpStringify(Poco::Dynamic::Var(o));
171 }
172 const eve::RenderStatusInfo s = cap->status();
173 o->set("width", s.width);
174 o->set("height", s.height);
175 o->set("pixelWidth", s.pixelWidth);
176 o->set("pixelHeight", s.pixelHeight);
177 o->set("had3DThisFrame", s.had3DThisFrame);
178 o->set("readbackEnabled", s.readbackEnabled);
179 o->set("backend", s.backend);
180 o->set("renderFlowEvents", static_cast<int>(DevTool::instance().renderFlow().eventCount()));
181 return mcpStringify(Poco::Dynamic::Var(o));
182}
183
184eve::IRenderCapture* mcpCapture() { return eve::cap::query<eve::IRenderCapture>(); }
185eve::ISceneQuery* mcpScene() { return eve::cap::query<eve::ISceneQuery>(); }
186eve::IPhysicsQuery* mcpPhysics() { return eve::cap::query<eve::IPhysicsQuery>(); }
187eve::IProcgenQuery* mcpProcgen() { return eve::cap::query<eve::IProcgenQuery>(); }
188eve::IParticlesQuery* mcpParticles() { return eve::cap::query<eve::IParticlesQuery>(); }
189eve::IAudioQuery* mcpAudio() { return eve::cap::query<eve::IAudioQuery>(); }
190eve::IEditorHost* mcpHost() { return eve::cap::query<eve::IEditorHost>(); }
191eve::IUIAutomation* mcpUI() { return eve::cap::query<eve::IUIAutomation>(); }
192eve::IEditorAutomation* mcpEditor() { return eve::cap::query<eve::IEditorAutomation>(); }
193eve::IPixelWorldAutomation* mcpPixelWorld() { return eve::cap::query<eve::IPixelWorldAutomation>(); }
194
201void runPendingVisionDump() {
202 if (!RenderVision::instance().pending()) return;
203 auto* cap = mcpCapture();
204 if (cap) RenderVision::instance().pollPending(cap, renderStatusText(cap));
205}
206
207Poco::JSON::Object::Ptr renderableObservation(eve::IRenderCapture& capture, int entityId, int generation) {
208 Poco::JSON::Object::Ptr output = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
209 auto inspected =
210 capture.inspectRenderable3D(static_cast<std::uint32_t>(entityId), static_cast<std::uint32_t>(generation));
211 if (!inspected) {
212 output->set("status", "stale");
213 output->set("entityId", entityId);
214 output->set("generation", generation);
215 output->set("error", inspected.status().describe());
216 return output;
217 }
218 const auto& info = inspected.value();
219 output->set("status", "ok");
220 output->set("entityId", info.entityId);
221 output->set("generation", info.generation);
222 Poco::JSON::Array::Ptr position = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
223 position->add(info.x);
224 position->add(info.y);
225 position->add(info.z);
226 output->set("position", position);
227 Poco::JSON::Array::Ptr tint = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
228 tint->add(info.tintR);
229 tint->add(info.tintG);
230 tint->add(info.tintB);
231 tint->add(info.tintA);
232 output->set("tint", tint);
233 output->set("metallic", info.metallic);
234 output->set("roughness", info.roughness);
235 output->set("parallaxScale", info.parallaxScale);
236 output->set("visible", info.visible);
237 output->set("receiveLight", info.receiveLight);
238 output->set("castShadow", info.castShadow);
239 output->set("receiveShadow", info.receiveShadow);
240 output->set("hasPackedMaterial", info.hasPackedMaterial);
241 output->set("hasTexture", info.hasTexture);
242 output->set("hasShader", info.hasShader);
243 return output;
244}
245
246Poco::JSON::Object::Ptr sceneNodeObservation(eve::ISceneQuery& scene, const std::string& host,
247 const std::string& node) {
248 Poco::JSON::Object::Ptr output = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
249 output->set("observer", "scene-node");
250 output->set("host", host.empty() ? scene.activeHost() : host);
251 output->set("node", node);
252 if (node.empty()) {
253 output->set("status", "not-found");
254 output->set("error", "Scene node is missing from the observed host");
255 return output;
256 }
257 auto lookedUp = host.empty() ? scene.getNode(node) : scene.getNodeIn(host, node);
258 if (!lookedUp) {
259 output->set("status", "not-found");
260 output->set("error", "Scene node is missing from the observed host");
261 return output;
262 }
263 const eve::SceneNodeInfo info = std::move(lookedUp).value();
264 output->set("status", "ok");
265 output->set("id", info.id);
266 output->set("name", info.name);
267 output->set("path", info.path);
268 output->set("visible", info.visible);
269 output->set("x", info.x);
270 output->set("y", info.y);
271 output->set("z", info.z);
272 output->set("yaw", info.yaw);
273 output->set("pitch", info.pitch);
274 output->set("roll", info.roll);
275 output->set("sx", info.sx);
276 output->set("sy", info.sy);
277 output->set("sz", info.sz);
278 output->set("parent", info.parent);
279 Poco::JSON::Array::Ptr children = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
280 for (const auto& child : info.children) children->add(child);
281 output->set("children", children);
282 return output;
283}
284
285Poco::JSON::Object::Ptr runtimeObservation(Poco::JSON::Object::Ptr args, std::string* error) {
286 const std::string observer = getArgString(args, "observer", "renderable3d");
287 if (observer == "renderable3d") {
288 auto* capture = mcpCapture();
289 if (!capture) {
290 if (error) *error = "graphics module not available";
291 return nullptr;
292 }
293 const int entityId = getArgInt(args, "entityId", -1);
294 const int generation = getArgInt(args, "generation", -1);
295 if (entityId < 0 || generation < 0) {
296 if (error) *error = "entityId and generation are required";
297 return nullptr;
298 }
299 auto output = renderableObservation(*capture, entityId, generation);
300 output->set("observer", observer);
301 return output;
302 }
303 if (observer == "scene-node") {
304 auto* scene = mcpScene();
305 if (!scene) {
306 if (error) *error = "scene module not available";
307 return nullptr;
308 }
309 return sceneNodeObservation(*scene, getArgString(args, "host"), getArgString(args, "node"));
310 }
311 if (error) *error = "unsupported observer: " + observer;
312 return nullptr;
313}
314
315struct ExpectationMatch {
316 bool valid = true;
317 double maxError = 0.0;
318 std::vector<std::string> mismatches;
319 std::string error;
320};
321
322bool isJsonObject(const Poco::Dynamic::Var& value) { return value.type() == typeid(Poco::JSON::Object::Ptr); }
323
324bool isJsonArray(const Poco::Dynamic::Var& value) { return value.type() == typeid(Poco::JSON::Array::Ptr); }
325
326void compareExpectation(const Poco::Dynamic::Var& actual, const Poco::Dynamic::Var& expected, const std::string& path,
327 double tolerance, ExpectationMatch* match) {
328 if (!match || !match->valid) return;
329 if (isJsonObject(expected)) {
330 if (!isJsonObject(actual)) {
331 match->valid = false;
332 match->error = "Expected object at " + path;
333 return;
334 }
335 auto actualObject = actual.extract<Poco::JSON::Object::Ptr>();
336 auto expectedObject = expected.extract<Poco::JSON::Object::Ptr>();
337 for (const auto& item : *expectedObject) {
338 const std::string childPath = path.empty() ? item.first : path + "." + item.first;
339 if (!actualObject->has(item.first)) {
340 match->valid = false;
341 match->error = "Observed value has no field " + childPath;
342 return;
343 }
344 compareExpectation(actualObject->get(item.first), item.second, childPath, tolerance, match);
345 }
346 return;
347 }
348 if (isJsonArray(expected)) {
349 if (!isJsonArray(actual)) {
350 match->valid = false;
351 match->error = "Expected array at " + path;
352 return;
353 }
354 auto actualArray = actual.extract<Poco::JSON::Array::Ptr>();
355 auto expectedArray = expected.extract<Poco::JSON::Array::Ptr>();
356 if (actualArray->size() < expectedArray->size()) {
357 match->valid = false;
358 match->error = "Observed array is shorter than expectation at " + path;
359 return;
360 }
361 for (std::size_t index = 0; index < expectedArray->size(); ++index) {
362 compareExpectation(actualArray->get(static_cast<unsigned>(index)),
363 expectedArray->get(static_cast<unsigned>(index)),
364 path + "[" + std::to_string(index) + "]", tolerance, match);
365 }
366 return;
367 }
368 if (expected.isNumeric()) {
369 if (!actual.isNumeric()) {
370 match->valid = false;
371 match->error = "Expected numeric value at " + path;
372 return;
373 }
374 const double error = std::abs(actual.convert<double>() - expected.convert<double>());
375 match->maxError = std::max(match->maxError, error);
376 if (error > tolerance) match->mismatches.push_back(path);
377 return;
378 }
379 if (expected.isBoolean()) {
380 if (!actual.isBoolean()) {
381 match->valid = false;
382 match->error = "Expected boolean value at " + path;
383 return;
384 }
385 if (actual.convert<bool>() != expected.convert<bool>()) match->mismatches.push_back(path);
386 return;
387 }
388 if (expected.isString()) {
389 if (!actual.isString()) {
390 match->valid = false;
391 match->error = "Expected string value at " + path;
392 return;
393 }
394 if (actual.convert<std::string>() != expected.convert<std::string>()) match->mismatches.push_back(path);
395 return;
396 }
397 if (expected.isEmpty()) {
398 if (!actual.isEmpty()) match->mismatches.push_back(path);
399 return;
400 }
401 match->valid = false;
402 match->error = "Unsupported expectation value at " + path;
403}
404
405Poco::JSON::Object::Ptr expectationValue(const ExpectationMatch& match) {
406 Poco::JSON::Object::Ptr output = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
407 output->set("valid", match.valid);
408 output->set("converged", match.valid && match.mismatches.empty());
409 output->set("maxError", match.maxError);
410 Poco::JSON::Array::Ptr mismatches = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
411 for (const auto& path : match.mismatches) mismatches->add(path);
412 output->set("mismatches", mismatches);
413 if (!match.error.empty()) output->set("error", match.error);
414 return output;
415}
416
417Poco::JSON::Object::Ptr observationEvent(Poco::JSON::Object::Ptr descriptor, Poco::JSON::Object::Ptr observation,
418 std::string* error) {
419 Poco::JSON::Object::Ptr event = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
420 event->set("observation", observation);
421 if (!observation || observation->optValue<std::string>("status", "unavailable") != "ok") {
422 event->set("status", "observation-unavailable");
423 event->set("converged", false);
424 return event;
425 }
426 if (!descriptor || !descriptor->has("expect")) return event;
427
428 double tolerance = 0.001;
429 if (descriptor->has("tolerance")) {
430 try {
431 tolerance = descriptor->get("tolerance").convert<double>();
432 } catch (...) {
433 tolerance = -1.0;
434 }
435 }
436 if (!std::isfinite(tolerance) || tolerance < 0.0) {
437 if (error) *error = "tolerance must be a finite non-negative number";
438 return nullptr;
439 }
440 const Poco::Dynamic::Var expected = descriptor->get("expect");
441 if (!isJsonObject(expected)) {
442 if (error) *error = "expect must be a JSON object";
443 return nullptr;
444 }
445 ExpectationMatch match;
446 compareExpectation(Poco::Dynamic::Var(observation), expected, "", tolerance, &match);
447 if (!match.valid) {
448 if (error) *error = match.error;
449 return nullptr;
450 }
451 event->set("expectation", expectationValue(match));
452 event->set("converged", match.mismatches.empty());
453 event->set("maxError", match.maxError);
454 return event;
455}
456
457std::string callTool(McpServer& mcp, const std::string& name, Poco::JSON::Object::Ptr args) {
458 auto& dbg = Debugger::instance();
459 auto& dap = DebugAdapter::instance();
460
461 if (name == "eve_status") return engineStatusJson(mcp);
462
463 if (name == "eve_api_search") {
464 const std::string query = getArgString(args, "query");
465 const std::string module = getArgString(args, "module");
466 const std::string scriptClass = getArgString(args, "class");
467 int limit = getArgInt(args, "limit", 20);
468 if (limit < 0) limit = 0;
469 const auto hits =
470 eve::script::generatedBindingContracts().search(query, module, scriptClass, static_cast<size_t>(limit));
471 std::ostringstream json;
472 json << "{\"ok\":true,\"schema\":\"eve.binding-api\",\"schemaVersion\":1,\"query\":\"" << mcpJsonEscape(query)
473 << "\",\"module\":\"" << mcpJsonEscape(module) << "\",\"class\":\"" << mcpJsonEscape(scriptClass)
474 << "\",\"count\":" << hits.size() << ",\"matches\":[";
475 for (size_t i = 0; i < hits.size(); ++i) {
476 if (i != 0) json << ',';
477 json << "{\"score\":" << hits[i].score << ",\"contract\":" << hits[i].contract.toJson() << '}';
478 }
479 json << "]}";
480 return json.str();
481 }
482
483 if (name == "eve_api_get") {
484 const std::string key = getArgString(args, "key");
485 const std::string scriptClass = getArgString(args, "class");
486 const std::string method = getArgString(args, "method");
488 const eve::script::BindingContract* contract = nullptr;
489 std::string lookupKey = key;
490 if (!key.empty()) {
492 // Agents often write slot.method or module.Class.method; accept those spellings.
493 if (!contract) {
494 const auto slash = key.find('/');
495 if (slash == std::string::npos) {
496 const auto firstDot = key.find('.');
497 if (firstDot != std::string::npos) {
498 lookupKey = key;
499 lookupKey[firstDot] = '/';
500 contract = registry.find(lookupKey);
501 }
502 }
503 }
504 } else if (!scriptClass.empty() && !method.empty()) {
505 contract = registry.findMethod(scriptClass, method);
506 } else if (!method.empty()) {
508 } else {
509 return "{\"ok\":false,\"error\":\"missing key or method\"}";
510 }
511 if (!contract) {
512 std::string needle = !key.empty() ? key : (!scriptClass.empty() ? scriptClass + "." + method : method);
513 for (char& ch : needle) {
514 if (ch == '/' || ch == '.') ch = ' ';
515 }
516 const auto hits = registry.search(needle, {}, {}, 5);
517 std::ostringstream json;
518 json << "{\"ok\":false,\"error\":\"binding not found or method name is ambiguous\"";
519 if (!hits.empty()) {
520 json << ",\"suggestions\":[";
521 for (size_t i = 0; i < hits.size(); ++i) {
522 if (i != 0) json << ',';
523 json << "{\"score\":" << hits[i].score << ",\"key\":\"" << mcpJsonEscape(hits[i].contract.key())
524 << "\"}";
525 }
526 json << "]";
527 }
528 json << "}";
529 return json.str();
530 }
531 return std::string("{\"ok\":true,\"schema\":\"eve.binding-api\",\"schemaVersion\":1,\"contract\":") +
532 contract->toJson() + "}";
533 }
534
535 // 引擎侧脚本组件数据的工具视图(J-3 的"引擎工具读得到")。没有脚本 VM 时是空列表,不是错误。
536 if (name == "eve_script_components") {
538 return payload ? std::move(payload).takeValue() : std::string("error: ") + payload.status().describe();
539 }
540
541 if (name == "eve_gameplay") {
542 if (!args || !args->has("request")) return "error: missing request";
543 std::string request;
544 try {
545 request = mcpStringify(args->get("request"));
546 } catch (const std::exception& error) {
547 return std::string("error: invalid request: ") + error.what();
548 }
550 return response ? std::move(response).takeValue() : std::string("error: ") + response.status().describe();
551 }
552
553 if (name == "eve_play") {
554 if (!args || !args->has("request")) return "error: missing request";
555 std::string request;
556 try {
557 request = mcpStringify(args->get("request"));
558 } catch (const std::exception& error) {
559 return std::string("error: invalid request: ") + error.what();
560 }
562 return response ? std::move(response).takeValue() : std::string("error: ") + response.status().describe();
563 }
564
565 if (name.rfind("eve_pixelworld_", 0) == 0) {
566 auto* provider = mcpPixelWorld();
567 if (!provider) return "{\"ok\":false,\"error\":\"pixelworld module not available\"}";
568 return provider->invoke(name.substr(std::string("eve_pixelworld_").size()),
569 mcpStringify(Poco::Dynamic::Var(args)));
570 }
571
572 // ============================= Game UI =============================
573 if (name == "eve_ui_tree") {
574 return mcpUI() ? mcpUI()->tree(getArgString(args, "host")) : "error: ui module not available";
575 }
576 if (name == "eve_ui_get") {
577 return mcpUI() ? mcpUI()->get(getArgString(args, "host"), getArgString(args, "widget"))
578 : "error: ui module not available";
579 }
580 if (name == "eve_ui_click") {
581 return mcpUI() ? mcpUI()->click(getArgString(args, "host"), getArgString(args, "widget"))
582 : "error: ui module not available";
583 }
584
585 // ============================= Editor command protocol =============================
586 const auto editorInvoke = [&](const char* operation) {
587 return mcpEditor() ? mcpEditor()->invoke(operation, mcpStringify(Poco::Dynamic::Var(args)))
588 : std::string("error: editor module not available");
589 };
590 if (name == "eve_editor_commands") return editorInvoke("commands");
591 if (name == "eve_editor_target_list") return editorInvoke("target-list");
592 if (name == "eve_editor_target_create") return editorInvoke("target-create");
593 if (name == "eve_editor_target_close") return editorInvoke("target-close");
594 if (name == "eve_editor_inspect") return editorInvoke("inspect");
595 if (name == "eve_editor_plan") return editorInvoke("plan");
596 if (name == "eve_editor_commit") return editorInvoke("commit");
597 if (name == "eve_editor_execute") return editorInvoke("execute");
598 if (name == "eve_editor_observe_start") {
599 auto* editor = mcpEditor();
600 if (!editor) return "error: editor module not available";
601 std::string error;
602 Poco::JSON::Object::Ptr observation = runtimeObservation(args, &error);
603 if (!observation) return "error: " + error;
604 if (observation->getValue<std::string>("status") != "ok") return mcpStringify(Poco::Dynamic::Var(observation));
605 Poco::JSON::Object::Ptr event = observationEvent(args, observation, &error);
606 if (!event) {
607 Poco::JSON::Object::Ptr invalid = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
608 invalid->set("status", "invalid-expectation");
609 invalid->set("error", error);
610 invalid->set("observation", observation);
611 return mcpStringify(Poco::Dynamic::Var(invalid));
612 }
613 Poco::JSON::Object::Ptr request = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
614 request->set("descriptor", args);
615 request->set("event", event);
616 return editor->invoke("observe-start", mcpStringify(Poco::Dynamic::Var(request)));
617 }
618 if (name == "eve_editor_observe_poll") {
619 auto* editor = mcpEditor();
620 if (!editor) return "error: editor module not available";
621 try {
622 Poco::JSON::Parser describeParser;
623 Poco::Dynamic::Var described =
624 describeParser.parse(editor->invoke("observe-describe", mcpStringify(Poco::Dynamic::Var(args))));
625 auto describedObject = described.extract<Poco::JSON::Object::Ptr>();
626 if (!describedObject || describedObject->optValue<std::string>("status", "") != "applied")
627 return mcpStringify(described);
628 auto descriptor = describedObject->getObject("descriptor");
629 std::string error;
630 Poco::JSON::Object::Ptr observation = runtimeObservation(descriptor, &error);
631 if (!observation) {
632 observation = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
633 observation->set("status", "unavailable");
634 observation->set("error", error);
635 }
636 Poco::JSON::Object::Ptr event = observationEvent(descriptor, observation, &error);
637 if (!event) {
638 event = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
639 event->set("observation", observation);
640 event->set("status", "expectation-observation-failed");
641 event->set("error", error);
642 }
643 Poco::JSON::Object::Ptr publish = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
644 publish->set("sessionId", getArgString(args, "sessionId"));
645 publish->set("event", event);
646 Poco::JSON::Parser publishParser;
647 Poco::Dynamic::Var published =
648 publishParser.parse(editor->invoke("observe-publish", mcpStringify(Poco::Dynamic::Var(publish))));
649 auto publishedObject = published.extract<Poco::JSON::Object::Ptr>();
650 if (!publishedObject || publishedObject->optValue<std::string>("status", "") != "applied")
651 return mcpStringify(published);
652 return editor->invoke("observe-poll", mcpStringify(Poco::Dynamic::Var(args)));
653 } catch (const std::exception& exception) {
654 return std::string("error: could not poll observation session: ") + exception.what();
655 }
656 }
657 if (name == "eve_editor_observe_close") return editorInvoke("observe-close");
658 if (name == "eve_editor_execute_observe") {
659 auto* editor = mcpEditor();
660 if (!editor) return "error: editor module not available";
661 std::string error;
662 Poco::JSON::Object::Ptr before = runtimeObservation(args, &error);
663 if (!before) return "error: " + error;
664 if (before->getValue<std::string>("status") != "ok") return mcpStringify(Poco::Dynamic::Var(before));
665
666 Poco::JSON::Object::Ptr output = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
667 output->set("before", before);
668 const bool hasExpectation = args && args->has("expect");
669 double tolerance = 0.001;
670 if (args && args->has("tolerance")) {
671 try {
672 tolerance = args->get("tolerance").convert<double>();
673 } catch (...) {
674 tolerance = -1.0;
675 }
676 }
677 if (!std::isfinite(tolerance) || tolerance < 0.0) {
678 output->set("status", "invalid-expectation");
679 output->set("error", "tolerance must be a finite non-negative number");
680 return mcpStringify(Poco::Dynamic::Var(output));
681 }
682 Poco::Dynamic::Var expected;
683 if (hasExpectation) {
684 expected = args->get("expect");
685 if (!isJsonObject(expected)) {
686 output->set("status", "invalid-expectation");
687 output->set("error", "expect must be a JSON object");
688 return mcpStringify(Poco::Dynamic::Var(output));
689 }
690 ExpectationMatch validation;
691 compareExpectation(Poco::Dynamic::Var(before), expected, "", tolerance, &validation);
692 if (!validation.valid) {
693 output->set("status", "invalid-expectation");
694 output->set("expectation", expectationValue(validation));
695 output->set("error", validation.error);
696 return mcpStringify(Poco::Dynamic::Var(output));
697 }
698 }
699 bool transactionAccepted = false;
700 try {
701 Poco::JSON::Parser parser;
702 Poco::Dynamic::Var transaction =
703 parser.parse(editor->invoke("execute", mcpStringify(Poco::Dynamic::Var(args))));
704 output->set("transaction", transaction);
705 Poco::JSON::Object::Ptr transactionObject = transaction.extract<Poco::JSON::Object::Ptr>();
706 transactionAccepted = transactionObject && transactionObject->optValue<bool>("accepted", false);
707 output->set("status", transactionAccepted ? "observed" : "transaction-rejected");
708 } catch (const std::exception& exception) {
709 output->set("status", "failed");
710 output->set("error", std::string("Could not parse Editor transaction response: ") + exception.what());
711 }
712 error.clear();
713 Poco::JSON::Object::Ptr after = runtimeObservation(args, &error);
714 if (!after) {
715 after = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
716 after->set("status", "unavailable");
717 after->set("error", error);
718 }
719 output->set("after", after);
720 if (transactionAccepted && after->getValue<std::string>("status") != "ok")
721 output->set("status", "runtime-observation-failed");
722 if (hasExpectation && after->getValue<std::string>("status") == "ok") {
723 ExpectationMatch match;
724 compareExpectation(Poco::Dynamic::Var(after), expected, "", tolerance, &match);
725 output->set("expectation", expectationValue(match));
726 output->set("converged", match.valid && match.mismatches.empty());
727 output->set("maxError", match.maxError);
728 if (!match.valid) {
729 output->set("status", "expectation-observation-failed");
730 output->set("error", match.error);
731 }
732 } else if (hasExpectation) {
733 output->set("converged", false);
734 }
735 try {
736 Poco::JSON::Parser parser;
737 Poco::Dynamic::Var editorState =
738 parser.parse(editor->invoke("inspect", mcpStringify(Poco::Dynamic::Var(args))));
739 output->set("editor", editorState);
740 } catch (const std::exception& exception) {
741 output->set("editorError", std::string("Could not parse Editor observation: ") + exception.what());
742 }
743 return mcpStringify(Poco::Dynamic::Var(output));
744 }
745 if (name == "eve_editor_cancel") return editorInvoke("cancel");
746 if (name == "eve_editor_undo") return editorInvoke("undo");
747 if (name == "eve_editor_redo") return editorInvoke("redo");
748 if (name == "eve_editor_diagnostics") return editorInvoke("diagnostics");
749
750 if (name == "eve_renderable3d_get") {
751 auto* capture = mcpCapture();
752 if (!capture) return "error: graphics module not available";
753 const int entityId = getArgInt(args, "entityId", -1);
754 const int generation = getArgInt(args, "generation", -1);
755 if (entityId < 0 || generation < 0) return "error: entityId and generation are required";
756 return mcpStringify(Poco::Dynamic::Var(renderableObservation(*capture, entityId, generation)));
757 }
758
759 // ============================= Scene / Entity =============================
760 if (name == "eve_scene_status") {
761 auto* scene = mcpScene();
762 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
763 if (!scene) {
764 o->set("error", "Scene module not available");
765 return mcpStringify(Poco::Dynamic::Var(o));
766 }
767 const std::string host = scene->activeHost();
768 if (host.empty()) {
769 o->set("activeHost", Poco::Dynamic::Var());
770 o->set("nodeCount", 0);
771 return mcpStringify(Poco::Dynamic::Var(o));
772 }
773 o->set("activeHost", host);
774 o->set("nodeCount", scene->nodeCount());
775 o->set("rootId", scene->rootId());
776 return mcpStringify(Poco::Dynamic::Var(o));
777 }
778
779 if (name == "eve_scene_nodes") {
780 auto* scene = mcpScene();
781 if (!scene || scene->activeHost().empty()) return "error: no active scene host";
782 const int limit = getArgInt(args, "limit", 500);
783 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
784 for (const auto& n : scene->nodes(limit)) {
785 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
786 o->set("id", n.id);
787 o->set("name", n.name);
788 o->set("path", n.path);
789 o->set("visible", n.visible);
790 arr->add(o);
791 }
792 return mcpStringify(Poco::Dynamic::Var(arr));
793 }
794
795 if (name == "eve_scene_node_get") {
796 auto* scene = mcpScene();
797 if (!scene || scene->activeHost().empty()) return "error: no active scene host";
798 const std::string id = getArgString(args, "id");
799 if (id.empty()) return "error: node not found: " + id;
800 auto lookedUp = scene->getNode(id);
801 if (!lookedUp) return "error: node not found: " + id;
802 const eve::SceneNodeInfo n = std::move(lookedUp).value();
803 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
804 o->set("id", n.id);
805 o->set("name", n.name);
806 o->set("path", n.path);
807 o->set("visible", n.visible);
808 o->set("x", n.x);
809 o->set("y", n.y);
810 o->set("z", n.z);
811 o->set("yaw", n.yaw);
812 o->set("pitch", n.pitch);
813 o->set("roll", n.roll);
814 o->set("sx", n.sx);
815 o->set("sy", n.sy);
816 o->set("sz", n.sz);
817 o->set("parent", n.parent);
818 Poco::JSON::Array::Ptr kids = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
819 for (const auto& c : n.children) kids->add(c);
820 o->set("children", kids);
821 return mcpStringify(Poco::Dynamic::Var(o));
822 }
823
824 if (name == "eve_scene_node_set") {
825 auto* scene = mcpScene();
826 if (!scene || scene->activeHost().empty()) return "error: no active scene host";
827 const std::string id = getArgString(args, "id");
828 if (id.empty()) return "error: node not found: " + id;
829 bool changed = false;
830 if (args && args->has("x") && args->has("y") && args->has("z")) {
831 if (scene->setNodeTransform(id, getArgFloat(args, "x"), getArgFloat(args, "y"), getArgFloat(args, "z")))
832 changed = true;
833 }
834 if (args && args->has("visible")) {
835 if (scene->setNodeVisible(id, getArgBool(args, "visible"))) changed = true;
836 }
837 return changed ? "ok" : "error: node not found: " + id;
838 }
839
840 // ============================= Procgen =============================
841 if (name == "eve_procgen_recipes") {
842 auto* pg = mcpProcgen();
843 if (!pg) return "error: Procgen module not available";
844 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
845 auto addList = [&](const char* key, const std::vector<std::string>& items) {
846 Poco::JSON::Array::Ptr a = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
847 for (const auto& it : items) a->add(it);
848 o->set(key, a);
849 };
850 addList("algorithms", pg->algorithms());
851 addList("meshRecipes", pg->meshRecipes());
852 addList("textureRecipes", pg->textureRecipes());
853 addList("pbrRecipes", pg->pbrRecipes());
854 return mcpStringify(Poco::Dynamic::Var(o));
855 }
856
857 if (name == "eve_procgen_map") {
858 auto* pg = mcpProcgen();
859 if (!pg) return "error: Procgen module not available";
860 const std::string algorithm = getArgString(args, "algorithm");
861 if (algorithm.empty()) return "error: missing algorithm";
862 std::vector<std::pair<std::string, std::string>> params;
863 for (const auto& key : {"roomCount", "roomMin", "roomMax", "corridorWidth", "autotile", "scale", "octaves"}) {
864 if (args && args->has(key)) params.emplace_back(key, std::to_string(getArgInt(args, key)));
865 }
866 if (args && args->has("corridorStyle"))
867 params.emplace_back("corridorStyle", getArgString(args, "corridorStyle"));
868 auto generated = pg->generateMap(algorithm, getArgInt(args, "width", 32), getArgInt(args, "height", 32),
869 static_cast<uint32_t>(getArgInt(args, "seed", 0)), params);
870 if (!generated) {
871 const auto* diag = generated.status().primaryDiagnostic();
872 return "error: " + (diag ? diag->message() : generated.status().describe());
873 }
874 return std::move(generated).value();
875 }
876
877 if (name == "eve_procgen_mesh") {
878 auto* pg = mcpProcgen();
879 if (!pg) return "error: Procgen module not available";
880 const std::string recipe = getArgString(args, "recipe");
881 if (recipe.empty()) return "error: missing recipe";
882 auto built =
883 pg->buildMesh(recipe, static_cast<uint32_t>(getArgInt(args, "seed", 0)), getArgInt(args, "width", -1),
884 getArgInt(args, "height", -1), getArgInt(args, "depth", -1));
885 if (!built) {
886 const auto* diag = built.status().primaryDiagnostic();
887 return "error: " + (diag ? diag->message() : built.status().describe());
888 }
889 const std::string json = std::move(built).value();
890 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
891 o->set("recipe", recipe);
892 try {
893 Poco::JSON::Parser parser;
894 Poco::Dynamic::Var parsed = parser.parse(json);
895 Poco::JSON::Object::Ptr jo = parsed.extract<Poco::JSON::Object::Ptr>();
896 o->set("vertices", jo->get("vertices"));
897 o->set("triangles", jo->get("triangles"));
898 } catch (...) {
899 return json;
900 }
901 return mcpStringify(Poco::Dynamic::Var(o));
902 }
903
904 // ============================= Physics =============================
905 if (name == "eve_physics_new_world") {
906 auto* ph = mcpPhysics();
907 if (!ph) return "error: Physics module not available";
908 const int id = ph->newWorld(getArgFloat(args, "gravityX", 0.f), getArgFloat(args, "gravityY", 900.f));
909 if (id < 0) return "error: failed to create world";
910 float gx = 0.f, gy = 0.f;
911 ph->worldGravity(id, &gx, &gy);
912 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
913 o->set("id", id);
914 o->set("gravityX", gx);
915 o->set("gravityY", gy);
916 return mcpStringify(Poco::Dynamic::Var(o));
917 }
918
919 if (name == "eve_physics_list_worlds") {
920 auto* ph = mcpPhysics();
921 if (!ph) return "error: Physics module not available";
922 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
923 for (int i = 0; i < ph->worldCount(); ++i) {
924 float gx = 0.f, gy = 0.f;
925 if (!ph->worldGravity(i, &gx, &gy)) continue;
926 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
927 o->set("id", i);
928 o->set("gravityX", gx);
929 o->set("gravityY", gy);
930 arr->add(o);
931 }
932 return mcpStringify(Poco::Dynamic::Var(arr));
933 }
934
935 if (name == "eve_physics_raycast") {
936 auto* ph = mcpPhysics();
937 if (!ph) return "error: Physics module not available";
939 if (!ph->rayCast(getArgInt(args, "world", 0), getArgFloat(args, "x1"), getArgFloat(args, "y1"),
940 getArgFloat(args, "x2"), getArgFloat(args, "y2"), &h))
941 return "error: unknown physics world id";
942 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
943 o->set("hit", h.hit);
944 if (h.hit) {
945 o->set("bodyId", h.bodyId);
946 o->set("x", h.x);
947 o->set("y", h.y);
948 o->set("normalX", h.normalX);
949 o->set("normalY", h.normalY);
950 o->set("fraction", h.fraction);
951 }
952 return mcpStringify(Poco::Dynamic::Var(o));
953 }
954
955 if (name == "eve_physics_remove_world") {
956 auto* ph = mcpPhysics();
957 if (!ph) return "error: Physics module not available";
958 return ph->removeWorld(getArgInt(args, "world", -1)) ? "ok" : "error: unknown physics world id";
959 }
960
961 // ============================= Render =============================
962 if (name == "eve_render_status") {
963 return renderStatusText(mcpCapture());
964 }
965
966 if (name == "eve_render_describe") {
967 const bool fresh = getArgBool(args, "fresh", false);
968 const std::string reason = getArgString(args, "reason");
969 return RenderVision::instance().describe(mcpCapture(), renderStatusText(mcpCapture()), fresh, reason);
970 }
971
972 if (name == "eve_render_vision_config") {
973 auto& rv = RenderVision::instance();
974 if (args && args->has("baseUrl")) rv.setBaseUrl(getArgString(args, "baseUrl"));
975 if (args && args->has("apiKey")) rv.setApiKey(getArgString(args, "apiKey"));
976 if (args && args->has("model")) rv.setModel(getArgString(args, "model"));
977 if (args && args->has("path")) rv.setPath(getArgString(args, "path"));
978 if (args && args->has("timeoutMs")) rv.setTimeoutMs(getArgInt(args, "timeoutMs", 20000));
979 return rv.configJson();
980 }
981
982 if (name == "eve_screenshot") {
983 auto* cap = mcpCapture();
984 if (!cap) return "error: Graphics module not available";
985 std::string path = getArgString(args, "path");
986 if (path.empty()) path = "mcp_screenshot.png";
987 // A relative path resolves against the project root: the host process may
988 // run from any working directory, and an agent has to be able to read the
989 // artifact back from the path it receives.
990 if (std::filesystem::path(path).is_relative() && !mcp.gameRoot().empty())
991 path = (std::filesystem::path(mcp.gameRoot()) / path).string();
992 // Report one separator convention: the project root already uses '/',
993 // and agents echo this path back into file tooling.
994 for (char& c : path) {
995 if (c == '\\') c = '/';
996 }
997
998 const eve::RenderStatusInfo status = cap->status();
999 auto captured = cap->savePng(path);
1000 if (!captured) {
1001 // Enabling readback and reading it back cannot happen inside one
1002 // presented frame: the swapchain copy is recorded by the next
1003 // present. Report that as a retryable state instead of a failure so
1004 // an unattended loop keeps polling instead of giving up.
1005 const bool retryable = !status.readbackEnabled;
1006 const auto* diag = captured.status().primaryDiagnostic();
1007 Poco::JSON::Object::Ptr o =
1008 mcpFailureObject(retryable ? "no-presented-frame" : "capture-failed",
1009 retryable ? "Wait one rendered frame and call eve_screenshot again"
1010 : "Check eve_render_status / graphics readiness, then retry",
1011 retryable, {"eve_render_status", "eve_screenshot"});
1012 o->set("reason", retryable ? "no-presented-frame" : "capture-failed");
1013 o->set("readbackEnabled", status.readbackEnabled);
1014 o->set("message", diag ? diag->message() : captured.status().describe());
1015 const std::string payload = mcpStringify(Poco::Dynamic::Var(o));
1016 return retryable ? payload : "error: " + payload;
1017 }
1018 const eve::CaptureImageInfo info = std::move(captured).value();
1019
1020 std::error_code sizeError;
1021 const auto bytes = std::filesystem::file_size(path, sizeError);
1022 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1023 o->set("ok", true);
1024 o->set("path", path);
1025 o->set("bytes", sizeError ? Poco::Int64(0) : static_cast<Poco::Int64>(bytes));
1026 o->set("width", info.width);
1027 o->set("height", info.height);
1028 return mcpStringify(Poco::Dynamic::Var(o));
1029 }
1030
1031 // ============================= Particles / Weather =============================
1032 if (name == "eve_particles_status") {
1033 auto* part = mcpParticles();
1034 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1035 if (!part) {
1036 o->set("error", "Particles module not available");
1037 return mcpStringify(Poco::Dynamic::Var(o));
1038 }
1039 o->set("emitterCount", part->emitterCount());
1040 return mcpStringify(Poco::Dynamic::Var(o));
1041 }
1042
1043 if (name == "eve_particles_emit") {
1044 auto* part = mcpParticles();
1045 if (!part) return "error: Particles module not available";
1046 float ex = 0.f, ey = 0.f;
1047 int cnt = 0;
1048 if (!part->createEmitter(getArgInt(args, "buffer", 1000), getArgFloat(args, "x"), getArgFloat(args, "y"),
1049 getArgString(args, "preset"), getArgInt(args, "count", 100), &ex, &ey, &cnt))
1050 return "error: failed to create emitter";
1051 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1052 o->set("x", ex);
1053 o->set("y", ey);
1054 o->set("count", cnt);
1055 return mcpStringify(Poco::Dynamic::Var(o));
1056 }
1057
1058 // ============================= Audio =============================
1059 if (name == "eve_audio_status") {
1060 auto* audio = mcpAudio();
1061 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1062 if (!audio) {
1063 o->set("error", "Audio module not available");
1064 return mcpStringify(Poco::Dynamic::Var(o));
1065 }
1066 o->set("volume", audio->volume());
1067 return mcpStringify(Poco::Dynamic::Var(o));
1068 }
1069
1070 if (name == "eve_audio_set_volume") {
1071 auto* audio = mcpAudio();
1072 if (!audio) return "error: Audio module not available";
1073 audio->setVolume(getArgFloat(args, "volume", 1.f));
1074 return "ok";
1075 }
1076
1077 if (name == "eve_audio_stop_all") {
1078 auto* audio = mcpAudio();
1079 if (!audio) return "error: Audio module not available";
1080 audio->stopAll();
1081 return "ok";
1082 }
1083
1084 // ============================= Host UI (headless MCP editor host) =====
1085 if (name == "eve_host_status") {
1086 return mcpHost() ? mcpHost()->status() : "error: ui module not available";
1087 }
1088 if (name == "eve_host_window_open") {
1089 const std::string title = getArgString(args, "title", "EVEngine AI Host");
1090 return mcpHost() ? mcpHost()->openWindow(title, getArgInt(args, "width", 1280), getArgInt(args, "height", 800))
1091 : "error: ui module not available";
1092 }
1093 if (name == "eve_host_window_close") {
1094 return mcpHost() ? mcpHost()->closeWindow() : "error: ui module not available";
1095 }
1096 if (name == "eve_host_window_state") {
1097 return mcpHost() ? mcpHost()->windowState() : "error: ui module not available";
1098 }
1099 if (name == "eve_host_editor_apply") {
1100 std::string json;
1101 if (args && args->has("editor")) {
1102 try {
1103 Poco::JSON::Object::Ptr o = args->getObject("editor");
1104 if (o)
1105 json = mcpStringify(Poco::Dynamic::Var(o));
1106 else
1107 json = getArgString(args, "editor");
1108 } catch (...) {
1109 json = getArgString(args, "editor");
1110 }
1111 }
1112 if (json.empty()) return "error: missing editor";
1113 return mcpHost() ? mcpHost()->applyEditor(json) : "error: ui module not available";
1114 }
1115 if (name == "eve_host_editor_remove") {
1116 return mcpHost() ? mcpHost()->removeEditor(getArgString(args, "id")) : "error: ui module not available";
1117 }
1118 if (name == "eve_host_editor_list") {
1119 return mcpHost() ? mcpHost()->listEditors() : "error: ui module not available";
1120 }
1121 if (name == "eve_host_editor_state") {
1122 return mcpHost() ? mcpHost()->editorState(getArgString(args, "id")) : "error: ui module not available";
1123 }
1124 if (name == "eve_host_editor_set_value") {
1125 if (!args || !args->has("value")) return "error: missing value";
1126 return mcpHost() ? mcpHost()->setEditorValue(getArgString(args, "editor"), getArgString(args, "widget"),
1127 mcpStringify(getArgVar(args, "value")))
1128 : "error: ui module not available";
1129 }
1130 if (name == "eve_host_editor_save") {
1131 return mcpHost() ? mcpHost()->saveEditor(getArgString(args, "id")) : "error: ui module not available";
1132 }
1133 if (name == "eve_host_editor_unload") {
1134 return mcpHost() ? mcpHost()->unloadEditor(getArgString(args, "id")) : "error: ui module not available";
1135 }
1136 if (name == "eve_host_vm_register") {
1137 return mcpHost() ? mcpHost()->registerVM(getArgString(args, "name"), getArgString(args, "source"))
1138 : "error: ui module not available";
1139 }
1140 if (name == "eve_host_vm_unregister") {
1141 return mcpHost() ? mcpHost()->unregisterVM(getArgString(args, "name")) : "error: ui module not available";
1142 }
1143 if (name == "eve_host_events") {
1144 return mcpHost() ? mcpHost()->consumeEvents(getArgString(args, "editor")) : "error: ui module not available";
1145 }
1146 if (name == "eve_host_widget_rect") {
1147 return mcpHost() ? mcpHost()->widgetRect(getArgString(args, "editor"), getArgString(args, "widget"))
1148 : "error: ui module not available";
1149 }
1150 if (name == "eve_host_capture") {
1151 return mcpHost() ? mcpHost()->capture(getArgString(args, "path")) : "error: ui module not available";
1152 }
1153 if (name == "eve_host_script") {
1154 return mcpHost() ? mcpHost()->runScript(getArgString(args, "source")) : "error: ui module not available";
1155 }
1156 if (name == "eve_host_resource_reload") {
1157 return mcpHost() ? mcpHost()->reloadResource(getArgString(args, "path")) : "error: ui module not available";
1158 }
1159 if (name == "eve_host_hot_reload_status") {
1160 return mcpHost() ? mcpHost()->hotReloadStatus() : "error: ui module not available";
1161 }
1162 if (name == "eve_host_shutdown") {
1163 if (mcpHost()) mcpHost()->requestExit();
1164 return "ok";
1165 }
1166
1167 if (name == "eve_eval") {
1168 const std::string expr = getArgString(args, "expression");
1169 if (expr.empty()) return "error: missing expression";
1170 auto info = dbg.evaluate(expr);
1171 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1172 o->set("expression", expr);
1173 o->set("name", info.name);
1174 o->set("value", info.value);
1175 o->set("type", info.type);
1176 o->set("ok", !info.value.empty() || info.type == "null" || !info.name.empty());
1177 return mcpStringify(Poco::Dynamic::Var(o));
1178 }
1179
1180 if (name == "eve_skeleton_inspect") {
1181 const std::string actor = getArgString(args, "actor");
1182 const std::string bone = getArgString(args, "bone");
1183 if (actor.empty()) return "error: missing actor";
1184 const std::string expr =
1185 "eve_mcp_skeleton_inspect(\"" + mcpJsonEscape(actor) + "\",\"" + mcpJsonEscape(bone) + "\")";
1186 auto info = dbg.evaluate(expr);
1187 if (info.value.empty()) return "error: eve_mcp_skeleton_inspect is unavailable";
1188 // Debugger string values are display-quoted. The project hook returns
1189 // canonical JSON, so remove only that outer presentation pair.
1190 if (info.value.size() >= 2 && info.value.front() == '"' && info.value.back() == '"')
1191 return info.value.substr(1, info.value.size() - 2);
1192 return info.value;
1193 }
1194
1195 if (name == "eve_pause") {
1196 dbg.pause(PauseReason::PauseKey);
1197 dap.notifyStopped(PauseReason::PauseKey, dbg.pauseLocation());
1198 return "paused";
1199 }
1200 if (name == "eve_continue") {
1201 dbg.resume();
1202 dap.notifyContinued();
1203 return "continued";
1204 }
1205 if (name == "eve_step_over") {
1206 dbg.stepOver();
1207 dap.notifyContinued();
1208 return "step_over";
1209 }
1210 if (name == "eve_step_into") {
1211 dbg.stepInto();
1212 dap.notifyContinued();
1213 return "step_into";
1214 }
1215 if (name == "eve_step_out") {
1216 dbg.stepOut();
1217 dap.notifyContinued();
1218 return "step_out";
1219 }
1220 if (name == "eve_step_frame") {
1221 dbg.stepFrame();
1222 dap.notifyContinued();
1223 return "step_frame";
1224 }
1225
1226 if (name == "eve_stack") {
1227 auto frames = dbg.stackTrace();
1228 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1229 for (const auto& f : frames) {
1230 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1231 o->set("id", f.id);
1232 o->set("name", f.name);
1233 o->set("source", f.loc.source);
1234 o->set("line", f.loc.line);
1235 o->set("function", f.loc.function);
1236 arr->add(o);
1237 }
1238 return mcpStringify(Poco::Dynamic::Var(arr));
1239 }
1240
1241 if (name == "eve_locals") {
1242 const int level = getArgInt(args, "level", 1);
1243 auto vars = dbg.locals(level);
1244 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1245 for (const auto& v : vars) {
1246 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1247 o->set("name", v.name);
1248 o->set("value", v.value);
1249 o->set("type", v.type);
1250 arr->add(o);
1251 }
1252 return mcpStringify(Poco::Dynamic::Var(arr));
1253 }
1254
1255 if (name == "eve_set_breakpoint") {
1256 const std::string source = getArgString(args, "source");
1257 const int line = getArgInt(args, "line");
1258 if (source.empty() || line <= 0) return "error: need source and line";
1259 const std::string condition = getArgString(args, "condition");
1260 const int id = dbg.setBreakpoint(source, line, true, condition);
1261 return "ok id=" + std::to_string(id);
1262 }
1263 if (name == "eve_clear_breakpoint") {
1264 const std::string source = getArgString(args, "source");
1265 const int line = getArgInt(args, "line");
1266 if (source.empty() || line <= 0) return "error: need source and line";
1267 return dbg.clearBreakpoint(source, line) ? "cleared" : "not_found";
1268 }
1269 if (name == "eve_list_breakpoints") {
1270 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1271 for (const auto& bp : dbg.breakpoints()) {
1272 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1273 o->set("id", bp.id);
1274 o->set("source", bp.source);
1275 o->set("line", bp.line);
1276 o->set("enabled", bp.enabled);
1277 o->set("condition", bp.condition);
1278 arr->add(o);
1279 }
1280 return mcpStringify(Poco::Dynamic::Var(arr));
1281 }
1282
1283 if (name == "eve_watch_add") {
1284 const std::string expr = getArgString(args, "expression");
1285 if (expr.empty()) return "error: missing expression";
1286 dbg.addWatch(expr);
1287 dbg.refreshWatches();
1288 return "ok";
1289 }
1290 if (name == "eve_watch_list") {
1291 dbg.refreshWatches();
1292 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1293 for (const auto& w : dbg.watches()) {
1294 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1295 o->set("expression", w.expression);
1296 o->set("value", w.value);
1297 o->set("ok", w.ok);
1298 arr->add(o);
1299 }
1300 return mcpStringify(Poco::Dynamic::Var(arr));
1301 }
1302
1303 if (name == "eve_snapshot_capture") {
1304 HSQUIRRELVM vm = dbg.vm();
1305 if (!vm) return "error: no VM";
1306 std::string err;
1307 std::string json = Snapshot::instance().capture(vm, &err);
1308 if (!err.empty() && json.empty()) return "error: " + err;
1309 return json;
1310 }
1311 if (name == "eve_snapshot_restore") {
1312 HSQUIRRELVM vm = dbg.vm();
1313 if (!vm) return "error: no VM";
1314 const std::string json = getArgString(args, "json");
1315 std::string err;
1316 if (!Snapshot::instance().restore(vm, json, &err)) return "error: " + err;
1317 return "ok";
1318 }
1319 if (name == "eve_snapshot_save") {
1320 HSQUIRRELVM vm = dbg.vm();
1321 if (!vm) return "error: no VM";
1322 const std::string path = getArgString(args, "path");
1323 std::string err;
1324 if (!Snapshot::instance().saveFile(vm, path, &err)) return "error: " + err;
1325 return "ok";
1326 }
1327 if (name == "eve_snapshot_load") {
1328 HSQUIRRELVM vm = dbg.vm();
1329 if (!vm) return "error: no VM";
1330 const std::string path = getArgString(args, "path");
1331 std::string err;
1332 if (!Snapshot::instance().loadFile(vm, path, &err)) return "error: " + err;
1333 return "ok";
1334 }
1335
1336 if (name == "eve_error_slice") {
1337 const std::string& last = mcpLastReport();
1338 if (!last.empty()) return last;
1339 return "no prior error";
1340 }
1341
1342 if (name == "eve_run_script") {
1343 HSQUIRRELVM vm = dbg.vm();
1344 if (!vm) return "error: no VM";
1345 const std::string source = getArgString(args, "source");
1346 if (source.empty()) return "error: missing source";
1347 std::string error;
1348 if (!runMcpVmSnippet(vm, source, &error)) return "error: " + error;
1349 return "ok";
1350 }
1351
1352 if (name == "eve_ai_note") {
1353 const std::string text = getArgString(args, "text");
1354 if (text.empty()) return "error: missing text";
1356 return "ok";
1357 }
1358 if (name == "eve_ai_log") return AiPanel::instance().formatLog(100);
1359
1360 // ===================== Scene Director (AI scene-authoring) =====================
1361 // Agent-drivable scene construction backed by the `scene_director` script kit.
1362 if (name == "eve_scene_director_install") {
1363 HSQUIRRELVM vm = dbg.vm();
1364 if (!vm) return "error: no VM";
1365 std::string err;
1366 // Explicit install is allowed to do heavy work; agents that hit other scene tools
1367 // first get deferred-to-update instead of blocking JSON-RPC (EM1).
1368 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/true)) return sceneDirectorToolError(name, err);
1369 return "ok";
1370 }
1371
1372 if (name == "eve_scene_director_status") {
1373 HSQUIRRELVM vm = dbg.vm();
1374 if (!vm) return "error: no VM";
1375 std::string err;
1376 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/false)) return sceneDirectorToolError(name, err);
1377 return callSceneDirectorReturn(vm, "return ::scene_director.status();", &err);
1378 }
1379
1380 if (name == "eve_scene_reset") {
1381 HSQUIRRELVM vm = dbg.vm();
1382 if (!vm) return "error: no VM";
1383 std::string err;
1384 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/false)) return sceneDirectorToolError(name, err);
1385 std::string out = callSceneDirectorReturn(vm, "return ::scene_director.reset();", &err);
1386 if (!err.empty()) return sceneDirectorToolError(name, err);
1387 return out;
1388 }
1389
1390 if (name == "eve_scene_modify") {
1391 HSQUIRRELVM vm = dbg.vm();
1392 if (!vm) return "error: no VM";
1393 std::string err;
1394 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/false)) return sceneDirectorToolError(name, err);
1395 const std::string action = getArgString(args, "action");
1396 const std::string target = getArgString(args, "target");
1397 Poco::Dynamic::Var paramsVar;
1398 if (args && args->has("params")) {
1399 try {
1400 paramsVar = Poco::Dynamic::Var(args->getObject("params"));
1401 } catch (...) {
1402 return sceneDirectorToolError(name, "params must be a JSON object");
1403 }
1404 }
1405 auto actionLiteral = sceneLiteral(Poco::Dynamic::Var(action));
1406 if (!actionLiteral.ok()) return sceneDirectorToolError(name, actionLiteral.status().describe());
1407 auto targetLiteral = sceneLiteral(Poco::Dynamic::Var(target));
1408 if (!targetLiteral.ok()) return sceneDirectorToolError(name, targetLiteral.status().describe());
1409 auto paramsLiteral = sceneLiteral(paramsVar);
1410 if (!paramsLiteral.ok()) return sceneDirectorToolError(name, paramsLiteral.status().describe());
1411 const std::string snippet = "return ::scene_director.modify(" + actionLiteral.value() + "," +
1412 targetLiteral.value() + "," + paramsLiteral.value() + ");";
1413 std::string out = callSceneDirectorReturn(vm, snippet, &err);
1414 if (!err.empty()) return sceneDirectorToolError(name, err);
1415 return out;
1416 }
1417
1418 // Batch white-box authoring: many scene_director.modify calls in one round-trip.
1419 if (name == "eve_scene_batch") {
1420 HSQUIRRELVM vm = dbg.vm();
1421 if (!vm) return "error: no VM";
1422 std::string err;
1423 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/false)) return sceneDirectorToolError(name, err);
1424 if (!args || !args->has("actions")) return sceneDirectorToolError(name, "actions array is required");
1425 Poco::Dynamic::Var actionsVar;
1426 try {
1427 actionsVar = Poco::Dynamic::Var(args->getArray("actions"));
1428 } catch (...) {
1429 return sceneDirectorToolError(name, "actions must be a JSON array");
1430 }
1431 Poco::JSON::Object::Ptr options = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1432 if (args->has("stopOnError")) {
1433 try {
1434 options->set("stopOnError", args->get("stopOnError").convert<bool>());
1435 } catch (...) {
1436 return sceneDirectorToolError(name, "stopOnError must be a boolean");
1437 }
1438 } else {
1439 options->set("stopOnError", true);
1440 }
1441 auto actionsLiteral = sceneLiteral(actionsVar);
1442 if (!actionsLiteral.ok()) return sceneDirectorToolError(name, actionsLiteral.status().describe());
1443 auto optionsLiteral = sceneLiteral(Poco::Dynamic::Var(options));
1444 if (!optionsLiteral.ok()) return sceneDirectorToolError(name, optionsLiteral.status().describe());
1445 const std::string snippet =
1446 "return ::scene_director.batch(" + actionsLiteral.value() + "," + optionsLiteral.value() + ");";
1447 std::string out = callSceneDirectorReturn(vm, snippet, &err);
1448 if (!err.empty()) return sceneDirectorToolError(name, err);
1449 return out;
1450 }
1451
1452 if (name == "eve_camera_generate") {
1453 HSQUIRRELVM vm = dbg.vm();
1454 if (!vm) return "error: no VM";
1455 std::string err;
1456 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/false)) return sceneDirectorToolError(name, err);
1457 const int count = getArgInt(args, "count", 6);
1458 const std::string snippet = "return ::scene_director.cameras(" + std::to_string(count) + ");";
1459 std::string out = callSceneDirectorReturn(vm, snippet, &err);
1460 if (!err.empty()) return sceneDirectorToolError(name, err);
1461 return out;
1462 }
1463
1464 if (name == "eve_scene_info") {
1465 HSQUIRRELVM vm = dbg.vm();
1466 if (!vm) return "error: no VM";
1467 std::string err;
1468 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/false)) return sceneDirectorToolError(name, err);
1469 std::string out = callSceneDirectorReturn(vm, "return ::scene_director.info();", &err);
1470 if (!err.empty()) return sceneDirectorToolError(name, err);
1471 return out;
1472 }
1473
1474 // ---- 场景巡检工具集(图像与 3D 几何数据严格同步) ----
1475 if (name == "inspect_generate_scene_camera_views") {
1476 const glm::vec3 center = argVec3(args, "center");
1477 const float fov = getArgFloat(args, "fov", 60.f);
1478 auto views = SceneInspect::instance().generateViews(center, fov);
1479 Poco::JSON::Object::Ptr root = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1480 Poco::JSON::Array::Ptr arr = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1481 for (const auto& v : views) {
1482 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1483 o->set("name", v.name);
1484 o->set("kind", v.kind);
1485 o->set("eye", vec3ToArray(v.eye));
1486 o->set("target", vec3ToArray(v.target));
1487 o->set("fov", static_cast<double>(v.fovYDeg));
1488 arr->add(o);
1489 }
1490 root->set("views", arr);
1491 return mcpStringify(Poco::Dynamic::Var(root));
1492 }
1493
1494 if (name == "set_camera_pose") {
1495 const glm::vec3 pos = argVec3(args, "pos", glm::vec3(0.f, 1.8f, 0.f));
1496 const glm::vec3 rot = argVec3(args, "rot", glm::vec3(0.f));
1497 const float fov = getArgFloat(args, "fov", 0.f);
1498 const bool ok = SceneInspect::instance().setCameraPose(pos, rot, fov);
1499 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1500 o->set("ok", ok);
1501 if (!ok) {
1502 o->set("error", "failed to set camera pose (no Graphics/Camera3D)");
1503 } else {
1504 try {
1505 Poco::JSON::Parser parser;
1506 o->set("pose", parser.parse(SceneInspect::instance().currentPoseJson()));
1507 } catch (...) {
1508 }
1509 }
1510 return mcpStringify(Poco::Dynamic::Var(o));
1511 }
1512
1513 if (name == "capture_render_frame") {
1514 const std::string dir = getArgString(args, "dir");
1515 const std::string tag = getArgString(args, "tag", "frame");
1516 std::vector<std::string> buffers;
1517 if (args && args->has("buffers")) {
1518 try {
1519 auto arr = args->getArray("buffers");
1520 if (arr) {
1521 for (size_t i = 0; i < arr->size(); ++i)
1522 buffers.push_back(arr->get(static_cast<unsigned int>(i)).convert<std::string>());
1523 }
1524 } catch (...) {
1525 }
1526 }
1527 const auto res = SceneInspect::instance().capture(dir, tag, buffers);
1528 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1529 o->set("ok", res.ok);
1530 if (res.ok) {
1531 o->set("png", res.pngPath);
1532 o->set("json", res.jsonPath);
1533 o->set("width", res.width);
1534 o->set("height", res.height);
1535 o->set("entityCount", res.entityCount);
1536 if (!res.depthPngPath.empty()) o->set("depthPng", res.depthPngPath);
1537 if (!res.normalPngPath.empty()) o->set("normalPng", res.normalPngPath);
1538 if (!res.idPngPath.empty()) o->set("idPng", res.idPngPath);
1539 if (!res.idJsonPath.empty()) o->set("idJson", res.idJsonPath);
1540 if (!res.unsupported.empty()) {
1541 Poco::JSON::Array::Ptr uns = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1542 for (const auto& u : res.unsupported) uns->add(u);
1543 o->set("unsupported", uns);
1544 }
1545 } else {
1546 o->set("error", res.error);
1547 }
1548 return mcpStringify(Poco::Dynamic::Var(o));
1549 }
1550
1551 if (name == "get_visible_entities_screen_bbox") {
1552 const bool hasPos = args && args->has("pos");
1553 const bool hasTarget = args && args->has("target");
1554 if (hasPos && hasTarget) {
1555 const glm::vec3 eye = argVec3(args, "pos");
1556 const glm::vec3 tgt = argVec3(args, "target");
1557 const float fov = getArgFloat(args, "fov", 0.f);
1558 return SceneInspect::instance().visibleEntitiesJson(&eye, &tgt, fov);
1559 }
1560 const float fov = getArgFloat(args, "fov", 0.f);
1561 return SceneInspect::instance().visibleEntitiesJson(nullptr, nullptr, fov);
1562 }
1563
1564 return "error: unknown tool " + name;
1565}
1566
1567// Revisions this server actually implements. The newline-delimited JSON-RPC
1568// shape and the tools/resources/prompts surface are shared by all of them, so a
1569// client asking for one of these may keep its own framing assumptions.
1570constexpr const char* kMcpProtocolLatest = "2025-06-18";
1571
1572bool isSupportedProtocol(const std::string& requested) {
1573 return requested == "2025-06-18" || requested == "2025-03-26" || requested == "2024-11-05";
1574}
1575
1576std::string handleInitialize(McpServer& mcp, const std::string& idJson, Poco::JSON::Object::Ptr params) {
1577 std::string clientName = "mcp-client";
1578 std::string requested = kMcpProtocolLatest;
1579 if (params) {
1580 try {
1581 if (params->has("clientInfo")) {
1582 auto info = params->getObject("clientInfo");
1583 if (info && info->has("name")) clientName = info->get("name").convert<std::string>();
1584 }
1585 if (params->has("protocolVersion")) requested = params->get("protocolVersion").convert<std::string>();
1586 } catch (...) {
1587 }
1588 }
1589 (void)mcp;
1590 AiPanel::instance().setClientName(clientName);
1591 AiPanel::instance().addLog("system", "mcp.initialize", clientName);
1592
1593 // The server must answer with a revision it implements; echoing an
1594 // arbitrary client string would claim support for a protocol that was never
1595 // built, and the client would then frame requests accordingly.
1596 const std::string protocol = isSupportedProtocol(requested) ? requested : kMcpProtocolLatest;
1597
1598 // Hand-built JSON keeps initialize compact (newline framing) without a Poco Object tree.
1599 const std::string resultJson =
1600 std::string("{\"protocolVersion\":\"") + mcpJsonEscape(protocol) +
1601 "\",\"capabilities\":{\"tools\":{},\"resources\":{},\"prompts\":{}},"
1602 "\"serverInfo\":{\"name\":\"evengine\",\"title\":\"EVEngine MCP\",\"version\":\"0.7.0\"},"
1603 "\"instructions\":\"EVEngine MCP for AI-assisted game development. Call eve_api_search/eve_api_get to look up "
1604 "this build's EveScript bindings before writing .nut (do not invent Unity C# names); prefer eve_play and "
1605 "editor commands over eve_eval for gameplay. Diagnose through the game's own channels: "
1606 "eve_console_read returns the runtime console (Squirrel print/error plus engine log lines) with a monotonic "
1607 "seq cursor, eve_error_slice returns the last script/render error slice, and eve_render_status with "
1608 "eve_screenshot/eve_screenshot_image capture engine-owned frames. Drive a run with eve_pause/eve_step_* or "
1609 "eve_play (clock/step/observe/capture/checkpoint/act), assert with eve_eval/eve_run_script and snapshot "
1610 "tools, and inspect live state with eve_editor_*/eve_scene_*/eve_ui_*. Use eve_restart (optional args) to "
1611 "soft-restart the game without reloading the resource cache — do not kill the process between AI debug "
1612 "iterations. eve_host_* tools create JSON-defined editor windows bound to Squirrel ViewModels (MVVM) for "
1613 "AI-crafted terrain/material/event editors.\"}";
1614 return makeResult(idJson, resultJson);
1615}
1616
1617std::string handleToolsList(const std::string& idJson) {
1618 // Complete tool objects, comma-separated; the array wrapper is added by
1619 // handleToolsList so project-exported tools can be appended last.
1620 const std::string kToolsBody(compiledMcpToolCatalog().schemas());
1621
1622 // Project-exported tools come last and are re-read every call: a script may
1623 // register or drop one at any time (hot reload of mcp.nut).
1624 std::string body = kToolsBody;
1625 const std::string scripted = scriptToolSchemas();
1626 if (!scripted.empty()) {
1627 body += ',';
1628 body += scripted;
1629 }
1630 // Toolset / read-only / exclude filters apply to both built-ins and script tools
1631 // so tools/list and tools/call stay consistent.
1633 std::string tools = "{\"tools\":[";
1634 tools += body;
1635 tools += "]}";
1636 return makeResult(idJson, tools);
1637}
1638
1639std::string handleToolsCall(McpServer& mcp, const std::string& idJson, Poco::JSON::Object::Ptr params) {
1640 if (!params || !params->has("name")) return makeError(idJson, -32602, "tools/call requires params.name");
1641 std::string name;
1642 try {
1643 name = params->get("name").convert<std::string>();
1644 } catch (...) {
1645 return makeError(idJson, -32602, "tools/call params.name must be a string");
1646 }
1647 Poco::JSON::Object::Ptr args = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1648 if (params->has("arguments")) {
1649 try {
1650 args = params->getObject("arguments");
1651 } catch (...) {
1652 }
1653 }
1654
1655 std::string detail;
1656 try {
1657 if (args) detail = mcpStringify(Poco::Dynamic::Var(args));
1658 } catch (...) {
1659 }
1660 AiPanel::instance().addLog("tool", name, detail);
1661
1662 if (!mcpToolAllowed(name)) {
1663 return makeResult(idJson, textContentResult(mcpToolFilteredPayload(name), true));
1664 }
1665 mcpFilterNoteCall(true, 0, false);
1666
1667 if (const auto route = compiledMcpToolCatalog().find(name)) {
1668 try {
1669 const auto payload = route->call(mcp, name, args);
1670 return makeResult(idJson, route->payload == McpToolPayload::ContentEnvelope
1671 ? payload
1672 : textContentResult(payload, payload.rfind("error:", 0) == 0));
1673 } catch (const std::exception& e) {
1674 AiPanel::instance().addLog("error", name, e.what());
1675 return makeResult(idJson, textContentResult(std::string("error: ") + e.what(), true));
1676 }
1677 }
1678
1679 // Project-exported script tools. Built-ins win: a script tool can never
1680 // shadow a compiled tool, which is why registration rejects their prefixes.
1681 if (isScriptTool(name)) {
1682 try {
1683 return makeResult(idJson, callScriptTool(name, args));
1684 } catch (const std::exception& e) {
1685 AiPanel::instance().addLog("error", name, e.what());
1686 return makeResult(idJson, textContentResult(std::string("error: ") + e.what(), true));
1687 }
1688 }
1689
1690 try {
1691 const std::string out = callTool(mcp, name, args);
1692 const bool isErr = out.rfind("error:", 0) == 0;
1693 return makeResult(idJson, textContentResult(out, isErr));
1694 } catch (const std::exception& e) {
1695 AiPanel::instance().addLog("error", name, e.what());
1696 return makeResult(idJson, textContentResult(std::string("error: ") + e.what(), true));
1697 }
1698}
1699
1700std::string handleResourcesList(const std::string& idJson) {
1701 return makeResult(idJson,
1702 "{\"resources\":["
1703 "{\"uri\":\"eve://status\",\"name\":\"status\",\"description\":\"Debugger / MCP / DAP "
1704 "status\",\"mimeType\":\"application/json\"},"
1705 "{\"uri\":\"eve://game-world\",\"name\":\"game-world\",\"description\":\"What kind of game "
1706 "world is running at runtime: script publishWorldContext, live domains, and configured "
1707 "/ instantiated modules\",\"mimeType\":\"application/json\"},"
1708 "{\"uri\":\"eve://error-report\",\"name\":\"error-report\",\"description\":\"Last DevTools error "
1709 "slice report\",\"mimeType\":\"text/plain\"},"
1710 "{\"uri\":\"eve://ai-session\",\"name\":\"ai-session\",\"description\":\"AI / MCP session "
1711 "log\",\"mimeType\":\"text/plain\"},"
1712 "{\"uri\":\"eve://callgraph\",\"name\":\"callgraph\",\"description\":\"CallGraph event "
1713 "summary\",\"mimeType\":\"application/json\"},"
1714 "{\"uri\":\"eve://crash-log\",\"name\":\"crash-log\",\"description\":\"Persistent crash/error "
1715 "log (eve.log) that survives a process death\",\"mimeType\":\"text/plain\"}"
1716 "]}");
1717}
1718
1719std::string handleResourcesRead(const std::string& idJson, Poco::JSON::Object::Ptr params) {
1720 if (!params || !params->has("uri")) return makeError(idJson, -32602, "resources/read requires params.uri");
1721 std::string uri;
1722 try {
1723 uri = params->get("uri").convert<std::string>();
1724 } catch (...) {
1725 return makeError(idJson, -32602, "resources/read params.uri must be a string");
1726 }
1727 std::string text;
1728 std::string mime = "text/plain";
1729 if (uri == "eve://status") {
1730 text = engineStatusJson(McpServer::instance());
1731 mime = "application/json";
1732 } else if (uri == "eve://game-world") {
1734 if (!snapshot) {
1735 const auto* diag = snapshot.status().primaryDiagnostic();
1736 return makeError(
1737 idJson, -32002,
1738 diag && !diag->message().empty() ? diag->message() : std::string("game world snapshot failed"));
1739 }
1740 auto json = snapshot.value().toJson();
1741 if (!json) {
1742 const auto* diag = json.status().primaryDiagnostic();
1743 return makeError(idJson, -32002,
1744 diag && !diag->message().empty() ? diag->message() : "game world JSON failed");
1745 }
1746 text = json.value();
1747 mime = "application/json";
1748 } else if (uri == "eve://error-report") {
1749 text = mcpLastReport();
1750 if (text.empty()) text = "(no error report yet)\n";
1751 } else if (uri == "eve://ai-session") {
1753 if (text.empty()) text = "(empty)\n";
1754 } else if (uri == "eve://callgraph") {
1755 Poco::JSON::Object::Ptr o = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1756 o->set("events", static_cast<int>(mcpCallgraphEvents()));
1757 o->set("stackDepth", static_cast<int>(mcpCallgraphStackDepth()));
1758 text = mcpStringify(Poco::Dynamic::Var(o));
1759 mime = "application/json";
1760 } else if (uri == "eve://crash-log") {
1761 // Same evidence eve_crash_report exposes, as a resource so a client can
1762 // attach it without a tool round trip. Bounded to the tail: a resource
1763 // read must not turn a long log into one enormous MCP frame.
1764 constexpr std::streamoff kCrashResourceBytes = 64 * 1024;
1765 text = "(no crash log yet)\n";
1766 const std::string path = crashLogSummary()->getValue<std::string>("path");
1767 std::error_code exists = std::error_code();
1768 if (!path.empty() && std::filesystem::exists(path, exists)) {
1769 std::ifstream in(path, std::ios::binary);
1770 if (in) {
1771 in.seekg(0, std::ios::end);
1772 const std::streamoff size = in.tellg();
1773 const std::streamoff start = size > kCrashResourceBytes ? size - kCrashResourceBytes : 0;
1774 in.seekg(start < 0 ? 0 : start);
1775 std::ostringstream buffer;
1776 buffer << in.rdbuf();
1777 text = buffer.str();
1778 if (start > 0) {
1779 const auto newline = text.find('\n');
1780 text.erase(0, newline == std::string::npos ? text.size() : newline + 1);
1781 text = "[…truncated; full log at " + path + "]\n" + text;
1782 }
1783 if (text.empty()) text = "(crash log is empty)\n";
1784 }
1785 }
1786 } else {
1787 return makeError(idJson, -32002, "Unknown resource: " + uri);
1788 }
1789
1790 Poco::JSON::Object::Ptr contentsItem = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1791 contentsItem->set("uri", uri);
1792 contentsItem->set("mimeType", mime);
1793 contentsItem->set("text", text);
1794 Poco::JSON::Array::Ptr contents = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1795 contents->add(contentsItem);
1796 Poco::JSON::Object::Ptr result = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1797 result->set("contents", contents);
1798 return makeResult(idJson, mcpStringify(Poco::Dynamic::Var(result)));
1799}
1800
1801std::string handlePromptsList(const std::string& idJson) {
1802 return makeResult(
1803 idJson,
1804 "{\"prompts\":["
1805 "{\"name\":\"debug_failure\",\"description\":\"Investigate the latest script/render error using MCP tools and "
1806 "the error slice.\"},"
1807 "{\"name\":\"test_scenario\",\"description\":\"Drive a reproducible in-engine test: pause, snapshot, eval "
1808 "assertions, continue.\"},"
1809 "{\"name\":\"ai_game_review\",\"description\":\"Review live game state for AI-generated content issues.\"}"
1810 "]}");
1811}
1812
1813std::string handlePromptsGet(const std::string& idJson, Poco::JSON::Object::Ptr params) {
1814 if (!params || !params->has("name")) return makeError(idJson, -32602, "prompts/get requires params.name");
1815 std::string name;
1816 try {
1817 name = params->get("name").convert<std::string>();
1818 } catch (...) {
1819 return makeError(idJson, -32602, "prompts/get params.name must be a string");
1820 }
1821 std::string text;
1822 if (name == "debug_failure") {
1823 text =
1824 "You are debugging an EVEngine game via MCP.\n"
1825 "1) Call eve_status and read resource eve://error-report.\n"
1826 "2) Use eve_stack / eve_locals / eve_eval to inspect state.\n"
1827 "3) Use eve_error_slice to narrow script/render causes.\n"
1828 "4) Propose a minimal fix; verify with eve_run_script or snapshot restore.";
1829 } else if (name == "test_scenario") {
1830 text =
1831 "Design a short automated test against the live EVEngine session:\n"
1832 "1) Call eve_game_world (or read eve://game-world) to learn genre/systems, then eve_play op=status.\n"
1833 "2) Observe declared script roots from game.agent.json; do not invent observation paths.\n"
1834 "3) Pause, step host frames, capture an engine screenshot, and checkpoint restore with eve_play.\n"
1835 "4) Use eve_gameplay for player-equivalent domain commands when the contract declares a gameplay-domain.\n"
1836 "5) Do not use eve_eval as the official observation path.";
1837 } else if (name == "ai_game_review") {
1838 text =
1839 "Review this AI-generated or AI-assisted game build:\n"
1840 "1) eve_game_world + eve_status + eve_ai_log to learn the world and recent agent actions.\n"
1841 "2) Spot-check critical roots with eve_play observe (or eve_eval only as a debug escape hatch).\n"
1842 "3) If unstable, pause and capture a snapshot.\n"
1843 "4) Summarize risks and suggested script fixes.";
1844 } else {
1845 return makeError(idJson, -32602, "Unknown prompt: " + name);
1846 }
1847
1848 Poco::JSON::Object::Ptr msg = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1849 msg->set("role", "user");
1850 Poco::JSON::Array::Ptr content = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1851 Poco::JSON::Object::Ptr part = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1852 part->set("type", "text");
1853 part->set("text", text);
1854 content->add(part);
1855 msg->set("content", content);
1856 Poco::JSON::Array::Ptr messages = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
1857 messages->add(msg);
1858 Poco::JSON::Object::Ptr result = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
1859 result->set("description", name);
1860 result->set("messages", messages);
1861 return makeResult(idJson, mcpStringify(Poco::Dynamic::Var(result)));
1862}
1863
1864std::string callCoreTool(McpServer& server, std::string_view name, Poco::JSON::Object::Ptr args) {
1865 return callTool(server, std::string(name), std::move(args));
1866}
1867
1868} // namespace
1869
1871
1872McpServer& McpServer::instance() {
1873 // Process-immortal singleton: the stdio reader thread (detached when
1874 // reading stdin) and cross-singleton calls make destruction unsafe; see
1875 // devtools/Immortal.hpp.
1876 return Immortal<McpServer>::get();
1877}
1878
1879McpServer::McpServer() = default;
1880
1881McpServer::~McpServer() {
1882 // Only reached if someone deletes the instance; keep sockets tidy without
1883 // touching AiPanel (may already be torn down in other lifetime models).
1884 std::lock_guard<std::mutex> lock(ioMu_);
1885 if (client_) {
1886 try {
1887 client_->close();
1888 } catch (...) {
1889 }
1890 client_.reset();
1891 }
1892 if (server_) {
1893 try {
1894 server_->close();
1895 } catch (...) {
1896 }
1897 server_.reset();
1898 }
1899 stdioQueue_.clear();
1900 listening_.store(false);
1901 hasClient_.store(false);
1902 port_.store(0);
1903 transport_.store(Transport::None);
1904}
1905
1906void McpServer::setGameRoot(std::string root) {
1907 for (char& c : root) {
1908 if (c == '\\') c = '/';
1909 }
1910 while (!root.empty() && (root.back() == '/' || root.back() == '\\')) root.pop_back();
1911 gameRoot_ = std::move(root);
1912}
1913
1914int McpServer::listen(uint16_t port) {
1915 stop();
1916 try {
1917 Poco::Net::SocketAddress addr("127.0.0.1", port);
1918 server_ = std::make_unique<Poco::Net::ServerSocket>(addr);
1919 server_->setBlocking(false);
1920 const int bound = static_cast<int>(server_->address().port());
1921 port_.store(bound);
1922 listening_.store(true);
1923 initialized_ = false;
1924 try {
1925 if (gameRoot_.empty()) setGameRoot(std::filesystem::current_path().string());
1926 } catch (...) {
1927 }
1930 AiPanel::instance().addLog("system", "mcp.listen", "listening on 127.0.0.1:" + std::to_string(bound));
1931 transport_.store(Transport::Tcp);
1932 return bound;
1933 } catch (...) {
1934 server_.reset();
1935 listening_.store(false);
1936 port_.store(0);
1937 transport_.store(Transport::None);
1939 return 0;
1940 }
1941}
1942
1943bool McpServer::listenStdio(std::istream& in, std::ostream& out) {
1944 stop();
1945 {
1946 std::lock_guard<std::mutex> lock(ioMu_);
1947 stdioQueue_.clear();
1948 }
1949 transport_.store(Transport::Stdio);
1950 listening_.store(true);
1951 port_.store(0);
1952 initialized_ = false;
1953 stdinClosed_.store(false);
1956 hasClient_.store(true);
1957 stdioIn_ = &in;
1958 stdioOut_ = &out;
1959 joinReader_ = (&in != &std::cin);
1960 try {
1961 stdioReader_ = std::thread([this, &in]() {
1962 std::string line;
1963 while (listening_.load() && std::getline(in, line)) {
1964 if (!line.empty() && line.back() == '\r') line.pop_back();
1965 if (line.empty()) continue;
1966 {
1967 std::lock_guard<std::mutex> lock(ioMu_);
1968 stdioQueue_.push_back(std::move(line));
1969 }
1970 }
1971 stdinClosed_.store(true);
1972 hasClient_.store(false);
1973 });
1974 } catch (...) {
1975 transport_.store(Transport::None);
1976 listening_.store(false);
1977 hasClient_.store(false);
1978 return false;
1979 }
1982 AiPanel::instance().addLog("system", "mcp.listen", "stdio transport ready (newline JSON-RPC)");
1983 return true;
1984}
1985
1986void McpServer::stop() {
1987 listening_.store(false);
1988 hasClient_.store(false);
1989 if (stdioReader_.joinable()) {
1990 if (joinReader_) {
1991 stdioReader_.join();
1992 } else {
1993 stdioReader_.detach();
1994 }
1995 }
1996 std::lock_guard<std::mutex> lock(ioMu_);
1997 if (client_) {
1998 try {
1999 client_->close();
2000 } catch (...) {
2001 }
2002 client_.reset();
2003 }
2004 if (server_) {
2005 try {
2006 server_->close();
2007 } catch (...) {
2008 }
2009 server_.reset();
2010 }
2011 stdioQueue_.clear();
2012 recvBuf_.clear();
2013 port_.store(0);
2014 transport_.store(Transport::None);
2015 initialized_ = false;
2016 stdioIn_ = nullptr;
2017 stdioOut_ = nullptr;
2018 AiPanel::instance().setMcpPort(0);
2019 AiPanel::instance().setMcpConnected(false);
2020 AiPanel::instance().setClientName({});
2021}
2022
2023void McpServer::poll() {
2024 if (!listening_.load()) return;
2025 if (transport_.load() == Transport::Stdio) {
2026 std::vector<std::string> batch;
2027 {
2028 std::lock_guard<std::mutex> lock(ioMu_);
2029 batch.swap(stdioQueue_);
2030 }
2031 for (const auto& line : batch) handleMessage(line);
2032 if (stdinClosed_.load() && batch.empty() && initialized_) {
2035 initialized_ = false;
2036 }
2037 flushPendingSceneDirectorInstall(Debugger::instance().vm());
2039 runPendingVisionDump();
2040 return;
2041 }
2042 acceptNonBlocking();
2043 readAndDispatch();
2044 flushPendingSceneDirectorInstall(Debugger::instance().vm());
2046 runPendingVisionDump();
2047}
2048
2049void McpServer::acceptNonBlocking() {
2050 if (!server_ || client_) return;
2051 try {
2052 Poco::Net::SocketAddress clientAddr;
2053 Poco::Net::StreamSocket ss = server_->acceptConnection(clientAddr);
2054 ss.setBlocking(true);
2055 ss.setReceiveTimeout(Poco::Timespan(0, 1000));
2056 client_ = std::make_unique<Poco::Net::StreamSocket>(ss);
2057 hasClient_.store(true);
2060 recvBuf_.clear();
2061 initialized_ = false;
2062 AiPanel::instance().setMcpConnected(true);
2063 AiPanel::instance().addLog("system", "mcp.accept", "client connected");
2064 } catch (const Poco::TimeoutException&) {
2065 } catch (const Poco::Net::NetException&) {
2066 } catch (...) {
2067 }
2068}
2069
2070bool McpServer::sendLine(const std::string& json) {
2071 if (transport_.load() == Transport::Stdio) {
2072 std::lock_guard<std::mutex> lock(ioMu_);
2073 if (!stdioOut_) return false;
2074 try {
2075 const std::string frame = json + "\n";
2076 (*stdioOut_) << frame;
2077 stdioOut_->flush();
2078 return true;
2079 } catch (...) {
2080 return false;
2081 }
2082 }
2083 if (!client_) return false;
2084 const std::string frame = json + "\n";
2085 try {
2086 const int sent = client_->sendBytes(frame.data(), static_cast<int>(frame.size()));
2087 return sent == static_cast<int>(frame.size());
2088 } catch (...) {
2089 client_.reset();
2090 hasClient_.store(false);
2091 AiPanel::instance().setMcpConnected(false);
2092 return false;
2093 }
2094}
2095
2096void McpServer::readAndDispatch() {
2097 if (!client_) return;
2098 char buf[8192];
2099 try {
2100 const int n = client_->receiveBytes(buf, sizeof(buf));
2101 if (n <= 0) {
2102 if (n == 0) {
2103 client_.reset();
2104 hasClient_.store(false);
2105 AiPanel::instance().setMcpConnected(false);
2106 AiPanel::instance().addLog("system", "mcp.disconnect", "client closed");
2109 }
2110 return;
2111 }
2112 recvBuf_.append(buf, static_cast<size_t>(n));
2113 } catch (const Poco::TimeoutException&) {
2114 return;
2115 } catch (const Poco::Net::NetException&) {
2116 client_.reset();
2117 hasClient_.store(false);
2118 AiPanel::instance().setMcpConnected(false);
2121 return;
2122 } catch (...) {
2123 client_.reset();
2124 hasClient_.store(false);
2125 AiPanel::instance().setMcpConnected(false);
2126 return;
2127 }
2128
2129 while (true) {
2130 const auto nl = recvBuf_.find('\n');
2131 if (nl == std::string::npos) break;
2132 std::string line = recvBuf_.substr(0, nl);
2133 recvBuf_.erase(0, nl + 1);
2134 if (!line.empty() && line.back() == '\r') line.pop_back();
2135 if (line.empty()) continue;
2136 handleMessage(line);
2137 }
2138}
2139
2140void McpServer::handleMessage(const std::string& json) {
2141 try {
2142 Poco::JSON::Parser parser;
2143 auto var = parser.parse(json);
2144 auto obj = var.extract<Poco::JSON::Object::Ptr>();
2145 if (!obj) return;
2146
2147 std::string method;
2148 if (obj->has("method")) {
2149 try {
2150 method = obj->get("method").convert<std::string>();
2151 } catch (const Poco::Exception& e) {
2152 sendLine(makeError("null", -32600, std::string("bad method: ") + e.displayText()));
2153 return;
2154 }
2155 }
2156 const bool hasId = obj->has("id");
2157 Poco::Dynamic::Var idVar;
2158 if (hasId) idVar = obj->get("id");
2159 std::string idJson = "null";
2160 try {
2161 if (hasId) idJson = idToJson(idVar);
2162 } catch (const Poco::Exception& e) {
2163 sendLine(makeError("null", -32600, std::string("bad id: ") + e.displayText()));
2164 return;
2165 }
2166
2167 if (!hasId) {
2168 if (method == "notifications/initialized" || method == "initialized") {
2169 initialized_ = true;
2170 AiPanel::instance().addLog("system", "mcp.initialized", "handshake complete");
2171 }
2172 return;
2173 }
2174
2175 auto params = [&]() -> Poco::JSON::Object::Ptr {
2176 if (!obj->has("params")) return Poco::JSON::Object::Ptr(new Poco::JSON::Object());
2177 try {
2178 return obj->getObject("params");
2179 } catch (...) {
2180 return Poco::JSON::Object::Ptr(new Poco::JSON::Object());
2181 }
2182 };
2183
2184 if (method == "initialize") {
2185 sendLine(handleInitialize(*this, idJson, params()));
2186 return;
2187 }
2188 if (method == "ping") {
2189 sendLine(makeResult(idJson, "{}"));
2190 return;
2191 }
2192 if (method == "tools/list") {
2193 sendLine(handleToolsList(idJson));
2194 return;
2195 }
2196 if (method == "tools/call") {
2197 sendLine(handleToolsCall(*this, idJson, params()));
2198 return;
2199 }
2200 if (method == "resources/list") {
2201 sendLine(handleResourcesList(idJson));
2202 return;
2203 }
2204 if (method == "resources/read") {
2205 sendLine(handleResourcesRead(idJson, params()));
2206 return;
2207 }
2208 if (method == "prompts/list") {
2209 sendLine(handlePromptsList(idJson));
2210 return;
2211 }
2212 if (method == "prompts/get") {
2213 sendLine(handlePromptsGet(idJson, params()));
2214 return;
2215 }
2216
2217 sendLine(makeError(idJson, -32601, "Method not found: " + method));
2218 } catch (const Poco::Exception& e) {
2219 sendLine(makeError("null", -32700, std::string("Parse error: ") + e.displayText()));
2220 } catch (const std::exception& e) {
2221 sendLine(makeError("null", -32603, e.what()));
2222 } catch (...) {
2223 sendLine(makeError("null", -32603, "Internal error"));
2224 }
2225}
2226
2227} // namespace eve::dev
LogicalId target
ActionParameterOperation operation
Value::Object payload
Duration start
float w
Definition AnimClip.cpp:738
int observer
Definition AnimSmr.cpp:162
int root
Definition AnimSmr.cpp:119
std::string output
std::string descriptor
Audio * audio
std::vector< QuestEvent > pending
const std::string & s
struct SQVM * HSQUIRRELVM
std::string title
bool changed
eve::Value condition
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
std::string name
Definition ECS.cpp:154
EnvironmentMetricContract contract
std::uint16_t method
Runtime game-world Discover snapshot for MCP / Play Host.
Versioned JSON facade shared by scripting, MCP and scenario tooling.
std::string message
DiagnosticCode code
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
glm::vec4 tint
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
int h
std::array< float, 3 > position
std::uint32_t bone
std::map< std::string, Node > nodes
std::string id
std::string response
Poco::JSON::Object::Ptr result
Playtest input batch tools for the embedded MCP server.
Snapshot snapshot
std::vector< RecipeParam > params
std::uint64_t bytes
bool exists
Shared helpers for MCP tools that drive the embedded scene_director kit.
Project-script → MCP export registry.
bool valid
double maxError
std::vector< std::string > mismatches
Named Agent task profiles that narrow the MCP tool surface.
#define EVE_MCP_TOOL_FAMILY(Id, Schemas, Handler, Payload)
Declare one family beside its implementation; CMake derives composition from compiled sources.
Toolset / read-only / exclude filtering for the embedded MCP server.
MeleePoint3 a
Definition MeleeHit.cpp:40
int level
const std::string * tag
ssq::Object frame
glm::dvec2 center
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
BakeRecipe recipe
float f
std::string action
Definition PlayHost.cpp:118
std::string path
Definition PlayHost.cpp:111
Versioned Play Host protocol for Agent pause / step / observe / capture.
std::string uri
std::weak_ptr< PrimitiveScene > scene
const eve::script::BindingContractRegistry & registry
std::string body
Object::Ptr value
int detail
glm::vec3 eye
const RoadNode * node
脚本组件数据的持久化信封(方案文档实施顺序第 4 步 / J-3 的存档通路)。
unsigned line
std::string text
ScriptStructure out
std::string_view source
std::string string
const SquirrelValueOptions & options
int count
int limit
Definition TreeMesh.cpp:166
int children
Definition TreeMesh.cpp:432
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
UIHostHandle host
uint32_t index
Audio control surface (provided by the audio module).
Definition AudioQuery.h:8
Module-neutral bridge from DevTools/MCP to the editor command protocol.
Declarative editor-host control (provided by the ui module).
Definition EditorHost.h:17
Particle system query surface (provided by the particles module).
2D physics world query surface (provided by the physics module).
Module-neutral JSON bridge from DevTools/MCP to PixelWorld tooling.
Procedural generation query surface (provided by the procgen module).
Frame capture + camera + visible-entity inspection (graphics).
virtual Result< CaptureImageInfo > savePng(const std::string &path)=0
Capture the last presented frame and write a PNG.
virtual Result< Renderable3DInfo > inspectRenderable3D(std::uint32_t entityId, std::uint32_t generation)=0
Inspect one live Renderable3D using its complete ECS identity.
virtual RenderStatusInfo status() const =0
Status.
Scene graph query/mutation surface (provided by the scene module).
Definition SceneQuery.h:31
Semantic retained-UI automation provided by the ui module.
void addNote(std::string text)
Definition AiPanel.cpp:95
std::string formatLog(size_t max=64) const
Definition AiPanel.cpp:106
void setMcpPort(int port)
Definition AiPanel.cpp:49
void addLog(std::string kind, std::string title, std::string detail={})
Definition AiPanel.cpp:84
static AiPanel & instance()
Definition AiPanel.cpp:15
void setMcpConnected(bool on)
Definition AiPanel.cpp:59
void setClientName(std::string name)
Definition AiPanel.cpp:69
static DebugAdapter & instance()
static Debugger & instance()
Definition Debugger.cpp:387
static DevTool & instance()
Definition DevTool.cpp:138
Embedded Model Context Protocol (MCP) server for AI-assisted game development.
Definition McpServer.hpp:35
void setGameRoot(std::string root)
Game / project directory hint for agents.
int listen(uint16_t port)
Bind TCP listen port (0 = ephemeral). Returns bound port or 0 on failure.
bool listenStdio(std::istream &in=std::cin, std::ostream &out=std::cout)
Switch to stdio transport (MCP stdio server). A reader thread pulls newline-delimited JSON from in in...
static McpServer & instance()
static RenderVision & instance()
void pollPending(eve::IRenderCapture *cap, const std::string &renderDataJson)
McpServer::poll hook: performs one pending dump when safe, clears flag.
std::string describe(eve::IRenderCapture *cap, const std::string &renderDataJson, bool fresh, const std::string &reason={})
Main-thread capture + vision describe. Returns the description text, or a string starting with "error...
std::string currentPoseJson()
当前激活相机位姿 JSON(eye/target/fov/viewport)。
std::string visibleEntitiesJson(const glm::vec3 *eye=nullptr, const glm::vec3 *target=nullptr, float fov=0.f)
生成当前视锥内可见实体的结构化 JSON: { camera, viewport, entities:[ { id, asset, world_aabb:{min,...
InspectCapture capture(const std::string &outDir={}, const std::string &tag="frame", const std::vector< std::string > &buffers={})
锁定当前相机 → 捕获渲染帧 PNG → 立刻导出配套可见实体几何 JSON。 两者共享同一相机位姿,杜绝图片与实体数据错位。 outDir 为空时使用缓存目录。返回文件路径与图像尺寸。 buffers...
static SceneInspect & instance()
bool setCameraPose(const glm::vec3 &eye, const glm::vec3 &rotYawPitch, float fov=0.f)
以 pos + 欧拉角 rot 设置相机位姿。 rot = [yawDeg, pitchDeg](与 firstperson 约定一致,Y-up)。 fov <= 0 时保持当前 FOV。
static std::vector< InspectView > generateViews(const glm::vec3 &center, float fov=60.f)
围绕 center 自动生成一组标准化巡检机位:
static Snapshot & instance()
Definition Snapshot.cpp:468
const BindingContract * find(std::string_view key) const noexcept
Finds a binding contract.
std::vector< BindingSearchHit > search(std::string_view query, std::string_view moduleFilter={}, std::string_view classFilter={}, size_t limit=20) const
Ranked substring/token search over keys, classes, methods and documentation ids.
const BindingContract * findMethod(std::string_view method) const noexcept
Finds a uniquely named method.
I * query()
Queries .
Definition Capability.h:88
bool ensureSceneDirectorInstalled(HSQUIRRELVM vm, std::string *err)
Convenience overload: allow heavy install immediately (tests / explicit install tool).
bool getArgBool(Poco::JSON::Object::Ptr args, const char *key, bool def=false)
Boolean argument, or def when absent or not convertible.
Definition McpArgs.hpp:65
int scriptToolCount()
Number of exported tools (for eve_status).
std::size_t mcpCallgraphStackDepth()
Definition DevTool.cpp:895
float getArgFloat(Poco::JSON::Object::Ptr args, const char *key, float def=0.f)
Floating-point argument, or def when absent or not convertible.
Definition McpArgs.hpp:55
Result< std::string > executePlayJson(std::string_view requestJson)
Parse, execute and serialize one Play JSON request against the live engine.
Definition PlayHost.cpp:898
bool mcpToolAllowed(std::string_view name)
Whether name is visible under the current env filter.
std::string mcpJsonEscape(const std::string &value)
Escape a raw string for embedding inside a JSON string literal.
Definition McpJson.hpp:31
void resetMcpFrameCapture()
Main-thread disconnect cleanup; workers observe cancellation before publishing files.
Result< std::string > sceneLiteral(const Poco::Dynamic::Var &value, int depth=0)
Encode owning JSON data as a Squirrel literal without losing pointer containers or precision.
Poco::Dynamic::Var getArgVar(Poco::JSON::Object::Ptr args, const char *key)
Raw JSON value of key, or an empty Var when absent.
Definition McpArgs.hpp:15
std::string callScriptTool(const std::string &name, Poco::JSON::Object::Ptr args)
Invoke one exported tool.
std::size_t mcpCallgraphEvents()
Definition DevTool.cpp:893
void flushPendingSceneDirectorInstall(HSQUIRRELVM vm)
Run a deferred scene_director install on the game/MCP poll thread.
std::string mcpStringify(const Poco::Dynamic::Var &value)
Compact single-line JSON text for a newline-framed MCP payload.
Definition McpJson.hpp:24
std::string textContentResult(const std::string &text, bool isError=false)
MCP tools/call result object carrying one text content item.
Definition McpJson.hpp:84
void resetMcpActionGuide()
Clear the process-local guide-pack session used by get/set.
const std::string & mcpLastReport()
Definition DevTool.cpp:907
Result< Value > liveGameWorldSnapshot()
Build the Discover snapshot against the live engine.
bool mcpDevAttached()
Thin hooks so McpServer.cpp need not include DevTool.hpp (avoids a cycle).
Definition DevTool.cpp:891
Poco::JSON::Object::Ptr crashLogSummary()
Summary of the persistent crash/error log (eve.log).
std::string sceneDirectorToolError(const std::string &name, const std::string &err)
Format a scene-director tool failure.
bool runMcpVmSnippet(HSQUIRRELVM vm, const std::string &source, std::string *err)
Compile and run a transient MCP snippet (no return value). @thread Game-loop / MCP poll thread with a...
std::string scriptToolSchemas()
Comma-free MCP tool schema fragments for every exported tool.
Poco::JSON::Object::Ptr mcpFailureObject(const std::string &error, const std::string &hint={}, bool retryable=false, const std::vector< std::string > &nextTools={})
Structured tool failure object for agent self-correction.
Definition McpJson.hpp:63
void pollMcpInputBatches()
Advance pending wait/capture batches once per game-loop poll. @thread MCP poll / game-loop thread onl...
std::string filterMcpToolsBody(std::string_view toolsBody)
Filter a JSON tools array body in place (objects joined by commas).
std::string mcpToolFilteredPayload(std::string_view name)
Human-readable rejection payload fields when a call is filtered out.
void mcpFilterNoteCall(bool allowed, std::size_t resultBytes, bool offeredEscalate)
Record a tools/call attempt for proxy metrics.
int getArgInt(Poco::JSON::Object::Ptr args, const char *key, int def=0)
Integer argument, or def when absent or not convertible.
Definition McpArgs.hpp:35
bool isScriptTool(const std::string &name)
Whether name is exported by the project script registry.
std::string getArgString(Poco::JSON::Object::Ptr args, const char *key, const std::string &def={})
String argument, or def when absent or not convertible.
Definition McpArgs.hpp:25
std::string_view mcpCoreToolSchemas()
Borrow legacy core tool schemas; process lifetime, synchronized first initialization....
const McpToolFamilyCatalog & compiledMcpToolCatalog()
Build the process-immortal compiled catalogue once, then borrow it until exit. @lifetime Survives sta...
@ Snapshot
Script state was restored while the debugger was already paused.
std::string callSceneDirectorReturn(HSQUIRRELVM vm, const std::string &snippet, std::string *err)
Compile+run a snippet that returns a value; serialize it as JSON.
Status invalid(const char *message)
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
Result< int > publish(Heightmap &target, std::vector< float > candidate)
Publish.
const BindingContractRegistry & generatedBindingContracts()
Process-wide generated Binding Contracts for this linked engine build.
EVENGINE_API_FOUNDATION Result< std::string > scriptComponentStatesJson()
引擎侧脚本组件数据的**工具视图**(MCP eve_script_components 与诊断用)。
Result< std::string > executeGameplayControlJson(std::string_view requestJson)
Parse, execute and serialize one gameplay-control JSON request.
Pixel size reported by a successful frame/image capture.
Ray-cast result (value type).
Render surface / frame state snapshot (value type).
Serializable snapshot of one scene node (value type, no scene types).
Definition SceneQuery.h:18
static T & get()
Returns the process-lifetime instance.
Definition Immortal.hpp:21
Complete script-facing contract for a native function or method.
glm::uvec4 info