zeuxis 0.2.0

Local read-only MCP screenshot server for screen/window/region capture
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
//! Versioned JSON contract between the MCP parent and capture worker process.
//!
//! Requests and responses are exchanged over stdio. The contract carries enough
//! target, dimension, and error metadata for the parent to adopt an encoded
//! artifact without rerunning capture work.

use serde::{Deserialize, Serialize};

use crate::{
    mcp::{
        errors::{ErrorCode, ServerError},
        result::CaptureTargetPayload,
    },
    storage::CaptureOutputFormat,
};

/// Worker JSON schema version; parent and child must agree before capture runs.
pub const WORKER_CONTRACT_VERSION: u32 = 1;

/// Output format names used in worker JSON requests and responses.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WorkerOutputFormat {
    Png,
    Jpeg,
    Webp,
}

impl WorkerOutputFormat {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Png => "png",
            Self::Jpeg => "jpeg",
            Self::Webp => "webp",
        }
    }

    pub const fn mime_type(self) -> &'static str {
        match self {
            Self::Png => "image/png",
            Self::Jpeg => "image/jpeg",
            Self::Webp => "image/webp",
        }
    }

    pub const fn file_suffix(self) -> &'static str {
        match self {
            Self::Png => ".png",
            Self::Jpeg => ".jpg",
            Self::Webp => ".webp",
        }
    }

    pub const fn to_storage(self) -> CaptureOutputFormat {
        match self {
            Self::Png => CaptureOutputFormat::Png,
            Self::Jpeg => CaptureOutputFormat::Jpeg,
            Self::Webp => CaptureOutputFormat::Webp,
        }
    }
}

impl From<CaptureOutputFormat> for WorkerOutputFormat {
    fn from(value: CaptureOutputFormat) -> Self {
        match value {
            CaptureOutputFormat::Png => Self::Png,
            CaptureOutputFormat::Jpeg => Self::Jpeg,
            CaptureOutputFormat::Webp => Self::Webp,
        }
    }
}

/// Capture operation requested from the subprocess worker.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CaptureOperation {
    CaptureScreen {
        monitor_id: Option<u32>,
    },
    CaptureActiveWindow,
    CaptureCursorWindow {
        include_system_windows: bool,
    },
    CaptureWindow {
        window_id: u32,
    },
    CaptureCursorRegion {
        size: u32,
    },
    CaptureRect {
        x: i32,
        y: i32,
        width: u32,
        height: u32,
    },
    CaptureMonitorRegion {
        monitor_id: u32,
        x: u32,
        y: u32,
        width: u32,
        height: u32,
    },
}

impl CaptureOperation {
    /// MCP tool name used as `capture_mode` in stored artifact metadata.
    pub const fn capture_mode(&self) -> &'static str {
        match self {
            Self::CaptureScreen { .. } => "capture_screen",
            Self::CaptureActiveWindow => "capture_active_window",
            Self::CaptureCursorWindow { .. } => "capture_cursor_window",
            Self::CaptureWindow { .. } => "capture_window",
            Self::CaptureCursorRegion { .. } => "capture_cursor_region",
            Self::CaptureRect { .. } => "capture_rect",
            Self::CaptureMonitorRegion { .. } => "capture_monitor_region",
        }
    }
}

/// Encoding and downscaling settings sent to the worker.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkerOutputOptions {
    pub format: WorkerOutputFormat,
    pub jpeg_quality: u8,
    pub max_dimension: Option<u32>,
}

/// Parent-to-child capture request.
///
/// `artifact_path` is chosen by the parent so the child writes directly into the
/// storage artifact directory that will later adopt the file.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkerRequest {
    pub v: u32,
    pub request_id: String,
    pub operation: CaptureOperation,
    pub output: WorkerOutputOptions,
    pub artifact_path: String,
}

