elicit_egui 0.11.1

Elicitation-enabled egui widget tools — dual-mode MCP tools with code emission
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! `EguiWinitPlugin` — MCP tools for egui + winit native application scaffolding.
//!
//! Provides descriptor-registry tools for composing a native egui app that uses
//! winit for window management and `egui_winit::State` for event integration.
//! All tools are **emit-only**: they build an [`EguiWinitDescriptor`] server-side
//! and `egui_winit__emit` produces a complete `main.rs` scaffold.
//!
//! # Tool namespace: `egui_winit__*`
//!
//! | Tool | Params | Returns | Description |
//! |---|---|---|---|
//! | `new` | `app_struct, title, width, height` | `{ config_id }` | Create app config |
//! | `set_title` | `config_id, title` | — | Set window title |
//! | `set_size` | `config_id, width, height` | — | Set initial window size |
//! | `set_renderer` | `config_id, renderer` | — | Set `wgpu` or `glow` backend |
//! | `set_theme` | `config_id, theme` | — | Set dark / light / system theme |
//! | `set_vsync` | `config_id, vsync` | — | Toggle vertical sync |
//! | `set_decorations` | `config_id, decorations` | — | Toggle OS window decorations |
//! | `set_resizable` | `config_id, resizable` | — | Toggle window resize |
//! | `describe` | `config_id` | JSON descriptor | Inspect current config |
//! | `emit` | `config_id` | `main.rs` source | Emit complete native app |

use std::collections::BTreeMap;
use std::sync::Arc;

use elicitation::{
    EguiWinitDescriptor, EguiWinitRenderer, EguiWinitTheme, PluginContext, VerifiedWorkflow,
    contracts::{Established, Prop},
};
use rmcp::{
    ErrorData,
    model::{CallToolRequestParams, CallToolResult, Content, Tool},
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use tracing::instrument;
use uuid::Uuid;

// ── Proposition ───────────────────────────────────────────────────────────────

/// Proposition: a native egui + winit application was successfully configured.
#[derive(elicitation::Elicit, ::serde::Serialize, ::serde::Deserialize, ::schemars::JsonSchema)]
pub struct EguiWinitAppConfigured;

impl Prop for EguiWinitAppConfigured {
    fn kani_proof() -> elicitation::proc_macro2::TokenStream {
        quote::quote! {
            #[kani::proof]
            fn verify_egui_winit_app_configured() {
                let configured: bool = kani::any();
                kani::assume(configured);
                assert!(configured, "egui winit app configured");
            }
        }
    }
    fn verus_proof() -> elicitation::proc_macro2::TokenStream {
        quote::quote! {
            verus! {
            pub fn verify_egui_winit_app_configured(ok: bool) -> (result: bool)
                ensures result == ok,
            { ok }
            }
        }
    }
    fn creusot_proof() -> elicitation::proc_macro2::TokenStream {
        quote::quote! {
            #[requires(true)]
            #[ensures(result == true)]
            #[trusted]
            pub fn verify_egui_winit_app_configured_contract() -> bool { true }
        }
    }
}
impl VerifiedWorkflow for EguiWinitAppConfigured {}

// ── Plugin context ────────────────────────────────────────────────────────────

/// Shared mutable state for [`EguiWinitPlugin`].
pub struct EguiWinitCtx {
    pub(crate) items: Mutex<BTreeMap<Uuid, EguiWinitDescriptor>>,
}

impl EguiWinitCtx {
    fn new() -> Self {
        Self {
            items: Mutex::new(BTreeMap::new()),
        }
    }
}

impl PluginContext for EguiWinitCtx {}

// ── Param / result structs ────────────────────────────────────────────────────

/// Parameters for `egui_winit__new`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitNewParams {
    /// Application struct name (PascalCase, e.g. `"MyApp"`).
    pub app_struct: String,
    /// Window title shown in the OS title bar.
    pub title: String,
    /// Initial window width in logical pixels.
    pub width: u32,
    /// Initial window height in logical pixels.
    pub height: u32,
}

/// Parameters for `egui_winit__set_title`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitSetTitleParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
    /// New window title.
    pub title: String,
}

/// Parameters for `egui_winit__set_size`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitSetSizeParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
    /// Window width in logical pixels.
    pub width: u32,
    /// Window height in logical pixels.
    pub height: u32,
}

