chromewright 0.4.0

Browser automation MCP server via Chrome DevTools Protocol (CDP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
use crate::error::{BrowserError, Result};
use crate::tools::core::structured_tool_failure;
use crate::tools::{DocumentResult, Tool, ToolContext, ToolResult};
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::de::Deserializer;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::borrow::Cow;

#[derive(Debug, Clone, Serialize)]
pub struct ExtractParams {
    /// CSS selector (optional, defaults to body)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,

    /// Format: "text" or "html"
    pub format: String,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
enum ExtractFormat {
    Text,
    Html,
}

impl ExtractFormat {
    fn as_str(self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Html => "html",
        }
    }
}

fn default_extract_format() -> ExtractFormat {
    ExtractFormat::Text
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct StrictExtractParams {
    /// Omit `selector` to extract from the whole document body.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,
    /// Output format to return.
    #[serde(default = "default_extract_format")]
    pub format: ExtractFormat,
}

impl From<StrictExtractParams> for ExtractParams {
    fn from(params: StrictExtractParams) -> Self {
        Self {
            selector: params.selector,
            format: params.format.as_str().to_string(),
        }
    }
}

impl<'de> Deserialize<'de> for ExtractParams {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        StrictExtractParams::deserialize(deserializer).map(Into::into)
    }
}

impl JsonSchema for ExtractParams {
    fn schema_name() -> Cow<'static, str> {
        "ExtractParams".into()
    }

    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        StrictExtractParams::json_schema(generator)
    }
}

fn parse_extract_format(format: &str) -> Result<ExtractFormat> {
    match format {
        "text" => Ok(ExtractFormat::Text),
        "html" => Ok(ExtractFormat::Html),
        other => Err(BrowserError::InvalidArgument(format!(
            "extract.format must be one of: text, html (received '{other}')"
        ))),
    }
}

#[derive(Default)]
pub struct ExtractContentTool;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExtractOutput {
    #[serde(flatten)]
    pub result: DocumentResult,
    pub content: String,
    pub format: String,
    pub length: usize,
}

impl Tool for ExtractContentTool {
    type Params = ExtractParams;
    type Output = ExtractOutput;

    fn name(&self) -> &str {
        "extract"
    }

    fn description(&self) -> &str {
        "Read page text or HTML when markdown is too lossy for a selector or the whole page."
    }

    fn execute_typed(
        &self,
        params: ExtractParams,
        context: &mut ToolContext,
    ) -> Result<ToolResult> {
        let ExtractParams { selector, format } = params;
        let format = parse_extract_format(&format)?;
        let format_label = format.as_str();
        let js_code = build_extract_js(selector.as_deref(), format_label);
        context.record_browser_evaluation();
        let result = match context.session.evaluate(&js_code, false) {
            Ok(result) => result,
            Err(BrowserError::EvaluationFailed(reason)) => {
                if let Some(missing_selector) = missing_selector_from_reason(&reason) {
                    return Ok(context.finish(extract_missing_target_failure(
                        &missing_selector,
                        format_label,
                    )));
                }

                return Err(BrowserError::EvaluationFailed(reason));
            }
            Err(other) => return Err(other),
        };
        let content = match parse_extract_output(result.value, selector.as_deref()) {
            Ok(content) => content,
            Err(ExtractFailure::MissingTarget(missing_selector)) => {
                return Ok(context.finish(extract_missing_target_failure(
                    &missing_selector,
                    format_label,
                )));
            }
            Err(ExtractFailure::InvalidPayload {
                reason,
                received_type,
            }) => {
                return Ok(context.finish(structured_tool_failure(
                    "invalid_extract_payload",
                    reason,
                    None,
                    None,
                    Some(serde_json::json!({
                        "suggested_tool": "snapshot",
                    })),
                    Some(serde_json::json!({
                        "format": format_label,
                        "selector": selector,
                        "received_type": received_type,
                    })),
                )));
            }
        };

        context.record_browser_evaluation();
        let document = context.session.document_metadata()?;

        Ok(context.finish(ToolResult::success_with(ExtractOutput {
            result: DocumentResult::new(document),
            length: content.len(),
            format: format_label.to_string(),
            content,
        })))
    }
}

