thoughtjack 0.6.0

Adversarial agent security testing tool
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use oatf::primitives::{interpolate_template, interpolate_value};
use serde_json::{Value, json};
use tokio::io::AsyncReadExt;
use tokio::process::{Child, ChildStderr};
use tokio::sync::{mpsc, watch};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

use crate::engine::driver::PhaseDriver;
use crate::engine::types::{Direction, DriveResult, ProtocolEvent};
use crate::error::EngineError;

use super::handler::{normalize_action, server_request_handler};
use super::multiplexer::MessageMultiplexer;
use super::transport::{
    McpClientTransportReader, McpClientTransportWriter, create_http_transport,
    spawn_stdio_transport,
};
use super::{
    CorrelatedResponse, DEFAULT_PHASE_TIMEOUT, DEFAULT_REQUEST_TIMEOUT, HANDLER_EVENT_BUFFER_SIZE,
    HandlerState, INIT_TIMEOUT, NOTIFICATION_BUFFER_SIZE, NotificationMessage,
    POST_ACTION_IDLE_TIMEOUT, PendingRequest, SERVER_REQUEST_BUFFER_SIZE,
};

// ============================================================================
// McpClientDriver
// ============================================================================

/// MCP client-mode protocol driver.
///
/// Connects to an MCP server, sends JSON-RPC requests, handles
/// server-initiated requests via a background handler task, and
/// emits protocol events for the `PhaseLoop`.
///
/// Implements: TJ-SPEC-018 F-004
pub struct McpClientDriver {
    /// Shared writer (driver + handler both write).
    pub(super) writer: Arc<tokio::sync::Mutex<Box<dyn McpClientTransportWriter>>>,
    /// Pending request map for response correlation.
    pub(super) pending: Arc<std::sync::Mutex<HashMap<String, PendingRequest>>>,
    /// Multiplexer (spawned on first `drive_phase()`).
    pub(super) mux: Option<MessageMultiplexer>,
    /// Notification receiver from multiplexer.
    pub(super) notification_rx: Option<mpsc::Receiver<NotificationMessage>>,
    /// Handler event receiver (handler emits events here, driver forwards to `PhaseLoop`).
    pub(super) handler_event_rx: Option<mpsc::Receiver<ProtocolEvent>>,
    /// Shared handler state.
    pub(super) handler_state: Arc<tokio::sync::RwLock<HandlerState>>,
    /// Handler task join handle.
    pub(super) handler_handle: Option<JoinHandle<()>>,
    /// Server capabilities (captured during init).
    pub(super) server_capabilities: Option<Value>,
    /// Negotiated protocol version from server init response.
    pub(super) negotiated_version: Option<String>,
    /// Per-request timeout.
    pub(super) request_timeout: std::time::Duration,
    /// Post-action event loop timeout.
    pub(super) phase_timeout: std::time::Duration,
    /// Whether initialization has completed.
    pub(super) initialized: bool,
    /// Next request ID counter.
    pub(super) next_request_id: u64,
    /// Bypass synthesize output validation.
    pub(super) raw_synthesize: bool,
    /// Transport reader (consumed on first `drive_phase()`).
    pub(super) reader: Option<Box<dyn McpClientTransportReader>>,
    /// Cancellation token for background tasks.
    pub(super) transport_cancel: CancellationToken,
    /// Spawned child process (for stdio transport).
    ///
    /// `spawn_stdio_transport` enables `kill_on_drop`, and `Drop` also
    /// proactively sends a kill signal for deterministic teardown.
    pub(super) child: Option<Child>,
    /// Stderr from spawned child (for diagnostics on exit).
    pub(super) child_stderr: Option<ChildStderr>,
}

impl McpClientDriver {
    fn cleanup_pending_request(&self, id_key: &str) {
        self.pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(id_key);
        if let Some(mux) = self.mux.as_ref() {
            mux.remove_response(id_key);
        }
    }

    /// Try to read buffered stderr from the child process.
    ///
    /// Consumes the stderr handle. Returns the output (truncated to 4 KB)
    /// or an empty string if no stderr is available.
    async fn capture_stderr(&mut self) -> String {
        let Some(mut stderr) = self.child_stderr.take() else {
            return String::new();
        };
        let mut buf = vec![0u8; 4096];
        match tokio::time::timeout(std::time::Duration::from_millis(100), stderr.read(&mut buf))
            .await
        {
            Ok(Ok(n)) if n > 0 => String::from_utf8_lossy(&buf[..n]).to_string(),
            _ => String::new(),
        }
    }

