载入中...
搜索中...
未找到
McpDomainTools.cpp
浏览该文件的文档.
3
6
8#include "common/Capability.h"
9#include "common/DecalQuery.h"
12#include "common/SensingQuery.h"
13
14#include <Poco/Dynamic/Var.h>
15#include <Poco/JSON/Object.h>
16#include <Poco/JSON/Parser.h>
17
18#include <algorithm>
19#include <array>
20#include <cstdint>
21#include <string>
22#include <string_view>
23
24namespace eve::dev {
25namespace {
26
27std::string textPayload(Poco::JSON::Object::Ptr object, bool isError = false) {
28 return textContentResult(mcpStringify(Poco::Dynamic::Var(object)), isError);
29}
30
31std::string errorPayload(const std::string& message) {
32 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
33 out->set("ok", false);
34 out->set("error", message);
35 return textPayload(out, true);
36}
37
39std::string unavailablePayload(const char* capability) {
40 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
41 out->set("ok", false);
42 out->set("unavailable", capability);
43 out->set("error", std::string(capability) + " is not provided by the loaded modules");
44 return textPayload(out);
45}
46
47// ============================== Decals =====================================
48
50std::array<float, 3> getArgVec3(Poco::JSON::Object::Ptr args, const char* key, const std::array<float, 3>& def) {
51 if (!args || !args->has(key)) return def;
52 try {
53 auto array = args->getArray(key);
54 if (array && array->size() >= 3) {
55 return {static_cast<float>(array->get(0).convert<double>()),
56 static_cast<float>(array->get(1).convert<double>()),
57 static_cast<float>(array->get(2).convert<double>())};
58 }
59 } catch (...) {
60 }
61 return def;
62}
63
65constexpr std::uint32_t kAllCategoryBits = 0xFFFFFFFFu;
66
67std::string decalStatus() {
68 auto* decals = eve::cap::query<eve::IDecalQuery>();
69 if (!decals) return unavailablePayload(eve::IDecalQuery::capabilityName);
70 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
71 out->set("ok", true);
72 out->set("count", decals->count());
73 return textPayload(out);
74}
75
76std::string decalProject(Poco::JSON::Object::Ptr args) {
77 auto* decals = eve::cap::query<eve::IDecalQuery>();
78 if (!decals) return unavailablePayload(eve::IDecalQuery::capabilityName);
79
80 // A decal needs a surface normal; up is the least surprising default, and a
81 // caller that omits it almost always means "on the ground".
82 const float nx = getArgFloat(args, "nx", 0.f);
83 const float ny = getArgFloat(args, "ny", 1.f);
84 const float nz = getArgFloat(args, "nz", 0.f);
85
86 // Zero means "engine default" for every size/time field: the decal module
87 // owns those defaults, so the tool must not invent a second set.
88 const int id =
89 decals->project(getArgFloat(args, "x"), getArgFloat(args, "y"), getArgFloat(args, "z"), nx, ny, nz,
90 /*albedoTexture=*/nullptr, getArgString(args, "kind"), getArgFloat(args, "size"),
91 getArgFloat(args, "depth"), getArgBool(args, "randomYaw"), getArgInt(args, "seed"),
92 getArgFloat(args, "fadeIn"), getArgFloat(args, "lifetime"), getArgFloat(args, "fadeOut"));
93 if (id <= 0) return errorPayload("decal projection was rejected");
94
95 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
96 out->set("ok", true);
97 out->set("id", id);
98 out->set("count", decals->count());
99 return textPayload(out);
100}
101
102std::string decalRemove(Poco::JSON::Object::Ptr args) {
103 auto* decals = eve::cap::query<eve::IDecalQuery>();
104 if (!decals) return unavailablePayload(eve::IDecalQuery::capabilityName);
105 const int id = getArgInt(args, "id", -1);
106 if (id <= 0) return errorPayload("missing decal id");
107 if (!decals->remove(id)) return errorPayload("no decal with id " + std::to_string(id));
108
109 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
110 out->set("ok", true);
111 out->set("count", decals->count());
112 return textPayload(out);
113}
114
115std::string decalClear() {
116 auto* decals = eve::cap::query<eve::IDecalQuery>();
117 if (!decals) return unavailablePayload(eve::IDecalQuery::capabilityName);
118 const int before = decals->count();
119 decals->clearAll();
120
121 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
122 out->set("ok", true);
123 out->set("removed", before);
124 out->set("count", decals->count());
125 return textPayload(out);
126}
127
128std::string decalSetLimit(Poco::JSON::Object::Ptr args) {
129 auto* decals = eve::cap::query<eve::IDecalQuery>();
130 if (!decals) return unavailablePayload(eve::IDecalQuery::capabilityName);
131 const std::string kind = getArgString(args, "kind");
132 if (kind.empty()) return errorPayload("missing kind");
133 const int limit = getArgInt(args, "limit", -1);
134 if (limit < 0) return errorPayload("limit must be >= 0");
135 decals->setLimit(kind, limit);
136
137 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
138 out->set("ok", true);
139 out->set("kind", kind);
140 out->set("limit", limit);
141 return textPayload(out);
142}
143
144// ====================== 3D spatial queries ==================================
145// The 2D tools (eve_physics_raycast) cannot answer "what is between the camera
146// and the player" or "how high is the ground here" in a 3D scene; these two
147// capabilities already existed and only lacked an agent surface.
148
149std::string physicsSphereCast(Poco::JSON::Object::Ptr args) {
150 if (!args || !args->has("from") || !args->has("to")) return errorPayload("from and to are required");
151 auto* cast = eve::cap::query<eve::ICameraObstructionQuery>();
152 if (!cast) return unavailablePayload(eve::ICameraObstructionQuery::capabilityName);
153
154 const std::array<float, 3> from = getArgVec3(args, "from", {0.f, 0.f, 0.f});
155 const std::array<float, 3> to = getArgVec3(args, "to", {0.f, 0.f, 0.f});
156 const float radius = getArgFloat(args, "radius", 0.f);
157 const long long mask = getArgInt64(args, "maskBits", static_cast<long long>(kAllCategoryBits));
158
160 const bool swept = cast->sphereCast(from[0], from[1], from[2], to[0], to[1], to[2], radius,
161 static_cast<std::uint64_t>(mask), getArgInt(args, "ignoredBodyId", -1), &hit);
162 if (!swept) return errorPayload("sphere cast is unavailable (no live 3D physics world)");
163
164 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
165 out->set("ok", true);
166 out->set("hit", hit.hit);
167 out->set("radius", radius);
168 if (hit.hit) {
169 out->set("bodyId", hit.bodyId);
170 out->set("fraction", hit.fraction);
171 Poco::JSON::Array::Ptr point = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
172 point->add(hit.x);
173 point->add(hit.y);
174 point->add(hit.z);
175 out->set("point", point);
176 Poco::JSON::Array::Ptr normal = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
177 normal->add(hit.normalX);
178 normal->add(hit.normalY);
179 normal->add(hit.normalZ);
180 out->set("normal", normal);
181 }
182 return textPayload(out);
183}
184
185std::string worldProjectDown(Poco::JSON::Object::Ptr args) {
186 auto* world = eve::cap::query<eve::IProcgenWorldQuery>();
187 if (!world) return unavailablePayload(eve::IProcgenWorldQuery::capabilityName);
188
189 const float x = getArgFloat(args, "x");
190 const float z = getArgFloat(args, "z");
191 const float maxY = getArgFloat(args, "maxY", 1000.f);
192 const float minY = getArgFloat(args, "minY", -1000.f);
193 const long long mask = getArgInt64(args, "maskBits", static_cast<long long>(kAllCategoryBits));
194
195 auto projected = world->projectDown(x, z, maxY, minY, static_cast<std::uint64_t>(mask));
196 if (!projected) return errorPayload("world projection failed: " + projected.status().describe());
197
198 const eve::ProcgenSurfaceHit& surface = projected.value();
199 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
200 out->set("ok", true);
201 out->set("hit", surface.hit);
202 out->set("x", x);
203 out->set("z", z);
204 if (surface.hit) {
205 out->set("objectId", static_cast<Poco::Int64>(surface.objectId));
206 out->set("y", surface.y);
207 Poco::JSON::Array::Ptr normal = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
208 normal->add(surface.normalX);
209 normal->add(surface.normalY);
210 normal->add(surface.normalZ);
211 out->set("normal", normal);
212 }
213 return textPayload(out);
214}
215
216// ========================== Profiler ========================================
217
219std::string profilerFrame() {
220 auto* profiler = eve::cap::query<eve::IProfilerQuery>();
221 if (!profiler) return unavailablePayload(eve::IProfilerQuery::capabilityName);
222 return textContentResult(profiler->frameJson());
223}
224
225std::string profilerReport() {
226 auto* profiler = eve::cap::query<eve::IProfilerQuery>();
227 if (!profiler) return unavailablePayload(eve::IProfilerQuery::capabilityName);
228 const std::string report = profiler->textReport();
229 return textContentResult(report.empty() ? "(no completed frame yet)\n" : report);
230}
231
232std::string profilerHotspots(Poco::JSON::Object::Ptr args) {
233 auto* profiler = eve::cap::query<eve::IProfilerQuery>();
234 if (!profiler) return unavailablePayload(eve::IProfilerQuery::capabilityName);
235 int limit = getArgInt(args, "limit", 8);
236 const double minSelfMs = static_cast<double>(getArgFloat(args, "minSelfMs", 0.f));
237 if (limit < 0) limit = 0;
238 if (limit > 64) limit = 64;
239 return textContentResult(profiler->hotspotsJson(static_cast<std::size_t>(limit), minSelfMs));
240}
241
242// ========================== Sensing =========================================
243
244std::string sensingLastQuery(Poco::JSON::Object::Ptr args) {
245 auto* sensing = eve::cap::query<eve::ISensingQuery>();
246 if (!sensing) return unavailablePayload(eve::ISensingQuery::capabilityName);
247
248 const bool hasIndex = args && args->has("world");
249 const int index = getArgInt(args, "world", -1);
250
251 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
252 out->set("ok", true);
253 out->set("worldCount", sensing->worldCount());
254
255 Poco::JSON::Array::Ptr worlds = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
256 bool found = false;
257 for (const auto& entry : sensing->lastQueries()) {
258 if (hasIndex && entry.index != index) continue;
259 found = true;
260 Poco::JSON::Object::Ptr item = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
261 item->set("index", entry.index);
262 // The world owns this document's schema (eve.sensing.lastQuery v1); nest
263 // it as an object so the agent does not have to parse JSON-in-JSON.
264 try {
265 Poco::JSON::Parser parser;
266 Poco::Dynamic::Var parsed = parser.parse(entry.lastQueryJson);
267 item->set("query", parsed);
268 } catch (...) {
269 item->set("query", entry.lastQueryJson);
270 }
271 worlds->add(item);
272 }
273 if (hasIndex && !found) {
274 Poco::JSON::Object::Ptr missing = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
275 missing->set("ok", false);
276 missing->set("error", "no live sensing world with index " + std::to_string(index));
277 return textPayload(missing, true);
278 }
279 out->set("worlds", worlds);
280 return textPayload(out);
281}
282
283} // namespace
284
285bool isMcpDomainTool(std::string_view name) {
286 return name == "eve_decal_status" || name == "eve_decal_project" || name == "eve_decal_remove" ||
287 name == "eve_decal_clear" || name == "eve_decal_set_limit" || name == "eve_physics_sphere_cast" ||
288 name == "eve_world_project_down" || name == "eve_profiler_frame" || name == "eve_profiler_report" ||
289 name == "eve_profiler_hotspots" || name == "eve_sensing_last_query";
290}
291
292std::string callMcpDomainTool(std::string_view name, Poco::JSON::Object::Ptr args) {
293 if (name == "eve_decal_status") return decalStatus();
294 if (name == "eve_decal_project") return decalProject(args);
295 if (name == "eve_decal_remove") return decalRemove(args);
296 if (name == "eve_decal_clear") return decalClear();
297 if (name == "eve_decal_set_limit") return decalSetLimit(args);
298 if (name == "eve_physics_sphere_cast") return physicsSphereCast(args);
299 if (name == "eve_world_project_down") return worldProjectDown(args);
300 if (name == "eve_profiler_frame") return profilerFrame();
301 if (name == "eve_profiler_report") return profilerReport();
302 if (name == "eve_profiler_hotspots") return profilerHotspots(args);
303 if (name == "eve_sensing_last_query") return sensingLastQuery(args);
304 return errorPayload("unknown domain tool '" + std::string(name) + "'");
305}
306
307std::string_view mcpDomainToolSchemas() {
308 return R"json({"name":"eve_decal_status","description":"Live decal count. Decals are runtime surface projections (scorch marks, blood, footprints) owned by the decal module.","inputSchema":{"type":"object","properties":{}}},{"name":"eve_decal_project","description":"Project a decal at a world position facing a normal. Omitted size/depth/lifetime/fade fields use the decal module defaults; no albedo texture is bound through this path, so decals take the module's default look.","inputSchema":{"type":"object","properties":{"x":{"type":"number"},"y":{"type":"number"},"z":{"type":"number"},"nx":{"type":"number"},"ny":{"type":"number"},"nz":{"type":"number"},"kind":{"type":"string","description":"decal kind; a kind with a configured limit evicts its oldest instance first"},"size":{"type":"number"},"depth":{"type":"number"},"randomYaw":{"type":"boolean"},"seed":{"type":"integer","description":"deterministic yaw seed"},"fadeIn":{"type":"number"},"lifetime":{"type":"number"},"fadeOut":{"type":"number"}},"required":["x","y","z"]}},{"name":"eve_decal_remove","description":"Remove one decal by id and report the remaining count.","inputSchema":{"type":"object","properties":{"id":{"type":"integer","minimum":1}},"required":["id"]}},{"name":"eve_decal_clear","description":"Remove every decal and report how many were dropped.","inputSchema":{"type":"object","properties":{}}},{"name":"eve_decal_set_limit","description":"Set the per-kind instance limit used for eviction; 0 disables eviction for that kind.","inputSchema":{"type":"object","properties":{"kind":{"type":"string"},"limit":{"type":"integer","minimum":0}},"required":["kind","limit"]}},{"name":"eve_physics_sphere_cast","description":"Sweep a sphere (radius 0 = ray) through every registered 3D physics world and return the closest hit: bodyId, fraction along the segment, world point and surface normal. This is the 3D counterpart of eve_physics_raycast, which only queries 2D worlds.","inputSchema":{"type":"object","properties":{"from":{"type":"array","items":{"type":"number"},"description":"[x,y,z] segment start"},"to":{"type":"array","items":{"type":"number"},"description":"[x,y,z] segment end"},"radius":{"type":"number","minimum":0,"description":"sphere radius (default 0 = ray)"},"maskBits":{"type":"integer","description":"collision category mask; default matches every category, 0 matches none"},"ignoredBodyId":{"type":"integer","description":"body to skip, e.g. the camera rig"}},"required":["from","to"]}},{"name":"eve_world_project_down","description":"Project a vertical ray through the procedural/3D world surface at (x,z) and return the closest hit height and normal. Use it to place objects on terrain or to check ground level under a moving entity.","inputSchema":{"type":"object","properties":{"x":{"type":"number"},"z":{"type":"number"},"maxY":{"type":"number","description":"projection start height (default 1000)"},"minY":{"type":"number","description":"projection end height (default -1000)"},"maskBits":{"type":"integer","description":"collision category mask; default matches every category"}},"required":["x","z"]}},{"name":"eve_profiler_frame","description":"Last completed frame's profile as JSON (schema eve.profiler.frame v2): enabled/hasFrame, cpuFrameMs, optional gpuMs, hotspots (top 8 by selfMs for quick triage), and full zones sorted by self time. Prefer eve_profiler_hotspots when you only need the expensive zones.","inputSchema":{"type":"object","properties":{}}},{"name":"eve_profiler_report","description":"Human-readable per-module/per-zone hotspot report of the last completed frame (the same text the profiler panel shows).","inputSchema":{"type":"object","properties":{}}},{"name":"eve_profiler_hotspots","description":"Top CPU zones of the last completed frame (schema eve.profiler.hotspots). Use after a scaled play/smoke run to spot unreasonable work (for example a full unit scan instead of sensing.query). limit defaults to 8 (max 64); minSelfMs drops quieter zones.","inputSchema":{"type":"object","properties":{"limit":{"type":"integer","minimum":0,"maximum":64,"description":"max zones to return (default 8)"},"minSelfMs":{"type":"number","minimum":0,"description":"drop zones with selfMs strictly below this threshold (default 0)"}}}},{"name":"eve_sensing_last_query","description":"Last completed sensing query of every live sensing world, with the world's own document (schema eve.sensing.lastQuery) nested as `query`: origin, shape kind, spatial scan counters, and the ranked candidates with their scores and score reasons. Answers why an NPC selected a particular target.","inputSchema":{"type":"object","properties":{"world":{"type":"integer","minimum":0,"description":"optional world index; omit to read every live world"}}}})json";
309}
310
311} // namespace eve::dev
312
313namespace eve::dev {
315} // namespace eve::dev
double z
double x
int mask
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
std::string to
std::string from
Capability-backed domain tool families for the embedded MCP server.
#define EVE_MCP_TOOL_FAMILY(Id, Schemas, Handler, Payload)
Declare one family beside its implementation; CMake derives composition from compiled sources.
double radius
Definition MeleeHit.cpp:42
Texture * normal
bool hit
bool found
ScriptStructure out
std::string kind
int limit
Definition TreeMesh.cpp:166
uint32_t index
glm::vec3 point
std::unordered_map< PhysicsWorldHandle::index_type, World3D * > worlds
Definition World3D.cpp:46
static constexpr const char * capabilityName
static constexpr const char * capabilityName
Definition DecalQuery.h:19
static constexpr const char * capabilityName
static constexpr const char * capabilityName
static constexpr const char * capabilityName
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
bool isMcpDomainTool(std::string_view name)
Whether name belongs to a capability-backed domain tool family.
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
std::string_view mcpDomainToolSchemas()
Comma-free MCP tool schema fragments for the domain families.
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
long long getArgInt64(Poco::JSON::Object::Ptr args, const char *key, long long def=0)
64-bit integer argument (sequence numbers, handles), or def.
Definition McpArgs.hpp:45
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
std::string callMcpDomainTool(std::string_view name, Poco::JSON::Object::Ptr args)
Execute one domain tool.
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
Closest hit returned by the optional camera-obstruction provider.
Value result for a procedural world-surface projection query.