/// Parameters for `egui_winit__set_renderer`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitSetRendererParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
    /// Backend: `"wgpu"` (default) or `"glow"`.
    pub renderer: EguiWinitRenderer,
}

/// Parameters for `egui_winit__set_theme`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitSetThemeParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
    /// Theme: `"dark"` (default), `"light"`, or `"system"`.
    pub theme: EguiWinitTheme,
}

/// Parameters for `egui_winit__set_vsync`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitSetVsyncParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
    /// Whether to enable vertical sync.
    pub vsync: bool,
}

/// Parameters for `egui_winit__set_decorations`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitSetDecorationsParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
    /// Whether to show OS window decorations (title bar, borders).
    pub decorations: bool,
}

/// Parameters for `egui_winit__set_resizable`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitSetResizableParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
    /// Whether the window can be resized by the user.
    pub resizable: bool,
}

/// Parameters for `egui_winit__describe`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitDescribeParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
}

/// Parameters for `egui_winit__emit`.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct EguiWinitEmitParams {
    /// Config UUID returned by `egui_winit__new`.
    pub config_id: String,
}

/// Result returned by `egui_winit__new`.
#[derive(Debug, Serialize, JsonSchema)]
pub struct EguiWinitNewResult {
    /// UUID for the new config — pass to all other `egui_winit__*` tools.
    pub config_id: String,
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn parse_id(s: &str) -> Result<Uuid, ErrorData> {
    s.parse::<Uuid>()
        .map_err(|_| ErrorData::invalid_params(format!("invalid UUID: {s}"), None))
}

fn json_result<T: Serialize>(value: &T) -> CallToolResult {
    match serde_json::to_string_pretty(value) {
        Ok(s) => CallToolResult::success(vec![Content::text(s)]),
        Err(e) => CallToolResult::error(vec![Content::text(format!("serialize error: {e}"))]),
    }
}

fn ok_text(s: impl Into<String>) -> CallToolResult {
    CallToolResult::success(vec![Content::text(s.into())])
}

// ── Emit helpers ──────────────────────────────────────────────────────────────

fn emit_wgpu(desc: &EguiWinitDescriptor) -> String {
    let app = &desc.app_struct;
    let title = &desc.title;
    let w = desc.width;
    let h = desc.height;
    let theme_line = match desc.theme {
        EguiWinitTheme::Dark => "        ctx.set_theme(egui::Theme::Dark);\n".to_string(),
        EguiWinitTheme::Light => "        ctx.set_theme(egui::Theme::Light);\n".to_string(),
        EguiWinitTheme::System => String::new(),
    };
    let deco = if desc.decorations {
        String::new()
    } else {
        "\n        .with_decorations(false)".to_string()
    };
    let resize = if desc.resizable {
        String::new()
    } else {
        "\n        .with_resizable(false)".to_string()
    };
    let transparent = if desc.transparent {
        "\n        .with_transparent(true)".to_string()
    } else {
        String::new()
    };
    let maximized = if desc.maximized {
        "\n        .with_maximized(true)".to_string()
    } else {
        String::new()
    };
    let vsync_mode = if desc.vsync {
        "wgpu::PresentMode::AutoVsync"
    } else {
        "wgpu::PresentMode::AutoNoVsync"
    };
    format!(
        r#"//! Generated by `egui_winit__emit` (renderer: wgpu).
//! Add this as `src/main.rs` in your binary crate.
//!
//! Required Cargo.toml dependencies:
//! ```toml
//! egui = "0.34"
//! egui-winit = "0.34"
//! egui-wgpu = {{ version = "0.34", features = ["winit"] }}
//! wgpu = "24"
//! winit = "0.30"
//! pollster = "0.4"
//! ```

use std::sync::Arc;
use egui_winit::State;
use winit::{{
    application::ApplicationHandler,
    event::WindowEvent,
    event_loop::{{ActiveEventLoop, ControlFlow, EventLoop}},
    window::{{Window, WindowId, WindowAttributes}},
}};

/// Your application state — add your own fields here.
#[derive(Default)]
struct {app} {{
    window: Option<Arc<Window>>,
    egui_state: Option<State>,
    surface: Option<wgpu::Surface<'static>>,
    device: Option<Arc<wgpu::Device>>,
    queue: Option<Arc<wgpu::Queue>>,
    renderer: Option<egui_wgpu::Renderer>,
    surface_config: Option<wgpu::SurfaceConfiguration>,
}}

impl {app} {{
    fn update(&mut self, ctx: &egui::Context) {{
        egui::CentralPanel::default().show(ctx, |ui| {{
            ui.heading("{title}");
            ui.label("Replace this with your UI.");
        }});
    }}
}}

impl ApplicationHandler for {app} {{
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {{
        let attrs = WindowAttributes::default()
            .with_title("{title}")
            .with_inner_size(winit::dpi::LogicalSize::new({w}_f64, {h}_f64)){deco}{resize}{transparent}{maximized};
        let window = Arc::new(event_loop.create_window(attrs).expect("create window"));

        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
        let surface = instance.create_surface(window.clone()).expect("create surface");
        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {{
            compatible_surface: Some(&surface),
            ..Default::default()
        }})).expect("find adapter");
        let (device, queue) = pollster::block_on(adapter.request_device(
            &wgpu::DeviceDescriptor::default(), None,
        )).expect("create device");
        let device = Arc::new(device);
        let queue = Arc::new(queue);

        let size = window.inner_size();
        let surface_format = surface.get_capabilities(&adapter).formats[0];
        let config = wgpu::SurfaceConfiguration {{
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width: size.width,
            height: size.height,
            present_mode: {vsync_mode},
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
        }};
        surface.configure(&device, &config);

        let ctx = egui::Context::default();
{theme_line}        let egui_state = State::new(
            ctx,
            egui::ViewportId::ROOT,
            &window,
            Some(window.scale_factor() as f32),
            None,
            Some(device.limits().max_texture_dimension_2d as usize),
        );
        let renderer = egui_wgpu::Renderer::new(&device, surface_format, None, 1, false);

        self.window = Some(window);
        self.egui_state = Some(egui_state);
        self.surface = Some(surface);
        self.device = Some(device);
        self.queue = Some(queue);
        self.renderer = Some(renderer);
        self.surface_config = Some(config);
    }}

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _id: WindowId,
        event: WindowEvent,
    ) {{
        let (window, state) = match (self.window.as_ref(), self.egui_state.as_mut()) {{
            (Some(w), Some(s)) => (w, s),
            _ => return,
        }};
        let response = state.on_window_event(window, &event);
        if response.repaint {{
            window.request_redraw();
        }}
        match event {{
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(size) => {{
                if let (Some(surface), Some(device), Some(cfg)) = (
                    self.surface.as_ref(),
                    self.device.as_ref(),
                    self.surface_config.as_mut(),
                ) {{
                    cfg.width = size.width.max(1);
                    cfg.height = size.height.max(1);
                    surface.configure(device, cfg);
                }}
                window.request_redraw();
            }}
            WindowEvent::RedrawRequested => {{
                let state = self.egui_state.as_mut().unwrap();
                let raw_input = state.take_egui_input(window);
                let ctx = state.egui_ctx().clone();
                let full_output = ctx.run(raw_input, |ctx| {{
                    self.update(ctx);
                }});
                state.handle_platform_output(window, full_output.platform_output);

                let (surface, device, queue, renderer, cfg) = match (
                    self.surface.as_ref(),
                    self.device.as_ref(),
                    self.queue.as_ref(),
                    self.renderer.as_mut(),
                    self.surface_config.as_ref(),
                ) {{
                    (Some(s), Some(d), Some(q), Some(r), Some(c)) => (s, d, q, r, c),
                    _ => return,
                }};
                let output = match surface.get_current_texture() {{
                    Ok(t) => t,
                    Err(_) => return,
                }};
                let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
                let clipped = ctx.tessellate(full_output.shapes, ctx.pixels_per_point());
                let screen = egui_wgpu::ScreenDescriptor {{
                    size_in_pixels: [cfg.width, cfg.height],
                    pixels_per_point: ctx.pixels_per_point(),
                }};
                let mut encoder = device.create_command_encoder(
                    &wgpu::CommandEncoderDescriptor {{ label: None }},
                );
                for (id, delta) in &full_output.textures_delta.set {{
                    renderer.update_texture(device, queue, *id, delta);
                }}
                renderer.update_buffers(device, queue, &mut encoder, &clipped, &screen);
                {{
                    let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {{
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {{
                            view: &view,
                            resolve_target: None,
                            ops: wgpu::Operations {{
                                load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                                store: wgpu::StoreOp::Store,
                            }},
                        }})],
                        ..Default::default()
                    }});
                    renderer.render(&mut rpass, &clipped, &screen);
                }}
                queue.submit(std::iter::once(encoder.finish()));
                output.present();
                for id in &full_output.textures_delta.free {{
                    renderer.free_texture(id);
                }}
                window.request_redraw();
            }}
            _ => {{}}
        }}
    }}
}}