    /// Generate the next monotonically increasing request ID.
    pub(super) const fn next_id(&mut self) -> u64 {
        let id = self.next_request_id;
        self.next_request_id += 1;
        id
    }

    /// Send a JSON-RPC request and await its correlated response.
    ///
    /// Registers the oneshot channel BEFORE sending to prevent races.
    /// Server-initiated requests are handled concurrently by the
    /// multiplexer + handler while this method awaits.
    ///
    /// # Errors
    ///
    /// Returns `EngineError::Driver` on timeout or multiplexer close.
    async fn send_and_await(
        &mut self,
        method: &str,
        params: Option<Value>,
        event_tx: &mpsc::Sender<ProtocolEvent>,
    ) -> Result<CorrelatedResponse, EngineError> {
        let id = json!(self.next_id());
        let id_key = id.to_string();

        // Register pending request for correlation (includes params for qualifier resolution)
        self.pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(
                id_key.clone(),
                PendingRequest {
                    method: method.to_string(),
                    params: params.clone(),
                },
            );

        // Register response channel BEFORE sending (prevents race)
        let mux = self
            .mux
            .as_ref()
            .ok_or_else(|| EngineError::Driver("multiplexer not started".to_string()))?;
        let response_rx = mux.register_response(&id);

        // Send request
        match tokio::time::timeout(self.request_timeout, async {
            self.writer
                .lock()
                .await
                .send_request_with_id(method, params.clone(), &id)
                .await
        })
        .await
        {
            Ok(Ok(())) => {}
            Ok(Err(err)) => {
                self.cleanup_pending_request(&id_key);
                return Err(err);
            }
            Err(_) => {
                self.cleanup_pending_request(&id_key);
                return Err(EngineError::Driver(format!(
                    "request timeout while sending '{method}' after {:?}",
                    self.request_timeout
                )));
            }
        }

        // Emit outgoing event
        let _ = event_tx
            .send(ProtocolEvent {
                direction: Direction::Outgoing,
                method: method.to_string(),
                content: params.unwrap_or(Value::Null),
            })
            .await;

        // Await response via oneshot — multiplexer handles concurrent server requests
        let response = match tokio::time::timeout(self.request_timeout, response_rx).await {
            Ok(Ok(resp)) => resp,
            Ok(Err(_)) => {
                self.cleanup_pending_request(&id_key);
                let reason = mux.close_reason();
                let stderr = self.capture_stderr().await;
                let mut msg = format!("multiplexer closed while awaiting '{method}': {reason}");
                if !stderr.is_empty() {
                    use std::fmt::Write;
                    let _ = write!(msg, "\nserver stderr: {stderr}");
                }
                return Err(EngineError::Driver(msg));
            }
            Err(_) => {
                self.cleanup_pending_request(&id_key);
                return Err(EngineError::Driver(format!(
                    "request timeout for '{method}' after {:?}",
                    self.request_timeout
                )));
            }
        };

        // Emit incoming event.
        // Merge request params into response content so qualifier resolution
        // can access the original request context (e.g., tools/call:calculator
        // resolves from params.name). Request params are placed under
        // `_request` to avoid collisions with response fields.
        let mut content = response.result.clone();
        if let Some(ref req_params) = response.request_params
            && let Some(obj) = content.as_object_mut()
        {
            obj.insert("_request".to_string(), req_params.clone());
        }
        let _ = event_tx
            .send(ProtocolEvent {
                direction: Direction::Incoming,
                method: response.method.clone(),
                content,
            })
            .await;

        Ok(response)
    }

    /// Forward any buffered events from handler and notifications to the `PhaseLoop`.
    ///
    /// Called between actions to minimize event forwarding latency.
    pub(super) fn forward_pending_events(&mut self, event_tx: &mpsc::Sender<ProtocolEvent>) {
        if let Some(ref mut rx) = self.handler_event_rx {
            while let Ok(evt) = rx.try_recv() {
                let _ = event_tx.try_send(evt);
            }
        }
        if let Some(ref mut rx) = self.notification_rx {
            while let Ok(notif) = rx.try_recv() {
                let _ = event_tx.try_send(ProtocolEvent {
                    direction: Direction::Incoming,
                    method: notif.method,
                    content: notif.params.unwrap_or(Value::Null),
                });
            }
        }
    }