impl WorkerRequest {
    /// Checks contract version, `request_id`, and `artifact_path` before capture.
    pub fn validate(&self) -> Result<(), WorkerErrorPayload> {
        if self.v != WORKER_CONTRACT_VERSION {
            return Err(WorkerErrorPayload::invalid_params(format!(
                "unsupported worker contract version {}; expected {}",
                self.v, WORKER_CONTRACT_VERSION
            )));
        }
        if self.request_id.trim().is_empty() {
            return Err(WorkerErrorPayload::invalid_params(
                "request_id must not be empty",
            ));
        }
        if self.artifact_path.trim().is_empty() {
            return Err(WorkerErrorPayload::invalid_params(
                "artifact_path must not be empty",
            ));
        }
        Ok(())
    }
}

/// Successful worker result for an encoded artifact on disk.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WorkerSuccessPayload {
    pub artifact_path: String,
    pub output_format: String,
    pub mime_type: String,
    pub width: u32,
    pub height: u32,
    pub source_width: u32,
    pub source_height: u32,
    pub input_units: String,
    pub input_width: Option<u32>,
    pub input_height: Option<u32>,
    pub target: CaptureTargetPayload,
}

/// Child-to-parent response with exclusive success or error payloads.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WorkerResponse {
    pub v: u32,
    pub request_id: String,
    pub ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<WorkerSuccessPayload>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<WorkerErrorPayload>,
}

impl WorkerResponse {
    /// Builds an `ok=true` response carrying encoded artifact metadata.
    pub fn success(request_id: impl Into<String>, result: WorkerSuccessPayload) -> Self {
        Self {
            v: WORKER_CONTRACT_VERSION,
            request_id: request_id.into(),
            ok: true,
            result: Some(result),
            error: None,
        }
    }

    /// Builds an `ok=false` response with a stable worker error payload.
    pub fn error(request_id: impl Into<String>, error: WorkerErrorPayload) -> Self {
        Self {
            v: WORKER_CONTRACT_VERSION,
            request_id: request_id.into(),
            ok: false,
            result: None,
            error: Some(error),
        }
    }

    /// Ensures version, `request_id`, and exclusive success/error payloads match `ok`.
    pub fn validate(&self) -> Result<(), WorkerErrorPayload> {
        if self.v != WORKER_CONTRACT_VERSION {
            return Err(WorkerErrorPayload::invalid_params(format!(
                "unsupported worker contract version {}; expected {}",
                self.v, WORKER_CONTRACT_VERSION
            )));
        }
        if self.request_id.trim().is_empty() {
            return Err(WorkerErrorPayload::invalid_params(
                "request_id must not be empty",
            ));
        }
        if self.ok {
            if self.error.is_some() {
                return Err(WorkerErrorPayload::invalid_params(
                    "ok response must not include error payload",
                ));
            }
            if self.result.is_none() {
                return Err(WorkerErrorPayload::invalid_params(
                    "ok response must include result payload",
                ));
            }
        } else {
            if self.result.is_some() {
                return Err(WorkerErrorPayload::invalid_params(
                    "error response must not include result payload",
                ));
            }
            if self.error.is_none() {
                return Err(WorkerErrorPayload::invalid_params(
                    "error response must include error payload",
                ));
            }
        }
        Ok(())
    }
}

/// Worker error payload preserving MCP error code and retryability semantics.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkerErrorPayload {
    pub error_code: String,
    pub message: String,
    pub retryable: bool,
}

impl WorkerErrorPayload {
    /// Worker-side `storage_failed` with retryable semantics preserved for the parent.
    pub fn storage_failed(message: impl Into<String>) -> Self {
        Self {
            error_code: ErrorCode::StorageFailed.as_str().to_owned(),
            message: message.into(),
            retryable: true,
        }
    }

    /// Worker-side `invalid_params` for malformed requests or responses.
    pub fn invalid_params(message: impl Into<String>) -> Self {
        Self {
            error_code: ErrorCode::InvalidParams.as_str().to_owned(),
            message: message.into(),
            retryable: false,
        }
    }

    /// Serializes a capture-time `ServerError` into worker JSON.
    pub fn from_server_error(error: &ServerError) -> Self {
        Self {
            error_code: error.error_code().to_owned(),
            message: error.message().to_owned(),
            retryable: error.retryable(),
        }
    }