fn main() {{
    let event_loop = EventLoop::new().expect("create event loop");
    event_loop.set_control_flow(ControlFlow::Poll);
    let mut app = {app}::default();
    event_loop.run_app(&mut app).expect("run event loop");
}}
"#,
        app = app,
        title = title,
        w = w,
        h = h,
        deco = deco,
        resize = resize,
        transparent = transparent,
        maximized = maximized,
        vsync_mode = vsync_mode,
        theme_line = theme_line,
    )
}

fn emit_glow(desc: &EguiWinitDescriptor) -> String {
    let app = &desc.app_struct;
    let title = &desc.title;
    let w = desc.width;
    let h = desc.height;
    format!(
        r#"//! Generated by `egui_winit__emit` (renderer: glow).
//! Add this as `src/main.rs` in your binary crate.
//!
//! Required Cargo.toml dependencies:
//! ```toml
//! egui = "0.34"
//! egui_glow = {{ version = "0.34", features = ["winit"] }}
//! winit = "0.30"
//! glutin = "0.32"
//! ```

use egui_winit::State;
use winit::{{
    application::ApplicationHandler,
    event::WindowEvent,
    event_loop::{{ActiveEventLoop, ControlFlow, EventLoop}},
    window::{{Window, WindowId, WindowAttributes}},
}};

/// Your application state.
#[derive(Default)]
struct {app} {{
    window: Option<Window>,
    egui_state: Option<State>,
    // TODO: add your glutin/glow context here
}}

impl {app} {{
    fn update(&mut self, ctx: &egui::Context) {{
        egui::CentralPanel::default().show(ctx, |ui| {{
            ui.heading("{title}");
            ui.label("Replace this with your UI.");
        }});
    }}
}}

impl ApplicationHandler for {app} {{
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {{
        let attrs = WindowAttributes::default()
            .with_title("{title}")
            .with_inner_size(winit::dpi::LogicalSize::new({w}_f64, {h}_f64));
        let window = event_loop.create_window(attrs).expect("create window");
        let ctx = egui::Context::default();
        let egui_state = State::new(
            ctx,
            egui::ViewportId::ROOT,
            &window,
            Some(window.scale_factor() as f32),
            None,
            None,
        );
        self.window = Some(window);
        self.egui_state = Some(egui_state);
        // TODO: initialise glutin display + glow context here
    }}

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _id: WindowId,
        event: WindowEvent,
    ) {{
        let (window, state) = match (self.window.as_ref(), self.egui_state.as_mut()) {{
            (Some(w), Some(s)) => (w, s),
            _ => return,
        }};
        let response = state.on_window_event(window, &event);
        if response.repaint {{
            window.request_redraw();
        }}
        match event {{
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::RedrawRequested => {{
                let state = self.egui_state.as_mut().unwrap();
                let raw_input = state.take_egui_input(window);
                let ctx = state.egui_ctx().clone();
                let _full_output = ctx.run(raw_input, |ctx| {{
                    self.update(ctx);
                }});
                // TODO: swap glow framebuffer here
                window.request_redraw();
            }}
            _ => {{}}
        }}
    }}
}}

fn main() {{
    let event_loop = EventLoop::new().expect("create event loop");
    event_loop.set_control_flow(ControlFlow::Poll);
    let mut app = {app}::default();
    event_loop.run_app(&mut app).expect("run event loop");
}}
"#,
        app = app,
        title = title,
        w = w,
        h = h,
    )
}