    /// Perform the MCP initialization handshake.
    ///
    /// Sends `initialize` request, captures server capabilities,
    /// sends `notifications/initialized` notification.
    ///
    /// # Errors
    ///
    /// Returns `EngineError::Driver` if initialization fails.
    ///
    /// Implements: TJ-SPEC-018 F-005
    #[allow(clippy::too_many_lines)]
    pub(super) async fn initialize(
        &mut self,
        state: &Value,
        event_tx: &mpsc::Sender<ProtocolEvent>,
    ) -> Result<(), EngineError> {
        let init_params = json!({
            "protocolVersion": "2025-11-25",
            "capabilities": build_client_capabilities(state),
            "clientInfo": {
                "name": "ThoughtJack",
                "version": env!("CARGO_PKG_VERSION"),
            }
        });

        let id = json!(self.next_id());
        let id_key = id.to_string();

        // Register pending request
        self.pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(
                id_key.clone(),
                PendingRequest {
                    method: "initialize".to_string(),
                    params: Some(init_params.clone()),
                },
            );

        // Register response channel BEFORE sending
        let mux = self
            .mux
            .as_ref()
            .ok_or_else(|| EngineError::Driver("multiplexer not started".to_string()))?;
        let response_rx = mux.register_response(&id);

        // Send initialize request
        match tokio::time::timeout(INIT_TIMEOUT, async {
            self.writer
                .lock()
                .await
                .send_request_with_id("initialize", Some(init_params.clone()), &id)
                .await
        })
        .await
        {
            Ok(Ok(())) => {}
            Ok(Err(err)) => {
                self.cleanup_pending_request(&id_key);
                return Err(err);
            }
            Err(_) => {
                self.cleanup_pending_request(&id_key);
                return Err(EngineError::Driver("initialization timeout".to_string()));
            }
        }

        // Emit outgoing event
        let _ = event_tx
            .send(ProtocolEvent {
                direction: Direction::Outgoing,
                method: "initialize".to_string(),
                content: init_params,
            })
            .await;

        // Await response
        let response = match tokio::time::timeout(INIT_TIMEOUT, response_rx).await {
            Ok(Ok(resp)) => resp,
            Ok(Err(_)) => {
                self.cleanup_pending_request(&id_key);
                let reason = mux.close_reason();
                let stderr = self.capture_stderr().await;
                let mut msg = format!("multiplexer closed during initialization: {reason}");
                if !stderr.is_empty() {
                    use std::fmt::Write;
                    let _ = write!(msg, "\nserver stderr: {stderr}");
                }
                return Err(EngineError::Driver(msg));
            }
            Err(_) => {
                self.cleanup_pending_request(&id_key);
                return Err(EngineError::Driver("initialization timeout".to_string()));
            }
        };

        // Check for error response (EC-MCPC-005)
        if response.is_error {
            return Err(EngineError::Driver(format!(
                "server rejected initialization: {}",
                response.result
            )));
        }

        // Capture server capabilities
        self.server_capabilities = Some(response.result.clone());

        // Extract negotiated protocol version and propagate to HTTP writer
        self.negotiated_version = response
            .result
            .get("protocolVersion")
            .and_then(Value::as_str)
            .map(String::from);
        let version = self
            .negotiated_version
            .clone()
            .unwrap_or_else(|| "2025-11-25".to_string());
        self.writer.lock().await.set_protocol_version(version).await;

        // Emit incoming event
        let _ = event_tx
            .send(ProtocolEvent {
                direction: Direction::Incoming,
                method: "initialize".to_string(),
                content: response.result,
            })
            .await;

        // Send initialized notification
        self.writer
            .lock()
            .await
            .send_notification("notifications/initialized", None)
            .await?;

        self.initialized = true;
        tracing::info!("MCP client initialization complete");

        Ok(())
    }

