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
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! rmcp `ServerHandler` that dispatches registered browser tools on a shared session.
//!
//! Tools share one [`BrowserSession`] lifecycle. Companion builds
//! (`from_companion`) also expose the bounded TUI resource catalog; standard
//! stdio/`serve` servers stay tools-only even when the `tui` feature is compiled.

use crate::browser::{BrowserSession, ConnectionOptions};
use crate::mcp::{convert_result, mcp_internal_error};
use crate::tools::ToolDescriptor;
#[cfg(feature = "tui")]
use crate::tools::ToolEffect;
use log::debug;
use rmcp::{
    ErrorData as McpError, RoleServer, ServerHandler,
    model::{
        CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams,
        ServerCapabilities, ServerInfo, Tool as McpTool, ToolAnnotations as McpToolAnnotations,
    },
    service::RequestContext,
};
use std::future;
use std::sync::Arc;

#[cfg(feature = "tui")]
use crate::tools::ToolResult as InternalToolResult;
#[cfg(feature = "tui")]
use crate::tui::{FinalizeOutcome, PageCoordinator, SharedTuiState};
#[cfg(feature = "tui")]
use rmcp::model::{
    ListResourceTemplatesResult, ListResourcesResult, ReadResourceRequestParams, ReadResourceResult,
};

/// Shared-session MCP server that dispatches registered browser tools via rmcp.
///
/// Implements `ServerHandler` for tool list/call. Tool-local failures map to
/// structured `CallToolResult` errors (preserving document, target, recovery);
/// infrastructure failures map to MCP internal errors. With the `tokio` feature,
/// tool work runs on a blocking pool so the async handler stays free.
///
/// Resource capability and the semantic catalog are available only on the
/// co-hosted TUI companion (`from_companion`). Standard stdio/serve servers
/// remain tools-only even when compiled with `feature = "tui"`.
#[derive(Clone)]
pub struct BrowserServer {
    session: Arc<BrowserSession>,
    #[cfg(feature = "tui")]
    coordinator: Option<Arc<PageCoordinator>>,
}

impl BrowserServer {
    /// Wrap an existing session so MCP tools share one browser lifecycle.
    pub fn from_session(session: BrowserSession) -> Self {
        Self {
            session: Arc::new(session),
            #[cfg(feature = "tui")]
            coordinator: None,
        }
    }

    /// Wrap an already-shared session (tools-only; no companion resource catalog).
    pub fn from_shared_session(session: Arc<BrowserSession>) -> Self {
        Self {
            session,
            #[cfg(feature = "tui")]
            coordinator: None,
        }
    }

    /// Co-hosted companion server over the TUI's shared session and coordination state.
    #[cfg(feature = "tui")]
    pub fn from_companion(coordinator: Arc<PageCoordinator>) -> Self {
        Self {
            session: coordinator.session().clone(),
            coordinator: Some(coordinator),
        }
    }

    /// Launch a browser with default options and expose it as an MCP server.
    pub fn new() -> Result<Self, String> {
        let session =
            BrowserSession::new().map_err(|e| format!("Failed to launch browser: {}", e))?;

        Ok(Self::from_session(session))
    }

    /// Launch with explicit options (headless, executable path, profile, port).
    pub fn with_options(options: crate::browser::LaunchOptions) -> Result<Self, String> {
        let session = BrowserSession::launch(options)
            .map_err(|e| format!("Failed to launch browser: {}", e))?;

        Ok(Self::from_session(session))
    }

    /// Attach to an existing DevTools / WebSocket endpoint as an MCP server.
    pub fn connect(options: ConnectionOptions) -> Result<Self, String> {
        let session = BrowserSession::connect(options)
            .map_err(|e| format!("Failed to connect browser session: {}", e))?;

        Ok(Self::from_session(session))
    }

    /// Borrow the shared browser session used for tool dispatch.
    pub(crate) fn session(&self) -> &BrowserSession {
        self.session.as_ref()
    }

    /// Advertise registered tools as rmcp descriptors (schemas + safety annotations).
    pub(crate) fn list_mcp_tools(&self) -> Vec<McpTool> {
        self.session()
            .tool_registry()
            .descriptors()
            .into_iter()
            .map(tool_descriptor_to_mcp)
            .collect()
    }

