umbriel-mcp 0.4.3

MCP server for the Umbriel Wayland compositor: windows, workspaces, outputs, pointer and keyboard input, screenshots with OCR, and the clipboard.
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
use crate::capture_target::{
    CaptureTarget, Choice, DEFAULT_RECORDING_SECONDS, Purpose, RECORDING_LENGTHS, human_duration,
    parse_choice,
};
use crate::config_edit::{BackupPolicy, PreparedChange, commit};
use anyhow::{Result, anyhow};
use rmcp::model::{ElicitRequestParams, ElicitationAction, ElicitationSchema, EnumSchema};
use rmcp::service::{ElicitationError, ElicitationMode, ServiceError};
use rmcp::{Peer, RoleServer, schemars};
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

pub const APPROVAL_WINDOW: Duration = Duration::from_secs(600);

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct WriteApproval {
    /// Write this change to your Umbriel config
    pub apply: bool,
    /// Keep a backup of the previous config next to it (backups accumulate in the config folder)
    #[serde(default = "keep_backup_unless_told_otherwise")]
    pub backup: bool,
    /// Also apply further config changes in this session without asking (changes with a caution,
    /// or that start programs, still ask)
    #[serde(default)]
    pub allow_rest_of_session: bool,
}

pub fn keep_backup_unless_told_otherwise() -> bool {
    true
}

rmcp::elicit_safe!(WriteApproval);

#[derive(Default)]
pub struct PendingChanges {
    held: Mutex<HashMap<String, (PreparedChange, Instant)>>,
    issued: AtomicU64,
    session_backup_choice: Mutex<Option<bool>>,
}

fn one_time_code(issued: &AtomicU64) -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_nanos() as u64)
        .unwrap_or_default();
    let sequence = issued.fetch_add(1, Ordering::SeqCst);
    let mixed = nanos ^ sequence.rotate_left(32) ^ u64::from(std::process::id()).rotate_left(16);
    format!("{:012x}", mixed & 0xffff_ffff_ffff)
}

impl PendingChanges {
    pub fn allow_rest_of_session(&self, keep_backup: bool) {
        *self
            .session_backup_choice
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(keep_backup);
    }