    /// Execute a single normalized action.
    ///
    /// # Errors
    ///
    /// Returns `EngineError::Driver` on request/response failure.
    ///
    /// Implements: TJ-SPEC-018 F-006
    #[allow(clippy::cognitive_complexity)]
    async fn execute_action(
        &mut self,
        action: &Value,
        extractors: &HashMap<String, String>,
        event_tx: &mpsc::Sender<ProtocolEvent>,
    ) -> Result<(), EngineError> {
        let action_type = action["type"].as_str().unwrap_or("");

        match action_type {
            "list_tools" => {
                self.send_and_await("tools/list", None, event_tx).await?;
            }
            "call_tool" => {
                let raw_name = action["name"].as_str().unwrap_or_default();
                let (name, name_diags) = interpolate_template(raw_name, extractors, None, None);
                if !name_diags.is_empty() {
                    tracing::warn!(raw_name, diagnostics = ?name_diags, "interpolation warnings in call_tool name");
                }
                let arguments = action.get("arguments").cloned().unwrap_or(json!({}));
                let (interpolated_args, args_diags) =
                    interpolate_value(&arguments, extractors, None, None);
                if !args_diags.is_empty() {
                    tracing::warn!(diagnostics = ?args_diags, "interpolation warnings in call_tool arguments");
                }
                let params = json!({"name": name, "arguments": interpolated_args});
                self.send_and_await("tools/call", Some(params), event_tx)
                    .await?;
            }
            "list_resources" => {
                self.send_and_await("resources/list", None, event_tx)
                    .await?;
            }
            "read_resource" => {
                let raw_uri = action["uri"].as_str().unwrap_or_default();
                let (uri, uri_diags) = interpolate_template(raw_uri, extractors, None, None);
                if !uri_diags.is_empty() {
                    tracing::warn!(diagnostics = ?uri_diags, "interpolation warnings in uri");
                }
                let params = json!({"uri": uri});
                self.send_and_await("resources/read", Some(params), event_tx)
                    .await?;
            }
            "list_prompts" => {
                self.send_and_await("prompts/list", None, event_tx).await?;
            }
            "get_prompt" => {
                let raw_name = action["name"].as_str().unwrap_or_default();
                let (name, name_diags) = interpolate_template(raw_name, extractors, None, None);
                if !name_diags.is_empty() {
                    tracing::warn!(diagnostics = ?name_diags, "interpolation warnings in name");
                }
                let arguments = action.get("arguments").cloned().unwrap_or(json!({}));
                let (interpolated_args, interpolated_args_diags) =
                    interpolate_value(&arguments, extractors, None, None);
                if !interpolated_args_diags.is_empty() {
                    tracing::warn!(diagnostics = ?interpolated_args_diags, "interpolation warnings in interpolated_args");
                }
                let params = json!({"name": name, "arguments": interpolated_args});
                self.send_and_await("prompts/get", Some(params), event_tx)
                    .await?;
            }
            "subscribe_resource" => {
                let raw_uri = action["uri"].as_str().unwrap_or_default();
                let (uri, uri_diags) = interpolate_template(raw_uri, extractors, None, None);
                if !uri_diags.is_empty() {
                    tracing::warn!(diagnostics = ?uri_diags, "interpolation warnings in uri");
                }
                let params = json!({"uri": uri});
                self.send_and_await("resources/subscribe", Some(params), event_tx)
                    .await?;
            }
            unknown => {
                tracing::warn!(action_type = %unknown, "unknown MCP client action type, skipping");
            }
        }

        Ok(())
    }