// ── Tool functions ────────────────────────────────────────────────────────────

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__new",
    description = "Create a new egui + winit native app config. \
                   Returns { config_id } for use with all other egui_winit__* tools. \
                   Establishes: EguiWinitAppConfigured.",
    emit = Auto
)]
#[instrument(skip(ctx), fields(app_struct = %p.app_struct, title = %p.title))]
async fn new_config(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitNewParams,
) -> Result<CallToolResult, ErrorData> {
    let id = Uuid::new_v4();
    let desc = EguiWinitDescriptor::new(p.app_struct, p.title, p.width, p.height);
    ctx.items.lock().await.insert(id, desc);
    let _proof: Established<EguiWinitAppConfigured> = Established::assert();
    Ok(json_result(&EguiWinitNewResult {
        config_id: id.to_string(),
    }))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__set_title",
    description = "Update the window title for an egui_winit config.",
    emit = Auto
)]
#[instrument(skip(ctx), fields(title = %p.title))]
async fn set_title(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitSetTitleParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    ctx.items
        .lock()
        .await
        .get_mut(&id)
        .ok_or_else(|| {
            ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
        })?
        .title = p.title;
    Ok(ok_text("title updated"))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__set_size",
    description = "Update the initial window size (logical pixels) for an egui_winit config.",
    emit = Auto
)]
#[instrument(skip(ctx), fields(width = p.width, height = p.height))]
async fn set_size(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitSetSizeParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    let mut items = ctx.items.lock().await;
    let desc = items.get_mut(&id).ok_or_else(|| {
        ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
    })?;
    desc.width = p.width;
    desc.height = p.height;
    Ok(ok_text("size updated"))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__set_renderer",
    description = "Set the GPU backend: 'wgpu' (default, recommended) or 'glow' (OpenGL).",
    emit = Auto
)]
#[instrument(skip(ctx), fields(renderer = ?p.renderer))]
async fn set_renderer(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitSetRendererParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    ctx.items
        .lock()
        .await
        .get_mut(&id)
        .ok_or_else(|| {
            ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
        })?
        .renderer = p.renderer;
    Ok(ok_text("renderer updated"))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__set_theme",
    description = "Set the colour theme: 'dark' (default), 'light', or 'system' (follow OS).",
    emit = Auto
)]
#[instrument(skip(ctx), fields(theme = ?p.theme))]
async fn set_theme(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitSetThemeParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    ctx.items
        .lock()
        .await
        .get_mut(&id)
        .ok_or_else(|| {
            ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
        })?
        .theme = p.theme;
    Ok(ok_text("theme updated"))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__set_vsync",
    description = "Enable or disable vertical sync (default: true). \
                   Affects the wgpu PresentMode: AutoVsync vs AutoNoVsync.",
    emit = Auto
)]
#[instrument(skip(ctx), fields(vsync = p.vsync))]
async fn set_vsync(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitSetVsyncParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    ctx.items
        .lock()
        .await
        .get_mut(&id)
        .ok_or_else(|| {
            ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
        })?
        .vsync = p.vsync;
    Ok(ok_text("vsync updated"))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__set_decorations",
    description = "Show or hide OS window decorations — title bar, border, close/min/max buttons \
                   (default: true).",
    emit = Auto
)]
#[instrument(skip(ctx), fields(decorations = p.decorations))]
async fn set_decorations(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitSetDecorationsParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    ctx.items
        .lock()
        .await
        .get_mut(&id)
        .ok_or_else(|| {
            ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
        })?
        .decorations = p.decorations;
    Ok(ok_text("decorations updated"))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__set_resizable",
    description = "Allow or prevent user window resize (default: true).",
    emit = Auto
)]
#[instrument(skip(ctx), fields(resizable = p.resizable))]
async fn set_resizable(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitSetResizableParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    ctx.items
        .lock()
        .await
        .get_mut(&id)
        .ok_or_else(|| {
            ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
        })?
        .resizable = p.resizable;
    Ok(ok_text("resizable updated"))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__describe",
    description = "Return a JSON snapshot of the current egui_winit config.",
    emit = Auto
)]
#[instrument(skip(ctx))]
async fn describe(
    ctx: Arc<EguiWinitCtx>,
    p: EguiWinitDescribeParams,
) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    let desc = ctx.items.lock().await.get(&id).cloned().ok_or_else(|| {
        ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
    })?;
    Ok(json_result(&desc))
}

