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
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
//! Companion-only TUI tool domain co-hosted with [`SharedTuiState`].
//!
//! These tools coordinate selection, attention, and semantic render views for the
//! terminal UI. They are never registered on standard [`crate::tools::ToolRegistry`]
//! defaults; the TUI companion binds them with shared state. Without co-hosted
//! state, calls return [`unavailable`].

use crate::error::Result;
use crate::tools::{Tool, ToolContext, ToolDescriptor, ToolResult, ToolSafetyAnnotations};
use crate::tui::{CoordinationError, SharedTuiState};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Shared parameter envelope for all companion TUI tools.
///
/// Fields are interpreted per tool name: selection/attention updates require
/// `semantic_ref`; render/inspect/query honor `limit`; attention set may carry
/// `message`. No field chooses arbitrary filesystem paths.
#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
pub struct TuiParams {
    /// Exact opaque semantic reference for selection/attention updates.
    pub semantic_ref: Option<String>,
    /// Optional bounded message for agent attention (never mutates Chrome).
    pub message: Option<String>,
    /// Character budget for render/outline payloads (defaults applied in [`execute`]).
    pub limit: Option<usize>,
}

/// Wire result for companion TUI tools: availability flag plus exclusive data or error.
///
/// Success always sets `available = true` and `data`; failures set `available = false`
/// and `error` without a `data` payload so clients need not inspect content shape.
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct TuiResult {
    /// Whether the companion runtime handled the request (false when TUI is not co-hosted).
    pub available: bool,
    /// Typed success payload when `available` is true and the tool succeeded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<TuiData>,
    /// Failure reason when the companion is unavailable or the tool failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Typed success payloads for the companion-only TUI tools.
///
/// A successful result always carries `data`; `error` is reserved for failed
/// requests so MCP clients do not have to infer success from an error-shaped
/// field containing page content.
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TuiData {
    /// Rendered semantic content (markdown/outline/debug text).
    Content {
        /// Bounded rendered text for the requested view.
        content: String,
    },
    /// Current human selection as an exact `semantic_ref`, if any.
    Selection {
        /// Selected component ref, or `None` when nothing is selected.
        semantic_ref: Option<String>,
    },
    /// Agent attention pointer and optional message (Chrome is not mutated).
    Attention {
        /// Attention target ref, or `None` when attention is cleared.
        semantic_ref: Option<String>,
        /// Document id the attention was last bound to.
        document_id: Option<String>,
        /// Document revision the attention was last bound to.
        revision: Option<String>,
        /// Optional agent-facing message (bounded, never written to the page).
        message: Option<String>,
    },
    /// Successful recapture identity after `tui_refresh`.
    Refresh {
        /// New document id after capture.
        document_id: String,
        /// New document revision after capture.
        revision: String,
        /// Page URL after capture.
        url: String,
        /// Page title after capture.
        title: String,
    },
    /// Mutation/coordination request accepted with no additional payload.
    Acknowledged,
}

/// Frozen companion tool names; must stay out of default/operator MCP registries.
pub const NAMES: [&str; 8] = [
    "tui_render",
    "tui_refresh",
    "tui_inspect",
    "tui_selection_read",
    "tui_selection_update",
    "tui_attention_read",
    "tui_attention_set",
    "tui_attention_clear",
];

/// MCP descriptors for the companion tool set (shared schemas, per-name safety hints).
///
/// Mutation-ish tools (`tui_refresh`, `*_update`, `*_set`, `*_clear`) clear the
/// read-only hint; none are marked destructive or open-world.
pub fn descriptors() -> Vec<ToolDescriptor> {
    NAMES
        .iter()
        .map(|name| ToolDescriptor {
            name: (*name).into(),
            description: "Shared TUI coordination operation".into(),
            parameters_schema: serde_json::to_value(schemars::schema_for!(TuiParams)).unwrap(),
            output_schema: serde_json::to_value(schemars::schema_for!(TuiResult)).unwrap(),
            annotations: ToolSafetyAnnotations {
                read_only_hint: *name != "tui_refresh"
                    && !name.ends_with("_set")
                    && !name.ends_with("_clear")
                    && !name.ends_with("_update"),
                destructive_hint: false,
                idempotent_hint: true,
                open_world_hint: false,
            },
        })
        .collect()
}

/// Dispatch a companion tool against co-hosted [`SharedTuiState`].
///
/// Reads selection/attention without touching Chrome. `tui_refresh` re-pulls the
/// current page into the semantic document. Unknown names return [`unavailable`].
pub fn execute(name: &str, params: TuiParams, shared: &SharedTuiState) -> TuiResult {
    match name {
        "tui_render" => match shared.render(params.limit.unwrap_or(32_000)) {
            Ok(content) => success(TuiData::Content { content }),
            Err(error) => failure(error),
        },
        // Browser mutation and its result are owned by PageCoordinator in the
        // companion handler. Direct storage-only execution is unavailable.
        "tui_refresh" => failure(CoordinationError::RuntimeRequired),
        "tui_inspect" => match shared.outline(params.limit.unwrap_or(32_000)) {
            Ok(content) => success(TuiData::Content { content }),
            Err(error) => failure(error),
        },
        "tui_selection_read" => success(TuiData::Selection {
            semantic_ref: shared.selection().map(|r| r.to_string()),
        }),
        "tui_selection_update" => params
            .semantic_ref
            .ok_or(CoordinationError::MalformedReference)
            .map(crate::semantic::SemanticRef::from_opaque)
            .and_then(|r| shared.set_selection(r))
            .map(|_| success(TuiData::Acknowledged))
            .unwrap_or_else(failure),
        "tui_attention_read" => {
            let attention = shared.attention();
            success(TuiData::Attention {
                semantic_ref: attention.semantic_ref.map(|r| r.to_string()),
                document_id: attention.document_id,
                revision: attention.revision,
                message: attention.message,
            })
        }
        "tui_attention_set" => params
            .semantic_ref
            .ok_or(CoordinationError::MalformedReference)
            .map(crate::semantic::SemanticRef::from_opaque)
            .and_then(|reference| shared.set_attention(reference, params.message.clone()))
            .map(|_| success(TuiData::Acknowledged))
            .unwrap_or_else(failure),
        "tui_attention_clear" => {
            shared.clear_attention();
            success(TuiData::Acknowledged)
        }
        _ => unavailable(),
    }
}

fn success(data: TuiData) -> TuiResult {
    TuiResult {
        available: true,
        data: Some(data),
        error: None,
    }
}

fn failure(error: impl std::fmt::Display) -> TuiResult {
    TuiResult {
        available: false,
        data: None,
        error: Some(error.to_string()),
    }
}

/// Result when the companion runtime is not co-hosted (no [`SharedTuiState`]).
///
/// Sets `available = false` and a stable error string; never panics.
pub fn unavailable() -> TuiResult {
    TuiResult {
        available: false,
        data: None,
        error: Some(
            "runtime-required: co-hosted TUI transport is not enabled in this foundation slice"
                .into(),
        ),
    }
}

/// [`Tool`] adapter for one companion TUI name, optionally bound to [`SharedTuiState`].
///
/// Without shared state, [`Tool::execute_typed`] still returns a successful outer
/// [`ToolResult`] whose payload is [`unavailable`] so MCP clients see a structured
/// companion-domain error rather than a hard tool failure.
#[derive(Clone)]
pub struct TuiTool {
    name: &'static str,
    shared: Option<SharedTuiState>,
}

impl TuiTool {
    /// Unbound companion tool; execution yields [`unavailable`] until shared state is attached.
    pub const fn new(name: &'static str) -> Self {
        Self { name, shared: None }
    }

    /// Companion tool bound to the co-hosted TUI coordination state.
    pub fn with_shared(name: &'static str, shared: SharedTuiState) -> Self {
        Self {
            name,
            shared: Some(shared),
        }
    }
}

impl Default for TuiTool {
    fn default() -> Self {
        Self::new(NAMES[0])
    }
}

impl Tool for TuiTool {
    type Params = TuiParams;
    type Output = TuiResult;

    fn name(&self) -> &str {
        self.name
    }

    fn description(&self) -> &str {
        "Shared TUI coordination operation"
    }

    fn parameters_schema(&self) -> Value {
        serde_json::to_value(schemars::schema_for!(TuiParams)).unwrap()
    }

    fn output_schema(&self) -> Value {
        serde_json::to_value(schemars::schema_for!(TuiResult)).unwrap()
    }

    /// Run against shared TUI state when bound; otherwise return [`unavailable`] as payload.
    ///
    /// Ignores browser [`ToolContext`]—companion tools coordinate TUI state, not CDP actions.
    ///
    /// # Errors
    ///
    /// This path does not return `Err`; companion failures are encoded inside [`TuiResult`].
    fn execute_typed(&self, params: TuiParams, _context: &mut ToolContext) -> Result<ToolResult> {
        let result = self
            .shared
            .as_ref()
            .map(|s| execute(self.name, params, s))
            .unwrap_or_else(unavailable);
        Ok(ToolResult::success_with(result))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browser::BrowserSession;
    use crate::browser::backend::FakeSessionBackend;
    use crate::dom::DocumentMetadata;
    use crate::semantic::SemanticDocument;
    use std::sync::Arc;

    fn document(revision: &str) -> SemanticDocument {
        SemanticDocument::empty(DocumentMetadata {
            document_id: "fake-tab".into(),
            revision: revision.into(),
            url: "https://example.test/".into(),
            title: "Example".into(),
            ready_state: "complete".into(),
            frames: vec![],
        })
        .expect("semantic document")
    }

    #[test]
    fn successful_render_is_typed_data_without_error_field() {
        let shared = SharedTuiState::new();
        shared.publish(document("one"));

        let result = execute("tui_render", TuiParams::default(), &shared);
        assert!(result.available);
        assert!(matches!(result.data, Some(TuiData::Content { .. })));
        assert!(result.error.is_none());
        let encoded = serde_json::to_value(result).expect("serialize result");
        assert!(encoded.get("data").is_some());
        assert!(encoded.get("error").is_none());
    }

    #[test]
    fn failed_render_has_only_error_shape() {
        let shared = SharedTuiState::new();

        let result = execute("tui_render", TuiParams::default(), &shared);
        assert!(!result.available);
        assert!(result.data.is_none());
        assert!(result.error.is_some());
        let encoded = serde_json::to_value(result).expect("serialize result");
        assert!(encoded.get("data").is_none());
        assert!(encoded.get("error").is_some());
    }

    #[test]
    fn shared_tool_calls_observe_the_published_state() {
        use crate::semantic::normalize::{RawSemanticNode, normalize_fixture};

        let shared = SharedTuiState::new();
        let doc = normalize_fixture(
            DocumentMetadata {
                document_id: "fake-tab".into(),
                revision: "shared-revision".into(),
                url: "https://example.test/".into(),
                title: "Example".into(),
                ready_state: "complete".into(),
                frames: vec![],
            },
            vec![RawSemanticNode {
                kind: "text".into(),
                tag: Some("p".into()),
                id: Some("spotlight".into()),
                unique_id: true,
                selector: None,
                text: Some("hello".into()),
                href: None,
                landmark: None,
                heading_level: None,
                ordered: None,
                label: None,
                src: None,
                alt: None,
                name: None,
                value: None,
                input_type: None,
                placeholder: None,
                checked: None,
                disabled: None,
                required: None,
                readonly: None,
                multiple: None,
                button_type: None,
                options: vec![],
                children: vec![],
            }],
        )
        .expect("doc");
        let reference = doc.semantic_refs().into_iter().next().unwrap();
        shared.publish(doc);
        shared
            .set_attention(reference.clone(), Some("agent focus".into()))
            .expect("attention");

        let render = execute("tui_render", TuiParams::default(), &shared);
        assert!(matches!(render.data, Some(TuiData::Content { .. })));
        let attention = execute("tui_attention_read", TuiParams::default(), &shared);
        assert!(matches!(
            attention.data,
            Some(TuiData::Attention {
                semantic_ref: Some(ref token),
                message: Some(ref message),
                ..
            }) if token == reference.as_str() && message == "agent focus"
        ));
    }

    #[test]
    fn attention_set_rejects_stale_and_requires_exact_ref() {
        use crate::semantic::normalize::{RawSemanticNode, normalize_fixture};

        let shared = SharedTuiState::new();
        let doc = normalize_fixture(
            DocumentMetadata {
                document_id: "fake-tab".into(),
                revision: "one".into(),
                url: "https://example.test/".into(),
                title: "Example".into(),
                ready_state: "complete".into(),
                frames: vec![],
            },
            vec![RawSemanticNode {
                kind: "text".into(),
                tag: Some("p".into()),
                id: Some("spotlight".into()),
                unique_id: true,
                selector: None,
                text: Some("hello".into()),
                href: None,
                landmark: None,
                heading_level: None,
                ordered: None,
                label: None,
                src: None,
                alt: None,
                name: None,
                value: None,
                input_type: None,
                placeholder: None,
                checked: None,
                disabled: None,
                required: None,
                readonly: None,
                multiple: None,
                button_type: None,
                options: vec![],
                children: vec![],
            }],
        )
        .expect("doc");
        let reference = doc.semantic_refs().into_iter().next().unwrap();
        shared.publish(doc);

        let missing = execute("tui_attention_set", TuiParams::default(), &shared);
        assert!(!missing.available);

        let stale = execute(
            "tui_attention_set",
            TuiParams {
                semantic_ref: Some("not-a-ref".into()),
                ..TuiParams::default()
            },
            &shared,
        );
        assert!(!stale.available);

        let ok = execute(
            "tui_attention_set",
            TuiParams {
                semantic_ref: Some(reference.to_string()),
                message: Some("focus".into()),
                ..TuiParams::default()
            },
            &shared,
        );
        assert!(ok.available);
        assert_eq!(shared.attention().semantic_ref.as_ref(), Some(&reference));
    }

    #[test]
    fn refresh_requires_the_active_companion_runtime() {
        let shared = SharedTuiState::new();

        let result = execute("tui_refresh", TuiParams::default(), &shared);
        assert!(!result.available);
        assert_eq!(
            result.error.as_deref(),
            Some("active TUI runtime is required")
        );
    }

    #[test]
    fn direct_registered_refresh_cannot_bypass_page_coordinator() {
        let shared = SharedTuiState::new();
        shared.activate_runtime();
        let mut session = BrowserSession::with_test_backend(FakeSessionBackend::new());
        session
            .tool_registry_mut()
            .register(TuiTool::with_shared("tui_refresh", shared));
        let before = session
            .extract_semantic_document()
            .expect("initial capture")
            .document
            .revision;

        let result = session
            .execute_tool("tui_refresh", serde_json::json!({}))
            .expect("structured runtime-required result");

        assert!(result.success);
        assert_eq!(
            result
                .data
                .as_ref()
                .and_then(|data| data["available"].as_bool()),
            Some(false)
        );
        assert_eq!(
            session
                .extract_semantic_document()
                .expect("capture after rejected refresh")
                .document
                .revision,
            before,
            "direct tool execution must not reload Chrome"
        );
    }

    #[test]
    fn refresh_reloads_and_publishes_a_fresh_semantic_revision() {
        let shared = SharedTuiState::new();
        shared.activate_runtime();
        let coordinator = crate::tui::PageCoordinator::new(
            Arc::new(BrowserSession::with_test_backend(FakeSessionBackend::new())),
            shared.clone(),
        );
        let result = coordinator.refresh().expect("refresh");
        assert_eq!(result.revision, "fake:2");
        assert_eq!(
            shared
                .active()
                .expect("published document")
                .document
                .revision,
            "fake:2"
        );
        assert!(shared.lifecycle().is_ready());
    }
}