chromewright 0.8.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
//! MCP tool that chooses a dropdown option after actionability checks succeed.
//!
//! Resolves a selector or revision-scoped cursor, then selects by option value.

use crate::browser::commands::{
    BrowserCommand, BrowserCommandResult, InteractionCommand, InteractionCommandResult,
    SelectInteractionRequest, TargetedInteractionRequest,
};
use crate::dom::{Cursor, NodeRef};
use crate::error::{BrowserError, Result};
#[cfg(test)]
use crate::tools::browser_kernel::render_browser_kernel_script;
use crate::tools::{
    TargetResolution, Tool, ToolContext, ToolResult,
    actionability::ActionabilityPredicate,
    core::PublicTarget,
    core::TargetedActionResult,
    services::interaction::{
        ActionabilityWaitState, DEFAULT_ACTIONABILITY_TIMEOUT_MS, build_actionability_failure,
        build_interaction_failure, build_interaction_handoff, decode_action_result,
        resolve_interaction_target, wait_for_actionability,
    },
};
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::de::Deserializer;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
#[cfg(test)]
use std::sync::OnceLock;

#[cfg(test)]
const SELECT_JS: &str = include_str!("select.js");
#[cfg(test)]
static SELECT_SHELL: OnceLock<crate::tools::browser_kernel::BrowserKernelTemplateShell> =
    OnceLock::new();

/// Dropdown value and selector/cursor target for a select interaction.
#[derive(Debug, Clone, Serialize)]
pub struct SelectParams {
    /// CSS selector (use either this or index, not both)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,

    /// Element index from DOM tree (use either this or selector, not both)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,

    /// Revision-scoped node reference from the snapshot tool
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_ref: Option<NodeRef>,

    /// Cursor from the snapshot or inspect_node tools
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<Cursor>,

    /// Value to select in the dropdown
    pub value: String,
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct StrictSelectParams {
    /// Target dropdown to operate on.
    pub target: PublicTarget,
    /// Value to select in the dropdown.
    pub value: String,
}

impl From<StrictSelectParams> for SelectParams {
    fn from(params: StrictSelectParams) -> Self {
        let (selector, cursor) = params.target.into_selector_or_cursor();
        Self {
            selector,
            index: None,
            node_ref: None,
            cursor,
            value: params.value,
        }
    }
}

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

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

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

/// Selects a dropdown option after actionability checks succeed.
#[derive(Default)]
pub struct SelectTool;

/// Targeted action result with the chosen value and visible selected text.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SelectOutput {
    /// Document + before/after target continuity after selection.
    #[serde(flatten)]
    pub result: TargetedActionResult,
    /// Option `value` that was selected.
    pub value: String,
    /// Visible option label when available.
    pub selected_text: Option<String>,
}

impl Tool for SelectTool {
    type Params = SelectParams;
    type Output = SelectOutput;

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

    fn description(&self) -> &str {
        "Choose a dropdown value. Usually after snapshot; next wait or snapshot."
    }

    fn execute_typed(&self, params: SelectParams, context: &mut ToolContext) -> Result<ToolResult> {
        let SelectParams {
            selector,
            index,
            node_ref,
            cursor,
            value,
        } = params;
        let target =
            match resolve_interaction_target("select", selector, index, node_ref, cursor, context)?
            {
                TargetResolution::Resolved(target) => target,
                TargetResolution::Failure(failure) => return Ok(context.finish(failure)),
            };

        let predicates = select_actionability_predicates();
        match wait_for_actionability(
            context,
            &target,
            predicates,
            DEFAULT_ACTIONABILITY_TIMEOUT_MS,
        )? {
            ActionabilityWaitState::Ready => {}
            ActionabilityWaitState::TimedOut(probe) => {
                return build_actionability_failure(
                    "select",
                    context.session,
                    &target,
                    &probe,
                    predicates,
                    None,
                )
                .map(|result| context.finish(result));
            }
        }

        context.record_browser_evaluation();
        let result = context
            .session
            .execute_command(BrowserCommand::Interaction(InteractionCommand::Select(
                SelectInteractionRequest {
                    target: TargetedInteractionRequest {
                        selector: target.selector.clone(),
                        target_index: target.browser_command_target_index(),
                    },
                    value: value.clone(),
                },
            )))
            .map_err(|e| match e {
                BrowserError::EvaluationFailed(reason) => BrowserError::ToolExecutionFailed {
                    tool: "select".to_string(),
                    reason,
                },
                other => other,
            })?;
        let BrowserCommandResult::Interaction(InteractionCommandResult::Select(select_result)) =
            result
        else {
            return Err(BrowserError::ToolExecutionFailed {
                tool: "select".to_string(),
                reason: "Browser command returned an unexpected result for select".to_string(),
            });
        };

        match parse_select_result(Some(
            serde_json::to_value(select_result).map_err(BrowserError::from)?,
        ))? {
            SelectParseResult::Success(selected_text) => {
                let handoff = build_interaction_handoff(context, &target)?;
                Ok(context.finish(ToolResult::success_with(SelectOutput {
                    result: TargetedActionResult::new(
                        "select",
                        handoff.document,
                        handoff.target_before,
                        handoff.target_after,
                        handoff.target_status,
                    ),
                    value,
                    selected_text,
                })))
            }
            SelectParseResult::Failure { code, error } => build_interaction_failure(
                "select",
                context.session,
                &target,
                code,
                error,
                Vec::new(),
                None,
            )
            .map(|result| context.finish(result)),
        }
    }
}