#[elicitation::elicit_tool(
    plugin = "egui_winit",
    name = "egui_winit__emit",
    description = "Emit a complete main.rs scaffold for the configured egui + winit native app. \
                   For 'wgpu' renderer: includes egui_winit::State + full wgpu render loop. \
                   For 'glow' renderer: includes egui_winit::State + glutin stub. \
                   The emitted code uses winit's ApplicationHandler pattern (winit 0.30+).",
    emit = Auto
)]
#[instrument(skip(ctx))]
async fn emit(ctx: Arc<EguiWinitCtx>, p: EguiWinitEmitParams) -> Result<CallToolResult, ErrorData> {
    let id = parse_id(&p.config_id)?;
    let desc = ctx.items.lock().await.get(&id).cloned().ok_or_else(|| {
        ErrorData::invalid_params(format!("unknown config_id: {}", p.config_id), None)
    })?;
    let src = match desc.renderer {
        EguiWinitRenderer::Wgpu => emit_wgpu(&desc),
        EguiWinitRenderer::Glow => emit_glow(&desc),
    };
    Ok(CallToolResult::success(vec![Content::text(src)]))
}

// ── Plugin struct + ElicitPlugin impl ─────────────────────────────────────────

/// MCP plugin providing `egui_winit__*` tools for native egui + winit app scaffolding.
///
/// Mirrors the structure of `egui_winit` just as `elicit_leptos::LeptosAxumPlugin`
/// mirrors `leptos_axum` in `elicit_leptos`. All tools emit Rust code; no windows
/// or GPU devices are created in the MCP server process.
///
/// # Composition
///
/// ```text
/// egui_winit__new(app_struct: "MyApp", title: "My App", width: 1280, height: 720)
///   → { config_id }
/// egui_winit__set_theme(config_id, theme: "dark")
/// egui_winit__set_renderer(config_id, renderer: "wgpu")
/// egui_winit__emit(config_id)
///   → main.rs with winit ApplicationHandler + egui_winit::State + wgpu render loop
/// ```
pub struct EguiWinitPlugin(Arc<EguiWinitCtx>);

