1use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use brep_render::engine_state::EngineState;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14#[serde(rename_all = "snake_case")]
15pub enum Phase {
16 Input,
18 Mutate,
20 Read,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
25pub struct Annotations {
26 pub read_only: bool,
27 pub destructive: bool,
28 pub idempotent: bool,
29 pub waits: bool,
31}
32
33impl Annotations {
34 pub const READ: Annotations = Annotations { read_only: true, destructive: false, idempotent: true, waits: false };
35 pub const INPUT: Annotations = Annotations { read_only: false, destructive: false, idempotent: false, waits: false };
36 pub const MUTATE: Annotations = Annotations { read_only: false, destructive: false, idempotent: false, waits: true };
37 pub const MUTATE_NOWAIT: Annotations = Annotations { read_only: false, destructive: false, idempotent: true, waits: false };
38 pub const DESTRUCTIVE: Annotations = Annotations { read_only: false, destructive: true, idempotent: false, waits: true };
39}
40
41pub struct Ctx<'a> {
43 pub app: &'a mut crate::app::BrepApp,
44 pub egui: &'a egui::Context,
45}
46
47pub enum Outcome {
49 Done(Value),
50 Blob { json: Value, bytes: Vec<u8> },
52 AwaitScreenshot { token: u64, region: crate::automation::cmd_capture::Region, document: Option<String>, ppp: f32, scale: f32 },
58 Poll(Poller),
64}
65
66pub type Poller = Box<dyn FnMut(&mut Ctx<'_>) -> Option<Result<Outcome, String>> + Send>;
68
69pub type InputHandler = fn(&mut crate::automation::pointer::Pointer, Value, &mut Vec<egui::Event>) -> Result<Value, String>;
70pub type AppHandler = fn(&mut Ctx<'_>, Value) -> Result<Outcome, String>;
71
72pub enum Handler {
73 Input(InputHandler),
74 App(AppHandler),
75}
76
77pub struct CommandSpec {
78 pub name: &'static str,
79 pub group: &'static str,
80 pub doc: &'static str,
81 pub phase: Phase,
82 pub annotations: Annotations,
83 pub args_schema: fn() -> Value,
84 pub result_schema: fn() -> Value,
85 pub handler: Handler,
86}
87
88macro_rules! app_command {
96 ($group:literal, $name:literal, $doc:expr, $args:ty, $handler:path, $phase:ident, $annotation:ident, $output:expr) => {
97 $crate::automation::command::CommandSpec {
98 name: $name,
99 group: $group,
100 doc: $doc,
101 phase: $crate::automation::command::Phase::$phase,
102 annotations: $crate::automation::command::Annotations::$annotation,
103 args_schema: $crate::automation::command::schema_of::<$args>,
104 result_schema: $output,
105 handler: $crate::automation::command::Handler::App($handler),
106 }
107 };
108 ($group:literal, $name:literal, $doc:expr, $args:ty, $handler:path, $phase:ident, $annotation:ident) => {
109 $crate::automation::command::app_command!($group, $name, $doc, $args, $handler, $phase, $annotation, $crate::automation::command::empty_result_schema)
110 };
111}
112pub(crate) use app_command;
113
114pub fn engine_call<A, R, E>(ctx: &mut Ctx<'_>, args: Value, f: impl FnOnce(&mut EngineState, A) -> Result<R, E>) -> Result<Outcome, String>
118where
119 A: serde::de::DeserializeOwned,
120 String: From<E>,
121{
122 let a: A = parse_args(args)?;
123 f(ctx.app.docs.engine_mut(), a)?;
124 Ok(Outcome::Done(serde_json::json!({})))
125}
126
127pub fn read_engine(ctx: &mut Ctx<'_>, args: Value, f: impl FnOnce(&EngineState) -> Value) -> Result<Outcome, String> {
130 let _: NoArgs = parse_args(args)?;
131 Ok(Outcome::Done(f(ctx.app.docs.engine())))
132}
133
134pub fn schema_of<T: schemars::JsonSchema>() -> Value {
142 let mut schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or(Value::Null);
143 normalize_bool_subschemas(&mut schema);
144 schema
145}
146
147pub fn empty_result_schema() -> Value {
151 serde_json::json!({
152 "type": "object",
153 "properties": {},
154 "additionalProperties": false,
155 "description": "No native application payload. The MCP adapter adds frame, optional notices and settlement information."
156 })
157}
158
159pub(super) fn normalize_bool_subschemas(node: &mut Value) {
164 match node {
165 Value::Object(map) => {
166 if let Some(Value::Object(props)) = map.get_mut("properties") {
167 for value in props.values_mut() {
168 if let Some(b) = value.as_bool() {
169 *value = if b { serde_json::json!({}) } else { serde_json::json!({"not": {}}) };
170 }
171 }
172 }
173 if let Some(items) = map.get_mut("items") {
174 if let Some(b) = items.as_bool() {
175 *items = if b { serde_json::json!({}) } else { serde_json::json!({"not": {}}) };
176 }
177 }
178 for value in map.values_mut() {
179 normalize_bool_subschemas(value);
180 }
181 }
182 Value::Array(arr) => {
183 for value in arr.iter_mut() {
184 normalize_bool_subschemas(value);
185 }
186 }
187 _ => {}
188 }
189}
190
191pub fn parse_args<T: serde::de::DeserializeOwned>(args: Value) -> Result<T, String> {
192 let args = if args.is_null() { Value::Object(Default::default()) } else { args };
194 serde_json::from_value(args).map_err(|e| format!("arguments: {e}"))
195}
196
197#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
199#[serde(deny_unknown_fields)]
200pub struct NoArgs {}
201
202#[derive(Debug, Default, Serialize, schemars::JsonSchema)]
204pub struct Empty {}
205
206pub fn registry() -> Vec<&'static CommandSpec> {
211 use crate::automation::*;
212 let sets: &[&[CommandSpec]] = &[
213 cmd_frame::COMMANDS,
214 cmd_files::COMMANDS,
215 cmd_import_preview::COMMANDS,
216 cmd_perf::COMMANDS,
217 cmd_input::COMMANDS,
218 cmd_capture::COMMANDS,
219 cmd_state::COMMANDS,
220 cmd_document::COMMANDS,
221 cmd_classes::COMMANDS,
222 cmd_history::COMMANDS,
223 cmd_scene::COMMANDS,
224 cmd_camera::COMMANDS,
225 cmd_navigate::COMMANDS,
226 cmd_settings::COMMANDS,
227 cmd_sketch::COMMANDS,
228 cmd_shell::COMMANDS,
229 cmd_ui::COMMANDS,
230 cmd_plugins::COMMANDS,
231 cmd_metadata::COMMANDS,
232 cmd_assembly::COMMANDS,
233 cmd_pmi::COMMANDS,
234 cmd_sheets::COMMANDS,
235 cmd_wire_harness::COMMANDS,
236 cmd_cam::COMMANDS,
237 cmd_exploded::COMMANDS,
238 cmd_instructions::COMMANDS,
239 cmd_instructions_motion::COMMANDS,
240 cmd_simulation::COMMANDS,
241 cmd_simulation_play::COMMANDS,
242 cmd_cam_sim::COMMANDS,
243 cmd_ecad::COMMANDS,
244 #[cfg(not(target_arch = "wasm32"))]
245 cmd_plm::COMMANDS,
246 #[cfg(not(target_arch = "wasm32"))]
247 cmd_kicad::COMMANDS,
248 ];
249 sets.iter().flat_map(|s| s.iter()).collect()
250}
251
252pub fn lookup(name: &str) -> Option<&'static CommandSpec> {
253 registry().into_iter().find(|c| c.name == name)
254}
255
256pub fn describe() -> Value {
259 Value::Array(
260 registry()
261 .into_iter()
262 .map(|c| {
263 serde_json::json!({
264 "name": c.name,
265 "group": c.group,
266 "doc": c.doc,
267 "phase": c.phase,
268 "annotations": c.annotations,
269 "argsSchema": (c.args_schema)(),
270 "resultSchema": (c.result_schema)(),
271 })
272 })
273 .collect(),
274 )
275}
276
277#[derive(Debug, Clone, Serialize, Deserialize)]
280pub struct Envelope {
281 pub id: u64,
282 pub cmd: String,
283 #[serde(default)]
284 pub args: Value,
285}
286
287#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
288#[serde(rename_all = "snake_case")]
289pub enum NoticeKind {
290 Panic,
291 LogError,
292 RunnerRefusal,
293 Toast,
294 Console,
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
298pub struct Notice {
299 pub kind: NoticeKind,
300 pub frame: u64,
301 pub text: String,
302}
303
304#[derive(Debug, Clone, Default, Serialize, Deserialize)]
305pub struct Reply {
306 pub id: u64,
307 pub frame: u64,
308 pub ok: bool,
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub result: Option<Value>,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
312 pub error: Option<String>,
313 #[serde(default, skip_serializing_if = "Vec::is_empty")]
314 pub notices: Vec<Notice>,
315 #[serde(skip)]
318 pub blob: Option<Vec<u8>>,
319}
320
321impl Reply {
322 pub fn ok(id: u64, frame: u64, result: Value, notices: Vec<Notice>) -> Self {
323 Self { id, frame, ok: true, result: Some(result), error: None, notices, blob: None }
324 }
325 pub fn err(id: u64, frame: u64, error: impl Into<String>, notices: Vec<Notice>) -> Self {
326 Self { id, frame, ok: false, result: None, error: Some(error.into()), notices, blob: None }
327 }
328
329 pub fn into_host(mut self) -> brep_mcp_core::host::Reply {
335 use brep_mcp_core::host::Reply as HostReply;
336 let blob = self.blob.take();
337 let (id, frame) = (self.id, self.frame);
338 match serde_json::to_value(&self).map_err(|e| e.to_string()).and_then(|v| HostReply::from_app(v, blob)) {
339 Ok(reply) => reply,
340 Err(e) => HostReply::err(id, frame, e),
341 }
342 }
343}
344