voidcrawl-mcp 0.5.0

Stdio MCP server exposing voidcrawl stealth headless Chrome to Claude Code and other MCP clients
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
//! Screen recording: a stateless variant that navigates a pooled tab and
//! records for a fixed duration, plus a start/stop pair that records an open
//! session while the caller drives it.
//!
//! These deliberately do **not** return frames inline. A screenshot is one
//! image; a recording is hundreds, and streaming them through an MCP response
//! would swamp the caller's context for no benefit. Frames and any encoded
//! artifact are written to disk and the response carries paths plus counts —
//! so an agent can hand the path to a human, feed it to a video tool, or read
//! back a single frame with an ordinary file read.

use std::{
    env, fs,
    path::{Path, PathBuf},
    time::Duration,
};

use rmcp::ErrorData;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use void_crawl_core::{
    Encoding, FrameFormat, MaskSpec, Page, Recording, RecordingOptions, SelectorEntry,
    VoidCrawlError,
};

use crate::{
    server::VoidCrawlServer,
    sessions::PendingRecording,
    tools::{
        selector::SelectorArg,
        viewport::{BboxArg, ScrollArg, ViewportArg},
        wait,
    },
};

pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
/// Default recording length. Short on purpose: a recording on a pooled tab
/// holds that browser's capture lock, and an agent that wants more can ask.
pub const DEFAULT_DURATION_SECS: f64 = 5.0;

/// One rectangle to black out in every frame.
///
/// Give exactly one of `bbox` (a rectangle you already know) or `selector`
/// (one to resolve). A selector mask is re-resolved while recording, so it
/// keeps covering an element that moves or scrolls; set `track: false` to pin
/// it where it started.
///
/// This is a geometric primitive, not a redaction policy: the server covers
/// the rectangles it is given and reports what it covered. It does not decide
/// what is sensitive, and a masked recording is not thereby a clean one.
#[derive(Debug, Clone, Deserialize, JsonSchema, Default)]
pub struct MaskArg {
    /// A viewport-relative rectangle in CSS pixels. Mutually exclusive with
    /// `selector`.
    #[serde(default)]
    pub bbox:     Option<BboxArg>,
    /// A Yosoi selector to resolve into a rectangle. One that matches
    /// nothing, is ambiguous, or is non-visual (jsonld/regex) fails the call
    /// before recording begins — an unresolvable mask is never skipped.
    /// Mutually exclusive with `bbox`.
    #[serde(default)]
    pub selector: Option<SelectorArg>,
    /// Re-resolve this mask while recording (default true; ignored for
    /// `bbox`).
    #[serde(default)]
    pub track:    Option<bool>,
    /// Name for this mask in the result. Defaults to one derived from the
    /// selector.
    #[serde(default)]
    pub label:    Option<String>,
}

impl MaskArg {
    fn resolve(self) -> Result<MaskSpec, ErrorData> {
        let spec = match (self.bbox, self.selector) {
            (Some(_), Some(_)) => {
                return Err(ErrorData::invalid_params(
                    "a mask takes either `bbox` or `selector`, not both",
                    None,
                ));
            }
            (None, None) => {
                return Err(ErrorData::invalid_params(
                    "a mask needs either `bbox` or `selector`",
                    None,
                ));
            }
            (Some(bbox), None) => MaskSpec::bbox(bbox.into()),
            (None, Some(selector)) => {
                let spec = MaskSpec::selector(selector.into());
                match self.track {
                    Some(track) => spec.with_track(track),
                    None => spec,
                }
            }
        };
        Ok(match self.label {
            Some(label) => spec.with_label(label),
            None => spec,
        })
    }
}

/// What one mask covered, so the caller can judge the artifact.
#[derive(Debug, Serialize, JsonSchema)]
pub struct MaskResult {
    pub label:            String,
    /// [x, y, width, height] in CSS pixels, as first resolved.
    pub bbox:             [u32; 4],
    pub tracked:          bool,
    /// Ticks where re-resolution failed. The mask kept its last known
    /// rectangle for those, so something was covered — whether it was the
    /// right thing is not knowable from here.
    pub unresolved_ticks: usize,
    /// Frames captured while the most recent re-resolution had failed. Above
    /// zero means those frames deserve a look before the recording is shared.
    pub stale_frames:     usize,
}