    fn session_backup_choice(&self) -> Option<bool> {
        *self
            .session_backup_choice
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn hold(&self, change: PreparedChange) -> String {
        let code = one_time_code(&self.issued);
        let mut held = self
            .held
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        held.retain(|_, (_, held_at)| held_at.elapsed() < APPROVAL_WINDOW);
        held.insert(code.clone(), (change, Instant::now()));
        code
    }

    pub fn take(&self, code: &str) -> Result<PreparedChange> {
        let mut held = self
            .held
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let (change, held_at) = held.remove(code.trim()).ok_or_else(|| {
            anyhow!(
                "no change is waiting for confirmation code {code}; it was already applied, has \
                 expired, or was never issued. Nothing was written."
            )
        })?;
        if held_at.elapsed() >= APPROVAL_WINDOW {
            return Err(anyhow!(
                "confirmation code {code} expired after {} minutes; nothing was written. Make the \
                 request again.",
                APPROVAL_WINDOW.as_secs() / 60
            ));
        }
        Ok(change)
    }
}

fn hold_for_confirmation(pending: &PendingChanges, change: PreparedChange) -> String {
    let preview = change.preview();
    let code = pending.hold(change);
    format!(
        "Nothing has been written yet. This client cannot ask the user directly, so ask them now: \
         show them exactly this change, ask whether to apply it and whether they want a backup of \
         the previous config kept (backups accumulate next to the config), and wait for an \
         explicit answer.\n\n{preview}\n\nOnly after the user approves, call \
         apply_config_change with confirmation \"{code}\" and backup set to their answer. If, \
         and only if, the user explicitly says to stop asking for the rest of this session, also \
         pass allow_rest_of_session: true; never set it on your own. The code works once and \
         expires in {} minutes. If they decline, do nothing.",
        APPROVAL_WINDOW.as_secs() / 60
    )
}

pub async fn ask_then_commit(
    peer: &Peer<RoleServer>,
    pending: &PendingChanges,
    change: PreparedChange,
    keep_newest: usize,
) -> Result<String> {
    if let Some(keep_backup) = pending.session_backup_choice()
        && change.reason_to_ask_anyway().is_none()
    {
        let report = commit(
            &change,
            BackupPolicy {
                keep_backup,
                keep_newest,
            },
        )?;
        return Ok(format!(
            "Applied without asking, because the user allowed config changes for the rest of this \
             session. Tell them what changed.\n{report}"
        ));
    }
    if !peer
        .supported_elicitation_modes()
        .contains(&ElicitationMode::Form)
    {
        return Ok(hold_for_confirmation(pending, change));
    }
    let question = format!(
        "umbriel-mcp wants to change your Umbriel config.\n\n{}\n\nApply this change? You can \
         also choose whether to keep a backup of the previous config, and whether to stop \
         asking for further changes in this session.",
        change.preview()
    );
    let not_written =
        |reason: &str| format!("{reason}, so nothing was written.\n{}", change.preview());
    match peer
        .elicit_with_timeout::<WriteApproval>(question, Some(APPROVAL_WINDOW))
        .await
    {
        Ok(Some(WriteApproval {
            apply: true,
            backup,
            allow_rest_of_session,
        })) => {
            if allow_rest_of_session {
                pending.allow_rest_of_session(backup);
            }
            commit(
                &change,
                BackupPolicy {
                    keep_backup: backup,
                    keep_newest,
                },
            )
        }
        Ok(_)
        | Err(ElicitationError::UserDeclined)
        | Err(ElicitationError::UserCancelled)
        | Err(ElicitationError::NoContent) => {
            Ok(not_written("The user did not approve the change"))
        }
        Err(ElicitationError::Service(ServiceError::Timeout { .. })) => Ok(not_written(&format!(
            "The user did not answer within {} minutes",
            APPROVAL_WINDOW.as_secs() / 60
        ))),
        Err(ElicitationError::CapabilityNotSupported) => Ok(hold_for_confirmation(pending, change)),
        Err(error) => Err(anyhow!(
            "could not ask the user to approve the change ({error}); nothing was written"
        )),
    }
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct LaunchApproval {
    /// Start this program
    pub start: bool,
    /// Also start further programs in this session without asking
    #[serde(default)]
    pub allow_rest_of_session: bool,
}

rmcp::elicit_safe!(LaunchApproval);

#[derive(Clone, Debug)]
pub enum Launch {
    App(String),
    Action(String),
}

impl Launch {
    pub fn program(&self) -> &str {
        match self {
            Launch::App(command) => command.trim(),
            Launch::Action(action) => action.trim(),
        }
    }
}

#[derive(Default)]
pub struct PendingLaunches {
    held: Mutex<HashMap<String, (Launch, Instant)>>,
    issued: AtomicU64,
    allowed_for_session: std::sync::atomic::AtomicBool,
}

impl PendingLaunches {
    pub fn allow_rest_of_session(&self) {
        self.allowed_for_session.store(true, Ordering::SeqCst);
    }

    fn allowed_for_session(&self) -> bool {
        self.allowed_for_session.load(Ordering::SeqCst)
    }

    fn hold(&self, launch: &Launch) -> String {
        let code = one_time_code(&self.issued);
        let mut held = self
            .held
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        held.retain(|_, (_, held_at)| held_at.elapsed() < APPROVAL_WINDOW);
        held.insert(code.clone(), (launch.clone(), Instant::now()));
        code
    }

    pub fn take(&self, code: &str) -> Result<Launch> {
        let mut held = self
            .held
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let (launch, held_at) = held.remove(code.trim()).ok_or_else(|| {
            anyhow!(
                "no program is waiting for confirmation code {code}; it was already started, has \
                 expired, or was never issued. Nothing was started."
            )
        })?;
        if held_at.elapsed() >= APPROVAL_WINDOW {
            return Err(anyhow!(
                "confirmation code {code} expired after {} minutes; nothing was started. Make the \
                 request again.",
                APPROVAL_WINDOW.as_secs() / 60
            ));
        }
        Ok(launch)
    }
}

pub enum LaunchDecision {
    Start { asked: bool },
    NotStarted(String),
}

pub async fn ask_before_launching(
    peer: &Peer<RoleServer>,
    pending: &PendingLaunches,
    launch: &Launch,
) -> Result<LaunchDecision> {
    let program = launch.program();
    if pending.allowed_for_session() {
        return Ok(LaunchDecision::Start { asked: false });
    }
    let hold = || {
        let code = pending.hold(launch);
        LaunchDecision::NotStarted(format!(
            "Nothing was started yet. This client cannot ask the user directly, so ask them now \
             whether to start this program:\n\n  {program}\n\nOnly after they agree, call \
             confirm_launch with confirmation \"{code}\". If, and only if, the user explicitly \
             says to stop asking about programs for the rest of this session, also pass \
             allow_rest_of_session: true; never set it on your own. The code works once and \
             expires in {} minutes. If they decline, do nothing.",
            APPROVAL_WINDOW.as_secs() / 60
        ))
    };
    if !peer
        .supported_elicitation_modes()
        .contains(&ElicitationMode::Form)
    {
        return Ok(hold());
    }
    let question = format!(
        "umbriel-mcp wants to start a program on your desktop:\n\n  {program}\n\nStart it? You \
         can also allow starting programs for the rest of this session."
    );
    let not_started = |reason: &str| {
        Ok(LaunchDecision::NotStarted(format!(
            "{reason}, so {program:?} was not started."
        )))
    };
    match peer
        .elicit_with_timeout::<LaunchApproval>(question, Some(APPROVAL_WINDOW))
        .await
    {
        Ok(Some(LaunchApproval {
            start: true,
            allow_rest_of_session,
        })) => {
            if allow_rest_of_session {
                pending.allow_rest_of_session();
            }
            Ok(LaunchDecision::Start { asked: true })
        }
        Ok(_)
        | Err(ElicitationError::UserDeclined)
        | Err(ElicitationError::UserCancelled)
        | Err(ElicitationError::NoContent) => not_started("The user did not allow it"),
        Err(ElicitationError::Service(ServiceError::Timeout { .. })) => not_started(&format!(
            "The user did not answer within {} minutes",
            APPROVAL_WINDOW.as_secs() / 60
        )),
        Err(ElicitationError::CapabilityNotSupported) => Ok(hold()),
        Err(error) => Err(anyhow!(
            "could not ask the user before starting the program ({error}); nothing was started"
        )),
    }
}

pub const CHOICE_WINDOW: Duration = Duration::from_secs(300);

pub enum CaptureAnswer {
    Chosen {
        target: CaptureTarget,
        seconds: Option<u32>,
    },
    NotChosen(String),
    NoDialog,
}

fn form_error(error: impl std::fmt::Display) -> anyhow::Error {
    anyhow!("could not build the capture choices: {error}")
}

fn length_choices() -> Result<EnumSchema> {
    let values = RECORDING_LENGTHS.iter().map(u32::to_string).collect();
    let titles = RECORDING_LENGTHS
        .iter()
        .map(|seconds| human_duration(*seconds))
        .collect();
    Ok(EnumSchema::builder(values)
        .enum_titles(titles)
        .map_err(form_error)?
        .with_default(DEFAULT_RECORDING_SECONDS.to_string())
        .map_err(form_error)?
        .build())
}

fn choice_form(choices: &[Choice], ask_length: bool) -> Result<ElicitationSchema> {
    let values = choices.iter().map(|choice| choice.value.clone()).collect();
    let titles = choices.iter().map(|choice| choice.title.clone()).collect();
    let target = EnumSchema::builder(values)
        .enum_titles(titles)
        .map_err(form_error)?
        .build();
    let mut form = ElicitationSchema::builder().required_enum_schema("target", target);
    if ask_length {
        form = form.required_enum_schema("duration", length_choices()?);
    }
    form.build().map_err(form_error)
}

pub async fn ask_what_to_capture(
    peer: &Peer<RoleServer>,
    purpose: Purpose,
    choices: &[Choice],
    ask_length: bool,
) -> Result<CaptureAnswer> {
    if !peer
        .supported_elicitation_modes()
        .contains(&ElicitationMode::Form)
    {
        return Ok(CaptureAnswer::NoDialog);
    }
    if choices.is_empty() {
        return Err(anyhow!("there is nothing on this desktop to capture"));
    }
    let message = match purpose {
        Purpose::Screenshot => "What should the screenshot show?",
        Purpose::Recording => "What should be recorded?",
    };
    let request = ElicitRequestParams::FormElicitationParams {
        meta: None,
        message: message.to_owned(),
        requested_schema: choice_form(choices, ask_length)?,
    };
    let nothing = |reason: &str| {
        Ok(CaptureAnswer::NotChosen(format!(
            "{reason}, so nothing was captured."
        )))
    };
    match peer
        .create_elicitation_with_timeout(request, Some(CHOICE_WINDOW))
        .await
    {
        Ok(answer) if answer.action == ElicitationAction::Accept => {
            let field = |name: &str| {
                answer
                    .content
                    .as_ref()
                    .and_then(|content| content.get(name))
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_owned)
            };
            let seconds = field("duration").and_then(|seconds| seconds.parse().ok());
            match field("target") {
                Some(value) => Ok(CaptureAnswer::Chosen {
                    target: parse_choice(&value)?,
                    seconds,
                }),
                None => nothing("The user did not pick anything"),
            }
        }
        Ok(_) => nothing("The user did not choose what to capture"),
        Err(ServiceError::Timeout { .. }) => nothing(&format!(
            "The user did not answer within {} minutes",
            CHOICE_WINDOW.as_secs() / 60
        )),
        Err(error) => Err(anyhow!("could not ask the user what to capture ({error})")),
    }
}