    /// Bootstrap the multiplexer and handler on first `drive_phase()` call.
    ///
    /// # Errors
    ///
    /// Returns `EngineError::Driver` if the reader has already been consumed
    /// (i.e., bootstrap was called twice).
    pub(super) fn bootstrap(
        &mut self,
        extractors: watch::Receiver<HashMap<String, String>>,
    ) -> Result<(), EngineError> {
        let reader = self.reader.take().ok_or_else(|| {
            EngineError::Driver(
                "MCP client reader already consumed (bootstrap called twice?)".into(),
            )
        })?;

        // Create channels
        let (server_request_tx, server_request_rx) = mpsc::channel(SERVER_REQUEST_BUFFER_SIZE);
        let (notification_tx, notification_rx) = mpsc::channel(NOTIFICATION_BUFFER_SIZE);
        let (handler_event_tx, handler_event_rx) = mpsc::channel(HANDLER_EVENT_BUFFER_SIZE);

        // Create multiplexer shared state
        let response_senders = Arc::new(std::sync::Mutex::new(HashMap::new()));
        let close_reason = Arc::new(std::sync::Mutex::new(None));

        // Spawn multiplexer
        let mux = MessageMultiplexer::spawn(
            reader,
            Arc::clone(&self.writer),
            Arc::clone(&self.pending),
            server_request_tx,
            notification_tx,
            response_senders,
            close_reason,
            self.transport_cancel.clone(),
        );

        // Spawn handler
        let handler_handle = tokio::spawn(server_request_handler(
            server_request_rx,
            Arc::clone(&self.writer),
            Arc::clone(&self.handler_state),
            extractors, // Ownership transfer — handler holds this for the driver's lifetime
            handler_event_tx,
            self.raw_synthesize,
            self.transport_cancel.clone(),
        ));

        self.mux = Some(mux);
        self.notification_rx = Some(notification_rx);
        self.handler_event_rx = Some(handler_event_rx);
        self.handler_handle = Some(handler_handle);

        Ok(())
    }
}

impl Drop for McpClientDriver {
    fn drop(&mut self) {
        // Stop background tasks first so no transport reads/writes continue
        // while process teardown is in-flight.
        self.transport_cancel.cancel();

        if let Some(handle) = self.handler_handle.take() {
            handle.abort();
        }
        if let Some(mux) = self.mux.take() {
            mux.abort();
        }

        if let Some(child) = self.child.as_mut() {
            let _ = child.start_kill();
        }
    }
}

// ============================================================================
// PhaseDriver Implementation
// ============================================================================

#[async_trait]
impl PhaseDriver for McpClientDriver {
    /// Execute the MCP client protocol work for a single phase.
    ///
    /// On the first call, bootstraps the multiplexer and handler.
    /// Performs initialization handshake if not yet done.
    /// Executes phase actions in order, forwarding handler events between each.
    /// After actions, enters an event loop forwarding handler/notification events
    /// until cancel or phase timeout.
    ///
    /// # Errors
    ///
    /// Returns `EngineError::Driver` on protocol-level failures.
    ///
    /// Implements: TJ-SPEC-018 F-004
    async fn drive_phase(
        &mut self,
        _phase_index: usize,
        state: &Value,
        extractors: watch::Receiver<HashMap<String, String>>,
        event_tx: mpsc::Sender<ProtocolEvent>,
        cancel: CancellationToken,
    ) -> Result<DriveResult, EngineError> {
        // Bootstrap on first call: spawn multiplexer and handler
        if self.mux.is_none() {
            self.bootstrap(extractors.clone())?;
        }

        // Initialize on first call
        if !self.initialized {
            self.initialize(state, &event_tx).await?;
        }

        // Update handler state for this phase
        {
            let mut hs = self.handler_state.write().await;
            hs.state = state.clone();
        }

        // Clone extractors for action interpolation
        let current_extractors = extractors.borrow().clone();

        // Execute actions defined in the phase state.
        // For action-driven phases, use a short post-action idle window rather
        // than waiting the full phase timeout.
        let has_actions = state
            .get("actions")
            .and_then(Value::as_array)
            .is_some_and(|actions| !actions.is_empty());
        if let Some(actions) = state.get("actions").and_then(Value::as_array) {
            for action_value in actions {
                // Forward any buffered handler events before each action
                self.forward_pending_events(&event_tx);

                // Normalize and execute action
                let normalized = normalize_action(action_value);
                self.execute_action(&normalized, &current_extractors, &event_tx)
                    .await?;
            }
        }

        // Post-action event loop: forward handler and notification events
        // until cancel fires or timeout expires. For phases that executed
        // explicit actions, use a short idle timeout to avoid stalling until
        // max-session on persistent HTTP transports.
        let idle_timeout = if has_actions {
            POST_ACTION_IDLE_TIMEOUT
        } else {
            self.phase_timeout
        };
        loop {
            tokio::select! {
                biased;
                () = cancel.cancelled() => {
                    break;
                }
                // Monitor handler task for panics
                result = async {
                    if let Some(ref mut handle) = self.handler_handle {
                        handle.await
                    } else {
                        std::future::pending().await
                    }
                } => {
                    if let Err(join_err) = result {
                        tracing::error!(
                            error = %join_err,
                            "server request handler task panicked"
                        );
                    }
                    // Handler exited (normally or via panic) — stop event loop
                    self.handler_handle = None;
                    break;
                }
                evt = async {
                    if let Some(ref mut rx) = self.handler_event_rx {
                        rx.recv().await
                    } else {
                        std::future::pending().await
                    }
                } => {
                    if let Some(evt) = evt {
                        let _ = event_tx.send(evt).await;
                    } else {
                        break;
                    }
                }
                notif = async {
                    if let Some(ref mut rx) = self.notification_rx {
                        rx.recv().await
                    } else {
                        std::future::pending().await
                    }
                } => {
                    if let Some(n) = notif {
                        let _ = event_tx.send(ProtocolEvent {
                            direction: Direction::Incoming,
                            method: n.method,
                            content: n.params.unwrap_or(Value::Null),
                        }).await;
                    } else {
                        break;
                    }
                }
                () = tokio::time::sleep(idle_timeout) => {
                    break;
                }
            }
        }

        Ok(DriveResult::Complete)
    }