    /// Run one tool call on the shared session and map the outcome to `CallToolResult`.
    ///
    /// Tool-local failures stay structured success/error content; only registry or
    /// conversion infrastructure issues become MCP internal errors.
    pub(crate) fn execute_tool_sync(
        &self,
        request: CallToolRequestParams,
    ) -> Result<CallToolResult, McpError> {
        #[cfg(feature = "tui")]
        if let Some(coordinator) = &self.coordinator {
            if request.name.as_ref() == "tui_refresh" {
                let result = match coordinator.refresh() {
                    Ok(page) => crate::tools::tui::TuiResult {
                        available: true,
                        data: Some(crate::tools::tui::TuiData::Refresh {
                            document_id: page.document_id,
                            revision: page.revision,
                            url: page.url,
                            title: page.title,
                        }),
                        error: None,
                    },
                    Err(error) => crate::tools::tui::TuiResult {
                        available: false,
                        data: None,
                        error: Some(error.to_string()),
                    },
                };
                return convert_result(InternalToolResult::success_with(result));
            }
            if self.session().tool_registry().effect(request.name.as_ref())
                == ToolEffect::BrowserMutation
            {
                // Companion page mutators own the same Loading → capture → Ready|Error
                // lifecycle as terminal actions and tui_refresh.
                return execute_companion_page_mutation(coordinator, request);
            }
        }

        let mut context = crate::tools::ToolContext::new(self.session());
        let params = request
            .arguments
            .map(serde_json::Value::Object)
            .unwrap_or_else(|| serde_json::json!({}));

        match self
            .session()
            .tool_registry()
            .execute(request.name.as_ref(), params, &mut context)
        {
            Ok(result) => convert_result(result),
            Err(error) => Err(mcp_internal_error(error)),
        }
    }

    #[cfg(feature = "tui")]
    fn companion_shared(&self) -> Option<&SharedTuiState> {
        self.coordinator.as_ref().map(|c| c.shared())
    }
}

/// Run a companion page mutation under the shared Loading lifecycle, then
/// settle/capture/publish Ready or Error with the last valid document retained.
#[cfg(feature = "tui")]
fn execute_companion_page_mutation(
    coordinator: &PageCoordinator,
    request: CallToolRequestParams,
) -> Result<CallToolResult, McpError> {
    let action = request.name.to_string();
    let transaction = match coordinator.begin_companion(&action) {
        Ok(transaction) => transaction,
        Err(error) => return convert_result(InternalToolResult::failure(error.to_string())),
    };
    let ticket = transaction.ticket();
    let session = coordinator.session().as_ref();

    let mut context = crate::tools::ToolContext::new(session);
    let params = request
        .arguments
        .map(serde_json::Value::Object)
        .unwrap_or_else(|| serde_json::json!({}));

    match session
        .tool_registry()
        .execute(request.name.as_ref(), params, &mut context)
    {
        Ok(result) if result.success => {
            match coordinator.finalize_browser_mutation(ticket, &action) {
                Ok(FinalizeOutcome::Published(_)) => {}
                Err(error) => {
                    return convert_result(InternalToolResult::failure(error.to_string()));
                }
            }
            convert_result(result)
        }
        Ok(result) => {
            let message = result
                .error
                .clone()
                .unwrap_or_else(|| format!("{action} failed"));
            let _ = coordinator.fail(ticket, &action, message);
            convert_result(result)
        }
        Err(error) => {
            let _ = coordinator.fail(ticket, &action, error.to_string());
            Err(mcp_internal_error(error))
        }
    }
}

#[cfg(feature = "tokio")]
fn join_blocking_tool_result(
    result: std::result::Result<Result<CallToolResult, McpError>, tokio::task::JoinError>,
) -> Result<CallToolResult, McpError> {
    match result {
        Ok(result) => result,
        Err(error) => Err(mcp_internal_error(error)),
    }
}

fn tool_descriptor_to_mcp(descriptor: ToolDescriptor) -> McpTool {
    let ToolDescriptor {
        name,
        description,
        parameters_schema,
        output_schema,
        annotations,
    } = descriptor;

    let input_schema = match parameters_schema {
        serde_json::Value::Object(object) => object,
        _ => serde_json::Map::new(),
    };
    let output_schema = match output_schema {
        serde_json::Value::Object(object) => Some(Arc::new(object)),
        _ => None,
    };

    let mut tool = McpTool::new(name, description, Arc::new(input_schema));
    tool.output_schema = output_schema;
    tool.annotations = Some(McpToolAnnotations::from_raw(
        None,
        Some(annotations.read_only_hint),
        Some(annotations.destructive_hint),
        Some(annotations.idempotent_hint),
        Some(annotations.open_world_hint),
    ));
    tool
}