#[derive(Debug, Deserialize, JsonSchema, Default)]
pub struct RecordArgs {
    /// Absolute URL to record.
    pub url:           String,
    /// How long to record, in seconds (default 5, max 120).
    #[serde(default)]
    pub duration_secs: Option<f64>,
    /// Optional wait strategy applied before recording starts:
    /// "networkidle" (default) or "selector:<css>".
    #[serde(default)]
    pub wait_for:      Option<String>,
    /// Navigation + wait timeout in seconds (default 30).
    #[serde(default)]
    pub timeout_secs:  Option<u64>,
    /// Directory for the frames and any encoded artifact. Defaults to a new
    /// directory under the system temp dir; the exact path is returned.
    #[serde(default)]
    pub output_dir:    Option<String>,
    /// Record as this device/viewport instead of the pool's default —
    /// one-shot, does not persist.
    #[serde(default)]
    pub viewport:      Option<ViewportArg>,
    /// Crop every frame to this CSS-pixel region. **Viewport-relative**,
    /// unlike `screenshot`'s page-relative bbox: a recording frame only ever
    /// contains the viewport. Mutually exclusive with `selectors`.
    #[serde(default)]
    pub bbox:          Option<BboxArg>,
    /// Crop to each of these Yosoi selectors' rectangles, producing one
    /// region per selector from a single recording. Each is resolved once at
    /// start and then held fixed, so an element that moves mid-recording
    /// drifts out of its crop. A selector matching nothing, ambiguous, or
    /// non-visual (jsonld/regex) fails the call before recording begins.
    /// Mutually exclusive with `bbox`.
    #[serde(default)]
    pub selectors:     Vec<SelectorArg>,
    /// Rectangles to paint solid black in every frame, before anything is
    /// cropped, written, or encoded. Orthogonal to `bbox`/`selectors` —
    /// combining them is normal: crop to the form, mask the password field
    /// inside it.
    #[serde(default)]
    pub masks:         Vec<MaskArg>,
    /// Outward padding in CSS pixels on every mask, to swallow antialiasing
    /// at the edges (default 2). Set 0 for the exact rectangle.
    #[serde(default)]
    pub mask_pad:      Option<u32>,
    /// Scroll before recording. Since a recording only captures the viewport,
    /// this is how you choose which part of a long page gets recorded.
    #[serde(default)]
    pub scroll:        Option<ScrollArg>,
    /// Frame-rate ceiling (default 10). Not a floor: Chrome emits frames when
    /// it paints, so a static page yields very few regardless.
    #[serde(default)]
    pub fps:           Option<u8>,
    /// Frame format: "jpeg" (default) or "png".
    #[serde(default)]
    pub format:        Option<String>,
    /// JPEG quality 1-100 (default 80). Ignored for png.
    #[serde(default)]
    pub quality:       Option<u8>,
    /// Also encode each region to a single file: any of "gif", "mp4",
    /// "webm". Requires the matching build feature (and, for mp4/webm, an
    /// ffmpeg binary); when unavailable this reports an error rather than
    /// silently skipping, and the frames remain on disk either way.
    #[serde(default)]
    pub encode:        Vec<String>,
    /// Write the individual frames to disk (default true). Set false when
    /// only an encoded artifact is wanted.
    #[serde(default)]
    pub write_frames:  Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema, Default)]
pub struct SessionRecordStartArgs {
    pub session_id:        String,
    /// Hard upper bound in seconds (default 30, max 120). The recording stops
    /// itself at this point even if `session_record_stop` is never called, so
    /// an abandoned recording can't hold the browser open.
    #[serde(default)]
    pub max_duration_secs: Option<f64>,
    #[serde(default)]
    pub output_dir:        Option<String>,
    #[serde(default)]
    pub viewport:          Option<ViewportArg>,
    #[serde(default)]
    pub bbox:              Option<BboxArg>,
    #[serde(default)]
    pub selectors:         Vec<SelectorArg>,
    /// Rectangles to paint solid black in every frame. See `record`'s
    /// `masks`.
    #[serde(default)]
    pub masks:             Vec<MaskArg>,
    #[serde(default)]
    pub mask_pad:          Option<u32>,
    #[serde(default)]
    pub scroll:            Option<ScrollArg>,
    #[serde(default)]
    pub fps:               Option<u8>,
    #[serde(default)]
    pub format:            Option<String>,
    #[serde(default)]
    pub quality:           Option<u8>,
    #[serde(default)]
    pub encode:            Vec<String>,
    #[serde(default)]
    pub write_frames:      Option<bool>,
}

