Skip to main content

iced_mcp/
lib.rs

1//! Lets AI agents see and drive a running [iced] application.
2//!
3//! The bridge wraps your program the way iced's own tester and devtools do:
4//! it adds a loopback socket, a widget wrapped around every window's view,
5//! and a log of your messages. The `iced-mcp-server` binary speaks MCP to the
6//! agent and this protocol to the app, so an agent can read the widget tree,
7//! click and type by text or id, scroll, drag, take screenshots and read what
8//! the app did in response — without the OS accessibility APIs or pixel
9//! guessing.
10//!
11//! ```no_run
12//! # #[derive(Default)] struct App; #[derive(Debug, Clone)] enum Message {}
13//! # impl App { fn update(&mut self, _: Message) {} fn view(&self) -> iced::Element<'_, Message> { iced::widget::text("").into() } }
14//! fn main() -> iced::Result {
15//!     let app = iced::application(App::default, App::update, App::view);
16//!     // Attached only when `ICED_MCP=1`; otherwise exactly `app.run()`.
17//!     iced_mcp::run(app)
18//! }
19//! ```
20//!
21//! Only build it into development binaries (behind a cargo feature): anyone
22//! who can reach the port can drive the app. It binds `127.0.0.1` only, and
23//! `ICED_MCP_TOKEN` makes connections present a token first.
24//!
25//! [iced]: https://iced.rs
26
27mod background;
28mod bridge;
29mod capture;
30mod collect;
31mod input;
32mod inspector;
33mod log;
34mod perf;
35mod registry;
36
37pub use iced_mcp_protocol as protocol;
38
39use bridge::Command;
40use iced_mcp_protocol::{
41    Acted, ActionInfo, ActionKind, ActionList, AppInfo, ClipboardContent, Outcome, QueryValue,
42    Request, Response, ScreenshotParams, StateDump, WindowAction, WindowInfo, DEFAULT_PORT,
43    ENV_BACKGROUND, ENV_ENABLE, ENV_FIXTURE, ENV_FIXTURE_ARGS, ENV_PORT, ENV_TOKEN,
44    PROTOCOL_VERSION,
45};
46use inspector::Inspector;
47use registry::{Job, Registry, Replier};
48
49use iced::application::Application;
50use iced::message::{MaybeClone, MaybeDebug};
51use iced::theme;
52use iced::Program;
53use iced::{window, Element, Point, Settings, Size, Subscription, Task};
54
55use futures::channel::mpsc::{self, UnboundedReceiver};
56use futures::stream::{self, Stream, StreamExt};
57use std::fmt;
58use std::sync::{Arc, Mutex};
59use std::time::Instant;
60
61/// Messages kept for the `messages` tool unless configured otherwise.
62const DEFAULT_MESSAGE_LOG: usize = 2000;
63
64/// Whether `ICED_MCP` asks for the bridge (set, and not `0`/`false`).
65pub fn enabled() -> bool {
66    std::env::var(ENV_ENABLE).is_ok_and(|v| !matches!(v.trim(), "" | "0" | "false"))
67}
68
69/// Runs `application`, with the bridge attached when [`enabled`] — the one
70/// line most apps need.
71pub fn run<P>(application: Application<P>) -> iced::Result
72where
73    P: Program + 'static,
74    P::Message: fmt::Debug + MaybeDebug + MaybeClone,
75{
76    if enabled() {
77        attach(application).run()
78    } else {
79        application.run()
80    }
81}
82
83/// Wraps any iced [`Program`] — usually an [`Application`] — with the bridge.
84pub fn attach<P: Program>(program: P) -> Attach<P> {
85    Attach {
86        program,
87        config: Config::from_env(),
88        registry: Registry::default(),
89        describe_state: None,
90        actions: Vec::new(),
91        queries: Vec::new(),
92        fixtures: Vec::new(),
93    }
94}
95
96/// [`run`], also sharing the app's state with the `state` tool (see
97/// [`Attach::state`]).
98pub fn run_with_state<P>(
99    application: Application<P>,
100    describe: impl Fn(&P::State) -> String + Send + Sync + 'static,
101) -> iced::Result
102where
103    P: Program + 'static,
104    P::Message: fmt::Debug + MaybeDebug + MaybeClone,
105{
106    if enabled() {
107        attach(application).state(describe).run()
108    } else {
109        application.run()
110    }
111}
112
113/// Where and how the bridge listens.
114#[derive(Debug, Clone)]
115pub struct Config {
116    /// Loopback port; `0` picks a free one (printed to stderr).
117    pub port: u16,
118    /// When set, connections must say `hello` with it first.
119    pub token: Option<String>,
120    /// Messages kept for the agent; `0` turns the log off.
121    pub message_log: usize,
122    /// Keep the app from taking keyboard focus when it starts or opens a
123    /// window (macOS; see the guide). `ICED_MCP_BACKGROUND=1`, which the
124    /// server's `launch` sets unless asked not to.
125    pub background: bool,
126}
127
128impl Config {
129    /// `ICED_MCP_PORT` and `ICED_MCP_TOKEN`, with defaults.
130    pub fn from_env() -> Self {
131        Self {
132            port: std::env::var(ENV_PORT)
133                .ok()
134                .and_then(|p| p.trim().parse().ok())
135                .unwrap_or(DEFAULT_PORT),
136            token: std::env::var(ENV_TOKEN).ok().filter(|t| !t.is_empty()),
137            message_log: DEFAULT_MESSAGE_LOG,
138            background: std::env::var(ENV_BACKGROUND)
139                .is_ok_and(|v| !matches!(v.trim(), "" | "0" | "false")),
140        }
141    }
142}
143
144/// A [`Program`] with the bridge attached.
145pub struct Attach<P: Program> {
146    program: P,
147    config: Config,
148    registry: Registry,
149    describe_state: Option<StateFn<P>>,
150    actions: Vec<AppAction<P>>,
151    queries: Vec<AppQuery<P>>,
152    fixtures: Vec<AppFixture<P>>,
153}
154
155/// A named state the app can be put in, for tests that must not depend on
156/// what ran before them.
157struct AppFixture<P: Program> {
158    name: String,
159    description: String,
160    load: FixtureFn<P>,
161}
162
163/// Builds a fixture's fresh state from its args.
164type FixtureStateFn<P> =
165    Arc<dyn Fn(&serde_json::Value) -> Result<<P as Program>::State, String> + Send + Sync>;
166/// Lists the messages that reach a fixture's state.
167type FixtureMessagesFn<P> =
168    Arc<dyn Fn(&serde_json::Value) -> Result<Vec<<P as Program>::Message>, String> + Send + Sync>;
169
170/// How a fixture puts the app in its state.
171enum FixtureFn<P: Program> {
172    /// Replaces the app's state with a fresh one.
173    State(FixtureStateFn<P>),
174    /// Sends these messages through `update`, in order.
175    Messages(FixtureMessagesFn<P>),
176}
177
178/// Answers a query from the app's state.
179type QueryFn<P> = Arc<
180    dyn Fn(&<P as Program>::State, &serde_json::Value) -> Result<serde_json::Value, String>
181        + Send
182        + Sync,
183>;
184
185struct AppQuery<P: Program> {
186    name: String,
187    description: String,
188    output_schema: Option<serde_json::Value>,
189    run: QueryFn<P>,
190}
191
192/// Turns an action's JSON arguments into the message that performs it.
193type ActionFn<P> =
194    Arc<dyn Fn(&serde_json::Value) -> Result<<P as Program>::Message, String> + Send + Sync>;
195
196struct AppAction<P: Program> {
197    name: String,
198    description: String,
199    run: ActionFn<P>,
200}
201
202/// Renders the app's state for the `state` tool.
203type StateFn<P> = Arc<dyn Fn(&<P as Program>::State) -> String + Send + Sync>;
204
205/// State dumps are cut here unless the request asks for less.
206const DEFAULT_STATE_CHARS: usize = 20_000;
207
208impl<P: Program + 'static> Attach<P>
209where
210    P::Message: fmt::Debug,
211{
212    pub fn config(mut self, config: Config) -> Self {
213        self.config = config;
214        self
215    }
216
217    /// Lets agents read the app's state with the `state` tool, rendered by
218    /// `describe` — usually `|state| format!("{state:#?}")`, or a summary
219    /// that leaves out what must not leave the app (keys, credentials).
220    /// Without it, `state` reports that the app does not share its state.
221    pub fn state(mut self, describe: impl Fn(&P::State) -> String + Send + Sync + 'static) -> Self {
222        self.describe_state = Some(Arc::new(describe));
223        self
224    }
225
226    /// Offers agents a named action: `run` turns its JSON `args` into the
227    /// message that does it (or an error saying what is wrong with them).
228    /// The message goes through your `update` like any other, so actions
229    /// cannot reach anything your own messages cannot. Say in
230    /// `description` what it does and which `args` it takes.
231    ///
232    /// ```ignore
233    /// iced_mcp::attach(app)
234    ///     .action("open_settings", "Opens the settings dialog. No args.", |_| Ok(Message::OpenSettings))
235    ///     .run()
236    /// ```
237    pub fn action(
238        mut self,
239        name: impl Into<String>,
240        description: impl Into<String>,
241        run: impl Fn(&serde_json::Value) -> Result<P::Message, String> + Send + Sync + 'static,
242    ) -> Self {
243        self.actions.push(AppAction {
244            name: name.into(),
245            description: description.into(),
246            run: Arc::new(run),
247        });
248        self
249    }
250
251    /// Offers agents a read-only question about the app: `run` answers it
252    /// from the current state as JSON (or says what is wrong with the
253    /// `args`). It runs on the UI thread between frames and cannot change
254    /// anything — use it for what the screen cannot say precisely: what is
255    /// under a point of a chart, the bars in view, a model's internals.
256    ///
257    /// ```ignore
258    /// iced_mcp::attach(app)
259    ///     .query("selection", "The selected items. No args.", |state, _| {
260    ///         Ok(serde_json::json!(state.selection))
261    ///     })
262    ///     .run()
263    /// ```
264    pub fn query(
265        mut self,
266        name: impl Into<String>,
267        description: impl Into<String>,
268        run: impl Fn(&P::State, &serde_json::Value) -> Result<serde_json::Value, String>
269            + Send
270            + Sync
271            + 'static,
272    ) -> Self {
273        self.queries.push(AppQuery {
274            name: name.into(),
275            description: description.into(),
276            output_schema: None,
277            run: Arc::new(run),
278        });
279        self
280    }
281
282    /// [`Attach::query`] with the JSON Schema of its answer (for instance
283    /// `serde_json::to_value(schemars::schema_for!(Reply))`), which agents
284    /// see in `app_actions` and can rely on.
285    pub fn query_with_schema(
286        mut self,
287        name: impl Into<String>,
288        description: impl Into<String>,
289        output_schema: serde_json::Value,
290        run: impl Fn(&P::State, &serde_json::Value) -> Result<serde_json::Value, String>
291            + Send
292            + Sync
293            + 'static,
294    ) -> Self {
295        self = self.query(name, description, run);
296        if let Some(query) = self.queries.last_mut() {
297            query.output_schema = Some(output_schema);
298        }
299        self
300    }
301
302    /// Offers a named state to start tests from — a fixture. `load` builds
303    /// a fresh app state from the fixture's JSON `args` (or says what is
304    /// wrong with them); loading the fixture replaces the app's state with
305    /// it, so whatever ran before leaves nothing behind. Agents list
306    /// fixtures with `fixtures`, load one with `load_fixture`, flows name
307    /// one in `fixture`, and `ICED_MCP_FIXTURE=name` starts the app in it.
308    ///
309    /// ```ignore
310    /// iced_mcp::attach(app)
311    ///     .fixture("empty-cart", "An empty cart. No args.", |_| Ok(Shop::default()))
312    ///     .fixture("full-cart", "A cart with {\"items\": n} items.", |args| {
313    ///         let n = args["items"].as_u64().unwrap_or(3) as usize;
314    ///         Ok(Shop::with_items(n))
315    ///     })
316    ///     .run()
317    /// ```
318    pub fn fixture(
319        mut self,
320        name: impl Into<String>,
321        description: impl Into<String>,
322        load: impl Fn(&serde_json::Value) -> Result<P::State, String> + Send + Sync + 'static,
323    ) -> Self {
324        self.fixtures.push(AppFixture {
325            name: name.into(),
326            description: description.into(),
327            load: FixtureFn::State(Arc::new(load)),
328        });
329        self
330    }
331
332    /// A fixture reached through the app's own messages instead of a fresh
333    /// state: `load` returns the messages (in order) that put the app in
334    /// it — say a reset followed by the data to load. Use it when the state
335    /// cannot be built from outside; the messages must undo whatever an
336    /// earlier test left, or the fixture does not isolate anything.
337    ///
338    /// ```ignore
339    /// .fixture_messages("signed-out", "No user. No args.", |_| Ok(vec![Message::SignOut]))
340    /// ```
341    pub fn fixture_messages(
342        mut self,
343        name: impl Into<String>,
344        description: impl Into<String>,
345        load: impl Fn(&serde_json::Value) -> Result<Vec<P::Message>, String> + Send + Sync + 'static,
346    ) -> Self {
347        self.fixtures.push(AppFixture {
348            name: name.into(),
349            description: description.into(),
350            load: FixtureFn::Messages(Arc::new(load)),
351        });
352        self
353    }
354
355    /// Starts the bridge and runs the program. If the port is taken the app
356    /// still runs, without the bridge, and says so on stderr.
357    pub fn run(self) -> iced::Result {
358        let (sender, receiver) = mpsc::unbounded();
359        if let Ok(mut inbox) = INBOX.lock() {
360            *inbox = Some(receiver);
361        }
362        if self.config.background {
363            BACKGROUND.store(background::install(), std::sync::atomic::Ordering::Relaxed);
364        }
365        match bridge::start(&self.config, sender) {
366            Ok(port) => eprintln!("iced-mcp: listening on 127.0.0.1:{port}"),
367            Err(error) => eprintln!(
368                "iced-mcp: could not listen on 127.0.0.1:{} ({error}); running without the bridge",
369                self.config.port
370            ),
371        }
372        iced_winit::run(self).map_err(iced::Error::from)
373    }
374}
375
376/// The program's state, with the bridge's beside it.
377pub struct State<P: Program> {
378    app: P::State,
379    registry: Registry,
380    log: log::Log,
381    /// The fixture loaded last, for `hello`.
382    fixture: Option<String>,
383    /// Why the start-up fixture did not load.
384    fixture_error: Option<String>,
385}
386
387/// The program's messages, with the bridge's beside them.
388pub struct Message<P: Program>(Inner<P>);
389
390enum Inner<P: Program> {
391    App(P::Message),
392    Command(Command),
393    Shot(Arc<window::Screenshot>, ScreenshotParams, Replier),
394    Closed(window::Id),
395    HighlightTick,
396    Clip(Option<String>, Replier),
397    /// Load the start-up fixture, once the app's boot task is done.
398    BootFixture(String, serde_json::Value),
399}
400
401impl<P: Program> fmt::Debug for Message<P>
402where
403    P::Message: fmt::Debug,
404{
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        match &self.0 {
407            Inner::App(message) => message.fmt(f),
408            Inner::Command(command) => write!(f, "IcedMcp({:?})", command.request),
409            Inner::Shot(..) => f.write_str("IcedMcp(Screenshot)"),
410            Inner::Closed(id) => write!(f, "IcedMcp(Closed({id}))"),
411            Inner::HighlightTick => f.write_str("IcedMcp(HighlightTick)"),
412            Inner::Clip(..) => f.write_str("IcedMcp(Clipboard)"),
413            Inner::BootFixture(name, _) => write!(f, "IcedMcp(Fixture({name:?}))"),
414        }
415    }
416}
417
418impl<P: Program> Clone for Message<P>
419where
420    P::Message: Clone,
421{
422    fn clone(&self) -> Self {
423        Self(match &self.0 {
424            Inner::App(message) => Inner::App(message.clone()),
425            Inner::Command(command) => Inner::Command(command.clone()),
426            Inner::Shot(shot, params, reply) => {
427                Inner::Shot(shot.clone(), params.clone(), reply.clone())
428            }
429            Inner::Closed(id) => Inner::Closed(*id),
430            Inner::HighlightTick => Inner::HighlightTick,
431            Inner::Clip(text, reply) => Inner::Clip(text.clone(), reply.clone()),
432            Inner::BootFixture(name, args) => Inner::BootFixture(name.clone(), args.clone()),
433        })
434    }
435}
436
437fn app<P: Program>(message: P::Message) -> Message<P> {
438    Message(Inner::App(message))
439}
440
441impl<P> Program for Attach<P>
442where
443    P: Program + 'static,
444    P::Message: fmt::Debug,
445{
446    type State = State<P>;
447    type Message = Message<P>;
448    type Theme = P::Theme;
449    type Renderer = P::Renderer;
450    type Executor = P::Executor;
451
452    fn name() -> &'static str {
453        P::name()
454    }
455
456    fn settings(&self) -> Settings {
457        self.program.settings()
458    }
459
460    fn window(&self) -> Option<window::Settings> {
461        self.program.window()
462    }
463
464    fn boot(&self) -> (Self::State, Task<Self::Message>) {
465        let (app_state, task) = self.program.boot();
466        let mut state = State {
467            app: app_state,
468            registry: self.registry.clone(),
469            log: log::Log::new(self.config.message_log),
470            fixture: None,
471            fixture_error: None,
472        };
473        let task = task.map(app::<P>);
474        match boot_fixture() {
475            None => (state, task),
476            Some(Ok((name, args))) => {
477                // After the app's own boot work, so it cannot undo the fixture.
478                (
479                    state,
480                    task.chain(Task::done(Message(Inner::BootFixture(name, args)))),
481                )
482            }
483            Some(Err(error)) => {
484                eprintln!("iced-mcp: {error}");
485                state.fixture_error = Some(error);
486                (state, task)
487            }
488        }
489    }
490
491    fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> {
492        match message.0 {
493            Inner::App(message) => {
494                let text = log::describe(&message);
495                let kind = perf::kind(&text).to_owned();
496                state.log.push(text);
497                let started = Instant::now();
498                let task = self.program.update(&mut state.app, message);
499                state.registry.lock().perf.update(&kind, started.elapsed());
500                task.map(app::<P>)
501            }
502            Inner::Clip(text, reply) => {
503                let _ = reply.try_send(Outcome::Ok(Response::Clipboard(ClipboardContent { text })));
504                Task::none()
505            }
506            Inner::Command(command) => self.command(state, command),
507            Inner::BootFixture(name, args) => match self.load_fixture(state, &name, &args) {
508                Ok(task) => task,
509                Err(error) => {
510                    eprintln!("iced-mcp: {error}");
511                    state.fixture_error = Some(error);
512                    Task::none()
513                }
514            },
515            Inner::Shot(shot, params, reply) => {
516                // Encoding a full frame is too slow for the UI thread.
517                let _ = std::thread::Builder::new()
518                    .name("iced-mcp-png".into())
519                    .spawn(move || {
520                        let outcome = match capture::encode(&shot, &params) {
521                            Ok(png) => Outcome::Ok(Response::Screenshot(png)),
522                            Err(error) => Outcome::Error(error),
523                        };
524                        let _ = reply.try_send(outcome);
525                    });
526                Task::none()
527            }
528            Inner::Closed(id) => {
529                state.registry.lock().remove(id);
530                Task::none()
531            }
532            Inner::HighlightTick => {
533                let now = Instant::now();
534                for slot in &mut state.registry.lock().slots {
535                    if slot
536                        .highlight
537                        .is_some_and(|highlight| highlight.expires_at <= now)
538                    {
539                        slot.highlight = None;
540                    }
541                }
542                Task::none()
543            }
544        }
545    }
546
547    fn view<'a>(
548        &self,
549        state: &'a Self::State,
550        window: window::Id,
551    ) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> {
552        let started = Instant::now();
553        let content = self.program.view(&state.app, window).map(app::<P>);
554        state.registry.lock().perf.view.push(started.elapsed());
555        Inspector::new(content, state.registry.clone(), window).into()
556    }
557
558    fn title(&self, state: &Self::State, window: window::Id) -> String {
559        self.program.title(&state.app, window)
560    }
561
562    fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> {
563        let mut subscriptions = vec![
564            self.program.subscription(&state.app).map(app::<P>),
565            Subscription::run(inbox).map(|command| Message(Inner::Command(command))),
566            window::close_events().map(|id| Message(Inner::Closed(id))),
567        ];
568        if state
569            .registry
570            .lock()
571            .slots
572            .iter()
573            .any(|slot| slot.highlight.is_some())
574        {
575            subscriptions
576                .push(Subscription::run(highlight_ticks).map(|()| Message(Inner::HighlightTick)));
577        }
578        Subscription::batch(subscriptions)
579    }
580
581    fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> {
582        self.program.theme(&state.app, window)
583    }
584
585    fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style {
586        self.program.style(&state.app, theme)
587    }
588
589    fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 {
590        self.program.scale_factor(&state.app, window)
591    }
592}
593
594impl<P> Attach<P>
595where
596    P: Program + 'static,
597    P::Message: fmt::Debug,
598{
599    fn command(
600        &self,
601        state: &mut State<P>,
602        Command { request, reply }: Command,
603    ) -> Task<Message<P>> {
604        let answer = |outcome: Outcome| {
605            let _ = reply.try_send(outcome);
606        };
607        let window_id = |name: Option<&str>| -> Result<window::Id, String> {
608            let mut windows = state.registry.lock();
609            if let Some(slot) = windows.find(name) {
610                return Ok(slot.id);
611            }
612            let known: Vec<String> = windows.slots.iter().map(|s| s.id.to_string()).collect();
613            Err(match name {
614                Some(name) => format!("no window '{name}'; open windows: {known:?}"),
615                None => "no window has rendered yet".into(),
616            })
617        };
618
619        match request {
620            Request::Hello(_) => {
621                let windows = state
622                    .registry
623                    .lock()
624                    .slots
625                    .iter()
626                    .map(|slot| WindowInfo {
627                        id: slot.id.to_string(),
628                        title: self.program.title(&state.app, slot.id),
629                        size: iced_mcp_protocol::Size {
630                            width: slot.size.width,
631                            height: slot.size.height,
632                        },
633                    })
634                    .collect();
635                answer(Outcome::Ok(Response::Hello(AppInfo {
636                    name: P::name().to_owned(),
637                    toolkit: "iced 0.14".into(),
638                    protocol: PROTOCOL_VERSION,
639                    pid: std::process::id(),
640                    windows,
641                    messages: state.log.is_enabled(),
642                    fixture: state.fixture.clone(),
643                    fixture_error: state.fixture_error.clone(),
644                    background: BACKGROUND.load(std::sync::atomic::Ordering::Relaxed),
645                })));
646                Task::none()
647            }
648            Request::Messages(params) => {
649                answer(Outcome::Ok(Response::Messages(state.log.read(&params))));
650                Task::none()
651            }
652            Request::Perf(params) => {
653                let mut windows = state.registry.lock();
654                answer(Outcome::Ok(Response::Perf(windows.perf.report())));
655                if params.reset {
656                    windows.perf = perf::Perf::default();
657                }
658                Task::none()
659            }
660            Request::State(params) => {
661                answer(match &self.describe_state {
662                    Some(describe) => Outcome::Ok(Response::State(state_dump(
663                        &describe(&state.app),
664                        params.filter.as_deref(),
665                        params.max_chars.unwrap_or(DEFAULT_STATE_CHARS),
666                    ))),
667                    None => Outcome::Error(
668                        "this app does not share its state: build it with \
669                         `iced_mcp::run_with_state(app, |s| format!(\"{s:#?}\"))` or \
670                         `iced_mcp::attach(app).state(..)`"
671                            .into(),
672                    ),
673                });
674                Task::none()
675            }
676            Request::Actions => {
677                answer(Outcome::Ok(Response::Actions(ActionList {
678                    actions: self
679                        .actions
680                        .iter()
681                        .map(|a| ActionInfo {
682                            name: a.name.clone(),
683                            description: a.description.clone(),
684                            kind: ActionKind::Action,
685                            output_schema: None,
686                        })
687                        .chain(self.queries.iter().map(|q| ActionInfo {
688                            name: q.name.clone(),
689                            description: q.description.clone(),
690                            kind: ActionKind::Query,
691                            output_schema: q.output_schema.clone(),
692                        }))
693                        .chain(self.fixtures.iter().map(|f| ActionInfo {
694                            name: f.name.clone(),
695                            description: f.description.clone(),
696                            kind: ActionKind::Fixture,
697                            output_schema: None,
698                        }))
699                        .collect(),
700                })));
701                Task::none()
702            }
703            Request::Action(params) => {
704                let Some(action) = self.actions.iter().find(|a| a.name == params.name) else {
705                    let known: Vec<&str> = self.actions.iter().map(|a| a.name.as_str()).collect();
706                    answer(Outcome::Error(format!(
707                        "no action '{}'; the app offers {known:?}",
708                        params.name
709                    )));
710                    return Task::none();
711                };
712                match (action.run)(&params.args) {
713                    Ok(message) => {
714                        answer(Outcome::Ok(Response::Done));
715                        Task::done(app::<P>(message))
716                    }
717                    Err(error) => {
718                        answer(Outcome::Error(format!("{}: {error}", params.name)));
719                        Task::none()
720                    }
721                }
722            }
723            Request::Query(params) => {
724                let Some(query) = self.queries.iter().find(|q| q.name == params.name) else {
725                    let known: Vec<&str> = self.queries.iter().map(|q| q.name.as_str()).collect();
726                    let hint = if self.actions.iter().any(|a| a.name == params.name) {
727                        " (that is an action: use run_app_action)"
728                    } else {
729                        ""
730                    };
731                    answer(Outcome::Error(format!(
732                        "no query '{}'{hint}; the app offers {known:?}",
733                        params.name
734                    )));
735                    return Task::none();
736                };
737                answer(match (query.run)(&state.app, &params.args) {
738                    Ok(value) => Outcome::Ok(Response::Value(QueryValue { value })),
739                    Err(error) => Outcome::Error(format!("{}: {error}", params.name)),
740                });
741                Task::none()
742            }
743            Request::Fixture(params) => {
744                match self.load_fixture(state, &params.name, &params.args) {
745                    Ok(task) => {
746                        answer(Outcome::Ok(Response::Done));
747                        task
748                    }
749                    Err(error) => {
750                        answer(Outcome::Error(error));
751                        Task::none()
752                    }
753                }
754            }
755            Request::Clipboard(params) => {
756                let read = move |text| Message(Inner::Clip(text, reply.clone()));
757                match params.write {
758                    Some(text) => iced::clipboard::write::<Message<P>>(text)
759                        .chain(iced::clipboard::read().map(read)),
760                    None => iced::clipboard::read().map(read),
761                }
762            }
763            Request::Snapshot(params) => {
764                let job = Job::Snapshot {
765                    grid: params.grid.unwrap_or(0.0).max(0.0),
766                    reply: reply.clone(),
767                };
768                self.enqueue(state, params.window.as_deref(), job, &reply);
769                Task::none()
770            }
771            Request::Probe(params) => {
772                let job = Job::Probe {
773                    point: Point::new(params.x, params.y),
774                    reply: reply.clone(),
775                };
776                self.enqueue(state, params.window.as_deref(), job, &reply);
777                Task::none()
778            }
779            Request::Act(params) => {
780                if params.frames.is_empty() {
781                    answer(Outcome::Error("act needs at least one frame".into()));
782                    return Task::none();
783                }
784                let job = Job::Act {
785                    frames: params.frames.into(),
786                    acted: Acted {
787                        messages: 0,
788                        captured: 0,
789                        frames: 0,
790                    },
791                    reply: reply.clone(),
792                };
793                self.enqueue(state, params.window.as_deref(), job, &reply);
794                Task::none()
795            }
796            Request::WidgetOperation(params) => {
797                let job = Job::WidgetOperation {
798                    id: params.id,
799                    operation: params.operation,
800                    reply: reply.clone(),
801                };
802                self.enqueue(state, params.window.as_deref(), job, &reply);
803                Task::none()
804            }
805            Request::Screenshot(params) => match window_id(params.window.as_deref()) {
806                Ok(id) => window::screenshot(id).map(move |shot| {
807                    Message(Inner::Shot(Arc::new(shot), params.clone(), reply.clone()))
808                }),
809                Err(error) => {
810                    answer(Outcome::Error(error));
811                    Task::none()
812                }
813            },
814            Request::Highlight(params) => {
815                match window_id(params.window.as_deref()) {
816                    Ok(id) => {
817                        let duration = std::time::Duration::from_millis(
818                            params.duration_ms.unwrap_or(1_500).clamp(100, 5_000),
819                        );
820                        self.registry.lock().slot(id).highlight = Some(registry::Highlight {
821                            bounds: params.bounds,
822                            expires_at: Instant::now() + duration,
823                        });
824                        answer(Outcome::Ok(Response::Done));
825                    }
826                    Err(error) => answer(Outcome::Error(error)),
827                }
828                Task::none()
829            }
830            Request::Window(params) => match window_id(params.window.as_deref()) {
831                Ok(id) => {
832                    answer(Outcome::Ok(Response::Done));
833                    match params.action {
834                        WindowAction::Resize { width, height } => {
835                            window::resize(id, Size::new(width, height))
836                        }
837                        WindowAction::Move { x, y } => window::move_to(id, Point::new(x, y)),
838                        WindowAction::Focus => window::gain_focus(id),
839                        WindowAction::Maximize { on } => window::maximize(id, on),
840                        WindowAction::Minimize { on } => window::minimize(id, on),
841                        WindowAction::Close => window::close(id),
842                    }
843                }
844                Err(error) => {
845                    answer(Outcome::Error(error));
846                    Task::none()
847                }
848            },
849        }
850    }
851
852    /// Puts the app in fixture `name`: replaces its state, or returns the
853    /// task that sends the fixture's messages in order.
854    fn load_fixture(
855        &self,
856        state: &mut State<P>,
857        name: &str,
858        args: &serde_json::Value,
859    ) -> Result<Task<Message<P>>, String> {
860        let Some(fixture) = self.fixtures.iter().find(|f| f.name == name) else {
861            let known: Vec<&str> = self.fixtures.iter().map(|f| f.name.as_str()).collect();
862            return Err(format!("no fixture '{name}'; the app offers {known:?}"));
863        };
864        let task = match &fixture.load {
865            FixtureFn::State(load) => {
866                state.app = load(args).map_err(|error| format!("fixture {name}: {error}"))?;
867                Task::none()
868            }
869            FixtureFn::Messages(load) => {
870                let messages = load(args).map_err(|error| format!("fixture {name}: {error}"))?;
871                messages.into_iter().fold(Task::none(), |task, message| {
872                    task.chain(Task::done(app::<P>(message)))
873                })
874            }
875        };
876        state.fixture = Some(name.to_owned());
877        state.fixture_error = None;
878        Ok(task)
879    }
880
881    /// Queues a job on its window; the window's inspector serves it on the
882    /// redraw that follows this update.
883    fn enqueue(&self, state: &mut State<P>, window: Option<&str>, job: Job, reply: &Replier) {
884        let mut windows = state.registry.lock();
885        match windows.find(window) {
886            Some(slot) => slot.jobs.push_back(job),
887            None => {
888                let _ = reply.try_send(Outcome::Error(match window {
889                    Some(name) => format!("no window '{name}'"),
890                    None => "no window has rendered yet".into(),
891                }));
892            }
893        }
894    }
895}
896
897/// The start-up fixture `ICED_MCP_FIXTURE` names, with its
898/// `ICED_MCP_FIXTURE_ARGS`; `None` when it names none.
899fn boot_fixture() -> Option<Result<(String, serde_json::Value), String>> {
900    parse_fixture_env(
901        std::env::var(ENV_FIXTURE).ok(),
902        std::env::var(ENV_FIXTURE_ARGS).ok(),
903    )
904}
905
906fn parse_fixture_env(
907    name: Option<String>,
908    args: Option<String>,
909) -> Option<Result<(String, serde_json::Value), String>> {
910    let name = name?.trim().to_owned();
911    if name.is_empty() {
912        return None;
913    }
914    let args = match args {
915        Some(json) if !json.trim().is_empty() => match serde_json::from_str(&json) {
916            Ok(args) => args,
917            Err(error) => {
918                return Some(Err(format!(
919                    "{ENV_FIXTURE_ARGS} is not JSON ({error}); fixture {name} not loaded"
920                )))
921            }
922        },
923        _ => serde_json::Value::Null,
924    };
925    Some(Ok((name, args)))
926}
927
928/// Whether the background guard is on, for `hello`.
929static BACKGROUND: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
930
931/// Requests from the socket, taken once by the subscription.
932static INBOX: Mutex<Option<UnboundedReceiver<Command>>> = Mutex::new(None);
933
934fn inbox() -> impl Stream<Item = Command> {
935    let receiver = INBOX.lock().ok().and_then(|mut inbox| inbox.take());
936    stream::iter(receiver).flatten()
937}
938
939/// The state text the request asked for: the lines matching `filter` (with
940/// their numbers) or all of it, cut at `max_chars`.
941fn state_dump(full: &str, filter: Option<&str>, max_chars: usize) -> StateDump {
942    let total_chars = full.chars().count();
943    let selected = match filter.map(str::to_lowercase) {
944        None => full.to_owned(),
945        Some(needle) => full
946            .lines()
947            .enumerate()
948            .filter(|(_, line)| line.to_lowercase().contains(&needle))
949            .map(|(n, line)| format!("{:>5}: {line}\n", n + 1))
950            .collect(),
951    };
952    let truncated = selected.chars().count() > max_chars;
953    let text = if truncated {
954        selected.chars().take(max_chars).collect()
955    } else {
956        selected
957    };
958    StateDump {
959        text,
960        total_chars,
961        truncated,
962    }
963}
964
965/// Ticks every 100 ms while a highlight is shown. A plain thread rather than
966/// `iced::time::every`, which exists only when the app enables iced's `tokio`
967/// or `smol` executor: the bridge must work with any executor. The thread
968/// ends at the first tick after the subscription (and so the receiver) drops.
969fn highlight_ticks() -> futures::channel::mpsc::Receiver<()> {
970    let (mut sender, receiver) = futures::channel::mpsc::channel(1);
971    std::thread::spawn(move || loop {
972        std::thread::sleep(std::time::Duration::from_millis(100));
973        match sender.try_send(()) {
974            Err(error) if error.is_disconnected() => break,
975            _ => {}
976        }
977    });
978    receiver
979}
980
981#[cfg(test)]
982mod tests {
983    use super::*;
984
985    #[derive(Debug, Default, PartialEq)]
986    struct Cart {
987        items: Vec<String>,
988    }
989
990    #[derive(Debug, Clone)]
991    enum CartMessage {
992        Add(String),
993    }
994
995    impl Cart {
996        fn update(&mut self, message: CartMessage) {
997            match message {
998                CartMessage::Add(item) => self.items.push(item),
999            }
1000        }
1001
1002        fn view(&self) -> Element<'_, CartMessage> {
1003            iced::widget::text(self.items.len()).into()
1004        }
1005    }
1006
1007    fn cart_app() -> Attach<impl Program<State = Cart, Message = CartMessage>> {
1008        attach(iced::application(Cart::default, Cart::update, Cart::view))
1009            .fixture("empty", "An empty cart.", |_| Ok(Cart::default()))
1010            .fixture("full", "Args: {\"items\": n}.", |args| {
1011                let n = args["items"].as_u64().ok_or("needs {\"items\": n}")?;
1012                Ok(Cart {
1013                    items: (0..n).map(|i| format!("item {i}")).collect(),
1014                })
1015            })
1016            .fixture_messages("one", "One item, via messages.", |_| {
1017                Ok(vec![CartMessage::Add("apple".into())])
1018            })
1019    }
1020
1021    /// Sends `request` through the program's update, as the socket does.
1022    fn ask<P: Program + 'static>(
1023        program: &Attach<P>,
1024        state: &mut State<P>,
1025        request: Request,
1026    ) -> Outcome
1027    where
1028        P::Message: fmt::Debug,
1029    {
1030        let (reply, answer) = std::sync::mpsc::sync_channel(1);
1031        let _ = program.update(state, Message(Inner::Command(Command { request, reply })));
1032        answer.try_recv().expect("an answer")
1033    }
1034
1035    #[test]
1036    fn fixtures_replace_the_state_and_are_listed() {
1037        let program = cart_app();
1038        let (mut state, _) = program.boot();
1039        state.app.items.push("left over".into());
1040
1041        let load = |name: &str, args| {
1042            Request::Fixture(iced_mcp_protocol::ActionParams {
1043                name: name.into(),
1044                args,
1045            })
1046        };
1047        let outcome = ask(
1048            &program,
1049            &mut state,
1050            load("full", serde_json::json!({"items": 2})),
1051        );
1052        assert!(
1053            matches!(outcome, Outcome::Ok(Response::Done)),
1054            "{outcome:?}"
1055        );
1056        assert_eq!(state.app.items, ["item 0", "item 1"], "nothing left over");
1057        assert_eq!(state.fixture.as_deref(), Some("full"));
1058
1059        let Outcome::Error(error) =
1060            ask(&program, &mut state, load("full", serde_json::Value::Null))
1061        else {
1062            panic!("bad args must fail");
1063        };
1064        assert_eq!(error, "fixture full: needs {\"items\": n}");
1065        let Outcome::Error(error) =
1066            ask(&program, &mut state, load("nope", serde_json::Value::Null))
1067        else {
1068            panic!("an unknown fixture must fail");
1069        };
1070        assert!(
1071            error.contains(r#"the app offers ["empty", "full", "one"]"#),
1072            "{error}"
1073        );
1074
1075        let Outcome::Ok(Response::Actions(list)) = ask(&program, &mut state, Request::Actions)
1076        else {
1077            panic!("actions");
1078        };
1079        let fixtures: Vec<_> = list
1080            .actions
1081            .iter()
1082            .filter(|a| a.kind == ActionKind::Fixture)
1083            .map(|a| a.name.as_str())
1084            .collect();
1085        assert_eq!(fixtures, ["empty", "full", "one"]);
1086
1087        let Outcome::Ok(Response::Hello(info)) = ask(
1088            &program,
1089            &mut state,
1090            Request::Hello(iced_mcp_protocol::Hello::default()),
1091        ) else {
1092            panic!("hello");
1093        };
1094        assert_eq!(info.fixture.as_deref(), Some("full"));
1095    }
1096
1097    #[test]
1098    fn the_start_up_fixture_comes_from_the_environment() {
1099        assert!(parse_fixture_env(None, None).is_none());
1100        assert!(parse_fixture_env(Some(" ".into()), None).is_none());
1101        let (name, args) = parse_fixture_env(Some("full".into()), Some(r#"{"items":3}"#.into()))
1102            .unwrap()
1103            .unwrap();
1104        assert_eq!((name.as_str(), args["items"].as_u64()), ("full", Some(3)));
1105        assert_eq!(
1106            parse_fixture_env(Some("full".into()), None)
1107                .unwrap()
1108                .unwrap()
1109                .1,
1110            serde_json::Value::Null
1111        );
1112        assert!(parse_fixture_env(Some("full".into()), Some("{oops".into()))
1113            .unwrap()
1114            .is_err());
1115    }
1116
1117    #[test]
1118    fn state_dumps_filter_by_line_and_cut() {
1119        let full = "App {\n    theme: Dark,\n    symbol: \"BTCUSDT\",\n}";
1120        let dump = state_dump(full, Some("SYMBOL"), 1000);
1121        assert_eq!(dump.text, "    3:     symbol: \"BTCUSDT\",\n");
1122        assert!(!dump.truncated);
1123        let cut = state_dump(full, None, 5);
1124        assert_eq!(cut.text, "App {");
1125        assert!(cut.truncated);
1126        assert_eq!(cut.total_chars, full.chars().count());
1127    }
1128}