lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
//! Embeddable MCP server: lets an AI agent drive and inspect a running lurq
//! app the way browser MCP tools drive a web page — screenshot, read the
//! element tree, click/type, navigate — plus lurq-specific state
//! introspection and app-defined custom tools.
//!
//! Nothing is exposed by default. Three enablement layers:
//! 1. the `mcp` Cargo feature (off by default) compiles this module in;
//! 2. [`Tree::enable_mcp`] starts the server — nothing listens without it;
//! 3. [`McpHandle`] toggles availability and scopes at runtime.
//!
//! ```ignore
//! let mcp = tree.enable_mcp(
//!   McpConfig::new().scopes([Scope::Observe, Scope::Interact]),
//! );
//! ```
//!
//! The server speaks streamable HTTP on `127.0.0.1` with a mandatory bearer
//! token, and announces itself in a discovery file
//! (`%LOCALAPPDATA%\lurq\mcp\<pid>.json` on Windows; XDG dirs on Linux).
//! Connect with `claude mcp add --transport http http://127.0.0.1:<port>/mcp`
//! and the token from the discovery file.
//!
//! An app with an MCP server of its own serves lurq's tools from it instead:
//! [`McpConfig::hosted`] starts no listener and writes no discovery file, and
//! [`McpHandle::service`] hands the host one [`McpService`] per client session.

use std::{
  borrow::Cow,
  collections::HashSet,
  future::Future,
  pin::Pin,
  sync::{Arc, mpsc as std_mpsc},
};

mod discovery;
mod file_dialogs;
mod held_input;
mod logs;
mod profiling;
mod registry;
mod server;
mod sessions;
mod shared;
mod tools;

pub(crate) use file_dialogs::ServingBroker;
pub use file_dialogs::{
  FileDialogBroker, FileDialogError, FileDialogFuture, FileDialogOperation, FileDialogRequest, FileDialogSelection,
};
pub use logs::{McpLogLayer, log_layer};
use registry::{ToolKind, ToolRegistry};
/// rmcp, re-exported so a host server that mounts [`McpService`] builds on the
/// same version.
pub use rmcp;
/// rmcp's schemars, re-exported so typed custom-tool inputs derive against
/// the same version: `#[derive(schemars::JsonSchema)]` with
/// `#[schemars(crate = "lurq::mcp::schemars")]`.
pub use rmcp::schemars;
pub use server::McpService;
use shared::McpShared;
pub use shared::{McpToolOutput, McpToolResult};

use crate::app::{App, Tree};

/// Coarse permission groups. Tools outside granted scopes are not listed to
/// the client at all (not merely rejected). Runtime-mutable via [`McpHandle`].
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Scope {
  /// Screenshots, tree reading, window listing, waiting, logs.
  Observe,
  /// Synthetic input, form set_value, window resizing.
  Interact,
  /// Router navigation.
  Navigate,
  /// App-defined scope for custom tools.
  Custom(Cow<'static, str>),
}

impl Scope {
  pub fn custom(name: impl Into<Cow<'static, str>>) -> Self {
    Self::Custom(name.into())
  }
}

/// Execution context handed to synchronous custom tools: full tree and app
/// access on the event-loop thread — the same powers and the same
/// no-blocking constraint as event handlers.
pub struct McpToolCtx<'a> {
  pub tree: &'a mut Tree,
  pub app: &'a mut App,
}

type CustomSyncHandler = Arc<registry::SyncToolHandler>;
type CustomAsyncHandler = Arc<registry::AsyncToolHandler>;

enum CustomToolKind {
  Sync(CustomSyncHandler),
  Async(CustomAsyncHandler),
}

