载入中...
搜索中...
未找到
McpScriptTools.cpp
浏览该文件的文档.
3
9
10#include <Poco/Dynamic/Var.h>
11#include <Poco/JSON/Array.h>
12#include <Poco/JSON/Object.h>
13
14#include <simplesquirrel/simplesquirrel.hpp>
15
16#include <algorithm>
17#include <cstddef>
18#include <cstdint>
19#include <mutex>
20#include <string>
21#include <utility>
22#include <vector>
23
24namespace eve::dev {
25namespace {
26
27// Bounds: a project script is not a trusted schema source, so every field the
28// agent receives is capped and every rejection is reported to the console.
29constexpr std::size_t kMaxTools = 128;
30constexpr std::size_t kMaxNameLength = 64;
31constexpr std::size_t kMinNameLength = 3;
32constexpr std::size_t kMaxDescription = 512;
33constexpr std::size_t kMaxSchemaBytes = 16 * 1024;
34constexpr std::size_t kMaxResultBytes = 256 * 1024;
35constexpr int kMaxArgumentDepth = 16;
36
38const char* const kReservedPrefixes[] = {"eve_", "inspect_", "set_", "capture_", "get_"};
39
40struct ScriptTool {
41 std::string name;
42 std::string description;
43 std::string inputSchemaJson;
44 HSQUIRRELVM vm = nullptr;
45 HSQOBJECT handler{};
46};
47
48std::mutex g_mutex;
49std::vector<ScriptTool> g_tools;
50
51bool hasReservedPrefix(const std::string& name) {
52 for (const char* raw : kReservedPrefixes) {
53 const std::string prefix(raw);
54 if (name.size() > prefix.size() && name.compare(0, prefix.size(), prefix) == 0) return true;
55 }
56 return false;
57}
58
63std::string tableString(HSQUIRRELVM vm, HSQOBJECT table, const char* key, const std::string& defaultValue = {}) {
64 const SQInteger top = sq_gettop(vm);
65 sq_pushobject(vm, table);
66 sq_pushstring(vm, key, -1);
67 std::string value = defaultValue;
68 if (SQ_SUCCEEDED(sq_get(vm, -2)) && sq_gettype(vm, -1) == OT_STRING) {
69 const SQChar* text = nullptr;
70 if (SQ_SUCCEEDED(sq_getstring(vm, -1, &text)) && text) value = text;
71 }
72 sq_settop(vm, top);
73 return value;
74}
75
77std::string tableFieldJson(HSQUIRRELVM vm, HSQOBJECT table, const char* field) {
78 const SQInteger top = sq_gettop(vm);
79 sq_pushobject(vm, table);
80 sq_pushstring(vm, field, -1);
81 std::string json;
82 if (SQ_SUCCEEDED(sq_get(vm, -2)) && sq_gettype(vm, -1) == OT_TABLE) json = sqValueToJson(vm, -1);
83 sq_settop(vm, top);
84 return json;
85}
86
88void pushJsonValue(HSQUIRRELVM vm, const Poco::Dynamic::Var& value, int depth) {
89 if (depth > kMaxArgumentDepth || value.isEmpty()) {
90 sq_pushnull(vm);
91 return;
92 }
93 if (value.isBoolean()) {
94 sq_pushbool(vm, value.convert<bool>() ? SQTrue : SQFalse);
95 return;
96 }
97 if (value.isInteger()) {
98 sq_pushinteger(vm, static_cast<SQInteger>(value.convert<Poco::Int64>()));
99 return;
100 }
101 if (value.isNumeric()) {
102 sq_pushfloat(vm, static_cast<SQFloat>(value.convert<double>()));
103 return;
104 }
105 if (value.isString()) {
106 const std::string text = value.convert<std::string>();
107 sq_pushstring(vm, text.c_str(), static_cast<SQInteger>(text.size()));
108 return;
109 }
110 if (value.type() == typeid(Poco::JSON::Array::Ptr)) {
111 auto array = value.extract<Poco::JSON::Array::Ptr>();
112 sq_newarray(vm, 0);
113 const SQInteger target = sq_gettop(vm);
114 for (unsigned index = 0; index < array->size(); ++index) {
115 pushJsonValue(vm, array->get(index), depth + 1);
116 sq_arrayappend(vm, target);
117 }
118 return;
119 }
120 if (value.type() == typeid(Poco::JSON::Object::Ptr)) {
121 auto object = value.extract<Poco::JSON::Object::Ptr>();
122 sq_newtable(vm);
123 const SQInteger target = sq_gettop(vm);
124 for (const auto& entry : *object) {
125 sq_pushstring(vm, entry.first.c_str(), static_cast<SQInteger>(entry.first.size()));
126 pushJsonValue(vm, entry.second, depth + 1);
127 sq_newslot(vm, target, SQFalse);
128 }
129 return;
130 }
131 sq_pushnull(vm);
132}
133
134std::string scriptErrorText(HSQUIRRELVM vm) {
136 if (!context.empty()) return eve::script::formatScriptError(context);
137 return "tool handler failed";
138}
139
140void reportRejection(const std::string& name, const std::string& reason) {
141 ConsolePanel::instance().addLog("warn", "eve.mcp.tool rejected '" + name + "': " + reason);
142}
143
150void releaseEntry(ScriptTool& tool, HSQUIRRELVM owner) {
151 if (tool.vm != owner || owner == nullptr || sq_isnull(tool.handler)) return;
152 sq_release(owner, &tool.handler);
153}
154
155std::string resultEnvelope(const std::string& text, bool isError) { return textContentResult(text, isError); }
156
158bool registerTool(HSQUIRRELVM vm, const std::string& name, HSQOBJECT spec) {
160 reportRejection(name,
161 "name must match [a-z][a-z0-9_]{2,63} and must not use a built-in prefix "
162 "(eve_ / inspect_ / set_ / capture_ / get_)");
163 return false;
164 }
165 if (compiledMcpToolCatalog().find(name)) {
166 reportRejection(name, "name belongs to a compiled tool provider");
167 return false;
168 }
169 if (spec._type != OT_TABLE) {
170 reportRejection(name, "spec must be a table with a handler closure");
171 return false;
172 }
173
174 const std::string description = tableString(vm, spec, "description");
175 if (description.size() > kMaxDescription) {
176 reportRejection(name, "description is longer than " + std::to_string(kMaxDescription) + " characters");
177 return false;
178 }
179
180 const std::string schema = tableFieldJson(vm, spec, "inputSchema");
181 if (schema.size() > kMaxSchemaBytes) {
182 reportRejection(name, "inputSchema serializes to more than " + std::to_string(kMaxSchemaBytes) + " bytes");
183 return false;
184 }
185 if (!schema.empty() && schema.front() != '{') {
186 reportRejection(name, "inputSchema must be a table describing a JSON object");
187 return false;
188 }
189
190 const SQInteger top = sq_gettop(vm);
191 sq_pushobject(vm, spec);
192 sq_pushstring(vm, "handler", -1);
193 const bool hasHandler =
194 SQ_SUCCEEDED(sq_get(vm, -2)) && (sq_gettype(vm, -1) == OT_CLOSURE || sq_gettype(vm, -1) == OT_NATIVECLOSURE);
195 if (!hasHandler) {
196 sq_settop(vm, top);
197 reportRejection(name, "spec.handler must be a function");
198 return false;
199 }
200 HSQOBJECT handler = {};
201 sq_getstackobj(vm, -1, &handler);
202 sq_addref(vm, &handler);
203 sq_settop(vm, top);
204
205 ScriptTool tool;
206 tool.name = name;
207 tool.description = description.empty() ? ("Project tool '" + name + "'") : description;
208 tool.inputSchemaJson = schema;
209 tool.vm = vm;
210 tool.handler = handler;
211
212 bool full = false;
213 {
214 std::lock_guard<std::mutex> lock(g_mutex);
215 const auto existing =
216 std::find_if(g_tools.begin(), g_tools.end(), [&](const ScriptTool& entry) { return entry.name == name; });
217 if (existing != g_tools.end()) {
218 // Re-registration replaces: a hot-reloaded mcp.nut must not
219 // accumulate duplicates or leak the previous closure.
220 releaseEntry(*existing, vm);
221 *existing = std::move(tool);
222 } else if (g_tools.size() >= kMaxTools) {
223 full = true;
224 } else {
225 g_tools.push_back(std::move(tool));
226 }
227 }
228 if (full) {
229 // push_back did not happen, so `tool` still owns the reference.
230 releaseEntry(tool, vm);
231 reportRejection(name, "registry is full (" + std::to_string(kMaxTools) + " tools)");
232 return false;
233 }
234 ConsolePanel::instance().addLog("info", "eve.mcp.tool registered: " + name);
235 return true;
236}
237
238} // namespace
239
240bool isValidScriptToolName(const std::string& name) {
241 if (name.size() < kMinNameLength || name.size() > kMaxNameLength) return false;
242 if (name.front() < 'a' || name.front() > 'z') return false;
243 for (char c : name) {
244 const bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
245 if (!ok) return false;
246 }
247 return !hasReservedPrefix(name);
248}
249
250bool isScriptTool(const std::string& name) {
251 std::lock_guard<std::mutex> lock(g_mutex);
252 return std::any_of(g_tools.begin(), g_tools.end(), [&](const ScriptTool& tool) { return tool.name == name; });
253}
254
255std::vector<std::string> scriptToolNames() {
256 std::lock_guard<std::mutex> lock(g_mutex);
257 std::vector<std::string> names;
258 names.reserve(g_tools.size());
259 for (const auto& tool : g_tools) names.push_back(tool.name);
260 return names;
261}
262
264 std::lock_guard<std::mutex> lock(g_mutex);
265 return static_cast<int>(g_tools.size());
266}
267
268std::string scriptToolSchemas() {
269 std::lock_guard<std::mutex> lock(g_mutex);
270 std::string out;
271 for (const auto& tool : g_tools) {
272 if (!out.empty()) out += ',';
273 out += "{\"name\":\"" + mcpJsonEscape(tool.name) + "\",\"description\":\"" + mcpJsonEscape(tool.description) +
274 "\",\"inputSchema\":";
275 out += tool.inputSchemaJson.empty() ? std::string("{\"type\":\"object\"}") : tool.inputSchemaJson;
276 out += "}";
277 }
278 return out;
279}
280
281std::string callScriptTool(const std::string& name, Poco::JSON::Object::Ptr args) {
282 HSQUIRRELVM vm = nullptr;
283 HSQOBJECT handler = {};
284 {
285 std::lock_guard<std::mutex> lock(g_mutex);
286 const auto found =
287 std::find_if(g_tools.begin(), g_tools.end(), [&](const ScriptTool& tool) { return tool.name == name; });
288 if (found == g_tools.end()) return resultEnvelope("error: unknown tool " + name, true);
289 vm = found->vm;
290 handler = found->handler;
291 // Hold our own reference across the call: the handler may unregister or
292 // clear the registry, and the closure must stay alive while it runs.
293 if (vm && !sq_isnull(handler)) sq_addref(vm, &handler);
294 }
295 if (!vm || sq_isnull(handler)) {
296 if (vm && !sq_isnull(handler)) sq_release(vm, &handler);
297 return resultEnvelope("error: tool '" + name + "' has no handler in this VM", true);
298 }
299
300 const SQInteger top = sq_gettop(vm);
301 sq_pushobject(vm, handler);
302 sq_pushroottable(vm);
303 if (args) {
304 pushJsonValue(vm, Poco::Dynamic::Var(args), 0);
305 } else {
306 sq_newtable(vm);
307 }
308
309 std::string text;
310 bool isError = false;
311 if (SQ_FAILED(sq_call(vm, 2, SQTrue, SQTrue))) {
312 text = "error: " + scriptErrorText(vm);
313 isError = true;
314 } else {
315 text = sqValueToJson(vm, -1);
316 if (text.size() > kMaxResultBytes) {
317 text = "error: tool '" + name + "' returned " + std::to_string(text.size()) + " bytes of JSON, above the " +
318 std::to_string(kMaxResultBytes) + " byte limit";
319 isError = true;
320 }
321 }
322 sq_settop(vm, top);
323 sq_release(vm, &handler);
324 return resultEnvelope(text, isError);
325}
326
328 std::vector<ScriptTool> dropped;
329 {
330 std::lock_guard<std::mutex> lock(g_mutex);
331 dropped.swap(g_tools);
332 }
333 for (auto& tool : dropped) releaseEntry(tool, owner);
334}
335
336void exposeMcpScriptApi(ssq::VM& vm) {
337 HSQUIRRELVM raw = vm.getHandle();
338 if (!raw) return;
339
340 try {
341 ssq::Table eveTable = vm.find("eve").toTable();
342 ssq::Table mcp = eveTable.addTable("mcp");
343
344 mcp.addFunc("tool", [raw](const std::string& name, ssq::Object spec) -> bool {
345 return registerTool(raw, name, spec.getRaw());
346 });
347
348 mcp.addFunc("remove", [raw](const std::string& name) -> bool {
349 bool removed = false;
350 {
351 std::lock_guard<std::mutex> lock(g_mutex);
352 const auto found = std::find_if(g_tools.begin(), g_tools.end(),
353 [&](const ScriptTool& entry) { return entry.name == name; });
354 if (found != g_tools.end()) {
355 releaseEntry(*found, raw);
356 g_tools.erase(found);
357 removed = true;
358 }
359 }
360 if (removed) ConsolePanel::instance().addLog("info", "eve.mcp.tool removed: " + name);
361 return removed;
362 });
363
364 mcp.addFunc("tools", []() { return scriptToolNames(); });
365
366 mcp.addFunc("clear", [raw]() -> int {
367 const int count = scriptToolCount();
369 ConsolePanel::instance().addLog("info", "eve.mcp.tool cleared " + std::to_string(count) + " tool(s)");
370 return count;
371 });
372
373 mcp.addFunc("attachEditor", [](ssq::Object hostObject) -> bool {
374 const auto attach = eve::editorMcpAttachHook();
375 if (!attach) {
376 ConsolePanel::instance().addLog("warn", "eve.mcp.attachEditor: editor hooks are not registered");
377 return false;
378 }
379 HSQUIRRELVM vm = hostObject.getHandle();
380 if (!vm || hostObject.isEmpty()) {
381 ConsolePanel::instance().addLog("warn", "eve.mcp.attachEditor requires an EditorHost instance");
382 return false;
383 }
384 SQUserPointer pointer = nullptr;
385 const SQInteger top = sq_gettop(vm);
386 sq_pushobject(vm, hostObject.getRaw());
387 const bool ok = SQ_SUCCEEDED(sq_getinstanceup(vm, -1, &pointer, nullptr));
388 sq_settop(vm, top);
389 if (!ok || !pointer) {
390 ConsolePanel::instance().addLog("warn", "eve.mcp.attachEditor requires an EditorHost instance");
391 return false;
392 }
393 const bool attached = attach(pointer);
394 if (attached) ConsolePanel::instance().addLog("info", "eve.mcp.attachEditor: host attached (mode A)");
395 return attached;
396 });
397
398 mcp.addFunc("detachEditor", []() -> bool {
399 const auto detach = eve::editorMcpDetachHook();
400 if (!detach) return false;
401 detach();
402 ConsolePanel::instance().addLog("info", "eve.mcp.detachEditor: host detached");
403 return true;
404 });
405 } catch (...) {
406 // `eve` table missing: leave the MCP export API unavailable rather than
407 // failing the whole DevTools script surface.
408 }
409}
410
411} // namespace eve::dev
LogicalId target
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
double raw
std::uint32_t dropped
std::int32_t c
double defaultValue
const char * description
std::string inputSchemaJson
HSQOBJECT handler
Project-script → MCP export registry.
std::shared_ptr< OceanGpuSpectrum > owner
Object::Ptr value
std::string pointer
bool found
int removed
std::string text
ScriptStructure out
int count
Json object
std::uint32_t depth
uint32_t index
const VegetationPresetContext & context
void addLog(std::string level, std::string text)
Append a leveled log line (thread-safe).
static ConsolePanel & instance()
SQInteger top
Definition Snapshot.cpp:115
bool isValidScriptToolName(const std::string &name)
Validate an exported tool name.
int scriptToolCount()
Number of exported tools (for eve_status).
std::string mcpJsonEscape(const std::string &value)
Escape a raw string for embedding inside a JSON string literal.
Definition McpJson.hpp:31
std::string callScriptTool(const std::string &name, Poco::JSON::Object::Ptr args)
Invoke one exported tool.
void clearScriptTools(HSQUIRRELVM owner)
Drop registry entries owned by owner.
std::vector< std::string > scriptToolNames()
Exported tool names in registration order.
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 scriptToolSchemas()
Comma-free MCP tool schema fragments for every exported tool.
void exposeMcpScriptApi(ssq::VM &vm)
Expose eve.mcp.tool/remove/tools/clear/attachEditor/detachEditor on a VM.
std::string sqValueToJson(HSQUIRRELVM vm, SQInteger idx, int depth=0)
Forward declaration: the key serializer falls back to the value serializer.
bool isScriptTool(const std::string &name)
Whether name is exported by the project script registry.
const McpToolFamilyCatalog & compiledMcpToolCatalog()
Build the process-immortal compiled catalogue once, then borrow it until exit. @lifetime Survives sta...
std::string formatScriptError(const ScriptErrorContext &ctx)
Formats a context into a human-readable multi-line report.
ScriptErrorContext takeLastScriptError(HSQUIRRELVM vm)
Consumes and clears the last recorded error for a VM.
EditorMcpAttachFn editorMcpAttachHook()
Current attach hook, or null.
EditorMcpDetachFn editorMcpDetachHook()
Current detach hook, or null.
Structured snapshot of a script error: message, throw site and stack.
Definition ScriptError.h:46