#[cfg(test)]
fn build_select_js(config: &serde_json::Value) -> String {
    render_browser_kernel_script(&SELECT_SHELL, SELECT_JS, "__SELECT_CONFIG__", config)
}

enum SelectParseResult {
    Success(Option<String>),
    Failure { code: String, error: String },
}

#[derive(Debug, Deserialize)]
struct RawSelectResult {
    success: bool,
    #[serde(default)]
    code: Option<String>,
    #[serde(default)]
    error: Option<String>,
    #[serde(default)]
    selected_text: Option<String>,
}

fn parse_select_result(value: Option<serde_json::Value>) -> Result<SelectParseResult> {
    let mut result_json = decode_action_result(
        value,
        serde_json::json!({
            "success": false,
            "code": "target_detached",
            "error": "Element is no longer present"
        }),
    )?;
    promote_legacy_select_fields(&mut result_json);
    let result: RawSelectResult = serde_json::from_value(result_json)?;

    if result.success {
        Ok(SelectParseResult::Success(result.selected_text))
    } else {
        Ok(SelectParseResult::Failure {
            code: result.code.unwrap_or_else(|| "invalid_target".to_string()),
            error: result.error.unwrap_or_else(|| "Select failed".to_string()),
        })
    }
}

fn promote_legacy_select_fields(result_json: &mut serde_json::Value) {
    let Some(object) = result_json.as_object_mut() else {
        return;
    };

    if object.contains_key("selected_text") {
        return;
    }

    if let Some(selected_text) = object.remove("selectedText") {
        object.insert("selected_text".to_string(), selected_text);
    }
}

fn select_actionability_predicates() -> &'static [ActionabilityPredicate] {
    &[
        ActionabilityPredicate::Present,
        ActionabilityPredicate::Visible,
        ActionabilityPredicate::Enabled,
        ActionabilityPredicate::Stable,
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use schemars::schema_for;
    use serde_json::json;

    #[test]
    fn test_select_params_deserializes_strict_target() {
        let json = serde_json::json!({
            "target": {
                "kind": "selector",
                "selector": "#country-select"
            },
            "value": "us"
        });

        let params: SelectParams = serde_json::from_value(json).unwrap();
        assert_eq!(params.selector, Some("#country-select".to_string()));
        assert_eq!(params.index, None);
        assert_eq!(params.value, "us");
    }

    #[test]
    fn test_select_params_deserializes_plain_string_target() {
        let json = serde_json::json!({
            "target": "#country-select",
            "value": "us"
        });

        let params: SelectParams = serde_json::from_value(json).unwrap();
        assert_eq!(params.selector, Some("#country-select".to_string()));
        assert_eq!(params.index, None);
        assert_eq!(params.value, "us");
    }

    #[test]
    fn test_select_params_rejects_legacy_public_target_fields() {
        let error = serde_json::from_value::<SelectParams>(json!({
            "selector": "#country-select",
            "value": "us"
        }))
        .expect_err("legacy selector field should be rejected");
        assert!(error.to_string().contains("unknown field `selector`"));

        let schema = schema_for!(SelectParams);
        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("select params schema should expose properties");
        assert!(properties.contains_key("target"));
        assert!(!properties.contains_key("selector"));
        assert!(!properties.contains_key("index"));
        assert!(!properties.contains_key("node_ref"));
        assert!(!properties.contains_key("cursor"));
    }

    #[test]
    fn test_parse_select_result_success() {
        let result = parse_select_result(Some(serde_json::Value::String(
            r#"{"success":true,"selected_text":"United Kingdom"}"#.to_string(),
        )))
        .expect("select result should parse");

        match result {
            SelectParseResult::Success(selected_text) => {
                assert_eq!(selected_text.as_deref(), Some("United Kingdom"));
            }
            SelectParseResult::Failure { error, .. } => panic!("unexpected failure: {error}"),
        }
    }

    #[test]
    fn test_parse_select_result_failure_uses_code_and_error() {
        let result = parse_select_result(Some(serde_json::json!({
            "success": false,
            "code": "invalid_target",
            "error": "Element is not a SELECT element"
        })))
        .expect("select result should parse");

        match result {
            SelectParseResult::Failure { code, error } => {
                assert_eq!(code, "invalid_target");
                assert_eq!(error, "Element is not a SELECT element");
            }
            SelectParseResult::Success(_) => panic!("expected failure"),
        }
    }

    #[test]
    fn test_decode_tool_result_json_rejects_invalid_json_string() {
        let error = decode_action_result(
            Some(serde_json::Value::String("not-json".to_string())),
            serde_json::json!({}),
        )
        .expect_err("invalid JSON should fail");

        assert!(matches!(error, BrowserError::JsonError(_)));
    }

    #[test]
    fn test_select_js_prefers_selector_before_target_index() {
        let select_js = build_select_js(&serde_json::json!({
            "selector": "#country-select",
            "target_index": 5,
            "value": "us",
        }));

        assert!(select_js.contains("function resolveTargetMatch(config, options)"));
        assert!(select_js.contains("const element = resolveTargetElement(config);"));
        assert!(select_js.contains("querySelectorAcrossScopes("));
        assert!(select_js.contains("searchActionableIndex(config.target_index)"));
    }
}