/// A custom tool registered by the embedding app.
///
/// ```ignore
/// McpTool::new("export_project")
///   .description("Export the current project to disk")
///   .scope(Scope::custom("project"))
///   .input_schema(serde_json::json!({
///     "type": "object",
///     "properties": { "path": { "type": "string" } },
///     "required": ["path"]
///   }))
///   .handler(|ctx, args| {
///     let path = args["path"].as_str().ok_or("path required")?;
///     // ctx.tree / ctx.app ...
///     Ok(serde_json::json!({ "ok": true }))
///   })
/// ```
pub struct McpTool {
  name: String,
  description: String,
  scope: Scope,
  read_only: bool,
  input_schema: serde_json::Value,
  kind: Option<CustomToolKind>,
}

impl McpTool {
  pub fn new(name: impl Into<String>) -> Self {
    Self {
      name: name.into(),
      description: String::new(),
      scope: Scope::custom("app"),
      read_only: false,
      input_schema: serde_json::json!({ "type": "object", "properties": {} }),
      kind: None,
    }
  }

  pub fn description(mut self, description: impl Into<String>) -> Self {
    self.description = description.into();
    self
  }

  pub fn scope(mut self, scope: impl Into<Scope>) -> Self {
    self.scope = scope.into();
    self
  }

  /// Hint that the tool does not modify the app.
  pub fn read_only(mut self) -> Self {
    self.read_only = true;
    self
  }

  /// JSON Schema for the tool's arguments. For typed inputs, derive
  /// `schemars::JsonSchema` (see [`schemars`]) and pass
  /// `serde_json::to_value(schemars::schema_for!(Input)).unwrap()`.
  pub fn input_schema(mut self, schema: serde_json::Value) -> Self {
    self.input_schema = schema;
    self
  }

  /// Synchronous handler, run on the event-loop thread with
  /// [`McpToolCtx`] access. Must not block (network, sleeps, dialogs) — a
  /// blocked handler freezes the UI.
  pub fn handler<F>(mut self, handler: F) -> Self
  where
    F: Fn(&mut McpToolCtx<'_>, serde_json::Value) -> Result<serde_json::Value, String> + Send + Sync + 'static,
  {
    self.kind = Some(CustomToolKind::Sync(Arc::new(handler)));
    self
  }

  /// Asynchronous handler, run on the MCP server's tokio runtime with **no**
  /// tree access — for I/O-bound work. Distinct from [`Self::handler`] at
  /// the type level so blocking tools can't freeze the UI by accident.
  pub fn async_handler<F, Fut>(mut self, handler: F) -> Self
  where
    F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<serde_json::Value, String>> + Send + 'static,
  {
    self.kind = Some(CustomToolKind::Async(Arc::new(move |args| {
      Box::pin(handler(args)) as Pin<Box<dyn Future<Output = Result<serde_json::Value, String>> + Send>>
    })));
    self
  }
}

impl From<&'static str> for Scope {
  fn from(name: &'static str) -> Self {
    Scope::custom(name)
  }
}

/// Configuration for [`Tree::enable_mcp`].
pub struct McpConfig {
  scopes: HashSet<Scope>,
  denied_tools: HashSet<String>,
  port: Option<u16>,
  app_name: Option<String>,
  include_devtools: bool,
  instructions: Option<String>,
  tools: Vec<McpTool>,
  file_dialogs: Option<FileDialogBroker>,
  hosted: bool,
  #[cfg(feature = "router")]
  navigator: Option<crate::router::Navigator>,
}

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

impl McpConfig {
  /// Defaults: `Observe` + `Interact` scopes, ephemeral port, devtools
  /// window hidden.
  pub fn new() -> Self {
    Self {
      scopes: HashSet::from([Scope::Observe, Scope::Interact]),
      denied_tools: HashSet::new(),
      port: None,
      app_name: None,
      include_devtools: false,
      instructions: None,
      tools: Vec::new(),
      file_dialogs: None,
      hosted: false,
      #[cfg(feature = "router")]
      navigator: None,
    }
  }