fn extract_missing_target_failure(selector: &str, format: &str) -> ToolResult {
    let error = format!("Element not found: {}", selector);

    structured_tool_failure(
        "element_not_found",
        error,
        None,
        None,
        Some(serde_json::json!({
            "suggested_tool": "snapshot",
        })),
        Some(serde_json::json!({
            "selector": selector,
            "format": format,
        })),
    )
}

fn missing_selector_from_reason(reason: &str) -> Option<String> {
    let (_, selector) = reason.rsplit_once("Element not found: ")?;
    let selector = selector.lines().next().unwrap_or(selector).trim();
    if selector.is_empty() {
        None
    } else {
        Some(selector.to_string())
    }
}

enum ExtractFailure {
    MissingTarget(String),
    InvalidPayload {
        reason: String,
        received_type: &'static str,
    },
}

fn parse_extract_output(
    value: Option<Value>,
    selector: Option<&str>,
) -> std::result::Result<String, ExtractFailure> {
    match value {
        Some(Value::String(content)) => Ok(content),
        Some(other) => {
            let received_type = value_kind(&other);
            Err(ExtractFailure::InvalidPayload {
                reason: format!("Extract returned an unexpected {received_type} payload"),
                received_type,
            })
        }
        None => match selector {
            Some(selector) => Err(ExtractFailure::MissingTarget(selector.to_string())),
            None => Err(ExtractFailure::InvalidPayload {
                reason: "Extract returned no content".to_string(),
                received_type: "null",
            }),
        },
    }
}