    /// Rehydrates worker JSON errors into MCP `ServerError` values for tool results.
    pub fn to_server_error(self) -> ServerError {
        match self.error_code.as_str() {
            "permission_denied" => ServerError::permission_denied(self.message),
            "capture_unsupported_on_platform" => {
                ServerError::capture_unsupported_on_platform(self.message)
            }
            "window_not_found" => ServerError::window_not_found(self.message),
            "monitor_not_found" => ServerError::monitor_not_found(self.message),
            "no_capture_yet" => ServerError::no_capture_yet(self.message),
            "invalid_region" => ServerError::invalid_region(self.message),
            "cursor_unavailable" => ServerError::cursor_unavailable(self.message),
            "encode_failed" => ServerError::encode_failed(self.message),
            "invalid_params" => ServerError::invalid_params(self.message),
            "storage_failed" => ServerError::storage_failed(self.message),
            _ => ServerError::storage_failed(format!(
                "unknown worker error code {}: {}",
                self.error_code, self.message
            )),
        }
    }
}

/// Decodes and validates a worker request JSON document.
pub fn parse_request_json(input: &str) -> Result<WorkerRequest, WorkerErrorPayload> {
    let request: WorkerRequest = serde_json::from_str(input).map_err(|error| {
        WorkerErrorPayload::invalid_params(format!("failed to decode worker request JSON: {error}"))
    })?;
    request.validate()?;
    Ok(request)
}

/// Decodes and validates a worker response JSON document.
pub fn parse_response_json(input: &str) -> Result<WorkerResponse, WorkerErrorPayload> {
    let response: WorkerResponse = serde_json::from_str(input).map_err(|error| {
        WorkerErrorPayload::invalid_params(format!(
            "failed to decode worker response JSON: {error}"
        ))
    })?;
    response.validate()?;
    Ok(response)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn worker_contract_request_json_roundtrip() {
        let request = WorkerRequest {
            v: WORKER_CONTRACT_VERSION,
            request_id: "req-1".to_owned(),
            operation: CaptureOperation::CaptureScreen { monitor_id: None },
            output: WorkerOutputOptions {
                format: WorkerOutputFormat::Png,
                jpeg_quality: 82,
                max_dimension: Some(1024),
            },
            artifact_path: "/tmp/zeuxis-test.png".to_owned(),
        };
        let json = serde_json::to_string(&request).expect("serialize request");
        let parsed = parse_request_json(&json).expect("parse request");
        assert_eq!(parsed, request);
    }

    #[test]
    fn worker_contract_response_json_roundtrip() {
        let response = WorkerResponse::error(
            "req-2",
            WorkerErrorPayload::storage_failed("unsupported mode"),
        );
        let json = serde_json::to_string(&response).expect("serialize response");
        let parsed = parse_response_json(&json).expect("parse response");
        assert_eq!(parsed, response);
    }

    #[test]
    fn worker_contract_request_rejects_version_mismatch() {
        let request = WorkerRequest {
            v: WORKER_CONTRACT_VERSION + 1,
            request_id: "req-3".to_owned(),
            operation: CaptureOperation::CaptureScreen { monitor_id: None },
            output: WorkerOutputOptions {
                format: WorkerOutputFormat::Png,
                jpeg_quality: 82,
                max_dimension: None,
            },
            artifact_path: "/tmp/zeuxis-test.png".to_owned(),
        };
        let json = serde_json::to_string(&request).expect("serialize request");
        let error = parse_request_json(&json).expect_err("version mismatch should fail");
        assert_eq!(error.error_code, "invalid_params");
    }

    #[test]
    fn worker_contract_response_rejects_missing_error_when_not_ok() {
        let response = WorkerResponse {
            v: WORKER_CONTRACT_VERSION,
            request_id: "req-4".to_owned(),
            ok: false,
            result: None,
            error: None,
        };
        let json = serde_json::to_string(&response).expect("serialize response");
        let error = parse_response_json(&json).expect_err("error payload should be required");
        assert_eq!(error.error_code, "invalid_params");
    }

    #[test]
    fn worker_contract_unknown_error_maps_to_storage_failed() {
        let error = WorkerErrorPayload {
            error_code: "nonesuch".to_owned(),
            message: "bad".to_owned(),
            retryable: false,
        };
        assert_eq!(error.to_server_error().error_code(), "storage_failed");
    }
}