  /// Serve the tools from the app's own MCP server instead of lurq's: no
  /// listener starts and no discovery file is written, so the host owns the
  /// port, the token, the discovery and its settings. The host mounts
  /// [`McpHandle::service`]; scopes, denies and [`McpHandle::set_enabled`] still
  /// decide which tools it lists and accepts. [`McpHandle::port`] is `0`.
  pub fn hosted(mut self) -> Self {
    self.hosted = true;
    self
  }

  /// Replace the granted scope set.
  pub fn scopes(mut self, scopes: impl IntoIterator<Item = Scope>) -> Self {
    self.scopes = scopes.into_iter().collect();
    self
  }

  /// Grant one more scope.
  pub fn scope(mut self, scope: Scope) -> Self {
    self.scopes.insert(scope);
    self
  }

  /// Per-tool deny list on top of scopes, for fine trimming.
  pub fn deny_tool(mut self, name: impl Into<String>) -> Self {
    self.denied_tools.insert(name.into());
    self
  }

  /// Fixed port instead of an ephemeral one.
  pub fn port(mut self, port: u16) -> Self {
    self.port = Some(port);
    self
  }

  /// Name announced in the discovery file and server info; defaults to the
  /// executable name.
  pub fn app_name(mut self, name: impl Into<String>) -> Self {
    self.app_name = Some(name.into());
    self
  }

  /// Expose the devtools window to MCP (it's tooling chrome and hidden by
  /// default; the audience is lurq's own development).
  pub fn include_devtools(mut self, include: bool) -> Self {
    self.include_devtools = include;
    self
  }

  /// Extra text appended to the server's instructions for the agent.
  pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
    self.instructions = Some(instructions.into());
    self
  }

  /// Register a custom tool. Built-in names are reserved under the `lurq_`
  /// prefix; duplicates and reserved names panic at [`Tree::enable_mcp`].
  pub fn tool(mut self, tool: McpTool) -> Self {
    self.tools.push(tool);
    self
  }

  /// Opt normal app picker handlers into request-scoped MCP selection.
  /// Also grant `Scope::custom("file_dialogs")`; no rfd call is intercepted.
  pub fn file_dialogs(mut self, broker: FileDialogBroker) -> Self {
    self.file_dialogs = Some(broker);
    self
  }

  /// Navigator for the built-in `lurq_navigate` tool (also settable later
  /// via [`McpHandle::set_navigator`]).
  #[cfg(feature = "router")]
  pub fn navigator(mut self, navigator: crate::router::Navigator) -> Self {
    self.navigator = Some(navigator);
    self
  }
}

/// Clonable runtime control for the MCP server: enable/disable, scope
/// changes, per-tool denies — for debug menus, env-var gating, or
/// support-session unlocks.
#[derive(Clone)]
pub struct McpHandle {
  shared: Arc<McpShared>,
  registry: Arc<ToolRegistry>,
  sender: std_mpsc::Sender<shared::McpRequest>,
  port: u16,
}

impl McpHandle {
  /// The bound port; the endpoint is `http://127.0.0.1:<port>/mcp`. `0` when
  /// the server is [hosted](McpConfig::hosted) or failed to start.
  pub fn port(&self) -> u16 {
    self.port
  }

  /// lurq's tools for one client session of a host app's MCP server
  /// ([`McpConfig::hosted`]), as an rmcp [`ServerHandler`](rmcp::ServerHandler).
  /// Build one per host session, e.g. in the session factory of rmcp's
  /// `StreamableHttpService`, or delegate `list_tools`, `call_tool` and
  /// `get_info` to it from the host's own handler. Input a client holds across
  /// calls is released when the service of its session is dropped.
  pub fn service(&self) -> McpService {
    McpService::new(self.shared.clone(), self.registry.clone(), self.sender.clone())
  }

  /// The bearer token clients must present (also in the discovery file).
  pub fn token(&self) -> &str {
    &self.shared.token
  }

  pub fn is_enabled(&self) -> bool {
    self.shared.is_enabled()
  }

