载入中...
搜索中...
未找到
McpSceneSearch.cpp
浏览该文件的文档.
1#include "common/Capability.h"
5
6#include <algorithm>
7#include <cmath>
8#include <set>
9#include <stdexcept>
10
11namespace eve::dev {
12namespace {
13using Object = Poco::JSON::Object;
14using Array = Poco::JSON::Array;
15
16std::string string(Object::Ptr args, const char* key, bool required = false) {
17 if (!args->has(key) && !required) return {};
18 if (!args->has(key) || !args->get(key).isString())
19 throw std::invalid_argument(std::string(key) + " must be a string");
20 auto value = args->getValue<std::string>(key);
21 if (value.size() > 512 || (required && value.empty()))
22 throw std::invalid_argument(std::string(key) + " invalid length");
23 return value;
24}
25
26double number(const Poco::Dynamic::Var& value) {
27 if (!value.isNumeric() || value.isBoolean()) throw std::invalid_argument("expected numeric scalar");
28 double out = value.convert<double>();
29 if (!std::isfinite(out)) throw std::invalid_argument("nonfinite scalar");
30 return out;
31}
32
33int integer(Object::Ptr args, const char* key, int fallback, int low, int high) {
34 if (!args->has(key)) return fallback;
35 if (!args->get(key).isInteger()) throw std::invalid_argument(std::string(key) + " must be an integer");
36 const double value = number(args->get(key));
37 if (value < low || value > high) throw std::invalid_argument(std::string(key) + " outside budget");
38 return int(value);
39}
40
41Array::Ptr array(Object::Ptr args, const char* key, std::size_t maximum) {
42 auto out = args->getArray(key);
43 if (!out || out->size() > maximum) throw std::invalid_argument(std::string(key) + " invalid array or budget");
44 return out;
45}
46
47std::vector<double> vector(Array::Ptr values) {
48 if (!values || values->size() < 1 || values->size() > 1024) throw std::invalid_argument("invalid vector dimension");
49 std::vector<double> out;
50 for (const auto& value : *values) out.push_back(number(value));
51 return out;
52}
53
54Object::Ptr envelope() {
55 Object::Ptr out = new Object;
56 out->set("schema", "eve.scene-search");
57 out->set("schemaVersion", 1);
58 out->set("ok", true);
59 return out;
60}
61
62Object::Ptr record(const SceneSearchRecord& input) {
63 Object::Ptr out = new Object;
64 out->set("id", input.id);
65 out->set("persistentId", input.persistentId);
66 out->set("name", input.name);
67 out->set("space", input.space);
68 out->set("text", input.text);
69 out->set("visible", input.visible);
70 out->set("layer", input.layer);
71 Array::Ptr tags = new Array, kinds = new Array, position = new Array;
72 for (const auto& tag : input.tags) tags->add(tag);
73 for (const auto& kind : input.kinds) kinds->add(kind);
74 for (double value : input.position) position->add(value);
75 out->set("tags", tags);
76 out->set("kinds", kinds);
77 out->set("position", position);
78 Array::Ptr axes = new Array;
79 for (const auto& axis : input.axes) {
80 Array::Ptr row = new Array;
81 for (double value : axis) row->add(value);
82 axes->add(row);
83 }
84 out->set("axes", axes);
85 if (input.bounds) {
86 Array::Ptr bounds = new Array;
87 for (double value : *input.bounds) bounds->add(value);
88 out->set("bounds", bounds);
89 }
90 return out;
91}
92
93std::string failed(std::string code, std::string message) {
94 auto out = envelope();
95 out->set("ok", false);
96 out->set("error", std::move(code));
97 out->set("message", std::move(message));
98 return textContentResult(mcpStringify(out), true);
99}
100std::string failed(const Status& status) {
101 return failed(std::string(statusCodeName(status.code())), status.describe());
102}
103} // namespace
104
105std::string callSceneSearch(std::string_view name, Object::Ptr args) try {
106 if (!args) throw std::invalid_argument("arguments required");
107 std::set<std::string> allowed;
108 if (name == "eve_scene_search_prepare")
109 allowed = {"host"};
110 else if (name == "eve_scene_search_status")
111 allowed = {};
112 else if (name == "eve_scene_search_publish")
113 allowed = {"snapshot", "model", "vectors"};
114 else if (name == "eve_scene_search")
115 allowed = {"snapshot", "model", "embedding", "kind", "space", "tags", "visible", "layer",
116 "center", "radius", "limit", "scanBudget", "pageToken", "spatial", "candidates"};
117 else
118 return failed("unknown_tool", "Unknown scene search tool");
119 for (const auto& entry : *args)
120 if (!allowed.contains(entry.first)) throw std::invalid_argument("unknown field: " + entry.first);
121 auto* provider = cap::query<ISceneSearch>();
122 if (!provider) return failed("scene-unavailable", "Scene module is absent or has not been initialized");
123 auto out = envelope();
124 if (name == "eve_scene_search_prepare" || name == "eve_scene_search_status") {
125 auto value =
126 name == "eve_scene_search_prepare" ? provider->prepare(string(args, "host", true)) : provider->status();
127 if (!value.ok()) return failed(value.status());
128 const auto& snapshot = value.value();
129 out->set("snapshot", snapshot.token);
130 out->set("host", snapshot.host);
131 out->set("model", snapshot.model);
132 out->set("backend", snapshot.model.empty() ? "none" : "hnswlib-0.8.0");
133 out->set("spatialContract",
134 "Node origins; 3D world +X right, +Y up, +Z forward; 2D +Y down. Node frames use local +Z forward, "
135 "not Camera3D view -Z. Use frame=observer with an explicit observer node to resolve perspective. "
136 "inside means origin in authored world AABB, not mesh containment. Resolve ambiguous anchor names "
137 "with semantic search first; spatial.reference and observer are exact node IDs.");
138 Array::Ptr records = new Array;
139 for (const auto& item : snapshot.records) records->add(record(item));
140 out->set("records", records);
141 } else if (name == "eve_scene_search_publish") {
143 batch.snapshot = string(args, "snapshot", true);
144 batch.model = string(args, "model", true);
145 const auto values = array(args, "vectors", 4096);
146 // Bound aggregate payload work before allocating normalized copies.
147 std::size_t scalars = 0;
148 for (std::size_t i = 0; i < values->size(); ++i) {
149 auto row = values->getArray(unsigned(i));
150 if (!row || (scalars += row->size()) > 4194304)
151 throw std::invalid_argument("embedding scalar budget exceeded");
152 batch.vectors.push_back(vector(row));
153 }
154 auto result = provider->publish(batch);
155 if (!result.ok()) return failed(result.status());
156 out->set("snapshot", batch.snapshot);
157 out->set("model", batch.model);
158 out->set("backend", "hnswlib-0.8.0");
159 } else {
160 SceneSearchQuery query;
161 query.snapshot = string(args, "snapshot", true);
162 query.model = string(args, "model");
163 query.kind = string(args, "kind");
164 query.space = string(args, "space");
165 query.pageToken = string(args, "pageToken");
166 query.limit = std::size_t(integer(args, "limit", 20, 1, 256));
167 query.scanBudget = std::size_t(integer(args, "scanBudget", 4096, 1, 4096));
168 query.candidates = std::size_t(integer(args, "candidates", 128, 1, 4096));
169 if (args->has("spatial")) {
170 auto spatial = array(args, "spatial", 16);
171 for (std::size_t i = 0; i < spatial->size(); ++i) {
172 auto item = spatial->getObject(unsigned(i));
173 if (!item) throw std::invalid_argument("spatial predicates must be objects");
174 for (const auto& entry : *item)
175 if (!std::set<std::string>{"relation", "reference", "frame", "observer", "distance", "margin"}
176 .contains(entry.first))
177 throw std::invalid_argument("unknown spatial field: " + entry.first);
179 const auto relation = string(item, "relation", true);
180 const auto frame = item->has("frame") ? string(item, "frame", true) : "world";
181 const auto relationAt =
183 const auto frameAt = std::find(sceneSpatialFrameNames.begin(), sceneSpatialFrameNames.end(), frame);
184 if (relationAt == sceneSpatialRelationNames.end() || frameAt == sceneSpatialFrameNames.end())
185 throw std::invalid_argument("unknown spatial relation/frame");
186 constraint.relation = SceneSpatialRelation(relationAt - sceneSpatialRelationNames.begin());
187 constraint.frame = SceneSpatialFrame(frameAt - sceneSpatialFrameNames.begin());
188 constraint.reference = string(item, "reference", true);
189 constraint.observer = string(item, "observer");
190 if (item->has("distance")) constraint.distance = number(item->get("distance"));
191 if (item->has("margin")) constraint.margin = number(item->get("margin"));
192 query.spatial.push_back(std::move(constraint));
193 }
194 }
195 if (args->has("visible")) {
196 if (!args->get("visible").isBoolean()) throw std::invalid_argument("visible must be boolean");
197 query.visible = args->getValue<bool>("visible");
198 }
199 if (args->has("layer")) query.layer = integer(args, "layer", 0, -2147483647, 2147483647);
200 if (args->has("embedding")) query.embedding = vector(array(args, "embedding", 1024));
201 if (args->has("center") != args->has("radius"))
202 throw std::invalid_argument("center and radius must be supplied together");
203 if (args->has("center")) {
204 const auto center = vector(array(args, "center", 3));
205 if (center.size() != 3 || !args->has("radius"))
206 throw std::invalid_argument("center requires three axes and radius");
207 query.center = std::array<double, 3>{center[0], center[1], center[2]};
208 }
209 if (args->has("radius")) query.radius = number(args->get("radius"));
210 if (args->has("tags")) {
211 auto tags = array(args, "tags", 64);
212 for (const auto& tag : *tags) {
213 if (!tag.isString() || tag.convert<std::string>().size() > 256)
214 throw std::invalid_argument("invalid tag");
215 query.tags.push_back(tag.convert<std::string>());
216 }
217 }
218 auto value = provider->query(query);
219 if (!value.ok()) return failed(value.status());
220 const auto& result = value.value();
221 out->set("snapshot", result.snapshot);
222 out->set("indexSnapshot", result.indexSnapshot);
223 out->set("model", result.model);
224 out->set("scanned", Poco::UInt64(result.scanned));
225 out->set("matched", Poco::UInt64(result.matched));
226 out->set("pageToken", result.pageToken);
227 out->set("truncated", !result.pageToken.empty());
228 out->set("consistency", "source-validated");
229 out->set("backend", query.embedding.empty() ? "structured" : "hnswlib-0.8.0");
230 out->set("approximate", result.approximate);
231 out->set("candidateTruncated", result.candidateTruncated);
232 Array::Ptr hits = new Array;
233 for (const auto& hit : result.hits) {
234 auto item = record(hit.record);
235 item->set("score", hit.score);
236 item->set("evidence", query.embedding.empty() ? "exact-filters" : "hnsw-cosine+exact-filters");
237 Array::Ptr spatial = new Array;
238 for (const auto& measured : hit.spatial) {
239 Object::Ptr evidence = new Object;
240 evidence->set("relation", std::string(sceneSpatialRelationNames[std::size_t(measured.relation)]));
241 evidence->set("frame", std::string(sceneSpatialFrameNames[std::size_t(measured.frame)]));
242 evidence->set("reference", measured.reference);
243 evidence->set("observer", measured.observer);
244 evidence->set("distance", measured.distance);
245 Array::Ptr offset = new Array;
246 for (double value : measured.offset) offset->add(value);
247 evidence->set("offsetRightUpForward", offset);
248 spatial->add(evidence);
249 }
250 item->set("spatialEvidence", spatial);
251 hits->add(item);
252 }
253 out->set("hits", hits);
254 }
256} catch (const std::exception& error) {
257 return failed("invalid_argument", error.what());
258}
259
260std::string_view sceneSearchSchemas() {
261 return R"JSON(
262{"name":"eve_scene_search_prepare","description":"Prepare a real scene semantic build snapshot (max 4096 nodes). Returns canonical model text, world pose/axes/bounds and snapshot token. Replaces the previous session. Encode all records outside the frame loop, then publish once to construct the hnswlib index. Scene entities remain unchanged.","inputSchema":{"type":"object","additionalProperties":false,"required":["host"],"properties":{"host":{"type":"string","minLength":1,"maxLength":256}}}},
263{"name":"eve_scene_search_status","description":"Inspect the current semantic/HNSW build and live geometry without rebuilding. Returns snapshot/model/backend and coordinate contract; semantic source changes return an explicit conflict.","inputSchema":{"type":"object","additionalProperties":false,"properties":{}}},
264{"name":"eve_scene_search_publish","description":"Scene build stage: validate all embeddings, construct an hnswlib HNSW index off to the side and publish atomically. One vector per prepared object in record order. Rejects changed semantic source, invalid vectors and mixed dimensions; prior index survives failure. Does not infer or modify scene facts.","inputSchema":{"type":"object","additionalProperties":false,"required":["snapshot","model","vectors"],"properties":{"snapshot":{"type":"string"},"model":{"type":"string","maxLength":512},"vectors":{"type":"array","maxItems":4096,"items":{"type":"array","minItems":1,"maxItems":1024,"items":{"type":"number"}}}}}},
265{"name":"eve_scene_search","description":"Read-only SceneHost search. With embedding, uses a published hnswlib index with exact eligible-label filtering. Resolve semantic anchor names first, then pass exact IDs in spatial predicates. 3D world axes: +X right, +Y up, +Z forward. Node/observer axes use local +Z forward, NOT Camera3D view -Z. Directional filters compare origins with margin; near uses Euclidean distance; inside means candidate origin in authored reference world AABB. Geometry is read live; changed semantic source requires rebuild. Results include measured spatial evidence. HNSW is approximate and candidates bounds the result window; candidateTruncated is separate from pagination. Without embedding, no model is needed.","inputSchema":{"type":"object","additionalProperties":false,"required":["snapshot"],"properties":{"snapshot":{"type":"string"},"model":{"type":"string"},"embedding":{"type":"array","minItems":1,"maxItems":1024,"items":{"type":"number"}},"kind":{"type":"string"},"space":{"type":"string"},"tags":{"type":"array","maxItems":64,"items":{"type":"string"}},"visible":{"type":"boolean"},"layer":{"type":"integer"},"center":{"type":"array","minItems":3,"maxItems":3,"items":{"type":"number"}},"radius":{"type":"number","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":256},"scanBudget":{"type":"integer","minimum":1,"maximum":4096},"pageToken":{"type":"string"},"candidates":{"type":"integer","minimum":1,"maximum":4096,"default":128},"spatial":{"type":"array","maxItems":16,"items":{"type":"object","additionalProperties":false,"required":["relation","reference"],"properties":{"relation":{"type":"string","enum":["left-of","right-of","above","below","in-front-of","behind","near","inside"]},"reference":{"type":"string","description":"Exact host-local reference node ID, not a guessed name"},"frame":{"type":"string","enum":["world","reference","observer"],"default":"world"},"observer":{"type":"string","description":"Required only for observer frame; exact node ID whose local +Z is forward"},"distance":{"type":"number","minimum":0,"default":5,"description":"World-unit radius for near"},"margin":{"type":"number","minimum":0,"default":0.01,"description":"World-unit dead zone for directional predicates; AABB tolerance for inside"}}}}}}}
266)JSON";
267}
269} // namespace eve::dev
eve::action::ActionSpatialBinding spatial
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
DiagnosticCode code
float maximum[3]
wgpu::PopErrorScopeStatus status
JointPoint2D axis
size_t offset
std::array< float, 3 > position
bool required
std::string relation
std::string evidence
Poco::JSON::Object::Ptr result
Snapshot snapshot
#define EVE_MCP_TOOL_FAMILY(Id, Schemas, Handler, Payload)
Declare one family beside its implementation; CMake derives composition from compiled sources.
std::unordered_set< std::string > tags
const std::string * tag
ssq::Object frame
glm::dvec2 center
std::string error
Definition Package.cpp:174
bool hit
std::set< std::string > values
Object::Ptr value
double number
SceneSpatialConstraint constraint
std::array< std::array< double, 3 >, 3 > axes
ScriptStructure out
std::string kind
std::string string
float size
Definition TreeMesh.cpp:158
std::string callSceneSearch(std::string_view name, Object::Ptr args)
std::string_view sceneSearchSchemas()
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
Result< T > failed(Status status, eve::DiagnosticCode code, RuleId rule, std::string message)
Construct a failed editing result with explicit status and diagnostic categories.
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
SceneSpatialFrame
World axes, reference node axes, or a separate observer node's axes.
Definition SceneSearch.h:36
constexpr std::string_view statusCodeName(StatusCode code) noexcept
Return the stable protocol spelling of a status code.
Definition Status.h:46
constexpr std::array< std::string_view, 3 > sceneSpatialFrameNames
Static protocol spellings, in SceneSpatialFrame order.
Definition SceneSearch.h:41
constexpr std::array< std::string_view, 8 > sceneSpatialRelationNames
Static protocol spellings, in SceneSpatialRelation order.
Definition SceneSearch.h:38
SceneSpatialRelation
Exact geometric relation; directional predicates compare node origins, not visual occlusion.
Definition SceneSearch.h:34
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120
One embedding space; revision must identify immutable model weights and encoding configuration.
Definition SceneSearch.h:59
std::vector< std::vector< double > > vectors
Definition SceneSearch.h:61
Exact structured filters, optional HNSW cosine retrieval and bounded pagination.
Definition SceneSearch.h:65
One AND constraint. References are host-local IDs resolved in the current authoritative projection.
Definition SceneSearch.h:43
glm::vec4 bounds