impl EguiWinitPlugin {
    /// Create a new plugin with an empty config registry.
    pub fn new() -> Self {
        Self(Arc::new(EguiWinitCtx::new()))
    }

    /// Invoke a tool by name directly — useful for tests.
    pub async fn invoke_tool(
        &self,
        name: &str,
        args: serde_json::Value,
    ) -> Result<CallToolResult, ErrorData> {
        let owned = name.to_string();
        let params = if let Some(m) = args.as_object().cloned() {
            CallToolRequestParams::new(owned).with_arguments(m)
        } else {
            CallToolRequestParams::new(owned)
        };
        let full_name = if name.starts_with("egui_winit__") {
            name.to_string()
        } else {
            format!("egui_winit__{name}")
        };
        let descriptor = elicitation::inventory::iter::<elicitation::PluginToolRegistration>()
            .filter(|r| r.plugin == "egui_winit")
            .find(|r| r.name == full_name)
            .map(|r| (r.constructor)())
            .ok_or_else(|| ErrorData::invalid_params(format!("unknown tool: {name}"), None))?;
        descriptor
            .dispatch(
                self.0.clone() as Arc<dyn std::any::Any + Send + Sync>,
                params,
            )
            .await
    }
}

impl Default for EguiWinitPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl elicitation::ElicitPlugin for EguiWinitPlugin {
    fn name(&self) -> &'static str {
        "egui_winit"
    }

    fn list_tools(&self) -> Vec<Tool> {
        elicitation::inventory::iter::<elicitation::PluginToolRegistration>()
            .filter(|r| r.plugin == "egui_winit")
            .map(|r| (r.constructor)().as_tool())
            .collect()
    }

    #[tracing::instrument(skip(self, _ctx), fields(tool = %params.name))]
    fn call_tool<'a>(
        &'a self,
        params: CallToolRequestParams,
        _ctx: rmcp::service::RequestContext<rmcp::RoleServer>,
    ) -> futures::future::BoxFuture<'a, Result<CallToolResult, ErrorData>> {
        let plugin_ctx = self.0.clone();
        Box::pin(async move {
            let name = params.name.as_ref();
            let full_name = if name.starts_with("egui_winit__") {
                name.to_string()
            } else {
                format!("egui_winit__{name}")
            };
            let descriptor = elicitation::inventory::iter::<elicitation::PluginToolRegistration>()
                .filter(|r| r.plugin == "egui_winit")
                .find(|r| r.name == full_name)
                .map(|r| (r.constructor)())
                .ok_or_else(|| ErrorData::invalid_params(format!("unknown tool: {name}"), None))?;
            descriptor
                .dispatch(plugin_ctx as Arc<dyn std::any::Any + Send + Sync>, params)
                .await
        })
    }
}