#[derive(Debug, Deserialize, JsonSchema, Default)]
pub struct SessionRecordStopArgs {
    pub session_id: String,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RegionResult {
    /// "viewport", "bbox", or a name derived from the selector.
    pub label:       String,
    /// [x, y, width, height] in CSS pixels, or null for the whole frame.
    pub bbox:        Option<[u32; 4]>,
    pub frame_count: usize,
    /// Directory holding this region's numbered frames, when frames were
    /// written.
    pub frames_dir:  Option<String>,
    /// Encoded artifacts written for this region.
    pub outputs:     Vec<String>,
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct RecordResult {
    pub output_dir:         String,
    pub regions:            Vec<RegionResult>,
    /// One entry per requested mask. An empty list means nothing was asked to
    /// be covered — not that there was nothing worth covering.
    pub masks:              Vec<MaskResult>,
    pub format:             String,
    pub duration_ms:        f64,
    pub frames_captured:    usize,
    /// Frames Chrome delivered that the fps ceiling discarded. Large next to
    /// a small `frames_captured` means `fps` was the binding constraint.
    pub frames_dropped:     usize,
    /// Frames per second actually achieved. Well below the requested `fps` on
    /// a mostly-static page — that's expected, not a fault.
    pub effective_fps:      f64,
    pub device_pixel_ratio: f64,
    /// Whether the recording had to hold the browser's capture lock. True for
    /// a pooled tab (it shares a window with its siblings, and a backgrounded
    /// tab in a shared window stops painting entirely).
    pub foregrounded:       bool,
    /// Set when frames were captured but encoding them failed — e.g. no
    /// ffmpeg on PATH. The frames on disk are still usable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encode_error:       Option<String>,
}

/// Cap on how long any one recording may run, whatever the caller asks for.
const MAX_DURATION_SECS: f64 = 120.0;

fn resolve_duration(secs: Option<f64>, default: f64) -> Result<Duration, VoidCrawlError> {
    let secs = secs.unwrap_or(default);
    if !secs.is_finite() || secs <= 0.0 {
        return Err(VoidCrawlError::RecordingError(
            "duration must be a positive number of seconds".into(),
        ));
    }
    if secs > MAX_DURATION_SECS {
        return Err(VoidCrawlError::RecordingError(format!(
            "duration {secs}s exceeds the {MAX_DURATION_SECS}s maximum"
        )));
    }
    Ok(Duration::from_secs_f64(secs))
}

fn resolve_format(name: Option<&str>) -> Result<FrameFormat, VoidCrawlError> {
    match name {
        None | Some("jpeg" | "jpg") => Ok(FrameFormat::Jpeg),
        Some("png") => Ok(FrameFormat::Png),
        Some(other) => Err(VoidCrawlError::RecordingError(format!(
            "unknown format {other:?}; expected 'jpeg' or 'png'"
        ))),
    }
}

fn resolve_encodings(names: &[String]) -> Result<Vec<Encoding>, VoidCrawlError> {
    names
        .iter()
        .map(|n| match n.as_str() {
            "gif" => Ok(Encoding::Gif),
            "mp4" => Ok(Encoding::Mp4),
            "webm" => Ok(Encoding::WebM),
            other => Err(VoidCrawlError::RecordingError(format!(
                "unknown encoding {other:?}; expected one of gif, mp4, webm"
            ))),
        })
        .collect()
}

/// A fresh directory for one recording's artifacts.
fn resolve_output_dir(explicit: Option<&str>) -> Result<PathBuf, VoidCrawlError> {
    let dir = match explicit {
        Some(d) => PathBuf::from(d),
        None => env::temp_dir().join("voidcrawl-recordings").join(uuid::Uuid::new_v4().to_string()),
    };
    fs::create_dir_all(&dir)
        .map_err(|e| VoidCrawlError::RecordingError(format!("create {}: {e}", dir.display())))?;
    Ok(dir)
}

#[allow(clippy::too_many_arguments)]
fn build_options(
    output_dir: PathBuf,
    viewport: Option<&ViewportArg>,
    bbox: Option<&BboxArg>,
    selectors: Vec<SelectorArg>,
    masks: Vec<MaskArg>,
    mask_pad: Option<u32>,
    scroll: Option<&ScrollArg>,
    fps: Option<u8>,
    duration: Duration,
    format: Option<&str>,
    quality: Option<u8>,
    encode: &[String],
    write_frames: Option<bool>,
) -> Result<RecordingOptions, ErrorData> {
    if bbox.is_some() && !selectors.is_empty() {
        return Err(ErrorData::invalid_params(
            "`bbox` and `selectors` are mutually exclusive",
            None,
        ));
    }

    let mut opts = RecordingOptions::default().with_dir(output_dir).with_max_duration(duration);
    opts.write_frames = write_frames.unwrap_or(true);
    opts.format = resolve_format(format).map_err(|e| to_invalid_params(&e))?;
    opts.encode = resolve_encodings(encode).map_err(|e| to_invalid_params(&e))?;

    if let Some(v) = viewport {
        opts = opts.with_viewport(v.resolve()?);
    }
    if let Some(b) = bbox {
        opts = opts.with_bbox((*b).into());
    }
    for selector in selectors {
        let entry: SelectorEntry = selector.into();
        opts = opts.with_selector(entry);
    }
    for mask in masks {
        opts = opts.with_mask(mask.resolve()?);
    }
    if let Some(pad) = mask_pad {
        opts = opts.with_mask_pad(pad);
    }
    if let Some(s) = scroll {
        opts = opts.with_scroll(s.resolve()?);
    }
    if let Some(fps) = fps {
        if fps == 0 {
            return Err(ErrorData::invalid_params("`fps` must be at least 1", None));
        }
        opts = opts.with_fps(fps);
    }
    if let Some(q) = quality {
        opts.quality = q;
    }
    Ok(opts)
}

fn to_invalid_params(e: &VoidCrawlError) -> ErrorData {
    ErrorData::invalid_params(e.to_string(), None)
}

/// Navigate a pooled tab and record it for a fixed duration.
pub async fn run(
    server: &VoidCrawlServer,
    args: RecordArgs,
) -> Result<RecordResult, VoidCrawlError> {
    let duration = resolve_duration(args.duration_secs, DEFAULT_DURATION_SECS)?;
    let output_dir = resolve_output_dir(args.output_dir.as_deref())?;
    let opts = build_options(
        output_dir.clone(),
        args.viewport.as_ref(),
        args.bbox.as_ref(),
        args.selectors,
        args.masks,
        args.mask_pad,
        args.scroll.as_ref(),
        args.fps,
        duration,
        args.format.as_deref(),
        args.quality,
        &args.encode,
        args.write_frames,
    )
    .map_err(|e| VoidCrawlError::RecordingError(e.message.to_string()))?;

    let pool = server.state().pool().await?;
    let tab = pool.acquire().await?;
    let result = async {
        let timeout = Duration::from_secs(args.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS));
        tab.page.goto_and_wait_for_idle(&args.url, timeout).await?;
        wait::apply_post_navigate(&tab.page, args.wait_for.as_deref(), timeout).await?;
        record_capturing_encode_errors(&tab.page, opts).await
    }
    .await;
    pool.release(tab).await;

    let (recording, encode_error) = result?;
    Ok(to_result(&recording, &output_dir, encode_error))
}

/// Begin recording an open session's page; the caller drives it and then
/// calls `session_record_stop`.
pub async fn session_start(
    server: &VoidCrawlServer,
    args: SessionRecordStartArgs,
) -> Result<SessionRecordStartResult, VoidCrawlError> {
    let duration = resolve_duration(args.max_duration_secs, 30.0)?;
    let output_dir = resolve_output_dir(args.output_dir.as_deref())?;
    let opts = build_options(
        output_dir.clone(),
        args.viewport.as_ref(),
        args.bbox.as_ref(),
        args.selectors,
        args.masks,
        args.mask_pad,
        args.scroll.as_ref(),
        args.fps,
        duration,
        args.format.as_deref(),
        args.quality,
        &args.encode,
        args.write_frames,
    )
    .map_err(|e| VoidCrawlError::RecordingError(e.message.to_string()))?;

    let session =
        server.state().sessions.get(&args.session_id).await.ok_or_else(|| {
            VoidCrawlError::Other(format!("no such session: {}", args.session_id))
        })?;

    // Reject a second start rather than silently dropping the first
    // recording's frames — same contract as `download_arm`.
    if session.pending_recording.lock().await.is_some() {
        return Err(VoidCrawlError::RecordingError(
            "a recording is already running on this session; call session_record_stop first".into(),
        ));
    }

    let handle = {
        let page = session.page.lock().await;
        page.start_recording(opts).await?
    };
    *session.pending_recording.lock().await =
        Some(PendingRecording { handle, output_dir: output_dir.clone() });

    Ok(SessionRecordStartResult {
        recording:  true,
        output_dir: output_dir.display().to_string(),
        message:    "recording — drive the session as usual, then call session_record_stop".into(),
    })
}

#[derive(Debug, Serialize, JsonSchema)]
pub struct SessionRecordStartResult {
    pub recording:  bool,
    /// Where the frames and artifacts will land.
    pub output_dir: String,
    pub message:    String,
}

/// Stop the recording started by `session_record_start` and write it out.
pub async fn session_stop(
    server: &VoidCrawlServer,
    args: SessionRecordStopArgs,
) -> Result<RecordResult, VoidCrawlError> {
    let session =
        server.state().sessions.get(&args.session_id).await.ok_or_else(|| {
            VoidCrawlError::Other(format!("no such session: {}", args.session_id))
        })?;

    let pending = session.pending_recording.lock().await.take().ok_or_else(|| {
        VoidCrawlError::RecordingError(
            "no recording is running on this session; call session_record_start first".into(),
        )
    })?;
    let PendingRecording { handle, output_dir } = pending;

    let page = session.page.lock().await;
    let recording = handle.stop(&page).await?;
    Ok(to_result(&recording, &output_dir, None))
}

/// Run a recording, downgrading an encode failure to a reported warning so a
/// missing ffmpeg doesn't throw away frames that were captured successfully.
async fn record_capturing_encode_errors(
    page: &Page,
    opts: RecordingOptions,
) -> Result<(Recording, Option<String>), VoidCrawlError> {
    let encode = opts.encode.clone();
    let mut fallback = opts.clone();
    match page.record(opts).await {
        Ok(rec) => Ok((rec, None)),
        Err(VoidCrawlError::RecordingEncodeError(msg)) if !encode.is_empty() => {
            // Retry once without encoding so the caller still gets frames.
            fallback.encode.clear();
            let rec = page.record(fallback).await?;
            Ok((rec, Some(msg)))
        }
        Err(e) => Err(e),
    }
}

fn to_result(rec: &Recording, output_dir: &Path, encode_error: Option<String>) -> RecordResult {
    let regions = rec
        .regions
        .iter()
        .map(|r| RegionResult {
            label:       r.label.clone(),
            bbox:        r.bbox.map(|b| [b.x, b.y, b.width, b.height]),
            frame_count: r.frames.len(),
            frames_dir:  Some(output_dir.join(&r.label).display().to_string()),
            outputs:     r.outputs.iter().map(|p| p.display().to_string()).collect(),
        })
        .collect();

    let masks = rec
        .masks
        .iter()
        .map(|m| MaskResult {
            label:            m.label.clone(),
            bbox:             [m.bbox.x, m.bbox.y, m.bbox.width, m.bbox.height],
            tracked:          m.tracked,
            unresolved_ticks: m.unresolved_ticks,
            stale_frames:     m.stale_frames,
        })
        .collect();

    RecordResult {
        output_dir: output_dir.display().to_string(),
        regions,
        masks,
        format: match rec.format {
            FrameFormat::Jpeg => "jpeg".into(),
            FrameFormat::Png => "png".into(),
        },
        duration_ms: rec.duration.as_secs_f64() * 1000.0,
        frames_captured: rec.frames_captured,
        frames_dropped: rec.frames_dropped,
        effective_fps: rec.effective_fps(),
        device_pixel_ratio: rec.device_pixel_ratio,
        foregrounded: rec.foregrounded,
        encode_error,
    }
}