    async fn on_phase_advanced(&mut self, _from: usize, _to: usize) -> Result<(), EngineError> {
        // No-op: handler state updated at start of next drive_phase,
        // extractors come from watch channel (always fresh).
        Ok(())
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// Build client capabilities from the phase state.
///
/// Advertises sampling, elicitation, and roots support based on
/// whether the state defines the corresponding response fields.
///
/// Implements: TJ-SPEC-018 F-005
pub(super) fn build_client_capabilities(state: &Value) -> Value {
    let mut caps = json!({});

    if state.get("sampling_responses").is_some() {
        caps["sampling"] = json!({});
    }
    if state.get("roots").is_some() {
        caps["roots"] = json!({"listChanged": false});
    }
    if state.get("elicitation_responses").is_some() {
        caps["elicitation"] = json!({});
    }

    caps
}

// ============================================================================
// Factory Function
// ============================================================================

/// Creates an `McpClientDriver` for stdio or HTTP transport.
///
/// Provide `command` for stdio transport (spawns a server process),
/// or `endpoint` for MCP Streamable HTTP transport.
///
/// # Errors
///
/// Returns `EngineError::Driver` if neither transport option is provided,
/// or if process spawn / HTTP client creation fails.
///
/// Implements: TJ-SPEC-018 F-001
pub fn create_mcp_client_driver(
    command: Option<&str>,
    args: &[String],
    endpoint: Option<&str>,
    headers: &[(String, String)],
    raw_synthesize: bool,
) -> Result<McpClientDriver, EngineError> {
    #[allow(clippy::type_complexity)]
    let (reader, writer, child, child_stderr): (
        Box<dyn McpClientTransportReader>,
        Box<dyn McpClientTransportWriter>,
        Option<Child>,
        Option<ChildStderr>,
    ) = match (command, endpoint) {
        (Some(cmd), _) => {
            let (r, w, mut c) = spawn_stdio_transport(cmd, args)?;
            let stderr = c.stderr.take();
            (Box::new(r), Box::new(w), Some(c), stderr)
        }
        (None, Some(ep)) => {
            let (r, w) = create_http_transport(ep, headers)?;
            (Box::new(r), Box::new(w), None, None)
        }
        (None, None) => {
            return Err(EngineError::Driver(
                "mcp_client mode requires --mcp-client-command (stdio) \
                 or --mcp-client-endpoint (HTTP)"
                    .to_string(),
            ));
        }
    };

    let transport_cancel = CancellationToken::new();

    Ok(McpClientDriver {
        writer: Arc::new(tokio::sync::Mutex::new(writer)),
        pending: Arc::new(std::sync::Mutex::new(HashMap::new())),
        mux: None,
        notification_rx: None,
        handler_event_rx: None,
        handler_state: Arc::new(tokio::sync::RwLock::new(HandlerState {
            state: Value::Null,
        })),
        handler_handle: None,
        server_capabilities: None,
        negotiated_version: None,
        request_timeout: DEFAULT_REQUEST_TIMEOUT,
        phase_timeout: DEFAULT_PHASE_TIMEOUT,
        initialized: false,
        next_request_id: 1,
        raw_synthesize,
        reader: Some(reader),
        transport_cancel,
        child,
        child_stderr,
    })
}