  /// Disable/enable serving without tearing the listener down. While
  /// disabled every tool is hidden and rejected.
  pub fn set_enabled(&self, enabled: bool) {
    self.shared.set_enabled(enabled);
  }

  pub fn set_scopes(&self, scopes: impl IntoIterator<Item = Scope>) {
    self.shared.set_scopes(scopes.into_iter().collect());
  }

  pub fn add_scope(&self, scope: Scope) {
    self.shared.add_scope(scope);
  }

  pub fn remove_scope(&self, scope: &Scope) {
    self.shared.remove_scope(scope);
  }

  pub fn deny_tool(&self, name: impl Into<String>) {
    self.shared.deny_tool(name);
  }

  pub fn allow_tool(&self, name: &str) {
    self.shared.allow_tool(name);
  }

  /// Navigator used by the built-in `lurq_navigate` tool. Typically set from
  /// a component once the router exists: `ctx.navigator()`.
  #[cfg(feature = "router")]
  pub fn set_navigator(&self, navigator: crate::router::Navigator) {
    *self.shared.navigator.write().unwrap() = Some(navigator);
  }
}

/// Parked `lurq_wait` reply on a tree, resolved as frames complete.
pub(crate) struct McpWaitEntry {
  pub(crate) mode: McpWaitMode,
  pub(crate) reply: Option<shared::McpReply>,
}

pub(crate) enum McpWaitMode {
  Frames(u32),
  Idle,
}

/// Per-tree MCP server state; present only on the root tree.
pub struct McpState {
  pub(crate) shared: Arc<McpShared>,
  pub(crate) registry: Arc<ToolRegistry>,
  pub(crate) receiver: std_mpsc::Receiver<shared::McpRequest>,
  pub(crate) include_devtools: bool,
  /// Pointer buttons and keys clients hold across calls, per window.
  pub(crate) held: parking_lot::Mutex<held_input::HeldInput>,
  server: Option<server::ServerRuntime>,
  discovery_path: Option<std::path::PathBuf>,
}

fn default_app_name() -> String {
  std::env::current_exe()
    .ok()
    .and_then(|path| path.file_stem().map(|stem| stem.to_string_lossy().into_owned()))
    .unwrap_or_else(|| "lurq-app".to_owned())
}

fn build_registry(tools: Vec<McpTool>) -> ToolRegistry {
  let mut registry = ToolRegistry {
    tools: registry::builtin_tools(cfg!(feature = "router")),
  };
  registry.tools.extend(profiling::registered_tools());
  for tool in tools {
    assert!(
      !tool.name.starts_with("lurq_"),
      "custom MCP tool {:?} uses the reserved lurq_ prefix",
      tool.name
    );
    assert!(
      registry.find(&tool.name).is_none(),
      "custom MCP tool {:?} is registered twice",
      tool.name
    );
    let kind = match tool.kind {
      Some(CustomToolKind::Sync(handler)) => ToolKind::Sync(handler),
      Some(CustomToolKind::Async(handler)) => ToolKind::Async(handler),
      None => panic!("custom MCP tool {:?} has no handler", tool.name),
    };
    registry.tools.push(registry::RegisteredTool {
      name: tool.name,
      description: tool.description,
      scope: tool.scope,
      read_only: tool.read_only,
      input_schema: tool.input_schema,
      kind,
    });
  }
  registry
}

