载入中...
搜索中...
未找到
Mcp.cpp
浏览该文件的文档.
1#include "McpSupervisor.h"
2#include "cmdline.h"
3
4#include "common/Capability.h"
5#include "common/EditorHost.h"
6#include "common/Module.h"
7#include "common/Runtime.h"
8#include "common/config.h"
12#include "scripts.h"
13
14#if EVENGINE_CMDLINE_DEVTOOLS && !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(EVENGINE_WEBGPU)
15#include "devtools/DevTool.hpp"
17#endif
18
19#include <simplesquirrel/simplesquirrel.hpp>
20#include <CLI11.hpp>
21#include <squirrel.h>
22
23#include <chrono>
24#include <cstdarg>
25#include <cstdio>
26#include <filesystem>
27#include <iostream>
28#include <map>
29#include <string>
30#include <thread>
31
32namespace eve::cmd {
33namespace {
34
36void hostPrintFunc(HSQUIRRELVM, const SQChar* s, ...) {
37 char buf[4096];
38 va_list args;
39 va_start(args, s);
40 vsnprintf(buf, sizeof(buf), s, args);
41 va_end(args);
42 fputs(buf, stderr);
43}
44
45bool endsWith(const std::string& value, const std::string& suffix) {
46 return value.size() >= suffix.size() &&
47 value.compare(value.size() - suffix.size(), suffix.size(), suffix) == 0;
48}
49
50bool isEditorHostResource(const std::string& path) {
51 if (path == "mcp.nut") return true;
52 if (path.rfind("mcp/", 0) == 0 && endsWith(path, ".nut")) return true;
53 if (path.rfind("editors/", 0) != 0) return false;
54 return endsWith(path, ".vm.nut") || endsWith(path, ".editor.json");
55}
56
57} // namespace
58
59struct McpArgs : Handler {
60 std::string root_path;
61 int port = 0;
62 int timeoutMs = 2000;
63 bool worker = false;
64
65 void setup(CLI::App& app, std::shared_ptr<CLI::Formatter> formatter) override {
66 auto mcp = app.add_subcommand(
67 "mcp", "Run a headless MCP host for AI agents (stdio by default; --port for TCP)");
68 mcp->allow_extras()->formatter(formatter);
69 mcp->add_option("--timeout-ms", timeoutMs, "Worker response budget in milliseconds (stdio)")
70 ->check(CLI::Range(1, 3600000));
71 mcp->add_flag("--worker", worker, "Internal unsupervised worker")->group("");
72 mcp->add_option("--port", port,
73 "Listen on this TCP port instead of stdio (Codex uses stdio)");
74 mcp->add_option("-r,--root", root_path, "Project root directory (default: current dir)");
75 }
76
77 int parse(CLI::App& app, Cmdline& cmd) override {
78 auto mcp = app.get_subcommand("mcp");
79 if (mcp->parsed()) {
80 std::string current_path = cmd.get_remaining(mcp);
81 if (!root_path.empty()) current_path = root_path;
82#if !defined(EVENGINE_ANDROID) && !defined(EVENGINE_IOS) && !defined(EVENGINE_WEBGPU)
83 if (port == 0 && !worker) return detail::runMcpSupervisor(current_path, timeoutMs);
84#endif
85 return cmd.McpHost(current_path, port);
86 }
87 return -1;
88 }
89};
90
92
93int Cmdline::McpHost(std::string path, int port) {
94#if !EVENGINE_CMDLINE_DEVTOOLS || defined(EVENGINE_ANDROID) || defined(EVENGINE_IOS) || defined(EVENGINE_WEBGPU)
95 (void)path;
96 (void)port;
97 std::cerr << "eve mcp: headless MCP host requires a desktop build with the devtools module" << std::endl;
98 return 4;
99#else
100 try {
101 std::string gameDir = path;
102 {
103 std::error_code ec;
104 if (path.empty() || path == ".")
105 gameDir = std::filesystem::current_path(ec).string();
106 else
107 gameDir = std::filesystem::absolute(path, ec).string();
108 if (ec) gameDir = path;
109 }
110
111 if (!gameDir.empty() && gameDir != ".") {
112 std::error_code ec;
113 std::filesystem::current_path(gameDir, ec);
114 if (ec) {
115 std::cerr << "Cannot chdir to project path '" << gameDir << "': " << ec.message()
116 << std::endl;
117 return 2;
118 }
119 }
120
121 Runtime runtime(2048, ssq::Libs::ALL);
122 runtime.initialize();
123 runtime.vm().setPrintFunc(&hostPrintFunc, &hostPrintFunc);
124
125 // Mount the project for PhysFS so script file APIs / editors/ resolve.
126 // Optional for the headless host: keep running when the environment
127 // cannot initialize PhysFS (sandboxed/CI shells), scripts just lose
128 // the PhysFS-backed file API.
129 eve::filesystem::Filesystem* projectFs = nullptr;
130 try {
131 projectFs = eve::filesystem::Filesystem::create();
132 if (projectFs) {
133 std::error_code ec;
134 auto cwd = std::filesystem::current_path(ec);
135 if (!ec) {
136 try {
137 projectFs->setSource(cwd.string());
138 } catch (...) {
139 }
140 }
141 }
143 } catch (const std::exception& e) {
144 std::cerr << "eve mcp: filesystem mount skipped (" << e.what() << ")" << std::endl;
145 }
146
147 // DevTools: attach the VM so eve_eval / eve_run_script / snapshot work;
148 // expose eve.dev. No statement-level local sampling (host is a service).
150 dt.attach(runtime, /*sampleLocals=*/false);
151 dt.exposeScriptApi(runtime.vm());
152
153 // Match load.nut's manifest order: requireAll() alone iterates an
154 // unordered registry and can construct editor consumers before their
155 // command/capability providers. Reuse the existing generated script
156 // manifest instead of maintaining a second native dependency list.
157 const auto moduleBootstrap = runtime.compileSource(std::string(module_list_content) + R"(
158 if (eve._bindAllNativeClasses() < 0)
159 throw "failed to bind native module classes";
160 foreach (entry in eve_modules) eve[entry.cls]();
161 )",
162 "mcp_modules.nut");
163 runtime.execute(moduleBootstrap);
164 // Registered native-only modules have no script slot in the manifest.
165
167
168 // Editor host: JSON Views <-> Squirrel ViewModel binding + window/render.
169 auto* host = eve::cap::query<eve::IEditorHost>();
170 if (host) {
171 host->start(runtime.vm(), gameDir, /*allowWindow=*/true);
172 host->exposeScriptApi(runtime.vm());
173 } else {
174 std::cerr << "eve mcp: editor host unavailable (ui module missing)"
175 << std::endl;
176 return 3;
177 }
178
179 // Unlike `eve run`, the MCP host does not execute load.nut. Start the
180 // same project watcher here and route editor/host scripts through the
181 // EditorHost while other assets keep using the shared asset reloaders.
182 auto* hot = eve::ModuleManager::getInstance<eve::filesystem::HotReload>("HotReload");
183 const int watchCount = projectFs && hot ? hot->watchTree(".") : 0;
184 host->setHotReloadWatchCount(watchCount);
185 if (std::filesystem::is_regular_file(std::filesystem::path(gameDir) / "mcp.nut")) {
186 const std::string initial = host->reloadResource("mcp.nut");
187 if (initial.rfind("error:", 0) == 0)
188 std::cerr << "MCP host script load failed: " << initial << std::endl;
189 }
190 std::cerr << "MCP hot-reload: watching " << watchCount << " path(s)" << std::endl;
191
192 auto& mcp = dt.mcp();
193 mcp.setGameRoot(gameDir);
194
195 if (port > 0) {
196 const int bound = dt.startMcp(static_cast<uint16_t>(port));
197 if (bound <= 0) {
198 std::cerr << "Failed to start MCP server on port " << port << std::endl;
199 return 3;
200 }
201 std::cerr << "MCP listening on 127.0.0.1:" << bound
202 << " (newline JSON-RPC; use tools/eve-mcp for Cursor stdio)" << std::endl;
203 } else {
204 if (!mcp.listenStdio()) {
205 std::cerr << "Failed to start stdio MCP transport" << std::endl;
206 return 3;
207 }
208 std::cerr << "MCP stdio transport ready (headless editor host; project=" << gameDir
209 << ")" << std::endl;
210 }
211
212 std::map<std::string, std::chrono::steady_clock::time_point> pendingReloads;
213 constexpr auto reloadDebounce = std::chrono::milliseconds(100);
214 while (!host->exitRequested()) {
215 dt.poll(); // drains MCP requests on the main thread
216 if (projectFs) {
217 while (true) {
218 const std::string kind = projectFs->pollWatch();
219 if (kind.empty()) break;
220 if (kind != "modified" && kind != "added" && kind != "movedTo") continue;
221 std::string changed = projectFs->getLastWatchPath();
223 if (!changed.empty()) pendingReloads[changed] = std::chrono::steady_clock::now();
224 }
225 }
226 const auto now = std::chrono::steady_clock::now();
227 for (auto it = pendingReloads.begin(); it != pendingReloads.end();) {
228 if (now - it->second < reloadDebounce) {
229 ++it;
230 continue;
231 }
232 const std::string changed = it->first;
233 if (isEditorHostResource(changed)) {
234 const std::string result = host->reloadResource(changed);
235 std::cerr << "MCP hot-reload: " << changed << ": " << result << std::endl;
236 } else if (hot && hot->tryReload(changed)) {
237 std::cerr << "MCP hot-reload asset: " << changed << std::endl;
238 }
239 it = pendingReloads.erase(it);
240 }
241 host->frame();
242 if (mcp.transport() == eve::dev::McpServer::Transport::Stdio &&
243 mcp.stdinClosed()) {
244 std::cerr << "MCP stdio closed; host exiting" << std::endl;
245 break;
246 }
247 std::this_thread::sleep_for(std::chrono::milliseconds(2));
248 }
249
250 host->stop();
251 dt.detach();
252 return 0;
253 } catch (const std::exception& e) {
254 std::cerr << "eve mcp failed: " << e.what() << std::endl;
255 return 3;
256 }
257#endif
258}
259
260} // namespace eve::cmd
const std::string & s
struct SQVM * HSQUIRRELVM
bool changed
int watchCount
Poco::JSON::Object::Ptr result
double dt
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
std::string kind
UIHostHandle host
static void requireAll()
Instantiates every registered module through its factory.
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:189
命令行模块(eve.cmd):run / build / package / test / zip / dev-server 等子命令入口。
Definition cmdline.h:34
static std::string get_remaining(CLI::App *sub, std::string default_path=".")
子命令剩余位置参数。
Definition cmdline.cpp:80
int McpHost(std::string path, int port)
无头 MCP 宿主:stdio(默认)或 TCP,供 AI 代理驱动。
Definition Mcp.cpp:93
static DevTool & instance()
Definition DevTool.cpp:138
EVENGINE_API_FOUNDATION public API.
Definition Filesystem.h:43
virtual bool setSource(std::string source)=0
Sets the path to the game source. This can only be set once.
virtual std::string pollWatch()=0
Pop next watch event kind: "added"|"removed"|"modified"|"movedFrom"|"movedTo". Empty string if queue ...
virtual std::string getLastWatchPath() const =0
static std::string normalizePath(std::string path)
Normalize path.
#define CMD_REG(name)
Definition cmdline.h:102
int runMcpSupervisor(const std::string &root, int timeoutMs)
Run the desktop stdio MCP supervisor synchronously on the main thread. Owns a worker process and its ...
void installScriptFileApi(ssq::VM &vm)
用 PhysFS 版本覆盖 Squirrel 的 file / dofile / loadfile 全局, 使脚本与资源从已挂载的游戏源(真实目录或内存挂载的 .eve 归档)解析; PhysFS 中不...
Definition FileApi.cpp:219
const char * module_list_content
One eve <subcommand> handler: CLI setup + argument parsing.
Definition cmdline.h:24
int parse(CLI::App &app, Cmdline &cmd) override
Parses arguments and runs the command; returns the exit code.
Definition Mcp.cpp:77
void setup(CLI::App &app, std::shared_ptr< CLI::Formatter > formatter) override
Registers options on the CLI11 sub-app.
Definition Mcp.cpp:65
std::string root_path
Definition Mcp.cpp:60