impl Drop for BrowserServer {
    fn drop(&mut self) {
        debug!("BrowserServer dropped");
    }
}

impl ServerHandler for BrowserServer {
    fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<CallToolResult, McpError>> + Send + '_ {
        #[cfg(feature = "tokio")]
        {
            let server = self.clone();
            #[cfg(feature = "tui")]
            let companion_request = server
                .coordinator
                .as_ref()
                .map(|coordinator| coordinator.begin_companion_request());
            async move {
                #[cfg(feature = "tui")]
                let companion_request = match companion_request {
                    Some(Some(request)) => Some(request),
                    Some(None) => return Err(mcp_internal_error("TUI companion is shutting down")),
                    None => None,
                };
                join_blocking_tool_result(
                    tokio::task::spawn_blocking(move || {
                        #[cfg(feature = "tui")]
                        let _companion_request = companion_request;
                        server.execute_tool_sync(request)
                    })
                    .await,
                )
            }
        }

        #[cfg(not(feature = "tokio"))]
        {
            future::ready(self.execute_tool_sync(request))
        }
    }

    fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + Send + '_ {
        future::ready(Ok(ListToolsResult::with_all_items(self.list_mcp_tools())))
    }

    #[cfg(feature = "tui")]
    fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ {
        future::ready(Ok(match self.companion_shared() {
            Some(shared) => crate::mcp::resources::list_resources(shared),
            None => ListResourcesResult::default(),
        }))
    }

    #[cfg(feature = "tui")]
    fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourceTemplatesResult, McpError>> + Send + '_
    {
        future::ready(Ok(match self.companion_shared() {
            Some(_) => crate::mcp::resources::resource_templates(),
            None => ListResourceTemplatesResult::default(),
        }))
    }

    #[cfg(feature = "tui")]
    fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ReadResourceResult, McpError>> + Send + '_ {
        future::ready(match self.companion_shared() {
            Some(shared) => {
                crate::mcp::resources::read_resource(shared, &request.uri).map_err(|error| {
                    match error {
                        crate::mcp::resources::ResourceError::MalformedUri => {
                            McpError::invalid_params(error.to_string(), None)
                        }
                        crate::mcp::resources::ResourceError::NotFound
                        | crate::mcp::resources::ResourceError::Coordination(_)
                        | crate::mcp::resources::ResourceError::Render(_) => {
                            McpError::resource_not_found(error.to_string(), None)
                        }
                    }
                })
            }
            None => Err(McpError::method_not_found::<
                rmcp::model::ReadResourceRequestMethod,
            >()),
        })
    }

    fn get_info(&self) -> ServerInfo {
        self.server_info()
    }
}

fn server_info() -> ServerInfo {
    ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
        .with_instructions("chromewright MCP server")
}