impl Tree {
  /// Start the embedded MCP server. Call once on the root tree; the returned
  /// [`McpHandle`] controls availability at runtime.
  ///
  /// The winit shell drains tool calls automatically. A headless harness
  /// (driving [`Tree::pass`] itself) must call
  /// [`Tree::drain_mcp_requests`] in its loop instead — tree reading and
  /// input work as-is; screenshots need a render surface.
  ///
  /// Panics on duplicate/reserved custom tool names or if called twice.
  pub fn enable_mcp(&mut self, config: McpConfig) -> McpHandle {
    assert!(self.mcp.is_none(), "enable_mcp called twice on this tree");

    let mut registry = build_registry(config.tools);
    if config.file_dialogs.is_some() {
      registry.tools.extend(tools::file_dialogs::registered_tools());
    }
    let registry = Arc::new(registry);
    let app_name = config.app_name.unwrap_or_else(default_app_name);
    let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
    let shared = Arc::new(McpShared::new(
      config.scopes,
      config.denied_tools,
      token,
      app_name,
      config.instructions,
    ));
    *shared.profiling.write().unwrap() = self.profiling_handle();
    shared
      .include_profile_devtools
      .store(config.include_devtools, std::sync::atomic::Ordering::Relaxed);
    if let Some(broker) = config.file_dialogs {
      broker.attach(&shared);
      // The window asks this broker from now on; the tree's other windows are told as they are reconciled.
      self.window().serve_file_dialogs(&broker.serving());
      *shared.file_dialogs.lock().unwrap() = Some(broker);
    }
    #[cfg(feature = "router")]
    if let Some(navigator) = config.navigator {
      *shared.navigator.write().unwrap() = Some(navigator);
    }

    let (sender, receiver) = std_mpsc::channel();
    if config.hosted {
      tracing::info!("lurq MCP tools are served by the app's own MCP server");
      self.mcp = Some(Box::new(McpState {
        shared: shared.clone(),
        registry: registry.clone(),
        receiver,
        include_devtools: config.include_devtools,
        held: Default::default(),
        server: None,
        discovery_path: None,
      }));
      return McpHandle {
        shared,
        registry,
        sender,
        port: 0,
      };
    }
    let server = match server::spawn(shared.clone(), registry.clone(), sender.clone(), config.port) {
      Ok(server) => server,
      Err(message) => {
        shared.set_enabled(false);
        let broker = shared.file_dialogs.lock().unwrap().clone();
        if let Some(broker) = broker {
          broker.shutdown();
        }
        // A dead listener with a live handle beats poisoning app startup.
        tracing::error!("failed to start MCP server: {message}");
        self.mcp = Some(Box::new(McpState {
          shared: shared.clone(),
          registry: registry.clone(),
          receiver,
          include_devtools: config.include_devtools,
          held: Default::default(),
          server: None,
          discovery_path: None,
        }));
        return McpHandle {
          shared,
          registry,
          sender,
          port: 0,
        };
      }
    };

    let port = server.port;
    let discovery_path = discovery::write(&shared.app_name, port, &shared.token);
    tracing::info!(
      "lurq MCP server listening on http://127.0.0.1:{port}/mcp{}",
      discovery_path
        .as_deref()
        .map(|path| format!(" (discovery: {})", path.display()))
        .unwrap_or_default()
    );

    self.mcp = Some(Box::new(McpState {
      shared: shared.clone(),
      registry: registry.clone(),
      receiver,
      include_devtools: config.include_devtools,
      held: Default::default(),
      server: Some(server),
      discovery_path,
    }));
    McpHandle {
      shared,
      registry,
      sender,
      port,
    }
  }

  /// Registered by the shell so request enqueues wake the idle event loop.
  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn set_mcp_waker(&self, waker: Arc<dyn Fn() + Send + Sync>) {
    if let Some(mcp) = &self.mcp {
      *mcp.shared.waker.lock().unwrap() = Some(waker);
    }
  }

  /// Execute all queued MCP tool calls against this (root) tree. The winit
  /// shell calls this every loop turn; headless harnesses call it between
  /// [`Tree::pass`] calls. It also releases input a client held across calls
  /// but can no longer release itself (its session ended, the window lost
  /// focus or closed, the tool became unavailable). A queued call whose
  /// caller stopped waiting (its reply deadline passed, or the client went
  /// away) is dropped without running. Returns whether any request was
  /// handled or held input released. Handlers that the calls reach see
  /// [`InputSource::Synthetic`](crate::app::events::InputSource::Synthetic).
  pub fn drain_mcp_requests(&mut self, app: &mut App) -> bool {
    crate::app::events::with_synthetic_input(|| self.drain_mcp_requests_synthetic(app))
  }