fn value_kind(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

fn build_extract_js(selector: Option<&str>, format: &str) -> String {
    let selector_literal = selector
        .map(|value| serde_json::to_string(value).expect("selector JSON serialization should work"))
        .unwrap_or_else(|| "null".to_string());
    let value_expr = if format == "html" {
        "element ? element.innerHTML : ''"
    } else {
        "element ? (element.innerText || element.textContent || '') : ''"
    };

    format!(
        "(() => {{
            const selector = {selector_literal};
            const element = selector ? document.querySelector(selector) : document.body;
            if (selector && !element) {{
                throw new Error(`Element not found: ${{selector}}`);
            }}
            return {value_expr};
        }})()"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browser::BrowserSession;
    use crate::browser::backend::{
        FakeSessionBackend, ScriptEvaluation, SessionBackend, TabDescriptor,
    };
    use crate::error::BrowserError;
    use crate::{dom::DocumentMetadata, dom::DomTree};
    use schemars::schema_for;
    use serde_json::json;
    use std::time::Duration;

    enum EvaluateOnlyOutcome {
        Success(Value),
        NoValue,
        EvaluationFailed(&'static str),
    }

    struct EvaluateOnlyBackend {
        outcome: EvaluateOnlyOutcome,
    }

    #[test]
    fn test_extract_params_use_enum_schema_and_reject_unknown_format() {
        let params: ExtractParams = serde_json::from_value(json!({
            "selector": "#content",
            "format": "html"
        }))
        .expect("strict extract params should deserialize");
        assert_eq!(params.selector.as_deref(), Some("#content"));
        assert_eq!(params.format, "html");

        let error = serde_json::from_value::<ExtractParams>(json!({
            "selector": "#content",
            "format": "markdown"
        }))
        .expect_err("unknown extract format should be rejected");
        assert!(error.to_string().contains("unknown variant `markdown`"));

        let schema = schema_for!(ExtractParams);
        let schema_json = serde_json::to_value(&schema).expect("schema should serialize");
        let properties = schema_json
            .get("properties")
            .and_then(|value| value.as_object())
            .expect("extract params schema should expose properties");
        let format_property = properties
            .get("format")
            .expect("format property should be present");
        let format_json =
            serde_json::to_string(format_property).expect("format schema should serialize");
        assert!(format_json.contains("$ref") || format_json.contains("enum"));
        let full_schema_json =
            serde_json::to_string(&schema_json).expect("extract schema should serialize");
        assert!(full_schema_json.contains("\"text\""));
        assert!(full_schema_json.contains("\"html\""));
    }

    #[test]
    fn test_extract_tool_rejects_invalid_typed_format_instead_of_coercing() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let tool = ExtractContentTool;
        let mut context = ToolContext::new(&session);

        let error = tool
            .execute_typed(
                ExtractParams {
                    selector: Some("#fake-target".to_string()),
                    format: "markdown".to_string(),
                },
                &mut context,
            )
            .expect_err("invalid typed format should be rejected");

        assert!(matches!(error, BrowserError::InvalidArgument(_)));
        assert!(error.to_string().contains("extract.format"));
    }

    impl SessionBackend for EvaluateOnlyBackend {
        fn navigate(&self, _url: &str) -> crate::error::Result<()> {
            unreachable!("navigate is not used in this test")
        }

        fn wait_for_navigation(&self) -> crate::error::Result<()> {
            unreachable!("wait_for_navigation is not used in this test")
        }

        fn wait_for_document_ready_with_timeout(
            &self,
            _timeout: Duration,
        ) -> crate::error::Result<()> {
            unreachable!("wait_for_document_ready_with_timeout is not used in this test")
        }

        fn document_metadata(&self) -> crate::error::Result<DocumentMetadata> {
            unreachable!("document_metadata is not used in this test")
        }

        fn extract_dom(&self) -> crate::error::Result<DomTree> {
            unreachable!("extract_dom is not used in this test")
        }

        fn extract_dom_with_prefix(&self, _prefix: &str) -> crate::error::Result<DomTree> {
            unreachable!("extract_dom_with_prefix is not used in this test")
        }

        fn evaluate(
            &self,
            _script: &str,
            _await_promise: bool,
        ) -> crate::error::Result<ScriptEvaluation> {
            match &self.outcome {
                EvaluateOnlyOutcome::Success(value) => Ok(ScriptEvaluation {
                    value: Some(value.clone()),
                    description: None,
                    type_name: Some(value_kind(value).to_string()),
                }),
                EvaluateOnlyOutcome::NoValue => Ok(ScriptEvaluation {
                    value: None,
                    description: None,
                    type_name: Some("undefined".to_string()),
                }),
                EvaluateOnlyOutcome::EvaluationFailed(reason) => {
                    Err(BrowserError::EvaluationFailed((*reason).to_string()))
                }
            }
        }

        fn capture_screenshot(&self, _full_page: bool) -> crate::error::Result<Vec<u8>> {
            unreachable!("capture_screenshot is not used in this test")
        }

        fn press_key(&self, _key: &str) -> crate::error::Result<()> {
            unreachable!("press_key is not used in this test")
        }

        fn list_tabs(&self) -> crate::error::Result<Vec<TabDescriptor>> {
            Ok(vec![TabDescriptor {
                id: "tab-1".to_string(),
                title: "about:blank".to_string(),
                url: "about:blank".to_string(),
            }])
        }

        fn active_tab(&self) -> crate::error::Result<TabDescriptor> {
            Ok(TabDescriptor {
                id: "tab-1".to_string(),
                title: "about:blank".to_string(),
                url: "about:blank".to_string(),
            })
        }

        fn open_tab(&self, _url: &str) -> crate::error::Result<TabDescriptor> {
            unreachable!("open_tab is not used in this test")
        }

        fn activate_tab(&self, _tab_id: &str) -> crate::error::Result<()> {
            unreachable!("activate_tab is not used in this test")
        }

        fn close_tab(&self, _tab_id: &str, _with_unload: bool) -> crate::error::Result<()> {
            unreachable!("close_tab is not used in this test")
        }

        fn close(&self) -> crate::error::Result<()> {
            unreachable!("close is not used in this test")
        }
    }

    #[test]
    fn test_extract_tool_supports_selector_text_on_fake_backend() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let tool = ExtractContentTool;
        let mut context = ToolContext::new(&session);

        let result = tool
            .execute_typed(
                ExtractParams {
                    selector: Some("#fake-target".to_string()),
                    format: "text".to_string(),
                },
                &mut context,
            )
            .expect("extract should succeed");

        assert!(result.success);
        let data = result.data.expect("extract should include data");
        assert_eq!(data["content"].as_str(), Some("Fake target"));
        assert_eq!(data["format"].as_str(), Some("text"));
    }

    #[test]
    fn test_extract_tool_supports_selector_html_on_fake_backend() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let tool = ExtractContentTool;
        let mut context = ToolContext::new(&session);

        let result = tool
            .execute_typed(
                ExtractParams {
                    selector: Some("#fake-target".to_string()),
                    format: "html".to_string(),
                },
                &mut context,
            )
            .expect("extract should succeed");

        assert!(result.success);
        let data = result.data.expect("extract should include data");
        assert_eq!(
            data["content"].as_str(),
            Some(r#"<button id="fake-target" class="fake">Fake target</button>"#)
        );
        assert_eq!(data["format"].as_str(), Some("html"));
    }

    #[test]
    fn test_extract_tool_returns_structured_failure_for_missing_selector() {
        let session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        let tool = ExtractContentTool;
        let mut context = ToolContext::new(&session);

        let result = tool
            .execute_typed(
                ExtractParams {
                    selector: Some("#missing".to_string()),
                    format: "text".to_string(),
                },
                &mut context,
            )
            .expect("missing selector should stay a tool failure");

        assert!(!result.success);
        assert_eq!(result.error.as_deref(), Some("Element not found: #missing"));
        let data = result
            .data
            .expect("missing selector should include failure details");
        assert_eq!(data["code"].as_str(), Some("element_not_found"));
        assert_eq!(data["details"]["selector"].as_str(), Some("#missing"));
        assert_eq!(data["details"]["format"].as_str(), Some("text"));
        assert_eq!(
            data["recovery"]["suggested_tool"].as_str(),
            Some("snapshot")
        );
    }

    #[test]
    fn test_extract_tool_returns_missing_target_failure_when_selector_yields_no_payload() {
        let session = BrowserSession::with_test_backend(EvaluateOnlyBackend {
            outcome: EvaluateOnlyOutcome::NoValue,
        });
        let tool = ExtractContentTool;
        let mut context = ToolContext::new(&session);

        let result = tool
            .execute_typed(
                ExtractParams {
                    selector: Some("#missing".to_string()),
                    format: "html".to_string(),
                },
                &mut context,
            )
            .expect("missing selector should stay a tool failure");

        assert!(!result.success);
        assert_eq!(result.error.as_deref(), Some("Element not found: #missing"));
        let data = result
            .data
            .expect("missing selector should include failure details");
        assert_eq!(data["code"].as_str(), Some("element_not_found"));
        assert_eq!(data["details"]["selector"].as_str(), Some("#missing"));
        assert_eq!(data["details"]["format"].as_str(), Some("html"));
        assert_eq!(
            data["recovery"]["suggested_tool"].as_str(),
            Some("snapshot")
        );
    }

    #[test]
    fn test_extract_tool_preserves_non_missing_selector_evaluation_failures() {
        let session = BrowserSession::with_test_backend(EvaluateOnlyBackend {
            outcome: EvaluateOnlyOutcome::EvaluationFailed(
                "Failed to execute 'querySelector' on 'Document': '[' is not a valid selector.",
            ),
        });
        let tool = ExtractContentTool;
        let mut context = ToolContext::new(&session);

        let err = tool
            .execute_typed(
                ExtractParams {
                    selector: Some("[".to_string()),
                    format: "text".to_string(),
                },
                &mut context,
            )
            .expect_err("invalid selector should not be rewritten as element_not_found");

        match err {
            BrowserError::EvaluationFailed(reason) => {
                assert!(reason.contains("not a valid selector"));
            }
            other => panic!("unexpected extract error: {other:?}"),
        }
    }

    #[test]
    fn test_extract_tool_returns_structured_failure_for_invalid_payload_shape() {
        let session = BrowserSession::with_test_backend(EvaluateOnlyBackend {
            outcome: EvaluateOnlyOutcome::Success(serde_json::json!({
                "content": "not-a-string"
            })),
        });
        let tool = ExtractContentTool;
        let mut context = ToolContext::new(&session);

        let result = tool
            .execute_typed(
                ExtractParams {
                    selector: Some("#fake-target".to_string()),
                    format: "text".to_string(),
                },
                &mut context,
            )
            .expect("invalid extract payload should stay a tool failure");

        assert!(!result.success);
        assert_eq!(
            result.error.as_deref(),
            Some("Extract returned an unexpected object payload")
        );
        let data = result
            .data
            .expect("invalid extract payload should include details");
        assert_eq!(data["code"].as_str(), Some("invalid_extract_payload"));
        assert_eq!(data["details"]["selector"].as_str(), Some("#fake-target"));
        assert_eq!(data["details"]["format"].as_str(), Some("text"));
        assert_eq!(data["details"]["received_type"].as_str(), Some("object"));
        assert_eq!(
            data["recovery"]["suggested_tool"].as_str(),
            Some("snapshot")
        );
    }
}