载入中...
搜索中...
未找到
McpRecipeTools.cpp
浏览该文件的文档.
3
9
10#include <Poco/Dynamic/Var.h>
11#include <Poco/JSON/Array.h>
12#include <Poco/JSON/Object.h>
13#include <Poco/JSON/Parser.h>
14
15#include <cmath>
16#include <cstdint>
17#include <string>
18#include <string_view>
19#include <vector>
20
21namespace eve::dev {
22namespace {
23
24struct RecipeParam {
25 const char* name;
26 const char* kind; // "int" | "number" | "bool"
27 const char* description;
29};
30
31struct RecipeDef {
32 const char* id;
33 const char* description;
34 std::vector<RecipeParam> params;
35};
36
37const std::vector<RecipeDef>& builtinRecipes() {
38 static const std::vector<RecipeDef> kRecipes = {
39 {"empty.clear", "Clear staged scene_director props (reset only).", {}},
40 {"ruins.moonlit",
41 "Moonlit ruins: ground plane, ruin block, and seeded trees.",
42 {{"seed", "int", "Placement RNG seed", 7.0}, {"trees", "int", "Number of trees (0-12)", 3.0}}},
43 {"plaza.sunlit",
44 "Sunlit plaza: ground, center marker, and perimeter posts.",
45 {{"seed", "int", "Placement RNG seed", 11.0}, {"posts", "int", "Perimeter posts (0-8)", 4.0}}},
46 };
47 return kRecipes;
48}
49
50const RecipeDef* findRecipe(std::string_view id) {
51 for (const auto& recipe : builtinRecipes()) {
52 if (recipe.id == id) return &recipe;
53 }
54 return nullptr;
55}
56
57std::string textPayload(Poco::JSON::Object::Ptr object, bool isError = false) {
58 return textContentResult(mcpStringify(Poco::Dynamic::Var(object)), isError);
59}
60
61std::string errorPayload(const std::string& message, const std::string& hint = {}) {
62 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
63 out->set("ok", false);
64 out->set("error", message);
65 if (message == "deferred-to-update") out->set("retryable", true);
66 if (!hint.empty()) out->set("hint", hint);
67 return textPayload(out, true);
68}
69
70Poco::JSON::Object::Ptr parseJsonObject(const std::string& text) {
71 try {
72 Poco::JSON::Parser parser;
73 auto root = parser.parse(text);
74 if (root.type() == typeid(Poco::JSON::Object::Ptr)) return root.extract<Poco::JSON::Object::Ptr>();
75 } catch (...) {
76 }
77 return {};
78}
79
80int paramInt(Poco::JSON::Object::Ptr params, const char* key, int fallback) {
81 if (!params || !params->has(key)) return fallback;
82 try {
83 return params->getValue<int>(key);
84 } catch (...) {
85 }
86 try {
87 return static_cast<int>(std::lround(params->getValue<double>(key)));
88 } catch (...) {
89 }
90 return fallback;
91}
92
93uint32_t lcgNext(uint32_t& state) {
94 state = state * 1664525u + 1013904223u;
95 return state;
96}
97
98double lcgUnit(uint32_t& state) { return static_cast<double>(lcgNext(state) & 0xFFFFFFu) / 16777216.0; }
99
100Poco::JSON::Object::Ptr actionObject(const std::string& action, const std::string& target,
101 Poco::JSON::Object::Ptr params) {
102 Poco::JSON::Object::Ptr item = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
103 item->set("action", action);
104 if (!target.empty()) item->set("target", target);
105 if (params) item->set("params", params);
106 return item;
107}
108
109Poco::JSON::Object::Ptr spawnParams(const std::string& id, const std::string& kind, double x, double y, double z,
110 double sx = 1.0, double sy = 1.0, double sz = 1.0, int seed = 7) {
111 Poco::JSON::Object::Ptr p = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
112 p->set("id", id);
113 p->set("kind", kind);
114 p->set("seed", seed);
115 Poco::JSON::Array::Ptr pos = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
116 pos->add(x);
117 pos->add(y);
118 pos->add(z);
119 p->set("pos", pos);
120 Poco::JSON::Array::Ptr scale = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
121 scale->add(sx);
122 scale->add(sy);
123 scale->add(sz);
124 p->set("scale", scale);
125 return p;
126}
127
128Poco::JSON::Array::Ptr expandRecipeActions(const RecipeDef& recipe, Poco::JSON::Object::Ptr params) {
129 Poco::JSON::Array::Ptr actions = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
130 if (std::string_view(recipe.id) == "empty.clear") {
131 actions->add(actionObject("reset", "", {}));
132 return actions;
133 }
134 if (std::string_view(recipe.id) == "ruins.moonlit") {
135 const int seed = paramInt(params, "seed", 7);
136 int trees = paramInt(params, "trees", 3);
137 if (trees < 0) trees = 0;
138 if (trees > 12) trees = 12;
139 actions->add(actionObject("reset", "", {}));
140 actions->add(actionObject("spawn", "", spawnParams("ground", "ground", 0.0, 0.0, 0.0, 12.0, 1.0, 12.0, seed)));
141 actions->add(
142 actionObject("spawn", "", spawnParams("ruin_core", "box", 0.0, 0.6, 0.0, 2.2, 1.4, 2.2, seed + 1)));
143 {
144 Poco::JSON::Object::Ptr light = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
145 light->set("ambient", 0.18);
146 light->set("moonlit", true);
147 actions->add(actionObject("lighting", "", light));
148 }
149 uint32_t rng = static_cast<uint32_t>(seed) * 2654435761u + 1u;
150 for (int i = 0; i < trees; ++i) {
151 const double angle = lcgUnit(rng) * 6.283185307179586;
152 const double radius = 3.5 + lcgUnit(rng) * 3.0;
153 const double x = std::cos(angle) * radius;
154 const double z = std::sin(angle) * radius;
155 actions->add(actionObject(
156 "spawn", "",
157 spawnParams("tree_" + std::to_string(i), "tree", x, 0.0, z, 1.0, 1.0, 1.0, seed + 10 + i)));
158 }
159 return actions;
160 }
161 if (std::string_view(recipe.id) == "plaza.sunlit") {
162 const int seed = paramInt(params, "seed", 11);
163 int posts = paramInt(params, "posts", 4);
164 if (posts < 0) posts = 0;
165 if (posts > 8) posts = 8;
166 actions->add(actionObject("reset", "", {}));
167 actions->add(
168 actionObject("spawn", "", spawnParams("plaza_ground", "ground", 0.0, 0.0, 0.0, 10.0, 1.0, 10.0, seed)));
169 actions->add(
170 actionObject("spawn", "", spawnParams("plaza_marker", "box", 0.0, 0.4, 0.0, 1.0, 0.8, 1.0, seed + 2)));
171 for (int i = 0; i < posts; ++i) {
172 const double angle = (6.283185307179586 * static_cast<double>(i)) / static_cast<double>(posts);
173 const double x = std::cos(angle) * 4.0;
174 const double z = std::sin(angle) * 4.0;
175 actions->add(actionObject(
176 "spawn", "",
177 spawnParams("post_" + std::to_string(i), "box", x, 0.7, z, 0.25, 1.4, 0.25, seed + 20 + i)));
178 }
179 return actions;
180 }
181 return actions;
182}
183
184std::string recipeList() {
185 Poco::JSON::Object::Ptr out = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
186 out->set("ok", true);
187 out->set("schemaId", "eve.recipe.list");
188 out->set("schemaVersion", 1);
189 Poco::JSON::Array::Ptr recipes = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
190 for (const auto& recipe : builtinRecipes()) {
191 Poco::JSON::Object::Ptr item = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
192 item->set("id", std::string(recipe.id));
193 item->set("description", std::string(recipe.description));
194 Poco::JSON::Array::Ptr params = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
195 for (const auto& param : recipe.params) {
196 Poco::JSON::Object::Ptr p = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
197 p->set("name", std::string(param.name));
198 p->set("kind", std::string(param.kind));
199 p->set("description", std::string(param.description));
200 p->set("default", param.defaultValue);
201 params->add(p);
202 }
203 item->set("params", params);
204 recipes->add(item);
205 }
206 out->set("recipes", recipes);
207 out->set("count", static_cast<int>(builtinRecipes().size()));
208 out->set("hint", "Call eve_recipe_apply with {id, params?} under content.scene / workshop.rpg");
209 return textPayload(out);
210}
211
212std::string recipeApply(Poco::JSON::Object::Ptr args) {
213 if (!args || !args->has("id")) {
214 return errorPayload("id is required", "Pass {id:\"ruins.moonlit\", params:{seed,trees}} from eve_recipe_list");
215 }
216 const std::string id = getArgString(args, "id");
217 const RecipeDef* recipe = findRecipe(id);
218 if (!recipe) {
219 return errorPayload("unknown recipe id '" + id + "'",
220 "Call eve_recipe_list; ids are registry strings, not free-form geometry");
221 }
222
223 Debugger& dbg = Debugger::instance();
224 HSQUIRRELVM vm = dbg.vm();
225 if (!vm) return errorPayload("no VM", "Attach a live eve run --mcp-port session first");
226
227 std::string err;
228 if (!ensureSceneDirectorInstalled(vm, &err, /*allowHeavyWork=*/false)) {
229 if (err == "deferred-to-update") {
230 return errorPayload("deferred-to-update",
231 "scene_director install was queued for the next eve.dev.poll; retry eve_recipe_apply");
232 }
233 return errorPayload(err.empty() ? "scene_director kit unavailable" : err);
234 }
235
236 Poco::JSON::Object::Ptr params;
237 if (args->has("params")) {
238 try {
239 params = args->getObject("params");
240 } catch (...) {
241 return errorPayload("params must be a JSON object");
242 }
243 }
244
245 Poco::JSON::Array::Ptr actions = expandRecipeActions(*recipe, params);
246 Poco::JSON::Object::Ptr options = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
247 options->set("stopOnError", getArgBool(args, "stopOnError", true));
248 auto actionsLiteral = sceneLiteral(Poco::Dynamic::Var(actions));
249 if (!actionsLiteral.ok()) return errorPayload(actionsLiteral.status().describe());
250 auto optionsLiteral = sceneLiteral(Poco::Dynamic::Var(options));
251 if (!optionsLiteral.ok()) return errorPayload(optionsLiteral.status().describe());
252
253 err.clear();
254 const std::string snippet =
255 "return ::scene_director.batch(" + actionsLiteral.value() + "," + optionsLiteral.value() + ");";
256 const std::string sceneOut = callSceneDirectorReturn(vm, snippet, &err);
257 if (!err.empty()) return errorPayload(err);
258
259 Poco::JSON::Object::Ptr report = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
260 report->set("schemaId", "eve.recipe.apply-report");
261 report->set("schemaVersion", 1);
262 report->set("id", id);
263 auto sceneObj = parseJsonObject(sceneOut);
264 if (sceneObj) {
265 report->set("scene", sceneObj);
266 const bool ok = sceneObj->optValue<bool>("ok", false);
267 report->set("ok", ok);
268 if (sceneObj->has("revision")) report->set("revision", sceneObj->get("revision"));
269 if (!ok) {
270 report->set("error", "recipe apply failed");
271 report->set("hint", "Inspect scene.results; recipe apply is transactional when stopOnError=true");
272 return textPayload(report, true);
273 }
274 } else {
275 report->set("ok", false);
276 report->set("error", "scene batch returned non-object JSON");
277 report->set("raw", sceneOut);
278 return textPayload(report, true);
279 }
280
281 if (args->has("expectedRevision")) {
282 const int expected = getArgInt(args, "expectedRevision", -1);
283 const int actual = sceneObj->optValue<int>("revision", -1);
284 if (expected >= 0 && actual >= 0 && expected != actual) {
285 report->set("ok", false);
286 report->set("error", "revision mismatch");
287 report->set("expectedRevision", expected);
288 report->set("revision", actual);
289 return textPayload(report, true);
290 }
291 }
292
293 err.clear();
294 const std::string infoOut = callSceneDirectorReturn(vm, "return ::scene_director.info();", &err);
295 if (err.empty()) {
296 if (auto info = parseJsonObject(infoOut)) report->set("info", info);
297 }
298 report->set("hint", "Recipe applied; escalate to verify.play for reachable/dialogue criteria");
299 return textPayload(report);
300}
301
302} // namespace
303
304bool isMcpRecipeTool(std::string_view name) { return name == "eve_recipe_list" || name == "eve_recipe_apply"; }
305
306std::string callMcpRecipeTool(std::string_view name, Poco::JSON::Object::Ptr args) {
307 if (name == "eve_recipe_list") return recipeList();
308 if (name == "eve_recipe_apply") return recipeApply(args);
309 return errorPayload("unknown recipe tool '" + std::string(name) + "'");
310}
311
312std::string_view mcpRecipeToolSchemas() {
313 return R"json({"name":"eve_recipe_list","description":"List registered content recipes (id + params). Prefer recipe id over free-form prop scripts under content.scene.","inputSchema":{"type":"object","properties":{}}},{"name":"eve_recipe_apply","description":"Apply one registered content recipe as a single scene_director.batch transaction. Returns {ok,id,scene,revision?,info}. Retry when retryable deferred-to-update.","inputSchema":{"type":"object","properties":{"id":{"type":"string","description":"Recipe id from eve_recipe_list"},"params":{"type":"object","description":"Recipe parameters (seed, trees, …)"},"expectedRevision":{"type":"integer","description":"Optional optimistic concurrency check"},"stopOnError":{"type":"boolean"}},"required":["id"]}})json";
314}
315
316} // namespace eve::dev
317
318namespace eve::dev {
320} // namespace eve::dev
double z
double y
double x
LogicalId target
int root
Definition AnimSmr.cpp:119
struct SQVM * HSQUIRRELVM
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
std::array< float, 3 > scale
std::string id
double defaultValue
const char * description
std::vector< RecipeParam > params
Content recipe list/apply facade for agent task profiles.
Shared helpers for MCP tools that drive the embedded scene_director kit.
#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
BakeRecipe recipe
std::vector< ActionSpec > actions
Definition PlayHost.cpp:127
std::string text
ScriptStructure out
std::string kind
Light3D::Data * light
Definition Shadow.cpp:147
const SquirrelValueOptions & options
uint32_t seed
Definition TreeMesh.cpp:276
float size
Definition TreeMesh.cpp:158
static Debugger & instance()
Definition Debugger.cpp:387
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
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.
bool isMcpRecipeTool(std::string_view name)
Whether name is eve_recipe_list or eve_recipe_apply.
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 mcpRecipeToolSchemas()
Comma-free MCP tool schema fragments for the recipe family.
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 callMcpRecipeTool(std::string_view name, Poco::JSON::Object::Ptr args)
Execute one recipe 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
std::string callSceneDirectorReturn(HSQUIRRELVM vm, const std::string &snippet, std::string *err)
Compile+run a snippet that returns a value; serialize it as JSON.
glm::uvec4 info