载入中...
搜索中...
未找到
McpToolFilter.cpp
浏览该文件的文档.
2
5
6#include <Poco/Dynamic/Var.h>
7#include <Poco/JSON/Array.h>
8#include <Poco/JSON/Object.h>
9#include <Poco/JSON/Parser.h>
10
11#include <cctype>
12#include <cstdlib>
13#include <mutex>
14#include <optional>
15#include <string>
16#include <string_view>
17#include <unordered_set>
18#include <vector>
19
20namespace eve::dev {
21namespace {
22
23std::string toLower(std::string_view value) {
24 std::string out(value);
25 for (char& c : out) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
26 return out;
27}
28
29std::vector<std::string> splitComma(std::string_view raw) {
30 std::vector<std::string> out;
31 std::size_t start = 0;
32 while (start < raw.size()) {
33 const std::size_t comma = raw.find(',', start);
34 const auto end = comma == std::string_view::npos ? raw.size() : comma;
35 std::string part = toLower(raw.substr(start, end - start));
36 while (!part.empty() && std::isspace(static_cast<unsigned char>(part.front()))) part.erase(part.begin());
37 while (!part.empty() && std::isspace(static_cast<unsigned char>(part.back()))) part.pop_back();
38 if (!part.empty()) out.push_back(std::move(part));
39 if (comma == std::string_view::npos) break;
40 start = comma + 1;
41 }
42 return out;
43}
44
45struct FilterConfig {
46 bool all = true;
47 bool readOnly = false;
48 std::unordered_set<std::string> tags;
49 std::unordered_set<std::string> exclude;
50};
51
52std::mutex g_mu;
53FilterConfig g_cfg;
54bool g_loaded = false;
55
56void loadConfigUnlocked() {
57 g_cfg = FilterConfig{};
58 if (const char* toolset = std::getenv("EVE_MCP_TOOLSET")) {
59 const auto parts = splitComma(toolset);
60 g_cfg.all = parts.empty();
61 for (const auto& part : parts) {
62 if (part == "all") {
63 g_cfg.all = true;
64 g_cfg.tags.clear();
65 break;
66 }
67 g_cfg.all = false;
68 g_cfg.tags.insert(part);
69 }
70 }
71 if (const char* ro = std::getenv("EVE_MCP_READONLY")) {
72 const std::string value = toLower(ro);
73 g_cfg.readOnly = !(value.empty() || value == "0" || value == "false" || value == "off" || value == "no");
74 }
75 if (const char* exclude = std::getenv("EVE_MCP_EXCLUDE")) {
76 for (auto& name : splitComma(exclude)) g_cfg.exclude.insert(std::move(name));
77 }
78 g_loaded = true;
79}
80
81const FilterConfig& config() {
82 std::lock_guard lock(g_mu);
83 if (!g_loaded) loadConfigUnlocked();
84 return g_cfg;
85}
86
87bool startsWith(std::string_view value, std::string_view prefix) {
88 return value.size() >= prefix.size() && value.compare(0, prefix.size(), prefix) == 0;
89}
90
91bool equalsAny(std::string_view value, std::initializer_list<const char*> names) {
92 for (const char* name : names) {
93 if (value == name) return true;
94 }
95 return false;
96}
97
98} // namespace
99
101 {
102 std::lock_guard lock(g_mu);
103 loadConfigUnlocked();
104 }
105 // Re-read EVE_MCP_PROFILE into the process overlay for EnvGuard tests.
106 if (const char* raw = std::getenv("EVE_MCP_PROFILE"))
108 else
110}
111
112std::vector<std::string> mcpToolTags(std::string_view name) {
113 std::vector<std::string> tags;
114 auto add = [&](const char* tag) { tags.emplace_back(tag); };
115 if (startsWith(name, "eve_frame_")) {
116 add("core");
117 add("scene");
118 return tags;
119 }
120
121 if (startsWith(name, "eve_host_")) {
122 add("host");
123 return tags;
124 }
125 if (startsWith(name, "eve_editor_") || name == "eve_renderable3d_get") {
126 add("editor");
127 return tags;
128 }
129 if (startsWith(name, "eve_input_") || name == "eve_whitebox_playtest") {
130 add("input");
131 add("play");
132 add("scene");
133 return tags;
134 }
135 if (startsWith(name, "eve_recipe_")) {
136 add("scene");
137 add("agent");
138 return tags;
139 }
140 if (startsWith(name, "eve_asset_kit_")) {
141 add("agent");
142 add("core");
143 return tags;
144 }
145 if (name == "eve_workshop") {
146 add("play");
147 add("scene");
148 add("agent");
149 return tags;
150 }
151 if (startsWith(name, "eve_agent_")) {
152 add("agent");
153 return tags;
154 }
155 if (name == "eve_game_world") {
156 add("core");
157 add("play");
158 return tags;
159 }
160 if (startsWith(name, "eve_pixelworld_") || name == "eve_play" || name == "eve_gameplay" ||
161 startsWith(name, "eve_ui_")) {
162 add("play");
163 return tags;
164 }
165 if (startsWith(name, "eve_scene_") || startsWith(name, "inspect_") || name == "set_camera_pose" ||
166 name == "capture_render_frame" || name == "get_visible_entities_screen_bbox" ||
167 startsWith(name, "eve_camera_")) {
168 add("scene");
169 return tags;
170 }
171 if (equalsAny(name, {"eve_eval",
172 "eve_run_script",
173 "eve_pause",
174 "eve_continue",
175 "eve_step_in",
176 "eve_step_over",
177 "eve_step_out",
178 "eve_stack",
179 "eve_locals",
180 "eve_set_breakpoint",
181 "eve_clear_breakpoint",
182 "eve_list_breakpoints",
183 "eve_watch_add",
184 "eve_watch_list",
185 "eve_snapshot_capture",
186 "eve_snapshot_restore",
187 "eve_snapshot_save",
188 "eve_snapshot_load",
189 "eve_error_slice",
190 "eve_skeleton_inspect"})) {
191 add("debug");
192 return tags;
193 }
194 if (startsWith(name, "eve_decal_") || startsWith(name, "eve_profiler_") || name == "eve_sensing_last_query" ||
195 name == "eve_world_project_down" || name == "eve_physics_sphere_cast" || startsWith(name, "eve_physics_") ||
196 startsWith(name, "eve_procgen_") || startsWith(name, "eve_particles_") || startsWith(name, "eve_audio_")) {
197 add("domain");
198 return tags;
199 }
200 add("core");
201 return tags;
202}
203
204bool mcpToolMutates(std::string_view name) {
205 if (name == "eve_frame_capture_export") return true;
206 if (startsWith(name, "eve_input_")) return name != "eve_input_poll" && name != "eve_input_status";
207 if (name == "eve_eval" || name == "eve_run_script" || name == "eve_restart") return true;
208 if (name == "eve_pause" || name == "eve_continue" || startsWith(name, "eve_step_")) return true;
209 if (startsWith(name, "eve_set_breakpoint") || startsWith(name, "eve_clear_breakpoint") ||
210 startsWith(name, "eve_watch_") || startsWith(name, "eve_snapshot_"))
211 return true;
212 if (name == "eve_ui_click" || name == "eve_play" || name == "eve_gameplay") return true;
213 if (name == "eve_scene_modify" || name == "eve_scene_batch" || name == "eve_scene_reset" ||
214 name == "eve_scene_node_set" || name == "set_camera_pose" || name == "eve_camera_generate" ||
215 name == "eve_whitebox_playtest" || name == "eve_recipe_apply")
216 return true;
217 if (name == "eve_action_guide_pack_set" || name == "eve_action_guide_capture" ||
218 name == "eve_action_guide_export" || name == "eve_action_guide_ingest" || name == "eve_action_guide_verify")
219 return true;
220 if (name == "eve_workshop") return true;
221 if (startsWith(name, "eve_editor_") &&
222 (name.find("execute") != std::string_view::npos || name.find("commit") != std::string_view::npos ||
223 name.find("plan") != std::string_view::npos || name.find("create") != std::string_view::npos ||
224 name.find("close") != std::string_view::npos || name.find("cancel") != std::string_view::npos ||
225 name.find("undo") != std::string_view::npos || name.find("redo") != std::string_view::npos ||
226 name.find("observe_start") != std::string_view::npos || name.find("observe_close") != std::string_view::npos))
227 return true;
228 if (startsWith(name, "eve_host_") && name != "eve_host_status" && name != "eve_host_window_state" &&
229 name != "eve_host_editor_list" && name != "eve_host_editor_state" && name != "eve_host_events" &&
230 name != "eve_host_widget_rect" && name != "eve_host_hot_reload_status" && name != "eve_host_capture")
231 return true;
232 if (startsWith(name, "eve_pixelworld_") && name.find("validate") == std::string_view::npos &&
233 name.find("diagnostics") == std::string_view::npos && name.find("samples") == std::string_view::npos &&
234 name.find("list") == std::string_view::npos && name != "eve_pixelworld_worlds")
235 return true;
236 if (startsWith(name, "eve_decal_") && name != "eve_decal_status") return true;
237 if (startsWith(name, "eve_physics_") && name != "eve_physics_list_worlds" && name != "eve_physics_raycast" &&
238 name != "eve_physics_sphere_cast")
239 return true;
240 if (startsWith(name, "eve_particles_") && name != "eve_particles_status") return true;
241 if (startsWith(name, "eve_audio_") && name != "eve_audio_status") return true;
242 if (startsWith(name, "eve_procgen_") && name != "eve_procgen_recipes") return true;
243 if (startsWith(name, "eve_agent_") && name != "eve_agent_session_status" && name != "eve_agent_session_evidence")
244 return true;
245 if (name == "eve_console_write" || name == "eve_console_clear" || name == "eve_ai_note") return true;
246 if (name == "eve_render_vision_config") return true;
247 return false;
248}
249
250bool mcpToolAllowed(std::string_view name) {
251 const FilterConfig& cfg = config();
252 if (cfg.exclude.count(toLower(name)) != 0) return false;
253 if (cfg.readOnly && mcpToolMutates(name)) return false;
254 if (!cfg.all) {
255 const auto tags = mcpToolTags(name);
256 bool hit = false;
257 for (const auto& tag : tags) {
258 if (cfg.tags.count(tag) != 0) {
259 hit = true;
260 break;
261 }
262 }
263 if (!hit) return false;
264 }
265 const std::string processProfile = mcpProcessProfile();
266 if (!mcpProfileAllowsTool(processProfile, name)) return false;
267 const std::string sessionProfile = mcpSessionProfile();
268 if (!mcpProfileAllowsTool(sessionProfile, name)) return false;
269 return true;
270}
271
272std::string filterMcpToolsBody(std::string_view toolsBody) {
273 if (toolsBody.empty()) return {};
274 const std::string wrapped = std::string("[") + std::string(toolsBody) + "]";
275 try {
276 Poco::JSON::Parser parser;
277 auto array = parser.parse(wrapped).extract<Poco::JSON::Array::Ptr>();
278 if (!array) return std::string(toolsBody);
279 Poco::JSON::Array::Ptr kept = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
280 for (std::size_t i = 0; i < array->size(); ++i) {
281 auto tool = array->getObject(static_cast<unsigned>(i));
282 if (!tool || !tool->has("name")) continue;
283 const std::string name = tool->getValue<std::string>("name");
284 if (mcpToolAllowed(name)) kept->add(tool);
285 }
286 if (kept->size() == 0) return {};
287 std::string out = mcpStringify(Poco::Dynamic::Var(kept));
288 if (out.size() >= 2 && out.front() == '[' && out.back() == ']') return out.substr(1, out.size() - 2);
289 return out;
290 } catch (...) {
291 return std::string(toolsBody);
292 }
293}
294
295std::string mcpToolFilteredPayload(std::string_view name) {
296 const std::string processProfile = mcpProcessProfile();
297 const std::string sessionProfile = mcpSessionProfile();
298 const std::string activeProfile = !sessionProfile.empty() ? sessionProfile : processProfile;
299
300 std::string error = "tool '" + std::string(name) +
301 "' is hidden by EVE_MCP_TOOLSET / EVE_MCP_READONLY / EVE_MCP_EXCLUDE / EVE_MCP_PROFILE";
302 std::string hint = "Adjust env filters or call eve_status; use EVE_MCP_TOOLSET=all to advertise every tool";
303 std::vector<std::string> next = {"eve_status"};
304 std::optional<McpProfileEscalate> escalate;
305 if (!activeProfile.empty() && !mcpProfileAllowsTool(activeProfile, name)) {
306 error = "tool '" + std::string(name) + "' is outside task profile '" + activeProfile + "'";
307 hint = "Call eve_agent_session_escalate with an allowed target, or start a new session with the needed profile";
308 next = {"eve_agent_session_status", "eve_agent_session_escalate"};
309 escalate = mcpProfileEscalateHint(activeProfile, name);
310 if (escalate) {
311 hint = "Escalate to profile '" + escalate->to + "': " + escalate->reason;
312 next = {"eve_agent_session_escalate", "eve_agent_session_status"};
313 }
314 }
315
316 Poco::JSON::Object::Ptr out = mcpFailureObject(error, hint, false, next);
317 out->set("filtered", true);
318 out->set("tool", std::string(name));
319 if (!activeProfile.empty()) out->set("profile", activeProfile);
320 if (!sessionProfile.empty()) out->set("sessionProfile", sessionProfile);
321 if (!processProfile.empty()) out->set("processProfile", processProfile);
322 if (escalate) {
323 Poco::JSON::Object::Ptr esc(new Poco::JSON::Object());
324 esc->set("to", escalate->to);
325 esc->set("reason", escalate->reason);
326 esc->set("errorCode", escalate->errorCode);
327 out->set("escalate", esc);
328 }
329 Poco::JSON::Array::Ptr tags = Poco::JSON::Array::Ptr(new Poco::JSON::Array());
330 for (const auto& tag : mcpToolTags(name)) tags->add(tag);
331 out->set("tags", tags);
332 out->set("mutates", mcpToolMutates(name));
333 const std::string payload = mcpStringify(Poco::Dynamic::Var(out));
334 mcpFilterNoteCall(false, payload.size(), escalate.has_value());
335 return payload;
336}
337
338} // namespace eve::dev
Value::Object payload
Duration start
std::vector< eve::artifact::PartView > parts
std::string name
Definition ECS.cpp:154
double raw
std::int32_t c
Named Agent task profiles that narrow the MCP tool surface.
bool all
bool readOnly
std::unordered_set< std::string > exclude
std::unordered_set< std::string > tags
Toolset / read-only / exclude filtering for the embedded MCP server.
const std::string * tag
std::string error
Definition Package.cpp:174
bool hit
Object::Ptr value
ScriptStructure out
size_t end
std::string mcpProcessProfile()
Current process-level profile; empty when unset.
std::vector< std::string > mcpToolTags(std::string_view name)
Classify a built-in or script tool into toolset tags.
bool mcpToolAllowed(std::string_view name)
Whether name is visible under the current env filter.
void mcpSetProcessProfile(std::string_view profile)
Install or clear the process-level profile (EVE_MCP_PROFILE mirror for tests).
std::string mcpStringify(const Poco::Dynamic::Var &value)
Compact single-line JSON text for a newline-framed MCP payload.
Definition McpJson.hpp:24
bool mcpToolMutates(std::string_view name)
Whether the tool mutates game / editor / host state.
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
void mcpToolFilterReloadForTest()
Test helper: clear cached env snapshot so the next allow check reloads.
std::string filterMcpToolsBody(std::string_view toolsBody)
Filter a JSON tools array body in place (objects joined by commas).
bool mcpProfileAllowsTool(std::string_view profile, std::string_view tool)
Whether tool is allowed under a concrete named profile (empty = no profile gate).
std::string mcpToolFilteredPayload(std::string_view name)
Human-readable rejection payload fields when a call is filtered out.
void mcpFilterNoteCall(bool allowed, std::size_t resultBytes, bool offeredEscalate)
Record a tools/call attempt for proxy metrics.
std::string mcpSessionProfile()
Current session-level profile; empty when no session overlay.
std::optional< McpProfileEscalate > mcpProfileEscalateHint(std::string_view profile, std::string_view tool)
Suggest an escalate edge when tool is denied by profile.