载入中...
搜索中...
未找到
McpProjectIndexTools.cpp
浏览该文件的文档.
2#include <Poco/JSON/Array.h>
3#include <algorithm>
4#include <cstdint>
5#include <map>
6#include <queue>
7#include <set>
8#include <stdexcept>
12
13namespace eve::dev {
14namespace {
15using namespace project_index;
16using Array = Poco::JSON::Array;
17struct State {
18 Snapshot snapshot;
19 uint64_t used = 0;
20};
21std::map<std::string, State> states;
22uint64_t sequence = 0;
23bool sameFiles(const Files& left, const Files& right) {
24 if (left.size() != right.size()) return false;
25 for (const auto& [path, file] : left) {
26 const auto other = right.find(path);
27 if (other == right.end() || file->hash != other->second->hash) return false;
28 }
29 return true;
30}
31State& stateFor(const std::filesystem::path& root) {
32 const auto key = pathText(root);
33 if (!states.contains(key) && states.size() >= 4) {
34 const auto oldest = std::min_element(states.begin(), states.end(), [](const auto& left, const auto& right) {
35 return left.second.used < right.second.used;
36 });
37 states.erase(oldest);
38 }
39 auto& state = states[key];
40 state.used = ++sequence;
41 return state;
42}
43void refresh(const std::filesystem::path& root, State& state) {
44 Object::Ptr stats = new Object();
45 auto files = scan(root, state.snapshot.files, stats);
46 if (!state.snapshot.revision.empty() && sameFiles(files, state.snapshot.files)) {
47 state.snapshot.stats = stats;
48 return;
49 }
50 auto candidate = project(std::move(files), stats, pathText(root.filename()), pathText(root));
51 // Detect a changed read set before publication; this is not a filesystem
52 // transaction. Consumers must recheck revision before a later action.
53 Object::Ptr confirmation = new Object();
54 if (!sameFiles(candidate.files, scan(root, candidate.files, confirmation)))
55 throw std::runtime_error("Project changed during indexing; retry");
56 state.snapshot = std::move(candidate);
57}
58Object::Ptr query(const Snapshot& snapshot, std::string_view mode, Object::Ptr args) {
59 const int limit = args->optValue<int>("maxNodes", 64), depth = args->optValue<int>("maxDepth", 8);
60 const int bytes = args->optValue<int>("maxBytes", 32768);
61 if (limit < 1 || limit > 256 || depth < 0 || depth > 8 || bytes < 1024 || bytes > 65536)
62 return mcpFailureObject("invalid_query", "maxNodes 1..256, maxDepth 0..8, maxBytes 1024..65536");
63 const auto expected = args->optValue<std::string>("expectedRevision", "");
64 if (!expected.empty() && expected != snapshot.revision) {
65 auto failure = mcpFailureObject("stale_project_revision", "Refresh project evidence and use the new revision");
66 failure->set("revision", snapshot.revision);
67 return failure;
68 }
69 Object::Ptr out = new Object();
70 out->set("ok", true);
71 out->set("schema", mode == "eve_task_context" ? "eve.project-context" : "eve.project-index");
72 out->set("schemaVersion", snapshot.automatic ? 2 : 1);
73 out->set("projectId", snapshot.projectId);
74 out->set("projectDir", snapshot.projectDir);
75 out->set("revision", snapshot.revision);
76 if (snapshot.automatic) out->set("analyzerHash", std::string(eve::script::scriptStructureProviderHash()));
77 out->set("declarationsResolved", snapshot.diagnostics.empty());
78 out->set("coverage", "partial-project");
79 out->set("evidence",
80 snapshot.automatic ? "compiler-structure+engine-contracts" : "source-metadata+checked-declarations");
81 out->set("untrustedProjectContent", true);
82 out->set("includeCalls", args->optValue<bool>("includeCalls", false));
83 out->set("limitations",
84 "Source evidence, not live state or runtime causality; symbol extraction is not compilation. Structural "
85 "addresses may change; declared semantic IDs survive unique source relocation.");
86 Array::Ptr diagnostics = new Array();
87 for (const auto& item : snapshot.diagnostics) diagnostics->add(item);
88 out->set("diagnostics", diagnostics);
89 out->set("stats", snapshot.stats);
90 Array::Ptr nodes = new Array(), edges = new Array(), contracts = new Array(), tests = new Array();
91 std::set<std::string> selected;
92 bool truncated = false;
93 if (mode == "eve_project_index_refresh") {
94 for (const auto& [id, item] : snapshot.nodes)
95 if (item->optValue<bool>("semantic", false) ||
96 (item->has("evidence") && (item->getValue<std::string>("evidence") == "project-declaration" ||
97 item->getValue<std::string>("evidence") == "engine-build-contract"))) {
98 if (selected.size() < static_cast<size_t>(limit))
99 selected.insert(id);
100 else
101 truncated = true;
102 }
103 } else {
104 const auto seed = args->optValue<std::string>("seed", "");
105 if (mode == "eve_task_context" && (seed.empty() || args->optValue<std::string>("task", "").empty()))
106 return mcpFailureObject("invalid_query", "Project task context requires seed and task");
107 if (!seed.empty()) {
108 if (!snapshot.nodes.contains(seed)) return mcpFailureObject("unknown_seed");
109 std::map<std::string, std::vector<size_t>> adjacency;
110 for (size_t i = 0; i < snapshot.edges.size(); ++i) {
111 const auto& edge = snapshot.edges[i];
112 adjacency[edge->getValue<std::string>("from")].push_back(i);
113 adjacency[edge->getValue<std::string>("to")].push_back(i);
114 }
115 std::queue<std::pair<std::string, int>> pending;
116 selected.insert(seed);
117 pending.emplace(seed, 0);
118 while (!pending.empty()) {
119 const auto [current, level] = pending.front();
120 pending.pop();
121 if (snapshot.automatic && !args->optValue<bool>("includeCalls", false) &&
122 snapshot.nodes.at(current)->getValue<std::string>("kind") == "test")
123 continue;
124 for (const auto i : adjacency[current]) {
125 const auto& edge = snapshot.edges[i];
126 if (snapshot.automatic && !args->optValue<bool>("includeCalls", false) &&
127 snapshot.nodes.at(current)->getValue<std::string>("kind") == "engine_api" &&
128 edge->getValue<std::string>("relation") != "tested_by")
129 continue;
130 if (snapshot.automatic && !args->optValue<bool>("includeCalls", false) &&
131 edge->getValue<std::string>("relation") == "calls")
132 continue;
133 const auto from = edge->getValue<std::string>("from"), to = edge->getValue<std::string>("to");
134 const auto next = from == current ? to : from;
135 if (selected.contains(next)) continue;
136 if (level >= depth || selected.size() >= static_cast<size_t>(limit)) {
137 truncated = true;
138 continue;
139 }
140 selected.insert(next);
141 pending.emplace(next, level + 1);
142 }
143 }
144 } else {
145 const auto kind = args->optValue<std::string>("kind", ""), text = args->optValue<std::string>("query", "");
146 for (const auto& [id, item] : snapshot.nodes) {
147 if (!kind.empty() && item->getValue<std::string>("kind") != kind) continue;
148 if (!text.empty() && id.find(text) == std::string::npos &&
149 item->getValue<std::string>("label").find(text) == std::string::npos)
150 continue;
151 if (selected.size() >= static_cast<size_t>(limit)) {
152 truncated = true;
153 continue;
154 }
155 selected.insert(id);
156 }
157 }
158 }
159 for (const auto& id : selected) {
160 const auto& item = snapshot.nodes.at(id);
161 if (snapshot.automatic && mode == "eve_project_index_refresh") {
162 Object::Ptr summary = new Object();
163 for (const auto* field : {"id", "kind", "label", "status", "source", "evidence", "schemaContract"})
164 if (item->has(field)) summary->set(field, item->get(field));
165 nodes->add(summary);
166 if (item->getValue<std::string>("kind") == "test") tests->add(summary);
167 continue;
168 }
169 if (snapshot.automatic && item->has("contract")) {
170 Object::Ptr indexed = new Object();
171 for (const auto& field : *item)
172 if (field.first != "contract") indexed->set(field.first, field.second);
173 indexed->set("contractKey", id.substr(4));
174 nodes->add(indexed);
175 } else
176 nodes->add(item);
177 if (item->has("contract")) contracts->add(item->get("contract"));
178 if (item->getValue<std::string>("kind") == "test") tests->add(item);
179 }
180 for (const auto& edge : snapshot.edges)
181 if (!(snapshot.automatic &&
182 (mode == "eve_project_index_refresh" ||
183 (!args->optValue<bool>("includeCalls", false) && edge->getValue<std::string>("relation") == "calls"))) &&
184 selected.contains(edge->getValue<std::string>("from")) &&
185 selected.contains(edge->getValue<std::string>("to")))
186 edges->add(edge);
187 out->set("nodes", nodes);
188 out->set("edges", edges);
189 out->set("contracts", contracts);
190 out->set("tests", tests);
191 out->set("truncated", truncated);
192 if (mode == "eve_task_context") out->set("task", args->getValue<std::string>("task"));
193 if (mcpStringify(out).size() > static_cast<size_t>(bytes))
194 return mcpFailureObject("context_budget_exceeded",
195 "Reduce maxNodes/depth or increase maxBytes; no partial evidence returned");
196 return out;
197}
198} // namespace
199bool isMcpProjectIndexTool(std::string_view name) {
200 return name == "eve_project_index_refresh" || name == "eve_project_index_query";
201}
202std::string callMcpProjectIndexTool(std::string_view name, Object::Ptr args) {
203 Object::Ptr result;
204 std::string lastRevision;
205 try {
206 if (!isMcpProjectIndexTool(name) && name != "eve_task_context")
207 return textContentResult(mcpStringify(mcpFailureObject("unknown_tool")), true);
208 const auto root = std::filesystem::canonical(sourcePath(requiredString(args, "projectDir")));
209 if (!std::filesystem::is_directory(root) || std::filesystem::is_symlink(root / "game.semantic.json") ||
210 (std::filesystem::exists(root / "game.semantic.json") &&
211 !std::filesystem::is_regular_file(root / "game.semantic.json")))
212 throw std::runtime_error("Project requires a directory and an optional regular game.semantic.json");
213 auto& state = stateFor(root);
214 lastRevision = state.snapshot.revision;
215 refresh(root, state);
216 result = query(state.snapshot, name, args);
217 } catch (const std::exception& error) {
218 result = mcpFailureObject("project_index_failed", error.what());
219 if (!lastRevision.empty()) result->set("lastGoodRevision", lastRevision);
220 }
221 return textContentResult(mcpStringify(result), !result->getValue<bool>("ok"));
222}
223std::string_view mcpProjectIndexToolSchemas() {
224 return R"JSON({"name":"eve_project_index_refresh","description":"Index current project source and checked semantic declarations without executing code. Reports revision, incremental parse stats and diagnostics.","inputSchema":{"type":"object","required":["projectDir"],"properties":{"projectDir":{"type":"string"},"maxNodes":{"type":"integer","minimum":1,"maximum":256},"maxBytes":{"type":"integer","minimum":1024,"maximum":65536}}}},
225{"name":"eve_project_index_query","description":"Query compiler-derived project semantics by seed, kind or text. includeCalls expands the full static call neighbourhood. Rejects stale expectedRevision; does not execute project code.","inputSchema":{"type":"object","required":["projectDir"],"properties":{"projectDir":{"type":"string"},"seed":{"type":"string"},"kind":{"type":"string"},"query":{"type":"string"},"includeCalls":{"type":"boolean"},"expectedRevision":{"type":"string"},"maxNodes":{"type":"integer","minimum":1,"maximum":256},"maxDepth":{"type":"integer","minimum":0,"maximum":8},"maxBytes":{"type":"integer","minimum":1024,"maximum":65536}}}})JSON";
226}
227} // namespace eve::dev
228
229namespace eve::dev {
231} // namespace eve::dev
int root
Definition AnimSmr.cpp:119
std::string selected
std::vector< QuestEvent > pending
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< CompiledTest > tests
HexVec3 left
HexVec3 right
std::int32_t second
std::int32_t first
std::string to
std::vector< Edge > edges
std::map< std::string, std::vector< size_t > > adjacency
std::map< std::string, Node > nodes
std::string from
Poco::JSON::Object::Ptr result
uint64_t used
Snapshot snapshot
std::uint64_t bytes
#define EVE_MCP_TOOL_FAMILY(Id, Schemas, Handler, Payload)
Declare one family beside its implementation; CMake derives composition from compiled sources.
int level
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
std::string file
std::vector< EquipmentStat > stats
std::string text
ScriptStructure out
std::string kind
double current
std::string string
std::string sourcePath
int limit
Definition TreeMesh.cpp:166
uint32_t seed
Definition TreeMesh.cpp:276
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
I * query()
Queries .
Definition Capability.h:88
std::string pathText(const std::filesystem::path &path)
UTF-8 source path, including Windows project names.
std::map< std::string, std::shared_ptr< const File > > Files
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
Files scan(const std::filesystem::path &root, const Files &previous, Object::Ptr stats)
Bounded filesystem scan. Parses only changed files; symlinks are excluded.
std::string requiredString(Object::Ptr object, const std::string &field)
Strict source string fields; invalid manifest shapes throw a diagnostic exception.
std::string callMcpProjectIndexTool(std::string_view name, Object::Ptr args)
bool isMcpProjectIndexTool(std::string_view name)
Recognizes project-index discovery/refresh tools; no project code is executed.
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
std::string_view mcpProjectIndexToolSchemas()
Comma-separated tool schemas without an enclosing array. @ownership Borrowed process-owned immutable ...
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
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
bool has(const std::vector< std::reference_wrapper< const HouseComponent > > &values)
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
EVENGINE_API_FOUNDATION std::string_view scriptStructureProviderHash()
Build-generated source fingerprint of the structural analyzer and project projection.
State
Lifecycle state of a generic transaction plan.
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120
std::map< std::string, Object::Ptr > nodes
std::vector< Object::Ptr > diagnostics