impl BrowserServer {
    fn server_info(&self) -> ServerInfo {
        #[cfg(feature = "tui")]
        if self.coordinator.is_some() {
            return ServerInfo::new(
                ServerCapabilities::builder()
                    .enable_tools()
                    .enable_resources()
                    .build(),
            )
            .with_instructions(
                "chromewright TUI companion MCP server (shared session, tui_* tools, semantic resources)",
            );
        }

        server_info()
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "tokio")]
    use super::join_blocking_tool_result;
    use super::{BrowserServer, server_info};
    use crate::browser::BrowserSession;
    use crate::browser::backend::FakeSessionBackend;
    use rmcp::model::CallToolRequestParams;
    #[cfg(feature = "tokio")]
    use serde_json::json;

    fn call_tool_request(
        name: &'static str,
        arguments: Option<serde_json::Map<String, serde_json::Value>>,
    ) -> CallToolRequestParams {
        let request = CallToolRequestParams::new(name);
        if let Some(arguments) = arguments {
            request.with_arguments(arguments)
        } else {
            request
        }
    }

    #[test]
    fn test_server_info_enables_tools_and_instructions() {
        let info = server_info();

        assert!(
            info.instructions
                .as_deref()
                .unwrap_or_default()
                .contains("chromewright MCP server")
        );
        assert!(info.capabilities.tools.is_some());
        assert!(
            info.capabilities.resources.is_none(),
            "standard stdio/serve servers must not advertise resources"
        );
    }

    #[cfg(feature = "tui")]
    #[test]
    fn tui_companion_server_info_enables_resources_while_stdio_does_not() {
        use crate::tui::SharedTuiState;
        use rmcp::ServerHandler;
        use std::sync::Arc;

        let session = Arc::new(BrowserSession::with_test_backend(FakeSessionBackend::new()));
        let shared = SharedTuiState::new();
        let companion = BrowserServer::from_companion(Arc::new(crate::tui::PageCoordinator::new(
            session.clone(),
            shared,
        )));
        assert!(companion.get_info().capabilities.resources.is_some());

        let stdio = BrowserServer::from_shared_session(session);
        assert!(stdio.get_info().capabilities.resources.is_none());
    }

    #[cfg(feature = "tui")]
    #[test]
    fn tui_companion_rejects_page_actions_while_loading() {
        use crate::tui::SharedTuiState;
        use std::sync::Arc;

        let session = Arc::new(BrowserSession::with_test_backend(FakeSessionBackend::new()));
        let shared = SharedTuiState::new();
        shared.activate_runtime();
        shared.begin_page_action("navigate").expect("claim loading");
        let server = BrowserServer::from_companion(Arc::new(crate::tui::PageCoordinator::new(
            session, shared,
        )));
        let result = server
            .execute_tool_sync(call_tool_request("navigate", None))
            .expect("tool-local rejection");
        assert_eq!(result.is_error, Some(true));
        let message = result
            .structured_content
            .as_ref()
            .and_then(|content| content.get("error"))
            .and_then(|error| error.as_str())
            .unwrap_or_default();
        assert!(
            message.contains("already in progress"),
            "unexpected rejection message: {message}"
        );
    }

    #[cfg(feature = "tui")]
    #[test]
    fn tui_companion_page_mutation_publishes_loading_to_ready_atomically() {
        use crate::tui::{Lifecycle, SharedTuiState};
        use serde_json::json;
        use std::sync::Arc;

        let session = Arc::new(BrowserSession::with_test_backend(FakeSessionBackend::new()));
        let shared = SharedTuiState::new();
        shared.activate_runtime();
        // Seed a known document so resources can observe retention across the mutation.
        let before = session.extract_semantic_document().expect("seed capture");
        shared.publish(before);
        let prior_revision = shared.active().unwrap().document.revision.clone();

        let server = BrowserServer::from_companion(Arc::new(crate::tui::PageCoordinator::new(
            session,
            shared.clone(),
        )));
        let mut args = serde_json::Map::new();
        args.insert("url".into(), json!("https://example.test/next"));
        let result = server
            .execute_tool_sync(call_tool_request("navigate", Some(args)))
            .expect("navigate");
        assert_eq!(result.is_error, Some(false));
        assert!(shared.lifecycle().is_ready());
        let after = shared.active().expect("published after navigate");
        assert_ne!(after.document.revision, prior_revision);
        assert_eq!(after.document.url, "https://example.test/next");
        // Concurrent mutation while ready is fine; while loading is rejected above.
        assert!(matches!(shared.lifecycle(), Lifecycle::Ready));
    }

    #[cfg(feature = "tui")]
    #[test]
    fn tui_refresh_failure_is_a_structured_domain_result() {
        use crate::tui::SharedTuiState;
        use std::sync::Arc;

        let shared = SharedTuiState::new();
        shared.activate_runtime();
        let session = Arc::new(BrowserSession::with_test_backend(FakeSessionBackend::new()));
        session.close_active_tab().expect("remove active tab");
        let server = BrowserServer::from_companion(Arc::new(crate::tui::PageCoordinator::new(
            session, shared,
        )));
        let result = server
            .execute_tool_sync(call_tool_request("tui_refresh", None))
            .expect("domain failure must not become an MCP error");
        assert_eq!(result.is_error, Some(false));
        let content = result.structured_content.expect("structured TUI result");
        assert_eq!(content.get("available"), Some(&serde_json::json!(false)));
        assert!(content.get("data").is_none());
        assert!(content.get("error").and_then(|v| v.as_str()).is_some());
    }

    #[cfg(feature = "tui")]
    #[test]
    fn deactivated_companion_mutation_is_rejected_before_browser_work() {
        use crate::tui::SharedTuiState;
        use std::sync::Arc;

        let shared = SharedTuiState::new();
        let session = Arc::new(BrowserSession::with_test_backend(FakeSessionBackend::new()));
        let initial_url = session.list_tabs().unwrap()[0].url.clone();
        let server = BrowserServer::from_companion(Arc::new(crate::tui::PageCoordinator::new(
            session.clone(),
            shared.clone(),
        )));
        let mut args = serde_json::Map::new();
        args.insert(
            "url".into(),
            serde_json::json!("https://example.test/blocked"),
        );
        let result = server
            .execute_tool_sync(call_tool_request("navigate", Some(args)))
            .expect("tool-local rejection");
        assert_eq!(result.is_error, Some(true));
        assert_eq!(session.list_tabs().unwrap()[0].url, initial_url);
        assert!(shared.lifecycle().is_ready());
    }

    #[cfg(feature = "tui")]
    #[test]
    fn companion_close_final_tab_preserves_refresh_failure_contract() {
        use crate::tui::SharedTuiState;
        use std::sync::Arc;

        let shared = SharedTuiState::new();
        shared.activate_runtime();
        let session = Arc::new(BrowserSession::with_test_backend(FakeSessionBackend::new()));
        shared.publish(session.extract_semantic_document().unwrap());
        let server = BrowserServer::from_companion(Arc::new(crate::tui::PageCoordinator::new(
            session,
            shared.clone(),
        )));
        let result = server
            .execute_tool_sync(call_tool_request("close_tab", None))
            .expect("close final tab");
        assert_eq!(result.is_error, Some(true));
        assert!(matches!(
            shared.lifecycle(),
            crate::tui::Lifecycle::Error { action, message }
                if action == "close_tab"
                    && message == crate::tui::CoordinationError::RefreshFailed.to_string()
        ));
        assert!(shared.active().is_ok(), "last valid document is retained");
        assert!(shared.selection().is_none());
        assert!(!shared.attention().is_set());
    }

    #[test]
    fn execute_tool_sync_converts_success_results() {
        let server = BrowserServer::from_session(BrowserSession::with_test_backend(
            FakeSessionBackend::new(),
        ));
        let result = server
            .execute_tool_sync(call_tool_request("tab_list", None))
            .expect("tab_list should execute");

        assert_eq!(result.is_error, Some(false));
        assert_eq!(
            result
                .structured_content
                .as_ref()
                .and_then(|content| content.get("count"))
                .and_then(|count| count.as_u64()),
            Some(1)
        );
    }

    #[test]
    fn execute_tool_sync_preserves_tool_local_failures() {
        let server = BrowserServer::from_session(BrowserSession::with_test_backend(
            FakeSessionBackend::new(),
        ));
        let result = server
            .execute_tool_sync(call_tool_request("missing_tool", None))
            .expect("tool-local failures should convert to CallToolResult");

        assert_eq!(result.is_error, Some(true));
        assert_eq!(
            result
                .structured_content
                .as_ref()
                .and_then(|content| content.get("code"))
                .and_then(|code| code.as_str()),
            Some("tool_error")
        );
    }

    #[test]
    fn list_mcp_tools_uses_metadata_without_tool_execution() {
        let server = BrowserServer::from_session(BrowserSession::with_test_backend(
            FakeSessionBackend::new(),
        ));
        let tools = server.list_mcp_tools();

        assert!(tools.iter().any(|tool| tool.name.as_ref() == "snapshot"));
    }

    #[cfg(feature = "tokio")]
    #[tokio::test]
    async fn blocking_join_failure_maps_to_internal_mcp_error() {
        let joined = tokio::task::spawn_blocking(|| {
            panic!("simulated blocking executor panic");
            #[allow(unreachable_code)]
            Ok(rmcp::model::CallToolResult::structured(json!({})))
        })
        .await;

        let error = join_blocking_tool_result(joined)
            .expect_err("blocking executor panic should map to MCP error");
        assert!(
            error
                .to_string()
                .contains("simulated blocking executor panic")
        );
    }
}