  fn drain_mcp_requests_synthetic(&mut self, app: &mut App) -> bool {
    self.reconcile_file_dialogs();
    let Some(state) = self.mcp.take() else {
      return false;
    };
    let mut did_work = false;
    while let Ok(request) = state.receiver.try_recv() {
      // The caller stopped waiting (its reply deadline passed, or it went
      // away) and was already answered with an error: running the call now
      // would act after the client was told it failed.
      if request.reply.is_closed() {
        tracing::debug!(tool = %request.tool, "dropped an MCP call whose caller stopped waiting");
        continue;
      }
      did_work = true;
      tools::execute(self, app, &state, request);
    }
    did_work |= tools::release_unreachable_holds(self, &state);
    self.mcp = Some(state);
    did_work
  }

  /// Whether nothing is left to draw: no redraw asked for, no animation, no canvas on its way, and nothing a
  /// finger left moving (its momentum, a list on its way to a page, content springing back), which the shell
  /// steps between frames and no animation counts.
  pub(crate) fn mcp_idle(&self) -> bool {
    !self.needs_redraw() && !self.has_active_timeline() && !self.has_moving_canvas() && self.finger_deadline().is_none()
  }

  /// Resolve parked `lurq_wait` replies after a pass; runs on every tree.
  pub(crate) fn mcp_notify_pass(&mut self, report: &crate::app::runtime::PassReport) {
    self.reconcile_file_dialogs();
    if self.mcp_wait_entries.is_empty() {
      return;
    }
    let rendered = report.rendered;
    let idle = self.mcp_idle();
    let mut keep_producing_frames = false;
    self.mcp_wait_entries.retain_mut(|entry| {
      let Some(reply) = entry.reply.take() else {
        return false;
      };
      if reply.is_closed() {
        // The HTTP side timed out and hung up; drop the entry.
        return false;
      }
      let done = match &mut entry.mode {
        McpWaitMode::Frames(remaining) => {
          if rendered {
            *remaining = remaining.saturating_sub(1);
          }
          *remaining == 0
        }
        McpWaitMode::Idle => rendered && idle,
      };
      if done {
        let _ = reply.send(Ok(McpToolOutput::Text("done".into())));
        false
      } else {
        if matches!(entry.mode, McpWaitMode::Frames(_)) {
          keep_producing_frames = true;
        }
        entry.reply = Some(reply);
        true
      }
    });
    // Only frame waits force more frames; idle waits must let the loop
    // settle or they would never resolve.
    if keep_producing_frames {
      self.request_redraw();
    }
  }

  /// Stop the MCP server and remove the discovery file, releasing any
  /// pointer button or key a client still holds. The shell calls this when
  /// the event loop exits; explicit callers (headless harnesses) may call it
  /// directly.
  pub fn shutdown_mcp(&mut self) {
    let Some(mut state) = self.mcp.take() else {
      return;
    };
    crate::app::events::with_synthetic_input(|| tools::release_all_holds(self, &state));
    let broker = state.shared.file_dialogs.lock().unwrap().clone();
    if let Some(broker) = broker {
      broker.shutdown();
    }
    if let Some(path) = &state.discovery_path {
      discovery::remove(path);
    }
    if let Some(server) = state.server.take() {
      server.cancel.cancel();
      // Wake the accept loop is not needed — cancellation resolves the
      // select. Give the thread a moment but never hang shutdown.
      let _ = server.join.join();
    }
  }
}

impl Drop for McpState {
  fn drop(&mut self) {
    self.shared.set_enabled(false);
    let broker = self.shared.file_dialogs.lock().unwrap().clone();
    if let Some(broker) = broker {
      broker.shutdown();
    }
  }
}